text:
/**
 * Grido date picker plugin.
 * @link https://github.com/dangrossman/bootstrap-daterangepicker
 *
 * @author Petr Bugyík
 * @param {jQuery} $
 * @param {Window} window
 * @param {undefined} undefined
 */
;
(function($, window, undefined) {
    /*jshint laxbreak: true, expr: true */
    "use strict";

    window.Grido.DatePicker =
    {
        /**
         * @returns {boolean}
         */
        isLoaded: function()
        {
            if ($.fn.daterangepicker === undefined) {
                console.error('Plugin "bootstrap-daterangepicker.js" is missing! Run `bower install bootstrap-daterangepicker` and load it.');
                return false;
            }

            return true;
        },

        /**
         * @param Grido
         * @returns {Grido.DatePicker}
         */
        init: function(Grido)
        {
            var $input,
                defaults = Grido.options.datepicker;

            var options = $.extend({
                autoApply: false,
                showDropdowns: true,
                autoUpdateInput: false,
                singleDatePicker: true,
                locale: {
                    format: defaults.format
                }
            }, defaults.options);

            Grido.$element.on('focus', 'input.date', function() {
                $input = $(this);
                $input.daterangepicker(options);
                $input.on('apply.daterangepicker', function(e, picker) {
                    $input.val(picker.startDate.format(defaults.format));
                    Grido.sendFilterForm();
                });
            });

            return this;
        }
    };

    window.Grido.Grid.prototype.onInit.push(function(Grido)
    {
        var DatePicker = window.Grido.DatePicker;
        DatePicker.isLoaded() && DatePicker.init(Grido);
    });

})(jQuery, window);


text:
module Sonar
  module Connector

    # Represents the status and statistics collected by various connectors
    # and is responsible for accessing, updating and persisting the status YAML file.
    class Status

      def initialize(config)
        @status_file = config.status_file
        load_status
      end

      def load_status
        @status = YAML.load_file(status_file) rescue {}
      end

      def save_status
        File.open(status_file, 'w') { |f| f << status.to_yaml }
      end

      def set(group, key, value)
        status[group] = {} unless status[group]
        status[group][key] = value
        status[group]['last_updated'] = Time.now.to_s
        save_status
      end

      def [](group)
        status[group]
      end

      def []=(group, hash)
        status[group] = hash
      end

      private

      attr_accessor :status_file
      attr_accessor :status

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace LeapList.Models
{
    public class NewUserVM
    {
        [Required]
        public string Username { get; set; }

        [Required]
        [DataType(DataType.EmailAddress)]
        [RegularExpression("^.+@.*", ErrorMessage = "Your E-mail must be a valid format.")]
        [Display(Name = "E-mail")]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Confirm Password")]
        [Compare("Password", ErrorMessage = "The password and confirmation do not match.")]
        public string ConfirmPassword { get; set; }
    }
}


text:
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later
 * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
 */
package org.hibernate.orm.persister.entity.spi;

/**
 * @author Steve Ebersole
 */
public enum InheritanceStrategy {
	/**
	 * No inheritance.  Similar to {@link #DISCRIMINATOR} in that there is just a
	 * single table, but with no discriminator column/formula.
	 */
	NONE,
	/**
	 * Uses a dedicated column to store a value indicating the row's concrete type.
	 * Inherently a single-table strategy.
	 */
	DISCRIMINATOR,
	/**
	 * Strategy using a complete table per each concrete subclass - the superclass columns
	 * are defined on each subclass table.  Querying is done via a SQL UNION over all the
	 * hierarchy tables.
	 */
	UNION,
	/**
	 * Strategy using a table per class, joined together.  Highly normalized.
	 */
	JOINED
}


text:
package com.lynden.gmapsfx;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class LegendBox {
    public static void display(String title) {
        Stage window = new Stage();

        //Block events to other windows
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle("Legend");
        window.setMinWidth(300);
        window.setMinHeight(450);

//        Button closeButton = new Button("Close this window");
//        closeButton.setOnAction(e -> window.close());
        Image img2 = new Image("https://trello-attachments.s3.amazonaws.com/57160d5151a9599742d33cc4/861x423/56ea29e10252ec40e9b0f41e482dace1/explaining_text.png",278,140,false,false);
        ImageView imgview2 = new ImageView(img2);
        imgview2.setTranslateY(0);
        imgview2.setTranslateX(0);

        Image img = new Image("https://trello-attachments.s3.amazonaws.com/57160d5151a9599742d33cc4/861x319/2f017c00cca6093002ab1bb382fbc20e/bluepkdot.png", 278, 106, false, false);
        ImageView imgView = new ImageView(img);
        imgView.setTranslateX(0);
        imgView.setTranslateY(0);

        Image mark = new Image("https://trello-attachments.s3.amazonaws.com/57160d5151a9599742d33cc4/750x320/a85af5a9d3f44fc6b5595834b1566eac/marker.png", 250, 107, false, false);
        ImageView markView = new ImageView(mark);
        markView.setTranslateX(-35);
        markView.setTranslateY(0);

        VBox layout = new VBox(10);
        layout.getChildren().addAll(imgview2,imgView, markView);
        layout.setAlignment(Pos.BOTTOM_RIGHT);

        //Display window and wait for it to be closed before returning
        Scene scene = new Scene(layout);
        window.setScene(scene);

        window.showAndWait();
    }
}


text:
#ifndef XEN_VM_STRING_STRING_MAP_MAP_H
#define XEN_VM_STRING_STRING_MAP_MAP_H

#include <xen/api/xen_common.h>

typedef struct xen_vm_string_string_map_map_contents
{
  xen_vm key;
  xen_string_string_map *val;
} xen_vm_string_string_map_map_contents;

typedef struct xen_vm_string_string_map_map
{
    size_t size;
    xen_vm_string_string_map_map_contents contents[];
} xen_vm_string_string_map_map;

/**
 * Allocate a xen_vm_string_string_map_map of the given size.
 */
extern xen_vm_string_string_map_map *
xen_vm_string_string_map_map_alloc(size_t size);

/**
 * Free the given xen_vm_string_string_map_map, and all referenced
 * values.  The given map must have been allocated by this library.
 */
extern void
xen_vm_string_string_map_map_free(xen_vm_string_string_map_map *map);

#endif


text:
package eu.securibox.cloudagents.core.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import eu.securibox.cloudagents.core.Utils;
import eu.securibox.cloudagents.core.types.CountryCode;

public class UriParameters extends HashMap<String, String> {

	/**
	 *
	 */
	private static final long serialVersionUID = 5698539679634758818L;

	public String getParameterString() throws UnsupportedEncodingException {
		if (this.size() == 0)
			return "";

		List<String> params = new ArrayList<String>();
		for (Entry<String, String> entry : this.entrySet()) {
			String key = entry.getKey();
			String value = URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
			params.add(key + "=" + value);
		}

		return String.join("&", params);
	}

	public void put(String key, int value) {
		if (value > 0)
			super.put(key, Integer.toString(value));
	}

	@Override
	public String put(String key, String value) {
		if (!Utils.nullOrEmpty(value))
			return super.put(key, value);
		return "";
	}

	public void put(String key, Date value) {
		if(value != null)
			super.put(key, new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'0000Z'").format(value));
	}

	public void put(String key, boolean value) {
		if(value)
			super.put(key, "true");
		else
			super.put(key,"false");
	}

	public void put(String key, CountryCode countryCode) {
		if(countryCode != null)
			this.put(key, countryCode.getCode());

	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:title=""
        android:icon="@drawable/menu_lists_button"
        android:showAsAction="always"
        >

        <!-- submenus -->
        <menu>
            <item
                android:id="@+id/menu_action_account"
                android:title="@string/submenu_account_setting"/>
            <item
                android:id="@+id/menu_action_user"
                android:title="@string/submenu_user_setting"/>
            <item
                android:id="@+id/menu_action_rating"
                android:title="@string/submenu_rating"/>
            <item
                android:id="@+id/menu_action_about"
                android:title="@string/submenu_about"/>
        </menu>
    </item>

</menu>


text:
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Thrift;
using Thrift.Protocols;
using Thrift.Transports;
using Thrift.Transports.Client;
using tutorial;
using shared;

namespace Client
{
    public class Program
    {
        private static readonly ILogger Logger = new LoggerFactory().CreateLogger(nameof(Client));

        private static void DisplayHelp()
        {
            Console.WriteLine(@"
Usage:
    Client.exe -h
        will diplay help information

    Client.exe -t:<transport> -p:<protocol>
        will run client with specified arguments (tcp transport and binary protocol by default)

Options:
    -t (transport):
        tcp - (default) tcp transport will be used (host - ""localhost"", port - 9090)
        tcpbuffered - buffered transport over tcp will be used (host - ""localhost"", port - 9090)
        namedpipe - namedpipe transport will be used (pipe address - "".test"")
        http - http transport will be used (address - ""http://localhost:9090"")
        tcptls - tcp tls transport will be used (host - ""localhost"", port - 9090)

    -p (protocol):
        binary - (default) binary protocol will be used
        compact - compact protocol will be used
        json - json protocol will be used

Sample:
    Client.exe -t:tcp -p:binary
");
        }

        public static void Main(string[] args)
        {
            args = args ?? new string[0];

            if (args.Any(x => x.StartsWith("-h", StringComparison.OrdinalIgnoreCase)))
            {
                DisplayHelp();
                return;
            }

            using (var source = new CancellationTokenSource())
            {
                RunAsync(args, source.Token).GetAwaiter().GetResult();
            }
        }

        private static async Task RunAsync(string[] args, CancellationToken cancellationToken)
        {
            var clientTransport = GetTransport(args);

            Logger.LogInformation($"Selected client transport: {clientTransport}");

            var clientProtocol = GetProtocol(args, clientTransport);

            Logger.LogInformation($"Selected client protocol: {clientProtocol}");

            await RunClientAsync(clientProtocol, cancellationToken);
        }

        private static TClientTransport GetTransport(string[] args)
        {
            var transport = args.FirstOrDefault(x => x.StartsWith("-t"))?.Split(':')?[1];

            Transport selectedTransport;
            if (Enum.TryParse(transport, true, out selectedTransport))
            {
                switch (selectedTransport)
                {
                    case Transport.Tcp:
                        return new TSocketClientTransport(IPAddress.Loopback, 9090);
                    case Transport.NamedPipe:
                        return new TNamedPipeClientTransport(".test");
                    case Transport.Http:
                        return new THttpClientTransport(new Uri("http://localhost:9090"), null);
                    case Transport.TcpBuffered:
                        return
                            new TBufferedClientTransport(
                                new TSocketClientTransport(IPAddress.Loopback, 9090));
                    case Transport.TcpTls:
                        return new TTlsSocketClientTransport(IPAddress.Loopback, 9090,
                            GetCertificate(), CertValidator, LocalCertificateSelectionCallback);
                    case Transport.Framed:
                        throw new NotSupportedException("Framed is not ready for samples");
                }
            }

            return new TSocketClientTransport(IPAddress.Loopback, 9090);
        }

        private static X509Certificate2 GetCertificate()
        {
            // due to files location in net core better to take certs from top folder
            var certFile = GetCertPath(Directory.GetParent(Directory.GetCurrentDirectory()));
            return new X509Certificate2(certFile, "ThriftTest");
        }

        private static string GetCertPath(DirectoryInfo di, int maxCount = 6)
        {
            var topDir = di;
            var certFile =
                topDir.EnumerateFiles("ThriftTest.pfx", SearchOption.AllDirectories)
                    .FirstOrDefault();
            if (certFile == null)
            {
                if (maxCount == 0)
                    throw new FileNotFoundException("Cannot find file in directories");
                return GetCertPath(di.Parent, maxCount - 1);
            }

            return certFile.FullName;
        }

        private static X509Certificate LocalCertificateSelectionCallback(object sender,
            string targetHost, X509CertificateCollection localCertificates,
            X509Certificate remoteCertificate, string[] acceptableIssuers)
        {
            return GetCertificate();
        }

        private static bool CertValidator(object sender, X509Certificate certificate,
            X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        private static TProtocol GetProtocol(string[] args, TClientTransport transport)
        {
            var protocol = args.FirstOrDefault(x => x.StartsWith("-p"))?.Split(':')?[1];

            Protocol selectedProtocol;
            if (Enum.TryParse(protocol, true, out selectedProtocol))
            {
                switch (selectedProtocol)
                {
                    case Protocol.Binary:
                        return new TBinaryProtocol(transport);
                    case Protocol.Compact:
                        return new TCompactProtocol(transport);
                    case Protocol.Json:
                        return new TJsonProtocol(transport);
                }
            }

            return new TBinaryProtocol(transport);
        }

        private static async Task RunClientAsync(TProtocol protocol,
            CancellationToken cancellationToken)
        {
            try
            {
                var client = new Calculator.Client(protocol);
                await client.OpenTransportAsync(cancellationToken);

                try
                {
                    // Async version

                    Logger.LogInformation("PingAsync()");
                    await client.pingAsync(cancellationToken);

                    Logger.LogInformation("AddAsync(1,1)");
                    var sum = await client.addAsync(1, 1, cancellationToken);
                    Logger.LogInformation($"AddAsync(1,1)={sum}");

                    var work = new Work
                    {
                        Op = Operation.DIVIDE,
                        Num1 = 1,
                        Num2 = 0
                    };

                    try
                    {
                        Logger.LogInformation("CalculateAsync(1)");
                        await client.calculateAsync(1, work, cancellationToken);
                        Logger.LogInformation("Whoa we can divide by 0");
                    }
                    catch (InvalidOperation io)
                    {
                        Logger.LogInformation("Invalid operation: " + io);
                    }

                    work.Op = Operation.SUBTRACT;
                    work.Num1 = 15;
                    work.Num2 = 10;

                    try
                    {
                        Logger.LogInformation("CalculateAsync(1)");
                        var diff = await client.calculateAsync(1, work, cancellationToken);
                        Logger.LogInformation($"15-10={diff}");
                    }
                    catch (InvalidOperation io)
                    {
                        Logger.LogInformation("Invalid operation: " + io);
                    }

                    Logger.LogInformation("GetStructAsync(1)");
                    var log = await client.getStructAsync(1, cancellationToken);
                    Logger.LogInformation($"Check log: {log.Value}");

                    Logger.LogInformation("ZipAsync() with delay 100mc on server side");
                    await client.zipAsync(cancellationToken);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex.ToString());
                }
                finally
                {
                    protocol.Transport.Close();
                }
            }
            catch (TApplicationException x)
            {
                Logger.LogError(x.ToString());
            }
        }

        private enum Transport
        {
            Tcp,
            NamedPipe,
            Http,
            TcpBuffered,
            Framed,
            TcpTls
        }

        private enum Protocol
        {
            Binary,
            Compact,
            Json,
        }
    }
}


text:
import webob.dec

from neutron.api.views import versions as versions_view
from neutron.openstack.common import log as logging
from neutron import wsgi

LOG = logging.getLogger(__name__)

class Versions(object):

    @classmethod
    def factory(cls, global_config, **local_config):
        return cls()

    @webob.dec.wsgify(RequestClass=wsgi.Request)
    def __call__(self, req):
        """Respond to a request for all Neutron API versions."""
        version_objs = [
            {
                "id": "v2.0",
                "status": "CURRENT",
            },
        ]

        if req.path != '/':
            return webob.exc.HTTPNotFound()

        builder = versions_view.get_view_builder(req)
        versions = [builder.build(version) for version in version_objs]
        response = dict(versions=versions)
        metadata = {
            "application/xml": {
                "attributes": {
                    "version": ["status", "id"],
                    "link": ["rel", "href"],
                }
            }
        }

        content_type = req.best_match_content_type()
        body = (wsgi.Serializer(metadata=metadata).
                serialize(response, content_type))

        response = webob.Response()
        response.content_type = content_type
        response.body = body

        return response


text:
import inspect
import os
import random
import sys
from time import sleep

import mpm_manager
from utils import config_file

FORMAT_PID_STR = "longpool format peer id"

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)

from vk_api.api import get_api
from vk_api.api import Message
from vk_api.api import api_request
from vk_api.api import vapi

import bot_header

# THIS METHOD EXECUTING WHEN USER SENT A MESSAGE TO YOU
# calling from main()
def on_message_received(message, lpt):
    e = message.extra
    # Getting list of modules
    manager = mpm_manager.ModuleManager()
    modules = manager.get_modules()

    # Exec each modules and get result
    for module in modules:
        result = module.execute_module(message, lpt)
        if result is not None:
            return result

    pass

# entry point of MESSAGE_SEND event of long pool server
# calling from long_pool_event.py
def main(resp, lp_thread_ins):
    #
    # Getting message from response
    message = Message()
    message = Message.from_long_pool(message, resp)
    #

    if message.is_out():
        bot_header.LP_MESSAGES_RECEIVED += 1
    else:
        bot_header.LP_MESSAGES_SENT += 1

    # Printing message to std out
    if message.is_loopback():
        sep = "<->"
    elif message.is_out():
        sep = "->"
    else:
        sep = "<-"

    fpid = False
    fpid = config_file.get_field(FORMAT_PID_STR) != "0"

    if fpid:
        u = vapi("users.get", "user_ids=%s" % message.pid)[0]
        lp_thread_ins.print("%s [%s]: %s" % (sep, "%s %s" % (u["first_name"], u["last_name"]), message.body))
    else:
        lp_thread_ins.print("%s [%s]: %s" % (sep, str(message.pid), message.body))

    #

    response_to_user = on_message_received(message, lp_thread_ins)
    if response_to_user is not None:
        send_response(lp_thread_ins, message, response_to_user)

def send_response(lp_thread_ins, message, response_to_user):
    # send response to vk_api user
    # getting api instance
    api = get_api(lpt=lp_thread_ins)
    # looking at config file
    make_typing = config_file.has("typing")
    # checking typing filed in config file
    if make_typing:
        read_message_before_typing = config_file.has("read before typing")
        ###
        # sets speed of typing (in seconds)
        # from time
        typing_speedf = config_file.get_field("typing speed from")
        # to time
        typing_speedt = config_file.get_field("typing speed to")
        # e.g: from 1 sec to 5 sec
        ###
        # don;t use random. use only typing_speedt
        static_typing = config_file.has("typing static")

        # getting random typing speed (by default)
        typing_time = random.randint(1, 5)
        # checking that typing_speedf and typing_speedt is number
        if str.isnumeric(typing_speedf) and str.isnumeric(typing_speedt):
            # checking static typing is enabled
            if not static_typing:
                # get random typing time
                typing_time = random.randint(int(typing_speedf), int(typing_speedt))
            else:
                # get time only from typing_speedt
                typing_time = int(typing_speedt)

        if read_message_before_typing:
            result = api_request(api, "messages.markAsRead", "message_ids=%s, peer_id=%s" % (message.mid, message.pid))
            lp_thread_ins.v("Marking '%s' as read... %s" % (message.body, str(result)))

        # sleep each 5 secs until end of typing duration
        def typing(typing_time, stime=1):
            i = 0
            while i < typing_time:
                result = api_request(api, "messages.setActivity", "peer_id=%s, type='typing'" % message.pid)
                # result = api.messages.setActivity(peer_id=message.pid, type="typing")
                lp_thread_ins.v("making typing request for %s... %s" % (message.body, str(result)))
                sleep(stime)
                i += stime

        typing(typing_time)

    # let's fucking do this!
    # sending message to peer
    random_id = random.randint(0, 100000)
    peer_id = message.pid
    messaget = response_to_user
    msendresult = api_request(api, "messages.send", "random_id=%s, peer_id=%s, message=\"%s\"" % (
        random_id, peer_id, messaget
    ))
    lp_thread_ins.v("sending %s to %s... %s" % (response_to_user, message.body, str(msendresult)))


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.concurrency;

import com.intellij.openapi.diagnostic.Logger;
import org.jetbrains.annotations.NotNull;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * This class implements the global delayed queue which is used by
 * {@link AppScheduledExecutorService} and {@link BoundedScheduledExecutorService}.
 * It starts the background thread which polls the queue for tasks ready to run and sends them to the appropriate executor.
 * The {@link #shutdown(SchedulingWrapper.MyScheduledFutureTask)} must be called before disposal.
 */
final class AppDelayQueue extends DelayQueue<SchedulingWrapper.MyScheduledFutureTask<?>> {
  private static final Logger LOG = Logger.getInstance(AppDelayQueue.class);
  private final TransferThread transferThread = new TransferThread();
  private final AtomicBoolean shutdown = new AtomicBoolean();
  private volatile SchedulingWrapper.MyScheduledFutureTask<Void> myPoisonPill;

  /** this thread takes the ready-to-execute scheduled tasks off the queue and passes them for immediate execution to {@link SchedulingWrapper#backendExecutorService} */
  AppDelayQueue() {
    transferThread.setDaemon(true); // mark as daemon to not prevent JVM to exit (needed for Kotlin CLI compiler)
    transferThread.start();
  }

  void shutdown(@NotNull SchedulingWrapper.MyScheduledFutureTask<Void> poisonPill) {
    if (shutdown.getAndSet(true)) {
      throw new IllegalStateException("Already shutdown");
    }
    myPoisonPill = poisonPill;
    super.offer(poisonPill);
  }

  boolean awaitTermination(long timeout, @NotNull TimeUnit unit) throws InterruptedException {
    if (!shutdown.get()) {
      throw new IllegalStateException("must call shutdown before");
    }
    long deadline = System.nanoTime() + unit.toNanos(timeout);
    try {
      myPoisonPill.get(timeout, unit);
    }
    catch (ExecutionException e) {
      throw new RuntimeException(e);
    }
    catch (TimeoutException e) {
      return false;
    }
    transferThread.join(TimeUnit.NANOSECONDS.toMillis(Math.max(1, deadline - System.nanoTime())));
    return !transferThread.isAlive();
  }

  @Override
  public boolean offer(@NotNull SchedulingWrapper.MyScheduledFutureTask<?> task) {
    if (shutdown.get()) {
      throw new IllegalStateException("Already shutdown");
    }
    return super.offer(task);
  }

  @NotNull
  Thread getThread() {
    return transferThread;
  }

  private class TransferThread extends Thread {
    private TransferThread() {
      super("Periodic tasks thread");
    }

    @Override
    public void run() {
      while (true) {
        try {
          SchedulingWrapper.MyScheduledFutureTask<?> task = take();
          if (LOG.isTraceEnabled()) {
            LOG.trace("Took "+BoundedTaskExecutor.info(task));
          }
          try {
            if (!task.executeMeInBackendExecutor()) {
              break;
            }
          }
          catch (Throwable e) {
            try {
              LOG.error("Error executing "+task, e);
            }
            catch (Throwable ignored) {
              // do not let it stop the thread
            }
          }
        }
        catch (InterruptedException e) {
          if (!shutdown.get()) {
            LOG.error(e);
          }
        }
      }
      LOG.debug("AppDelayQueue.TransferrerThread Stopped");
    }
  }
}


text:
// Type definitions for broken-link-checker 0.7
// Project: https://github.com/stevenvachon/broken-link-checker
// Definitions by: Anh Le <https://github.com/Haizzz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

export interface Options {
    acceptedSchemes?: string[];
    cacheExpiryTime?: number;
    cacheResponses?: boolean;
    excludedKeywords?: string[];
    excludedSchemes?: string[];
    excludeExternalLinks?: boolean;
    excludeInternalLinks?: boolean;
    excludeLinksToSamePage?: boolean;
    filterLevel?: 0 | 1 | 2 | 3;
    honorRobotExclusions?: boolean;
    maxSockets?: number;
    maxSocketsPerHost?: number;
    rateLimit?: number;
    requestMethod?: string;
    retry405Head?: boolean;
    userAgent?: string;
}
/** Declaration file generated by dts-gen */

export class HtmlChecker {
    constructor(
        options: Options,
        handlers: {
            html?: (tree: any, robots: any) => void;
            junk?: (result: any) => void;
            link?: (result: any) => void;
            complete?: () => void;
        },
    );

    clearCache(): any;

    numActiveLinks(): any;

    numQueuedLinks(): any;

    pause(): any;

    resume(): any;

    scan(html: any, baseUrl: any, robots: any): any;
}

export class HtmlUrlChecker {
    constructor(
        options: Options,
        handlers: {
            html?: (tree: any, robots: any) => void;
            junk?: (result: any) => void;
            link?: (result: any) => void;
            page?: (error: any, pageUrl: any, customData: any) => void;
            end?: () => void;
        },
    );

    clearCache(): any;

    dequeue(id: any): any;

    enqueue(pageUrl: any, customData: any): any;

    numActiveLinks(): any;

    numPages(): any;

    numQueuedLinks(): any;

    pause(): any;

    resume(): any;
}

export class SiteChecker {
    constructor(
        options: Options,
        handlers: {
            robots?: (robots: any, customData: any) => void;
            html?: (tree: any, robots: any) => void;
            junk?: (result: any) => void;
            link?: (result: any) => void;
            page?: (error: any, pageUrl: any, customData: any) => void;
            site?: (error: any, siteUrl: any, customData: any) => void;
            end?: () => void;
        },
    );

    clearCache(): any;

    dequeue(id: any): any;

    enqueue(firstPageUrl: any, customData: any): any;

    numActiveLinks(): any;

    numPages(): any;

    numQueuedLinks(): any;

    numSites(): any;

    pause(): any;

    resume(): any;
}

export class UrlChecker {
    constructor(
        options: Options,
        handlers: {
            link?: (result: any) => void;
            end?: () => void;
        },
    );

    clearCache(): any;

    dequeue(id: any): any;

    enqueue(url: any, baseUrl: any, customData: any): any;

    numActiveLinks(): any;

    numQueuedLinks(): any;

    pause(): any;

    resume(): any;
}

export const BLC_EXTERNAL: string;

export const BLC_HTML: string;

export const BLC_INTERNAL: string;

export const BLC_INVALID: string;

export const BLC_KEYWORD: string;

export const BLC_ROBOTS: string;

export const BLC_SAMEPAGE: string;

export const BLC_SCHEME: string;

export const BLC_UNKNOWN: string;

export const ERRNO_EACCES: string;

export const ERRNO_EADDRINFO: string;

export const ERRNO_EADDRINUSE: string;

export const ERRNO_EADDRNOTAVAIL: string;

export const ERRNO_EAFNOSUPPORT: string;

export const ERRNO_EAGAIN: string;

export const ERRNO_EAIFAMNOSUPPORT: string;

export const ERRNO_EAISERVICE: string;

export const ERRNO_EAISOCKTYPE: string;

export const ERRNO_EALREADY: string;

export const ERRNO_EBADF: string;

export const ERRNO_EBUSY: string;

export const ERRNO_ECANCELED: string;

export const ERRNO_ECHARSET: string;

export const ERRNO_ECONNABORTED: string;

export const ERRNO_ECONNREFUSED: string;

export const ERRNO_ECONNRESET: string;

export const ERRNO_EDESTADDRREQ: string;

export const ERRNO_EEXIST: string;

export const ERRNO_EFAULT: string;

export const ERRNO_EHOSTUNREACH: string;

export const ERRNO_EINTR: string;

export const ERRNO_EINVAL: string;

export const ERRNO_EIO: string;

export const ERRNO_EISCONN: string;

export const ERRNO_EISDIR: string;

export const ERRNO_ELOOP: string;

export const ERRNO_EMFILE: string;

export const ERRNO_EMSGSIZE: string;

export const ERRNO_ENAMETOOLONG: string;

export const ERRNO_ENETDOWN: string;

export const ERRNO_ENETUNREACH: string;

export const ERRNO_ENFILE: string;

export const ERRNO_ENOBUFS: string;

export const ERRNO_ENODEV: string;

export const ERRNO_ENOENT: string;

export const ERRNO_ENOMEM: string;

export const ERRNO_ENONET: string;

export const ERRNO_ENOSPC: string;

export const ERRNO_ENOSYS: string;

export const ERRNO_ENOTCONN: string;

export const ERRNO_ENOTDIR: string;

export const ERRNO_ENOTEMPTY: string;

export const ERRNO_ENOTFOUND: string;

export const ERRNO_ENOTSOCK: string;

export const ERRNO_ENOTSUP: string;

export const ERRNO_EOF: string;

export const ERRNO_EPERM: string;

export const ERRNO_EPIPE: string;

export const ERRNO_EPROTO: string;

export const ERRNO_EPROTONOSUPPORT: string;

export const ERRNO_EPROTOTYPE: string;

export const ERRNO_EROFS: string;

export const ERRNO_ESHUTDOWN: string;

export const ERRNO_ESPIPE: string;

export const ERRNO_ESRCH: string;

export const ERRNO_ETIMEDOUT: string;

export const ERRNO_EXDEV: string;

export const ERRNO_OK: string;

export const ERRNO_UNKNOWN: string;

export const HTTP_100: string;

export const HTTP_101: string;

export const HTTP_102: string;

export const HTTP_103: string;

export const HTTP_200: string;

export const HTTP_201: string;

export const HTTP_202: string;

export const HTTP_203: string;

export const HTTP_204: string;

export const HTTP_205: string;

export const HTTP_206: string;

export const HTTP_207: string;

export const HTTP_208: string;

export const HTTP_226: string;

export const HTTP_300: string;

export const HTTP_301: string;

export const HTTP_302: string;

export const HTTP_303: string;

export const HTTP_304: string;

export const HTTP_305: string;

export const HTTP_307: string;

export const HTTP_308: string;

export const HTTP_400: string;

export const HTTP_401: string;

export const HTTP_402: string;

export const HTTP_403: string;

export const HTTP_404: string;

export const HTTP_405: string;

export const HTTP_406: string;

export const HTTP_407: string;

export const HTTP_408: string;

export const HTTP_409: string;

export const HTTP_410: string;

export const HTTP_411: string;

export const HTTP_412: string;

export const HTTP_413: string;

export const HTTP_414: string;

export const HTTP_415: string;

export const HTTP_416: string;

export const HTTP_417: string;

export const HTTP_418: string;

export const HTTP_421: string;

export const HTTP_422: string;

export const HTTP_423: string;

export const HTTP_424: string;

export const HTTP_425: string;

export const HTTP_426: string;

export const HTTP_428: string;

export const HTTP_429: string;

export const HTTP_431: string;

export const HTTP_451: string;

export const HTTP_500: string;

export const HTTP_501: string;

export const HTTP_502: string;

export const HTTP_503: string;

export const HTTP_504: string;

export const HTTP_505: string;

export const HTTP_506: string;

export const HTTP_507: string;

export const HTTP_508: string;

export const HTTP_509: string;

export const HTTP_510: string;

export const HTTP_511: string;


text:
taskBoardDirectives.directive('includeReplace', function () {
    return {
        restrict: 'A',
        replace: true,
        templateUrl: function(element, attributes) {
            return attributes.includeReplace;
        }
    };
});


text:
package io.astefanutti.metrics.cdi.se;

import com.codahale.metrics.health.HealthCheckRegistry;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;

public class HealthCheckRegistryProducerMethodBean {

    @Produces
    @ApplicationScoped
    HealthCheckRegistry registry() {
        return new HealthCheckRegistry();
    }
}


text:
typedef enum {
    kEnemyRankMerchant,
    kEnemyRankNormal,
    kEnemyRankSpecial,
    kEnemyRankBoss
} EnemyRank;

// Enumaration containing enemy types
typedef enum {
    kEnemyType1,
    kEnemyType2,
    kEnemyType3,
    kEnemyType4,
    kEnemyType5
} EnemyType;

// Enumaration containing enemy abilities
typedef enum {
    kEnemyAbilityNone,
    kEnemyAbilityShop,
    kEnemyAbilityGold,
    kEnemyAbilityExperience,
    kEnemyAbilityHeal,
    kEnemyAbilityReflect,
    kEnemyAbilityDrainLife,
    kEnemyAbilityDoubleStrike,
    kEnemyAbilityBlind,
    kEnemyAbilityDragonFire,
    kEnemyAbilityEarthquake,
    kEnemyAbilityTeleport,
    kEnemyAbilityPoison,
    kEnemyAbilityPhysicalDefence,
    kEnemyAbilityMagicalDefence,
    kEnemyAbilityNegateEnergy,
    kEnemyAbilityFreezeTime,
    kEnemyAbilityConfusion,
    kEnemyAbilitySabotage,
    kEnemyAbilityTransmutation,
    kEnemyAbilityNullification,
    kEnemyAbilityTemporalSwift
} EnemyAbility;

#endif


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

<title>CommitLogSegment (apache-cassandra API)</title>
<meta name="date" content="2016-06-06">
<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

org.apache.cassandra.db.commitlog

Class CommitLogSegment

java.lang.Object

org.apache.cassandra.db.commitlog.CommitLogSegment

Direct Known Subclasses:

FileDirectSegment, MemoryMappedSegment

public abstract class CommitLogSegment
extends java.lang.Object

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
CommitLogSegment.CommitLogSegmentFileComparator

Field Summary

Fields

Modifier and Type
Field and Description

CommitLogDescriptor
descriptor

static int
ENTRY_OVERHEAD_SIZE

long
id

Method Summary

All Methods Instance Methods Abstract Methods Concrete Methods

Modifier and Type
Method and Description

protected java.util.Map<java.lang.String,java.lang.String>
additionalHeaderParameters()

Provide any additional header data that should be stored in the CommitLogDescriptor.

boolean
contains(ReplayPosition context)

Check to see if a certain ReplayPosition is contained by this segment file.

long
contentSize()

java.lang.String
dirtyString()

ReplayPosition
getContext()

java.util.Collection<java.util.UUID>
getDirtyCFIDs()

java.lang.String
getName()

java.lang.String
getPath()

protected void
internalClose()

Close the segment file.

boolean
isStillAllocating()

boolean
isUnused()

void
markClean(java.util.UUID cfId,
         ReplayPosition context)

Marks the ColumnFamily specified by cfId as clean for this log segment.

abstract long
onDiskSize()

java.lang.String
toString()

protected void
writeSyncMarker(java.nio.ByteBuffer buffer,
               int offset,
               int filePos,
               int nextMarker)

Create a sync marker to delineate sections of the commit log, typically created on each sync of the file.

Methods inherited from class java.lang.Object

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

Field Detail

ENTRY_OVERHEAD_SIZE

public static final int ENTRY_OVERHEAD_SIZE

See Also:

Constant Field Values

id

public final long id

descriptor

public final CommitLogDescriptor descriptor

Method Detail

additionalHeaderParameters

protected java.util.Map<java.lang.String,java.lang.String> additionalHeaderParameters()

Provide any additional header data that should be stored in the CommitLogDescriptor.

writeSyncMarker

protected void writeSyncMarker(java.nio.ByteBuffer buffer,
                               int offset,
                               int filePos,
                               int nextMarker)

Create a sync marker to delineate sections of the commit log, typically created on each sync of the file.
 The sync marker consists of a file pointer to where the next sync marker should be (effectively declaring the length
 of this section), as well as a CRC value.

Parameters:

buffer - buffer in which to write out the sync marker.

offset - Offset into the buffer at which to write the sync marker.

filePos - The current position in the target file where the sync marker will be written (most likely different from the buffer position).

nextMarker - The file position of where the next sync marker should be.

isStillAllocating

public boolean isStillAllocating()

getContext

public ReplayPosition getContext()

Returns:

the current ReplayPosition for this log segment

getPath

public java.lang.String getPath()

Returns:

the file path to this segment

getName

public java.lang.String getName()

Returns:

the file name of this segment

internalClose

protected void internalClose()

Close the segment file. Do not call from outside this class, use syncAndClose() instead.

markClean

public void markClean(java.util.UUID cfId,
                      ReplayPosition context)

Marks the ColumnFamily specified by cfId as clean for this log segment. If the
 given context argument is contained in this file, it will only mark the CF as
 clean if no newer writes have taken place.

Parameters:

cfId - the column family ID that is now clean

context - the optional clean offset

getDirtyCFIDs

public java.util.Collection<java.util.UUID> getDirtyCFIDs()

Returns:

a collection of dirty CFIDs for this segment file.

isUnused

public boolean isUnused()

Returns:

true if this segment is unused and safe to recycle or delete

contains

public boolean contains(ReplayPosition context)

Check to see if a certain ReplayPosition is contained by this segment file.

Parameters:

context - the replay position to be checked

Returns:

true if the replay position is contained by this segment file.

dirtyString

public java.lang.String dirtyString()

onDiskSize

public abstract long onDiskSize()

contentSize

public long contentSize()

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

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 © 2016 The Apache Software Foundation


text:
% This file is a demonstration of how to call gbvs()

% make some parameters
params = makeGBVSParams;

% could change params like this
params.contrastwidth = .11;

% example of itti/koch saliency map call
params.useIttiKochInsteadOfGBVS = 1;
outitti = gbvs('samplepics/1.jpg',params);
figure;
subplot(1,2,1);
imshow(imread('samplepics/1.jpg'));
title('image');
subplot(1,2,2);
imshow(outitti.master_map_resized);
title('Itti, Koch Saliency Map');
fprintf(1,'Now waiting for user to press enter...\n');
pause;

% example of calling gbvs() with default params and then displaying result
outW = 200;
out = {};
% compute saliency maps for some images
for i = 1 : 5

  img = imread(sprintf('samplepics/%d.jpg',i));

  tic;

    % this is how you call gbvs
    % leaving out params reset them to all default values (from
    % algsrc/makeGBVSParams.m)
    out{i} = gbvs( img );

  toc;

  % show result in a pretty way

  s = outW / size(img,2) ;
  sz = size(img); sz = sz(1:2);
  sz = round( sz * s );

  img = imresize( img , sz , 'bicubic' );
  saliency_map = imresize( out{i}.master_map , sz , 'bicubic' );
  if ( max(img(:)) > 2 ) img = double(img) / 255; end
  img_thresholded = img .* repmat( saliency_map >= prctile(saliency_map(:),75) , [ 1 1 size(img,3) ] );

  figure;
  subplot(2,2,1);
  imshow(img);
  title('original image');

  subplot(2,2,2);
  imshow(saliency_map);
  title('GBVS map');

  subplot(2,2,3);
  imshow(img_thresholded);
  title('most salient (75%ile) parts');

  subplot(2,2,4);
  show_imgnmap(img,out{i});
  title('saliency map overlayed');

  if ( i < 5 )
    fprintf(1,'Now waiting for user to press enter...\n');
    pause;
  end

end


text:
/* MENU STYLES */

/* BASIC MENU STYLES */
/* these styles form the base styles for every menu and should be overridden for specific menus*/

.rb_menu .menu_sections_wrap {
  text-align: left;
}

.rb_menu .menu_sections_division {
  font-weight: bold;
  margin-bottom: 1em;
}

/* the list of menu sections */

.rb_menu .sections_list {
  margin: 0 0 1.5em;
}

.rb_menu .sections_list {
    list-style: none outside none;
    margin: 0;
    margin-bottom: 1em;
    padding: 0;
}

.rb_menu .sections_list li {
    margin: 0 10px 10px 0;
    padding: 0;
    float: left;
}

.rb_menu .sections_list li a {

  display: block;
  padding: 5px 10px;
  margin: 0;

  color: #444;

  text-decoration: none;
  letter-spacing: 1px;
  /*text-shadow: 0 1px 0 #fff;*/
  /*text-transform: lowercase;*/
  /*text-transform: uppercase;*/

}

.rb_menu .round_corners .sections_list li a {
	-webkit-border-radius: 3px;
     -moz-border-radius: 3px;
          border-radius: 3px;
}

.rb_menu .sections_list li a:hover {
    background-color: #cfcfcf;
}

.rb_menu .sections_list li a.active {
  color: #fff;
  background-color: #636363;

}

/* basic section name and subsection styles */
.rb_menu .menu_section_name_wrap,
.rb_menu .menu_subsection_name_wrap {
	margin: 20px 0 15px;
  background-color: #F4F4F4;
	padding: 7px 5px;
  text-align: left;
}

.rb_menu .round_corners .menu_section_name_wrap,
.rb_menu .round_corners .menu_subsection_name_wrap {
	-webkit-border-radius: 3px;
     -moz-border-radius: 3px;
          border-radius: 3px;
}

.rb_menu .menu_section_name,
.rb_menu .menu_subsection_name {
  /*width: 300px;*/
	/*color: #666;*/
	/*display: inline-block;*/
	/*font-family: Georgia,Times New Roman;*/
	/*font-size: 14pt;*/
	font-style: italic;
	letter-spacing: -0.2pt;

}

/* if photos are hidden */
.rb_menu .hide_position_photos .menu_section_name,
.rb_menu .hide_position_photos .menu_subsection_name {
    width: 500px;
}

.rb_menu .menu_section_volume,
.rb_menu .menu_subsection_volume {
	width: 85px;
	/*color: #228593;*/
	text-align: right;
}

/* basic position styles */

.rb_menu .menu_position {
	padding: 10px 5px;
  margin: 20px 0;
}

/* position photo column */
.rb_menu .position_photo {
	width: 200px;
  /*width: auto;*/
  /*width: 10%;*/
  /*min-width: 200px;*/
  /*max-width: 200px;*/
}

.rb_menu .position_photo img {
  /*border: 1px solid #333;*/
  /*background-color: #CDE8E9;*/
  /*margin: 3px 6px 3px 0;*/
  /*max-height: 90px;*/
  max-width: 200px;
  /*padding: 3px;*/
  vertical-align: middle;
  opacity: 1;
}

.rb_menu .round_corners .position_photo img {
	-webkit-border-radius: 3px;
     -moz-border-radius: 3px;
          border-radius: 3px;
}

.rb_menu .position_photo img:hover {
    /*border: 1px solid #fff;*/
    opacity: 0.8;
}

/* position description column */
.rb_menu .position_description_wrap {
    width: 350px;
    /*width: auto;*/
    /*width: 70%;*/
    padding: 0 0 0 10px;
    /*color: #D2D7B7;*/
}

/* if position photos are hidden */
.rb_menu .hide_position_photos .position_description_wrap {
    width: 575px;
    padding: 0;
}

.rb_menu .position_name {
	font-weight: bold;
}

.rb_menu .position_about {
	/*color:#FFF8C6;*/
}

/* position price column */
.rb_menu .position_price {
	width: 75px;
  /*width: 10%;*/
	text-align: right;
	font-weight: bold;
}

/* BASIC STYLES FOR SPECIFIC MENU TYPES */

/* bar_menu */

.rb_menu .bar_menu .menu_section_name {
    width: 423px;
}

.rb_menu .bar_menu td.menu_section_volume {
    width: 75px;
}

.rb_menu .bar_menu .position_description_wrap {
    width: 218px;
}

/* bar_menu with no photos */

.rb_menu .bar_menu .hide_position_photos .position_description_wrap {
    width: 420px;
}

/* wine_menu  */
.rb_menu .wine_menu .menu_section_name,
.rb_menu .wine_menu .menu_subsection_name {
    width: 423px;
}

.rb_menu .wine_menu .menu_section_volume {
    width: 75px;
}

.rb_menu .wine_menu .position_description_wrap {
    width: 218px;
}

/* wine_menu with no photos */

.rb_menu .wine_menu .hide_position_photos .position_description_wrap {
    width: 420px;
}

/* hookah_menu */

.rb_menu .hookah_menu .menu_section_name {
    width: 500px;
}

.rb_menu .hookah_menu .position_description_wrap {
    width: 570px;
    padding: 0;
}

/* MENU COLOR VARIANTS */

/* azure */
.rb_menu .azure .menu_section_name_wrap,
.rb_menu .azure .menu_subsection_name_wrap {
	background-color: #CFFAFA;
}

.rb_menu .azure .sections_list li a {
  color: #4A6D6E;
  /*background-color: #EBFDFE;*/
  /*background-color: rgba(235, 253, 254, 0.8);*/
}

/*should be before :hover */
.rb_menu .azure .sections_list li a:hover {
    background-color: #EBFDFE;
}

.rb_menu .azure .sections_list li a.active {
  color: #fff;
  background-color: #24BDAF;

}

.rb_menu .azure .no_photo {
  background-color: #E2FCFC;
}

/* grey */
.rb_menu .grey .menu_section_name_wrap,
.rb_menu .grey .menu_subsection_name_wrap {
	background-color: #F4F4F4;
}

.rb_menu .grey .sections_list li a {
  color: #1A688F;
  background-color: #eee;
  /*background-color: rgba(238, 238, 238, 0.8);*/
}

/*should be before :hover */
.rb_menu .grey .sections_list li a:hover {
    background-color: #E4E4E4;
}

.rb_menu .grey .sections_list li a.active {
  color: #000;
  background-color: #EEEEEE;
  /*background-color: transparent;*/
  font-weight: bold;

}

.rb_menu .grey .no_photo {
  background-color: #F8F8F8;
}

/* END MENU STYLES */

/* no photo replacement */

.no_photo {
    background-color:#F8F8F8;
    color:#666;
    font-size:9px;
    height:100px;
    width:100px;

    text-align:center;
    text-decoration: none;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
}

.no_photo .no_photo_text {
    padding: 27px 0 0;
    margin: 0 10px;
}

.no_photo {
    font-size:12px;
    height:150px;
    width:200px;
    line-height: 150px;
    padding: 0;
}

.no_photo .no_photo_text {
    padding: 0;
}

.related_item_image_wrap .no_photo {
    position: relative;
    font-size:25px;
    height:70px;
    width:100px;
    line-height: 17px;
    padding: 0;
}

.related_item_image_wrap .no_photo .no_photo_link{
    position: absolute;
    left: 0px;
    right: 0px;
    width: 100px;
    height: 70px;
    line-height: 70px;
}


text:
"use strict";

var fs = require("fs"),
    path = require("path"),
    assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("lodash"),
    httputil = require("./lib/http"),
    gj = httputil.getJSON,
    pj = httputil.postJSON,
    oauthutil = require("./lib/oauth"),
    apputil = require("./lib/app"),
    actutil = require("./lib/activity"),
    validActivity = actutil.validActivity,
    setupApp = apputil.setupApp,
    newPair = oauthutil.newPair;

var tc = _.clone(require("./config.json"));

var suite = vows.describe("configured user and tokens");

suite.addBatch({
    "When we set up the app with configured users": {
        topic: function() {
            setupApp(this.callback);
        },
        teardown: function(app) {
            app.close();
        },
        "it works": function(err, app) {
            assert.ifError(err);
        },
        "and we request the user profile with the configured credentials": {
            topic: function() {
                var callback = this.callback;
                var client = tc.clients[0];
                var user = tc.users[0];
                var token = user.tokens[0];
                var nickname = user.nickname;
                var cred = {
                    consumer_key: client.client_id,
                    consumer_secret: client.client_secret,
                    token: token.token,
                    token_secret: token.token_secret
                };
                gj("http://localhost:4815/api/user/" + nickname, cred, callback);
            },
            "it works": function(err, body, resp) {
                assert.ifError(err);
                assert.isObject(body);
            }
        },
        "and we post a new activity with the configured credentials": {
            topic: function() {
                var callback = this.callback;
                var client = tc.clients[0];
                var user = tc.users[0];
                var token = user.tokens[0];
                var nickname = user.nickname;
                var cred = {
                    consumer_key: client.client_id,
                    consumer_secret: client.client_secret,
                    token: token.token,
                    token_secret: token.token_secret
                };
                var url = "http://localhost:4815/api/user/"+nickname+"/feed";
                var act = {
                        verb: "post",
                        object: {
                            objectType: "note",
                            content: "Hello, world."
                        }
                    };

                pj(url, cred, act, callback);
            },
            "it works": function(err, body) {
                assert.ifError(err);
                validActivity(body);
            }
        }
    }
});

suite["export"](module);


text:
package server

import (
//	"testing"
)


text:
void interpola_spline (int numero_keys,Vector **t_entrada,Vector **t_salida,info_pos_path *keys);
void interpola_spline_scale (int numero_keys,Vector **t_entrada,Vector **t_salida,info_scale_path *keys);
void interpola_spline_fov (int numero_keys,float **t_entrada,float **t_salida,info_fov_path *keys);
void interpola_spline_roll (int numero_keys,float **t_entrada,float **t_salida,info_roll_path *keys);
void interpola_rotaciones(int numero_keys,Quaternion **t_entrada,Quaternion **t_salida,info_rot_path *keys);

void InterpolaPosicion(int numero_keys,
		       Vector *t_entrada,
		       Vector *t_salida,
		       info_pos_path *keys,
		       float frame,
		       float *x,float *y,float *z);
void InterpolaScale(int numero_keys,
		    Vector *t_entrada,
		    Vector *t_salida,
		    info_scale_path *keys,
		    float frame,
		    float *scalex,float *scaley,float *scalez);
void InterpolaFov(int numero_keys,
		       float *t_entrada,
		       float *t_salida,
		       info_fov_path *keys,
		       float frame,
		       float *fov);
void InterpolaRoll(int numero_keys,
		       float *t_entrada,
		       float *t_salida,
		       info_roll_path *keys,
		       float frame,
		       float *roll);
void InterpolaRotacion(int numero_keys,
		       Quaternion *tangentes_entrada,
		       Quaternion *tangentes_salida,
		       info_rot_path *keys,
		       float frame,
		       Quaternion *quat);
#endif


text:
package org.locationtech.geowave.core.ingest.operations;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.locationtech.geowave.core.cli.annotations.GeowaveOperation;
import org.locationtech.geowave.core.cli.api.OperationParams;
import org.locationtech.geowave.core.cli.api.ServiceEnabledCommand;
import org.locationtech.geowave.core.cli.operations.config.options.ConfigOptions;
import org.locationtech.geowave.core.ingest.hdfs.mapreduce.IngestFromHdfsDriver;
import org.locationtech.geowave.core.ingest.hdfs.mapreduce.IngestFromHdfsPlugin;
import org.locationtech.geowave.core.ingest.hdfs.mapreduce.MapReduceCommandLineOptions;
import org.locationtech.geowave.core.ingest.operations.options.IngestFormatPluginOptions;
import org.locationtech.geowave.core.store.api.Index;
import org.locationtech.geowave.core.store.cli.CLIUtils;
import org.locationtech.geowave.core.store.cli.VisibilityOptions;
import org.locationtech.geowave.core.store.cli.store.DataStorePluginOptions;
import org.locationtech.geowave.core.store.index.IndexStore;
import org.locationtech.geowave.core.store.ingest.LocalInputCommandLineOptions;
import org.locationtech.geowave.core.store.util.DataStoreUtils;
import org.locationtech.geowave.mapreduce.operations.ConfigHDFSCommand;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;

@GeowaveOperation(name = "mrToGW", parentOperation = IngestSection.class)
@Parameters(commandDescription = "Ingest supported files that already exist in HDFS")
public class MapReduceToGeoWaveCommand extends ServiceEnabledCommand<Void> {

  @Parameter(
      description = "<path to base directory to write to> <store name> <comma delimited index list>")
  private List<String> parameters = new ArrayList<>();

  @ParametersDelegate
  private VisibilityOptions ingestOptions = new VisibilityOptions();

  @ParametersDelegate
  private MapReduceCommandLineOptions mapReduceOptions = new MapReduceCommandLineOptions();

  @ParametersDelegate
  private LocalInputCommandLineOptions localInputOptions = new LocalInputCommandLineOptions();

  // This helper is used to load the list of format SPI plugins that will be
  // used
  @ParametersDelegate
  private IngestFormatPluginOptions pluginFormats = new IngestFormatPluginOptions();

  private DataStorePluginOptions inputStoreOptions = null;

  private List<Index> inputIndices = null;

  @Override
  public boolean prepare(final OperationParams params) {

    // TODO: localInputOptions has 'extensions' which doesn't mean
    // anything for MapReduce to GeoWave.

    // Based on the selected formats, select the format plugins
    pluginFormats.selectPlugin(localInputOptions.getFormats());

    return true;
  }

  /**
   * Prep the driver & run the operation.
   *
   * @throws Exception
   */
  @Override
  public void execute(final OperationParams params) throws Exception {

    // Ensure we have all the required arguments
    if (parameters.size() != 3) {
      throw new ParameterException(
          "Requires arguments: <path to base directory to write to> <store name> <comma delimited index list>");
    }

    computeResults(params);
  }

  @Override
  public boolean runAsync() {
    return true;
  }

  public List<String> getParameters() {
    return parameters;
  }

  public void setParameters(
      final String hdfsPath,
      final String storeName,
      final String commaSeparatedIndexes) {
    parameters = new ArrayList<>();
    parameters.add(hdfsPath);
    parameters.add(storeName);
    parameters.add(commaSeparatedIndexes);
  }

  public VisibilityOptions getIngestOptions() {
    return ingestOptions;
  }

  public void setIngestOptions(final VisibilityOptions ingestOptions) {
    this.ingestOptions = ingestOptions;
  }

  public MapReduceCommandLineOptions getMapReduceOptions() {
    return mapReduceOptions;
  }

  public void setMapReduceOptions(final MapReduceCommandLineOptions mapReduceOptions) {
    this.mapReduceOptions = mapReduceOptions;
  }

  public LocalInputCommandLineOptions getLocalInputOptions() {
    return localInputOptions;
  }

  public void setLocalInputOptions(final LocalInputCommandLineOptions localInputOptions) {
    this.localInputOptions = localInputOptions;
  }

  public IngestFormatPluginOptions getPluginFormats() {
    return pluginFormats;
  }

  public void setPluginFormats(final IngestFormatPluginOptions pluginFormats) {
    this.pluginFormats = pluginFormats;
  }

  public DataStorePluginOptions getInputStoreOptions() {
    return inputStoreOptions;
  }

  public List<Index> getInputIndices() {
    return inputIndices;
  }

  @Override
  public Void computeResults(final OperationParams params) throws Exception {
    if (mapReduceOptions.getJobTrackerOrResourceManagerHostPort() == null) {
      throw new ParameterException(
          "Requires job tracker or resource manager option (try geowave help <command>...)");
    }

    final String basePath = parameters.get(0);
    final String inputStoreName = parameters.get(1);
    final String indexList = parameters.get(2);
    // Config file
    final File configFile = getGeoWaveConfigFile(params);

    final Properties configProperties = ConfigOptions.loadProperties(configFile);
    final String hdfsHostPort = ConfigHDFSCommand.getHdfsUrl(configProperties);

    inputStoreOptions = CLIUtils.loadStore(inputStoreName, configFile, params.getConsole());

    final IndexStore indexStore = inputStoreOptions.createIndexStore();
    inputIndices = DataStoreUtils.loadIndices(indexStore, indexList);

    // Ingest Plugins
    final Map<String, IngestFromHdfsPlugin<?, ?>> ingestPlugins =
        pluginFormats.createHdfsIngestPlugins();

    // Driver
    final IngestFromHdfsDriver driver =
        new IngestFromHdfsDriver(
            inputStoreOptions,
            inputIndices,
            ingestOptions,
            mapReduceOptions,
            ingestPlugins,
            hdfsHostPort,
            basePath);

    // Execute
    if (!driver.runOperation()) {
      throw new RuntimeException("Ingest failed to execute");
    }
    return null;
  }
}


text:
Hekateros Control Package
=============

The **ROS** *chess_server* node provides services and subscriptions to play
chess using the GNU chess gnuchess as the backend engine.

The gnuchess (http://www.gnu.org/software/chess) engine is unmodified
(and hence, apt-get installable).

In addition to *chess_server*, the *chess_vis* ROS node provide a graphical
user interface to *chess_server*.


text:
package appwarp;

import java.util.HashMap;

import com.shephertz.app42.gaming.multiplayer.client.events.ChatEvent;
import com.shephertz.app42.gaming.multiplayer.client.events.LobbyData;
import com.shephertz.app42.gaming.multiplayer.client.events.MoveEvent;
import com.shephertz.app42.gaming.multiplayer.client.events.RoomData;
import com.shephertz.app42.gaming.multiplayer.client.events.UpdateEvent;
import com.shephertz.app42.gaming.multiplayer.client.listener.NotifyListener;

public class NotificationListener implements NotifyListener{

	private WarpController callBack;

	public NotificationListener(WarpController callBack) {
		this.callBack = callBack;
	}

	public void onChatReceived(ChatEvent event) {

	}

	public void onRoomCreated(RoomData arg0) {

	}

	public void onRoomDestroyed(RoomData arg0) {

	}

	public void onUpdatePeersReceived(UpdateEvent event) {
		callBack.onGameUpdateReceived(new String(event.getUpdate()));
	}

	public void onUserJoinedLobby(LobbyData arg0, String arg1) {

	}

	public void onUserJoinedRoom(RoomData data, String username) {
		callBack.onUserJoinedRoom(data.getId(), username);
	}

	public void onUserLeftLobby(LobbyData arg0, String arg1) {

	}

	public void onUserLeftRoom(RoomData roomData, String userName) {
		callBack.onUserLeftRoom(roomData.getId(), userName);
	}

	@Override
	public void onGameStarted (String arg0, String arg1, String arg2) {

	}

	@Override
	public void onGameStopped (String arg0, String arg1) {

	}

	@Override
	public void onMoveCompleted (MoveEvent me) {

	}

	@Override
	public void onPrivateChatReceived (String arg0, String arg1) {

	}

	@Override
	public void onUserChangeRoomProperty (RoomData roomData, String userName, HashMap<String, Object> properties, HashMap<String, String> lockProperties) {
		int code = Integer.parseInt(properties.get("result").toString());
		callBack.onResultUpdateReceived(userName, code);
	}

	@Override
	public void onUserPaused (String arg0, boolean arg1, String arg2) {

	}

	@Override
	public void onUserResumed (String arg0, boolean arg1, String arg2) {

	}

}


text:
'use strict';

import * as platform from 'vs/base/common/platform';
import * as paths from 'vs/base/common/paths';
import { OpenContext } from 'vs/platform/windows/common/windows';
import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, IResolvedWorkspace } from 'vs/platform/workspaces/common/workspaces';
import { Schemas } from 'vs/base/common/network';

export interface ISimpleWindow {
	openedWorkspace?: IWorkspaceIdentifier;
	openedFolderPath?: string;
	openedFilePath?: string;
	extensionDevelopmentPath?: string;
	lastFocusTime: number;
}

export interface IBestWindowOrFolderOptions<W extends ISimpleWindow> {
	windows: W[];
	newWindow: boolean;
	reuseWindow: boolean;
	context: OpenContext;
	filePath?: string;
	userHome?: string;
	codeSettingsFolder?: string;
	workspaceResolver: (workspace: IWorkspaceIdentifier) => IResolvedWorkspace;
}

export function findBestWindowOrFolderForFile<W extends ISimpleWindow>({ windows, newWindow, reuseWindow, context, filePath, workspaceResolver }: IBestWindowOrFolderOptions<W>): W | string {
	if (!newWindow && filePath && (context === OpenContext.DESKTOP || context === OpenContext.CLI || context === OpenContext.DOCK)) {
		const windowOnFilePath = findWindowOnFilePath(windows, filePath, workspaceResolver);
		if (windowOnFilePath) {
			return windowOnFilePath;
		}
	}

	return !newWindow ? getLastActiveWindow(windows) : null;
}

function findWindowOnFilePath<W extends ISimpleWindow>(windows: W[], filePath: string, workspaceResolver: (workspace: IWorkspaceIdentifier) => IResolvedWorkspace): W {

	// First check for windows with workspaces that have a parent folder of the provided path opened
	const workspaceWindows = windows.filter(window => !!window.openedWorkspace);
	for (let i = 0; i < workspaceWindows.length; i++) {
		const window = workspaceWindows[i];
		const resolvedWorkspace = workspaceResolver(window.openedWorkspace);
		if (resolvedWorkspace && resolvedWorkspace.folders.some(folder => folder.uri.scheme === Schemas.file && paths.isEqualOrParent(filePath, folder.uri.fsPath, !platform.isLinux /* ignorecase */))) {
			return window;
		}
	}

	// Then go with single folder windows that are parent of the provided file path
	const singleFolderWindowsOnFilePath = windows.filter(window => typeof window.openedFolderPath === 'string' && paths.isEqualOrParent(filePath, window.openedFolderPath, !platform.isLinux /* ignorecase */));
	if (singleFolderWindowsOnFilePath.length) {
		return singleFolderWindowsOnFilePath.sort((a, b) => -(a.openedFolderPath.length - b.openedFolderPath.length))[0];
	}

	return null;
}

export function getLastActiveWindow<W extends ISimpleWindow>(windows: W[]): W {
	const lastFocusedDate = Math.max.apply(Math, windows.map(window => window.lastFocusTime));

	return windows.filter(window => window.lastFocusTime === lastFocusedDate)[0];
}

export function findWindowOnWorkspace<W extends ISimpleWindow>(windows: W[], workspace: (IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier)): W {
	return windows.filter(window => {

		// match on folder
		if (isSingleFolderWorkspaceIdentifier(workspace)) {
			if (typeof window.openedFolderPath === 'string' && (paths.isEqual(window.openedFolderPath, workspace, !platform.isLinux /* ignorecase */))) {
				return true;
			}
		}

		// match on workspace
		else {
			if (window.openedWorkspace && window.openedWorkspace.id === workspace.id) {
				return true;
			}
		}

		return false;
	})[0];
}

export function findWindowOnExtensionDevelopmentPath<W extends ISimpleWindow>(windows: W[], extensionDevelopmentPath: string): W {
	return windows.filter(window => {

		// match on extension development path
		if (paths.isEqual(window.extensionDevelopmentPath, extensionDevelopmentPath, !platform.isLinux /* ignorecase */)) {
			return true;
		}

		return false;
	})[0];
}

export function findWindowOnWorkspaceOrFolderPath<W extends ISimpleWindow>(windows: W[], path: string): W {
	return windows.filter(window => {

		// check for workspace config path
		if (window.openedWorkspace && paths.isEqual(window.openedWorkspace.configPath, path, !platform.isLinux /* ignorecase */)) {
			return true;
		}

		// check for folder path
		if (window.openedFolderPath && paths.isEqual(window.openedFolderPath, path, !platform.isLinux /* ignorecase */)) {
			return true;
		}

		return false;
	})[0];
}


text:
from collections import defaultdict, OrderedDict

class HookRegistry():
    def __init__(self):
        self.hooks = defaultdict(OrderedDict)

    def register(self, name, func):
        self.hooks[name][func] = True

    def run_hook(self, name, *args, **kwargs):
        for hook in self.hooks[name]:
            kwargs = hook(*args, **kwargs)
        return kwargs

registry = HookRegistry()


text:
module CalculableAttrs::ActiveRecord::Querying
   delegate :calculate_attrs, :includes_calculable_attrs, :joins_calculable_attrs,  to: :all
end


text:
<?php

declare (strict_types=1);
namespace RectorPrefix20210615\Helmich\TypoScriptParser;

use RectorPrefix20210615\Symfony\Component\Config\FileLocator;
use RectorPrefix20210615\Symfony\Component\DependencyInjection\ContainerBuilder;
use RectorPrefix20210615\Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use RectorPrefix20210615\Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
/**
 * Class TypoScriptParserExtension
 *
 * @package Helmich\TypoScriptParser
 * @codeCoverageIgnore
 */
class TypoScriptParserExtension implements \RectorPrefix20210615\Symfony\Component\DependencyInjection\Extension\ExtensionInterface
{
    /**
     * Loads a specific configuration.
     *
     * @param array            $configs   An array of configuration values
     * @param ContainerBuilder $container A ContainerBuilder instance
     *
     * @throws \InvalidArgumentException When provided tag is not defined in this extension
     *
     * @api
     * @psalm-suppress MissingReturnType Signature is determined by Symfony DI -- nothing to fix, here
     */
    public function load(array $configs, \RectorPrefix20210615\Symfony\Component\DependencyInjection\ContainerBuilder $container)
    {
        $loader = new \RectorPrefix20210615\Symfony\Component\DependencyInjection\Loader\YamlFileLoader($container, new \RectorPrefix20210615\Symfony\Component\Config\FileLocator(__DIR__ . '/../config'));
        $loader->load('services.yml');
    }
    /**
     * Returns the namespace to be used for this extension (XML namespace).
     *
     * @return string The XML namespace
     *
     * @api
     */
    public function getNamespace()
    {
        return 'http://example.org/schema/dic/' . $this->getAlias();
    }
    /**
     * Returns the base path for the XSD files.
     *
     * @return false
     *
     * @api
     */
    public function getXsdValidationBasePath()
    {
        return \false;
    }
    /**
     * Returns the recommended alias to use in XML.
     *
     * This alias is also the mandatory prefix to use when using YAML.
     *
     * @return string The alias
     *
     * @api
     */
    public function getAlias()
    {
        return 'typoscript_parser';
    }
}


text:
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Emby.ApiClient.Net;

namespace Emby.ApiClient
{
    public class ServerLocator : IServerLocator
    {
        private readonly IJsonSerializer _jsonSerializer = new NewtonsoftJsonSerializer();
        private readonly ILogger _logger;

        public ServerLocator()
            : this(new NullLogger())
        {
        }

        public ServerLocator(ILogger logger)
        {
            _logger = logger;
        }

        public Task<List<ServerDiscoveryInfo>> FindServers(int timeoutMs, CancellationToken cancellationToken = default(CancellationToken))
        {
            var taskCompletionSource = new TaskCompletionSource<List<ServerDiscoveryInfo>>();
            var serversFound = new ConcurrentBag<ServerDiscoveryInfo>();

            _logger.Debug("Searching for servers with timeout of {0} ms", timeoutMs);

            var innerCancellationSource = new CancellationTokenSource();
            var linkedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(
                innerCancellationSource.Token, cancellationToken);

            BeginFindServers(serversFound, taskCompletionSource, innerCancellationSource);

            Task.Run(async () =>
            {
                try
                {
                    await Task.Delay(timeoutMs, linkedCancellationSource.Token).ConfigureAwait(false);
                    taskCompletionSource.TrySetResult(serversFound.ToList());
                }
                catch (OperationCanceledException)
                {

                }
            });

            return taskCompletionSource.Task;
        }

        private void BeginFindServers(ConcurrentBag<ServerDiscoveryInfo> serversFound, TaskCompletionSource<List<ServerDiscoveryInfo>> taskCompletionSource, CancellationTokenSource cancellationTokenSource)
        {
            FindServers(serversFound.Add, exception =>
            {
                taskCompletionSource.TrySetException(exception);
                cancellationTokenSource.Cancel();

            }, cancellationTokenSource.Token);
        }

        private async void FindServers(Action<ServerDiscoveryInfo> serverFound, Action<Exception> error, CancellationToken cancellationToken)
        {
            var serverIdsFound = new List<string>();

            // Create a udp client
            using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort())))
            {
                // Construct the message the server is expecting
                var bytes = Encoding.UTF8.GetBytes("who is EmbyServer?");

                // Send it - must be IPAddress.Broadcast, 7359
                var targetEndPoint = new IPEndPoint(IPAddress.Broadcast, 7359);

                try
                {
                    // Send the broadcast
                    await client.SendAsync(bytes, bytes.Length, targetEndPoint).ConfigureAwait(false);

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        // Get a result back
                        var result = await client.ReceiveAsync().ConfigureAwait(false);

                        if (result.RemoteEndPoint.Port == targetEndPoint.Port)
                        {
                            // Convert bytes to text
                            var json = Encoding.UTF8.GetString(result.Buffer);

                            _logger.Debug("Received response from endpoint: " + result.RemoteEndPoint + ". Response: " + json);

                            if (!string.IsNullOrEmpty(json))
                            {
                                try
                                {
                                    var info = _jsonSerializer.DeserializeFromString<ServerDiscoveryInfo>(json);

                                    if (!serverIdsFound.Contains(info.Id))
                                    {
                                        serverIdsFound.Add(info.Id);
                                        info.EndpointAddress = result.RemoteEndPoint.Address.ToString();
                                        serverFound(info);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.ErrorException("Error parsing server discovery info", ex);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    error(ex);
                }
            }
        }

        /// <summary>
        /// Gets a random port number that is currently available
        /// </summary>
        private static int GetRandomUnusedPort()
        {
            var listener = new TcpListener(IPAddress.Any, 0);
            listener.Start();
            var port = ((IPEndPoint)listener.LocalEndpoint).Port;
            listener.Stop();
            return port;
        }
    }
}


text:
import sqlite3
import time

class Drink():
	def __init__(self,mass,gender,quantity,ABV,at_time,name):
		self.name = name
		self.mass = mass #in grams
		self.gender = gender
		self.quantity = quantity
		self.ABV = ABV
		self.at_time = at_time
		self.removed = False

	def getCurrent(self):
		#A = self.grams_alcohol
		A = (self.quantity * (self.ABV/100.0)) * 23.35
		W = self.mass
		if self.gender == 'Female':
			R = 0.55
		else:
			R = 0.68
		H = (time.mktime(time.localtime()) - time.mktime(self.at_time)) / 3600
		BAC = (((A)/(W*R))*100)-(H*.015)
		val = str(BAC)
		try:
			val = float(val[:7])
		except:
			val = 0
		if val < 0:
			return 0
		val = round(val*1000)/1000.0
		return val

	def getInitial(self):
		#A = self.grams_alcohol
		A = (self.quantity * (self.ABV/100.0)) * 23.35
		W = self.mass
		if self.gender == 'Female':
			R = 0.55
		else:
			R = 0.68
		H = (time.mktime(time.localtime()) - time.mktime(self.at_time)) / 3600
		BAC = (((A)/(W*R))*100)
		BAC = round(BAC*1000)/1000.0
		return BAC

	def __str__(self):
		return "{4}: {0} oz. of \"{3}\" at {1}% ABV added {2} to your BAC.".format(
			self.quantity,
			self.ABV,
			self.getInitial(),
			self.name,
			time.strftime("%H:%M:%S",self.at_time))

create_drink_table = """
CREATE TABLE IF NOT EXISTS drinks(
	drink_id INT PRIMARY KEY,
	session_id INT,
	drinker_gender INT,
	drinker_mass INT,
	drink_quantity REAL,
	drink_ABV REAL,
	drink_name TEXT,
	drink_removed INT);"""

insert_drink = """INSERT INTO drinks VALUES(?,?,?,?,?,?,?,?)"""

get_drink = """SELECT * FROM drinks WHERE drink_id=?"""

update_drink = """UPDATE drinks SET
	drinker_gender=?,
	drinker_mass=?,
	drink_quantity=?,
	drink_ABV=?,
	drink_name=?,
	drink_removed=?
	WHERE drink_id=?"""

get_sessions = "SELECT DISTINCT session_id FROM drinks"

get_session = "SELECT * FROM drinks WHERE session_id=?"

last_session = "SELECT session_id FROM drinks ORDER BY session_id DESC LIMIT 1"

dbname = '/drinks.db'

def Build_DB(location):
	con = sqlite3.connect(location + dbname)
	c = con.cursor()
	c.execute(create_drink_table)
	con.commit()
	c.close()
	con.close()

def save(session_start,drink_list,location):
	Build_DB(location)
	print("Location:", location)
	con = sqlite3.connect(location+dbname)
	c = con.cursor()
	drinks = {}
	print("saving drinks")
	for drink in drink_list:
		removed = 0
		if drink.removed:
			removed = 1

		gender = 1
		if drink.gender == 'Male':
			gender = 0

		mass = drink.mass
		oz = drink.quantity
		abv = drink.ABV
		name = drink.name
		drink_id = time.strftime("%Y%m%d%H%M%S",drink.at_time)
		print("Saving drink: ", drink_id)

		c.execute(get_drink,(drink_id,))
		try:
			if len(c.fetchall()) > 0:
				c.execute(update_drink,
					(gender,
					mass,
					oz,
					abv,
					name,
					removed,
					drink_id))
			else:
				c.execute(insert_drink,
					(drink_id,
					time.strftime("%Y%m%d%H%M%S",session_start),
					gender,
					mass,
					oz,
					abv,
					name,
					removed))
			print("saved drink: ", str(drink))
		except sqlite3.IntegrityError as ie:
			print("id collision. probably drink button spam.",ie,drink_id)
		con.commit()
	c.close()

def load(location,session_id=None):
	pass

def load_last(location):
	con = sqlite3.connect(location + dbname)
	c = con.cursor()
	try:
		c.execute(last_session)
	except sqlite3.OperationalError as oe:
		print("No table, must be first run.")
		return (None,[])
	ret = []
	sid = None
	try:
		sid = c.fetchone()[0]
		print("sid: ", sid)
		c.execute(get_session,(sid,))
		for row in c.fetchall():
			drink = Drink(row[3],row[2],row[4],row[5],time.strptime(str(row[0]),"%Y%m%d%H%M%S"),row[6])
			if row[7]:
				drink.removed = True
			if not drink.removed:
				ret.append(drink)
			print(str(drink),drink.removed)
	except Exception as e:
		print("Hit an error: ",e)
	c.close()
	con.close()
	return (sid,ret)

def get_Sessions(location):
	pass


text:
===============================
GEARMAN_INVALID_WORKER_FUNCTION
===============================

Please see :c:type:`GEARMAN_INVALID_WORKER_FUNCTION`


text:
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".

Replace this with more appropriate tests for your application.
"""

# from django.test import TestCase
from unittest import TestCase, main
import doctest
from pug.invest import util
import pandas as pd
np = pd.np
from scipy.optimize import minimize

class SimpleTest(TestCase):
    def test_optimal_threshold(self):
        """
        Test using scipy.optimize.minimize on a bumpy data set to find the clipping threshold
        """
        return
        t = ['2014-12-09T00:00', '2014-12-09T00:15', '2014-12-09T00:30', '2014-12-09T00:45', '2014-12-09T01:00', '2014-12-09T01:15', '2014-12-09T01:30', '2014-12-09T01:45']
        ts = pd.Series([217, 234, 235, 231, 219, 219, 231, 232], index=pd.to_datetime(t))
        thresh=234
        capacity=562.5
        util.clipped_area(ts, thresh=thresh)
        pd.DataFrame({'ts': ts, 'thresh': pd.Series(thresh*np.ones(len(ts)), index=ts.index)}).plot()

        # invest.util.clipping_params()
        ts.index = ts.index.astype(np.int64)
        costs = []
        weights = np.ones(4)

        def cost_fun(x, *args):
            thresh = x[0]
            ts, capacity, bounds, costs, weights = args
            integral = util.clipped_area(ts, thresh=thresh)
            cost = 0
            terms = np.array([(100. * (integral - capacity) / capacity) ** 2,
                              1. / (((thresh - bounds[0]) / max(bounds))**2)**0.5,
                              1. / (((thresh - bounds[1]) / max(bounds))**2)**0.5,
                              1.1 ** (integral / capacity)])
            cost = np.sum(weights * terms)
            costs += [(thresh, cost, integral)]
            return cost

        bounds = (ts.min(), ts.max())
        thresh0 = 0.4*bounds[1] + 0.6*bounds[0]
        optimum = minimize(fun=cost_fun, x0=[thresh0], bounds=[bounds], args=(ts, capacity, bounds, costs, weights))
        thresh = optimum.x[0]
        integral = util.clipped_area(ts, thresh=thresh)
        self.assertGreater(capacity, integral)
        self.assertLess((capacity-integral)/capacity, 0.01)

class InvestDocTest(TestCase):

    def test_module(self, module=None):
        if module is not None:
            failure_count, test_count = doctest.testmod(module, raise_on_error=False, verbose=True)
            msg = "Ran {0} tests in {3} and {1} passed ({2} failed)".format(test_count, test_count-failure_count, failure_count, module.__file__)
            print msg
            if failure_count:
                # print "Ignoring {0} doctest failures...".format(__file__)
                self.fail(msg)
            # return failure_count, test_count

    def test_util(self):
        self.test_module(util)

if __name__ == '__main__':
    main()


text:
package figtree

import (
	"encoding/json"
	"fmt"
	"reflect"
	"regexp"

	"emperror.dev/errors"
	"gopkg.in/yaml.v3"
)

const (
	defaultSource  = "default"
	overrideSource = "override"
	promptSource   = "prompt"
	yamlSource     = "yaml"
	jsonSource     = "json"
)

type option interface {
	IsDefined() bool
	GetValue() any
	SetValue(any) error
	SetSource(SourceLocation)
	GetSource() SourceLocation
	IsDefault() bool
	IsOverride() bool
}

// StringifyValue is global variable to indicate if the Option should be
// serialized as just the value (when value is true) or if the entire Option
// struct should be serialized.  This is a hack, and not recommended for general
// usage, but can be useful for debugging.
var StringifyValue = true

// stringMapRegex is used in option parsing for map types Set routines
var stringMapRegex = regexp.MustCompile("[:=]")

// FileCoordinate represents the line/column of an option
type FileCoordinate struct {
	Line   int
	Column int
}

// ideally these would be const if Go supported const structs?
var (
	// DefaultSource will be the value of the `Source` property
	// for Option[T] when they are constructed via `NewOption[T]`.
	DefaultSource = NewSource(defaultSource)

	// OverrideSource will be the value of the `Source` property
	// for Option[T] when they are populated via kingpin command
	// line option.
	OverrideSource = NewSource(overrideSource)
)

type SourceLocation struct {
	Name     string
	Location *FileCoordinate
}

func (s SourceLocation) String() string {
	if s.Location != nil {
		return fmt.Sprintf("%s:%d:%d", s.Name, s.Location.Line, s.Location.Column)
	}
	return s.Name
}

type SourceOption func(*SourceLocation) *SourceLocation

func WithLocation(location *FileCoordinate) SourceOption {
	return func(s *SourceLocation) *SourceLocation {
		s.Location = location
		return s
	}
}

func NewSource(name string, opts ...SourceOption) SourceLocation {
	l := SourceLocation{
		Name: name,
	}
	for _, o := range opts {
		o(&l)
	}
	return l
}

type Option[T any] struct {
	Source  SourceLocation
	Defined bool
	Value   T
}

func NewOption[T any](dflt T) Option[T] {
	return Option[T]{
		Source:  NewSource(defaultSource),
		Defined: true,
		Value:   dflt,
	}
}

func (o Option[T]) IsDefined() bool {
	return o.Defined
}

func (o *Option[T]) SetSource(source SourceLocation) {
	o.Source = source
}

func (o *Option[T]) GetSource() SourceLocation {
	return o.Source
}

func (o *Option[T]) IsDefault() bool {
	return o.Source.Name == defaultSource
}

func (o *Option[T]) IsOverride() bool {
	return o.Source.Name == overrideSource
}

func (o Option[T]) GetValue() any {
	return o.Value
}

// WriteAnswer implements the Settable interface as defined by the
// survey prompting library:
// https://github.com/AlecAivazis/survey/blob/v2.3.5/core/write.go#L15-L18
func (o *Option[T]) WriteAnswer(name string, value any) error {
	if v, ok := value.(T); ok {
		o.Value = v
		o.Defined = true
		o.Source = NewSource(promptSource)
		return nil
	}
	return errors.Errorf("Got %T expected %T type: %v", value, o.Value, value)
}

// Set implements part of the Value interface as defined by the kingpin command
// line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/values.go#L26-L29
func (o *Option[T]) Set(s string) error {
	err := convertString(s, &o.Value)
	if err != nil {
		return err
	}
	o.Source = OverrideSource
	o.Defined = true
	return nil
}

// String implements part of the Value interface as defined by the kingpin
// command line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/values.go#L26-L29
func (o Option[T]) String() string {
	if StringifyValue {
		return fmt.Sprint(o.Value)
	}
	return fmt.Sprintf("{Source:%s Defined:%t Value:%v}", o.Source, o.Defined, o.Value)
}

// SetValue implements the Settings interface as defined by the kingpin
// command line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/parsers.go#L13-L15
func (o *Option[T]) SetValue(v any) error {
	if val, ok := v.(T); ok {
		o.Value = val
		o.Defined = true
		return nil
	}
	// look for type conversions as well, like:
	// (*Option[float64]).SetValue(float32)
	// There might be a better way to do this, but with
	// Generics I could not find a better way to convert
	// the input type to match the Option type.
	dst := reflect.ValueOf(o.Value)
	dstType := reflect.ValueOf(v).Type()
	src := reflect.ValueOf(v)
	if src.CanConvert(dstType) {
		dst.Set(src.Convert(dstType))
		o.Defined = true
		return nil
	}

	return errors.Errorf("Got %T expected %T type: %v", v, o.Value, v)
}

// UnmarshalYAML implement the Unmarshaler interface used by the
// yaml library:
// https://github.com/go-yaml/yaml/blob/v3.0.1/yaml.go#L36-L38
func (o *Option[T]) UnmarshalYAML(node *yaml.Node) error {
	if err := node.Decode(&o.Value); err != nil {
		return err
	}
	var loc *FileCoordinate
	if node.Line > 0 || node.Column > 0 {
		loc = &FileCoordinate{Line: node.Line, Column: node.Column}
	}
	o.Source = NewSource(yamlSource, WithLocation(loc))
	o.Defined = true
	return nil
}

// MarshalYAML implements the Marshaler interface used by the yaml library:
// https://github.com/go-yaml/yaml/blob/v3.0.1/yaml.go#L50-L52
func (o Option[T]) MarshalYAML() (any, error) {
	if StringifyValue {
		// First double check if the Value has a custom Marshaler.
		// Note we can't use `o.Value.(yaml.Marshaler)` directly because
		// you cannot do type assertions on generic types.  First we check
		// if Value is a direct (non pointer) type
		var q any = &o.Value
		if marshaler, ok := q.(yaml.Marshaler); ok {
			return marshaler.MarshalYAML()
		}
		// Now we try again for cases where Value is a pointer type.
		q = o.Value
		if marshaler, ok := q.(yaml.Marshaler); ok {
			return marshaler.MarshalYAML()
		}
		return o.Value, nil
	}
	// need a copy of this struct without the MarshalYAML interface attached
	return struct {
		Value   T
		Source  string
		Defined bool
	}{
		Value:   o.Value,
		Source:  o.Source.String(),
		Defined: o.Defined,
	}, nil
}

// UnmarshalJSON implements the Unmarshaler interface as defined by json:
// https://cs.opensource.google/go/go/+/refs/tags/go1.18.3:src/encoding/json/decode.go;l=118-120
func (o *Option[T]) UnmarshalJSON(b []byte) error {
	if err := json.Unmarshal(b, &o.Value); err != nil {
		return err
	}
	o.Source = NewSource(jsonSource)
	o.Defined = true
	return nil
}

// MarshalJSON implements the Marshaler interface as defined by json:
// https://cs.opensource.google/go/go/+/refs/tags/go1.18.3:src/encoding/json/encode.go;l=225-227
func (o Option[T]) MarshalJSON() ([]byte, error) {
	if StringifyValue {
		return json.Marshal(o.Value)
	}
	// need a copy of this struct without the MarshalJSON interface attached
	return json.Marshal(struct {
		Value   T
		Source  string
		Defined bool
	}{
		Value:   o.Value,
		Source:  o.Source.String(),
		Defined: o.Defined,
	})
}

// IsBoolFlag implements part of the boolFlag interface as defined by the
// kingpin command line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/values.go#L42-L45
func (o Option[T]) IsBoolFlag() bool {
	// TODO hopefully Go will get template specializations so we can
	// implement this function specifically for Option[bool], but for
	// now we have to use runtime reflection to determine the type.
	v := reflect.ValueOf(o.Value)
	if v.Kind() == reflect.Bool {
		return true
	}
	return false
}

type MapOption[T any] map[string]Option[T]

// Set implements part of the Value interface as defined by the kingpin command
// line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/values.go#L26-L29
func (o *MapOption[T]) Set(value string) error {
	parts := stringMapRegex.Split(value, 2)
	if len(parts) != 2 {
		return errors.Errorf("expected KEY=VALUE got '%s'", value)
	}
	val := Option[T]{}
	if err := val.Set(parts[1]); err != nil {
		return err
	}
	(*o)[parts[0]] = val
	return nil
}

// IsCumulative implements part of the remainderArg interface as defined by the
// kingpin command line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/values.go#L49-L52
func (o MapOption[T]) IsCumulative() bool {
	return true
}

// String implements part of the Value interface as defined by the kingpin
// command line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/values.go#L26-L29
func (o MapOption[T]) String() string {
	return fmt.Sprint(map[string]Option[T](o))
}

func (o MapOption[T]) Map() map[string]T {
	tmp := map[string]T{}
	for k, v := range o {
		tmp[k] = v.Value
	}
	return tmp
}

// WriteAnswer implements the Settable interface as defined by the
// survey prompting library:
// https://github.com/AlecAivazis/survey/blob/v2.3.5/core/write.go#L15-L18
func (o *MapOption[T]) WriteAnswer(name string, value any) error {
	tmp := Option[T]{}
	if v, ok := value.(T); ok {
		tmp.Value = v
		tmp.Defined = true
		tmp.Source = NewSource(promptSource)
		(*o)[name] = tmp
		return nil
	}
	return errors.Errorf("Got %T expected %T type: %v", value, tmp.Value, value)
}

func (o MapOption[T]) IsDefined() bool {
	// true if the map has any keys
	return len(o) > 0
}

type ListOption[T any] []Option[T]

// Set implements part of the Value interface as defined by the kingpin command
// line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/values.go#L26-L29
func (o *ListOption[T]) Set(value string) error {
	val := Option[T]{}
	if err := val.Set(value); err != nil {
		return err
	}
	*o = append(*o, val)
	return nil
}

// WriteAnswer implements the Settable interface as defined by the
// survey prompting library:
// https://github.com/AlecAivazis/survey/blob/v2.3.5/core/write.go#L15-L18
func (o *ListOption[T]) WriteAnswer(name string, value any) error {
	tmp := Option[T]{}
	if v, ok := value.(T); ok {
		tmp.Value = v
		tmp.Defined = true
		tmp.Source = NewSource(promptSource)
		*o = append(*o, tmp)
		return nil
	}
	return errors.Errorf("Got %T expected %T type: %v", value, tmp.Value, value)
}

// IsCumulative implements part of the remainderArg interface as defined by the
// kingpin command line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/values.go#L49-L52
func (o ListOption[T]) IsCumulative() bool {
	return true
}

// String implements part of the Value interface as defined by the kingpin
// command line option library:
// https://github.com/alecthomas/kingpin/blob/v1.3.4/values.go#L26-L29
func (o ListOption[T]) String() string {
	return fmt.Sprint([]Option[T](o))
}

func (o ListOption[T]) Append(values ...T) ListOption[T] {
	results := o
	for _, val := range values {
		results = append(results, NewOption(val))
	}
	return results
}

func (o ListOption[T]) Slice() []T {
	tmp := []T{}
	for _, elem := range o {
		tmp = append(tmp, elem.Value)
	}
	return tmp
}

func (o ListOption[T]) IsDefined() bool {
	// true if the list is not empty
	return len(o) > 0
}


text:
angular.module('appRoutes', ['ngRoute', 'ui.router']).config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {

$locationProvider.html5Mode(false);

	// For any unmatched url, redirect to /state1
	$urlRouterProvider.otherwise("/");

	$stateProvider
		.state('home', {
			url: '/',
			templateUrl: 'views/home.html',
			controller: 'MainController'
		})

		.state('about', {
			url: '/about',
			templateUrl: 'views/about.html',
			controller: 'AboutController'
		})

		.state('contact', {
			url: '/contact',
			templateUrl: 'views/contact.html',
			controller: 'ContactController'
		})
}]);


text:
import schema from "protocol-buffers-schema";

const proto = `syntax = "proto2";

message Point {
  required int32 x = 1;
  required int32 y=2;
  optional string label = 3;
}

message Line {
  required Point start = 1;
  required Point end = 2;
  optional string label = 3;
}`;

// pass a buffer or string to schema.parse
const sch = schema.parse(proto);

// will print out the schema as a javascript object
console.log(sch);


text:
package com.show.tt.ui.adapter.album;

import java.io.Serializable;

/**
 *
 * @Description 图片对象
 * @author Nana
 * @date 2014-5-9
 *
 */
@SuppressWarnings("serial")
public class ImageItem implements Serializable {
    private String imageId;
    private String thumbnailPath;
    private String imagePath;
    private boolean isSelected = false;

    public String getImageId() {
        return imageId;
    }

    public void setImageId(String imageId) {
        this.imageId = imageId;
    }

    public String getThumbnailPath() {
        return thumbnailPath;
    }

    public void setThumbnailPath(String thumbnailPath) {
        this.thumbnailPath = thumbnailPath;
    }

    public String getImagePath() {
        return imagePath;
    }

    public void setImagePath(String imagePath) {
        this.imagePath = imagePath;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }
}


text:
require('dotenv').config();
const express = require('express');
const proxy = require('http-proxy-middleware');

const contact = require('./api/contact');

const app = express();

app.get(
  '*',
  proxy({
    target: 'http://localhost:3000',
  }),
);

app.post('/api/contact', contact);

app.listen(4000);


text:
package com.github.yaterz.ctci.ciii;

/**
 * Towers of Hanoi
 * 3 towers and N disks of different sizes which can slide onto any tower
 * Start with the disks sorted in ascending order of size from top to bottom (bottom of tower has largest plate)
 * Move the disks from the first tower to the last with the following constraints
 *
 * 1 disk can be moved at at time
 * A disk is slid (pop()) off the top of one tower onto the top (push()) of the next
 * A disk can only be placed on top of a larger disk
 *
 * @author mattyaterz
 * @since 11/22/14
 */
public class C3E4Solution {

    public static class HanoiTowers<E extends Comparable<E>> {
        public HanoiTowers( LinkedStack<E> tower ) {
            this.first = tower;
        }

        public void execute() {

        }

        LinkedStack<E> first = new LinkedStack<>();
        LinkedStack<E> middle = new LinkedStack<>();
        LinkedStack<E> last = new LinkedStack<>();
    }
}


text:
pymatgen.analysis.interface module
==================================

.. automodule:: pymatgen.analysis.interface
   :members:
   :undoc-members:
   :show-inheritance: