text:
/* $NetBSD: coscreg.h,v 1.1 2001/10/05 22:27:54 reinoud Exp $ */

/*
 * Copyright (c) 1996 Mark Brinicombe
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Mark Brinicombe
 *      for the NetBSD Project.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Termination and DMA enable registers provided by
 * Andreas Gandor <andi@knipp.de>
 */

#ifndef _COSCREG_H_
#define _COSCREG_H_

#include <acorn32/podulebus/escvar.h>

typedef volatile unsigned short vu_short;

typedef struct cosc_regmap {
	esc_regmap_t	esc;
	vu_char		*chipreset;
	vu_char		*inten;
	vu_char		*status;
	vu_char		*term;
	vu_char		*led;
} cosc_regmap_t;
typedef cosc_regmap_t *cosc_regmap_p;

/*
#define COSC_CONTROL_CHIPRESET
#define	COSC_CONTROL_INTEN
#define COSC_STATUS
#define COSC_CONTROL_LED
*/

#define COSC_CONFIG_CONTROL_REG1	0x0ff0
#define COSC_CONFIG_CONTROL_REG1_MASK	0x97
#define COSC_CONFIG_CONTROL_REG2	0x0ff4
#define COSC_CONFIG_CONTROL_REG2_MASK	0x07
#define COSC_CONFIG_CONTROL_REG3	0x0ff8
#define COSC_CONFIG_CONTROL_REG3_MASK	0x83
#define COSC_CONFIG_CONTROL_REG4	0x0ffc
#define COSC_CONFIG_CONTROL_REG4_MASK	0xec
#define COSC_CONFIG_TERMINATION		0x1000
#define COSC_CONFIG_TERMINATION_ON	0x01
#define COSC_CONFIG_FIRST_SCANNED	0x1040	/* Used by RiscOS */
#define COSC_CONFIG_INC_FURTHER_PARTS	0x1048	/* Used by RiscOS */
#define COSC_CONFIG_SYNCH_MODE		0x1050
#define COSC_CONFIG_SYNCH_MODE_ON	0x01
#define COSC_CONFIG_SHUTDOWN		0x1054	/* Used by RiscOS */
#define COSC_CONFIG_SHUTDOWN_SPINDOWN	0x01	/* Used by RiscOS */
#define COSC_CONFIG_SHUTDOWN_EJECT	0x02	/* Used by RiscOS */
#define COSC_CONFIG_DELAY_REMOVABLE	0x105c	/* Used by RiscOS */
#define COSC_CONFIG_DELAY_HARDDISC	0x1060	/* Used by RiscOS */
#define COSC_CONFIG_DELAY_BOOT		0x1064	/* Used by RiscOS */
#define COSC_CONFIG_CDROM		0x1068	/* Used by RiscOS */

#define COSC_TERMINATION_CONTROL	0x2600
#define COSC_TERMINATION_ON		0x00
#define COSC_TERMINATION_OFF		0x01
#define COSC_REGISTER_00		0x2800
#define COSC_REGISTER_01		0x2a00
#define COSC_PAGE_REGISTER		0x3000

#define COSC_ESCOFFSET_BASE		0x3c00
#define COSC_ESCOFFSET_TCL		0x0000
#define COSC_ESCOFFSET_TCM		0x0004
#define COSC_ESCOFFSET_FIFO		0x0008
#define COSC_ESCOFFSET_COMMAND		0x000c
#define COSC_ESCOFFSET_DESTID		0x0010
#define COSC_ESCOFFSET_TIMEOUT		0x0014
#define COSC_ESCOFFSET_PERIOD		0x0018
#define COSC_ESCOFFSET_OFFSET		0x001c
#define COSC_ESCOFFSET_CONFIG1		0x0020
#define COSC_ESCOFFSET_CLOCKCONV	0x0024
#define COSC_ESCOFFSET_TEST		0x0028
#define COSC_ESCOFFSET_CONFIG2		0x002c
#define COSC_ESCOFFSET_CONFIG3		0x0030
#define COSC_ESCOFFSET_CONFIG4		0x0034
#define COSC_ESCOFFSET_TCH		0x0038
#define COSC_ESCOFFSET_FIFOBOTTOM	0x003c

#endif /* _COSCREG_H_ */


text:
FROM tomcat:8.5-jdk8-openjdk

LABEL maintainer=pulkitc@vmware.com

#change me according to what GemFire cluster name is in the k8s cluster.
#Format should be <cluster name>-<number of clusters in this k8s cluster>-locator.<namespace>
ARG locator_host={\"p-cloudcache\":[{\"credentials\":{\"locators\":[\"gemfire-1-locator.gemfire-cluster[10334]\"]}}]}
ENV DISCOVERY_ENV=K8S
ENV VCAP_SERVICES=$locator_host
COPY ndbench-web/build/libs/ndbench-web-0.5.0-SNAPSHOT.war /usr/local/tomcat/webapps/ROOT.war
EXPOSE 8080
CMD ["catalina.sh", "run"]

redpajama_set_name: RedPajamaGithub


text:
{% if page.bg %}

{% else %}

{% endif %}

        {% if page.summary %}
          {{ page.summary }}
        {% endif %}


text:
require 'spec_helper'

describe ExtensionsController do

end


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Testing;
using Xunit;

#if !IIS_FUNCTIONALS
using Microsoft.AspNetCore.Server.IIS.FunctionalTests;

#if IISEXPRESS_FUNCTIONALS
namespace Microsoft.AspNetCore.Server.IIS.IISExpress.FunctionalTests;
#elif NEWHANDLER_FUNCTIONALS
namespace Microsoft.AspNetCore.Server.IIS.NewHandler.FunctionalTests;
#elif NEWSHIM_FUNCTIONALS
namespace Microsoft.AspNetCore.Server.IIS.NewShim.FunctionalTests;
#endif

#else
namespace Microsoft.AspNetCore.Server.IIS.FunctionalTests;
#endif

[Collection(IISCompressionSiteCollection.Name)]
public class CompressionTests : FixtureLoggedTest
{
    private readonly IISCompressionSiteFixture _fixture;

    public CompressionTests(IISCompressionSiteFixture fixture) : base(fixture)
    {
        _fixture = fixture;
    }

    [ConditionalFact]
    [RequiresIIS(IISCapability.DynamicCompression)]
    public async Task BufferingDisabledWithCompressedRequest()
    {
        using (var connection = _fixture.CreateTestConnection())
        {
            var requestLength = 0;
            var messages = new List<string>();
            for (var i = 1; i < 100; i++)
            {
                var message = i + Environment.NewLine;
                requestLength += message.Length;
                messages.Add(message);
            }

            await connection.Send(
                "POST /ReadAndWriteEchoLinesNoBuffering HTTP/1.1",
                $"Content-Length: {requestLength}",
                "Accept-Encoding: gzip",
                "Response-Content-Type: text/event-stream",
                "Host: localhost",
                "Connection: close",
                "",
                "");

            await connection.Receive(
                "HTTP/1.1 200 OK",
                "");
            await connection.ReceiveHeaders();

            foreach (var message in messages)
            {
                await connection.Send(message);
                await connection.ReceiveChunk(message);
            }

            await connection.Send("\r\n");
            await connection.ReceiveChunk("");
            await connection.WaitForConnectionClose();
        }
    }

    [ConditionalFact]
    [RequiresIIS(IISCapability.DynamicCompression)]
    public async Task BufferingDisabledWithoutCompressedRequest()
    {
        using (var connection = _fixture.CreateTestConnection())
        {
            var requestLength = 0;
            var messages = new List<string>();
            for (var i = 1; i < 100; i++)
            {
                var message = i + Environment.NewLine;
                requestLength += message.Length;
                messages.Add(message);
            }

            await connection.Send(
                "POST /ReadAndWriteEchoLinesNoBuffering HTTP/1.1",
                $"Content-Length: {requestLength}",
                "Accept-Encoding: identity",
                "Response-Content-Type: text/event-stream",
                "Host: localhost",
                "Connection: close",
                "",
                "");

            await connection.Receive(
                "HTTP/1.1 200 OK",
                "");
            await connection.ReceiveHeaders();

            foreach (var message in messages)
            {
                await connection.Send(message);
                await connection.ReceiveChunk(message);
            }

            await connection.Send("\r\n");
            await connection.ReceiveChunk("");
            await connection.WaitForConnectionClose();
        }
    }

    [ConditionalFact]
    [RequiresIIS(IISCapability.DynamicCompression)]
    public async Task DynamicResponsesAreCompressed()
    {
        var handler = new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip
        };
        var client = new HttpClient(handler)
        {
            BaseAddress = _fixture.Client.BaseAddress,
            Timeout = TimeSpan.FromSeconds(200),
        };
        client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
        client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("identity", 0));
        client.DefaultRequestHeaders.Add("Response-Content-Type", "text/event-stream");
        var messages = "Message1\r\nMessage2\r\n\r\n";

        // Send messages with terminator
        var response = await client.PostAsync("ReadAndWriteEchoLines", new StringContent(messages));
        Assert.Equal(messages, await response.Content.ReadAsStringAsync());
        Assert.True(response.Content.Headers.TryGetValues("Content-Type", out var contentTypes));
        Assert.Single(contentTypes, "text/event-stream");
        // Not the cleanest check but I wasn't able to figure out other way to check
        // that response was compressed
        Assert.Contains("gzip", response.Content.GetType().FullName, StringComparison.OrdinalIgnoreCase);
    }
}


text:
package org.simpleflatmapper.jpa.beans;

import org.openjdk.jmh.infra.Blackhole;
import org.simpleflatmapper.param.LimitParam;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.swing.text.html.parser.Entity;
import java.util.List;

/**
 * Created by aroger on 17/10/2015.
 */
public class JPATester {

    public static void select4Fields(EntityManagerFactory entityManagerFactory, LimitParam limitParam, Blackhole blackhole) {
        select(entityManagerFactory, limitParam, blackhole, "select s from MappedObject4 s");
    }

    public static void select16Fields(EntityManagerFactory entityManagerFactory, LimitParam limitParam, Blackhole blackhole) {
        select(entityManagerFactory, limitParam, blackhole, "select s from MappedObject16 s");
    }

    public static void select(EntityManagerFactory entityManagerFactory, LimitParam limit, Blackhole blackhole, String strQuery)  {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {
            Query query = entityManager.createQuery(strQuery);
            query.setMaxResults(limit.limit);
            List<?> sr = query.getResultList();
            for (Object o : sr) {
                blackhole.consume(o);
            }
        } finally {
            entityManager.close();
        }
    }
}


text:
@interface ViewController:AKTViewController

@end


text:
this is a personal project. i wanted to make an 'assistant' that runs on my pi.
it is basically a bunch a programs that can run by controlling the sense hat joystick.

this readme is incomplete, more to come...

the raspberry pi has a sense-hat attachment that consists of an 8x8 led grid, an joystick, and sensors that can detect ambient temperature, humidity and pressure, and more. so i decided to write a bunch of python3 modules to run on a headless pi3 with an sense hat attached. each program is "mapped" to an led light on the sense hat, and each program can be chosen by using the joystick, and pressed down to run the module mapped to the chosen led.

benson.py is added to crontab to run automatically from boot. all interactions with the pi is achieved through the led grid and the joystick, so there is no need to have an screen or keyboard/mouse attached after initial setup of the pi is done. eventually 64 programs can be mapped to the entire led grid.

hardware requirements:
* raspberry pi 3 (i only have rpi3s but should run on other pis with wifi access)
* official raspberry pi sense hat
* a speaker for sound
* monitor/keyboard/mouse for initial setup of the pi

software requirements:
* python3
* pip3 install these python3 packages:

  sense-hat - should come installed on raspbian already

  requests - used to get forecast info

  gtts - use google test to speech api

* apt-get install additional software:

  vlc - play the mp3 generated from gtts

  exfat-fuse - mount exfat thumb drives

  ntfs-3g - mount ntfs thumb drives

  samba - smb support

  samba-common-bin - this is need by samba

third-party apis needed:
  forecast.io - for weather forecast

setup
1. attach the sense hat to the pi, and connect a speaker to it
2. enable ssh and make sure wifi is working
3. then install all the software requirments, and setup a smb share
4. clone this repo to /home/pi. do chown -R on the folder so you can edit the files locally
5. edit crontab to make the main script auto run on boot, from terminal type 'crontab -e'
   and add this line to the end of the file:
   @reboot python3 /home/pi/Benson/benson.py &
6. reboot


text:
namespace xig {

bool isPrimitive(const data_ptr &d) {
  switch (d->type()) {
  case data_type::integer:
  case data_type::decimal:
  case data_type::none:
  case data_type::boolean:
  case data_type::string:
  case data_type::keyword:
    return true;
  default:
    return false;
  }
}

data_ptr lookupSymbol(enviroment &env, data_ptr input_data, debug_info debug) {
  auto sym = input_data->as_symbol().as_std_string();
  auto symbol_value = env.find(input_data->as_symbol());
  if (!symbol_value) {
    throw error(error_type::invalid_arguments,
                "Cannot Find Symbol: " +
                    input_data->as_symbol().as_std_string(),
                debug);
  }
  return symbol_value;
}

data_ptr processSymbolProcess(enviroment &env, data_ptr input_data, int loc,
                              debug_info debug) {
  switch (input_data->as_process().as_std_vector().at(loc)->type()) {
  case data_type::symbol:
    debug.function_call_list.push_back(input_data->as_process()
                                           .as_std_vector()
                                           .at(loc)
                                           ->as_symbol()
                                           .as_std_string());
  case data_type::process: {
    std::vector<data_ptr> new_proc_data =
        input_data->as_process().as_std_vector();
    new_proc_data.at(loc) =
        evaluate(env, input_data->as_process().as_std_vector().at(loc), debug);
    input_data = make_process(new_proc_data);
    break;
  }
  default:
    break;
  }
  return input_data;
}

data_ptr handleProcess(enviroment &env, data_ptr input_data, debug_info debug) {
  if (input_data->as_process().as_std_vector().size() == 0)
    return make_none();

  // if first arg is symbol or process, evaluate it
  input_data = processSymbolProcess(env, input_data, 0, debug);

  if (input_data->as_process().as_std_vector().at(0)->type() ==
      data_type::function) {
    auto process_copy = input_data->as_process().as_std_vector();
    auto firstElement = process_copy.begin() + 1;
    auto lastElement = process_copy.end();
    std::vector<data_ptr> functionArgs(firstElement, lastElement);

    return input_data->as_process().as_std_vector().at(0)->as_function().call(
        {functionArgs, env, debug});
  }

  if (input_data->as_process().as_std_vector().size() == 3) {
    input_data = processSymbolProcess(env, input_data, 1, debug);
    if (input_data->as_process().as_std_vector().at(1)->type() ==
        data_type::function) {
      std::vector<data_ptr> functionArgs = {
          input_data->as_process().as_std_vector().at(0),
          input_data->as_process().as_std_vector().at(2)};
      return input_data->as_process().as_std_vector().at(1)->as_function().call(
          call_info(functionArgs, env, debug));
    }
  }

  auto return_value = make_none();
  for (auto item : input_data->as_process().as_std_vector())
    return_value = evaluate(env, item, debug);
  return return_value;
}

data_ptr handleTuple(enviroment &env, data_ptr input_data, debug_info debug) {
  std::vector<data_ptr> new_tuple_data;
  for (auto data : input_data->as_tuple().as_std_vector()) {
    new_tuple_data.push_back(evaluate(env, data, debug));
  }
  return make_tuple(new_tuple_data);
}

data_ptr handleMap(enviroment &env, data_ptr input_data, debug_info debug) {
  std::map<data_ptr, data_ptr> new_map_data;
  for (auto data : input_data->as_map().as_std_map()) {
    auto first = data.first;
    auto second = data.second;
    new_map_data[evaluate(env, first, debug)] = evaluate(env, second, debug);
  }
  return make_map(new_map_data);
}

data_ptr evaluate(enviroment &env, data_ptr input_data, debug_info debug) {
  if (isPrimitive(input_data))
    return input_data;

  if (input_data->type() == data_type::symbol)
    return lookupSymbol(env, input_data, debug);

  if (input_data->type() == data_type::process)
    return handleProcess(env, input_data, debug);

  if (input_data->type() == data_type::tuple)
    return handleTuple(env, input_data, debug);

  if (input_data->type() == data_type::map)
    return handleMap(env, input_data, debug);

  return make_none();
}
}


text:
import Login from './Login';
import Pro from './profile';
import React from 'react';
const title = 'Log In';

export default {

  path: '/login',

  action() {
    return {
      title,
      component: <Login title={title} />,
    };
  },

};

const Profile = {
  path: '/Profile',
  action() {
    return {
      title: "Profile",
      component: <Pro />,
    };
  }
};

export {Profile}


text:
namespace Google.Cloud.Datastore.V1.Snippets
{
    // [START datastore_v1_generated_Datastore_BeginTransaction_async]
    using Google.Cloud.Datastore.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedDatastoreClientSnippets
    {
        /// <summary>Snippet for BeginTransactionAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task BeginTransactionRequestObjectAsync()
        {
            // Create client
            DatastoreClient datastoreClient = await DatastoreClient.CreateAsync();
            // Initialize request argument(s)
            BeginTransactionRequest request = new BeginTransactionRequest
            {
                ProjectId = "",
                TransactionOptions = new TransactionOptions(),
            };
            // Make the request
            BeginTransactionResponse response = await datastoreClient.BeginTransactionAsync(request);
        }
    }
    // [END datastore_v1_generated_Datastore_BeginTransaction_async]
}


text:
from rosdep2.catkin_support import get_installer, get_catkin_view, ValidationFailed, resolve_for_os

from rosdep2.platforms.debian import APT_INSTALLER
import pytest

@pytest.mark.online
def test_workflow():
    try:
        installer = get_installer(APT_INSTALLER)
        view = get_catkin_view('fuerte', 'ubuntu', 'lucid')
        resolved = resolve_for_os('cmake', view, installer, 'ubuntu', 'lucid')
        assert ['cmake'] == resolved
        resolved = resolve_for_os('python', view, installer, 'ubuntu', 'lucid')
        assert resolved == ['python-dev']
    except ValidationFailed:
        # tests fail on the server because 'rosdep init' has not been run
        pass


text:
package com.dengjian.soccermap.ui.view;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dengjian.soccermap.R;
import com.dengjian.soccermap.adapter.FcRaceSchedulesAdapter;
import com.dengjian.soccermap.model.RaceData;
import com.dengjian.soccermap.model.SoccerConstants;
import com.dengjian.soccermap.model.StatisticsConstants;
import com.dengjian.soccermap.ui.activity.MainActivity;
import com.dengjian.soccermap.ui.fragment.UtilFragmentManager;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dengjian697 on 17/4/5.
 */
public class FcPopupWindow extends PopupWindow {
    private Context mContext;
    private MainActivity mActivity;
    private TextView mTvFcLogo;
//    private TextView mTvFcIntro;
    private ListView mLvFcRace;
    private FcRaceSchedulesAdapter mFcRaceAdapter;
    private String mFcName;

    public FcPopupWindow(Context context, String fcName) {
        super(context);
        mContext = context;
        mActivity = (MainActivity) context;
        mFcName = fcName;
        initView(context);
    }

    public void setName(String fcName) {
        mFcName = fcName;
        if (null != mTvFcLogo && null != SoccerConstants.getInstance().getTeamLogoMap().get(mFcName))
            mTvFcLogo.setCompoundDrawables(mContext.getResources().getDrawable(SoccerConstants
                    .getInstance().getTeamLogoMap().get(mFcName)), null, null, null);
        if (null != mActivity && null != mFcRaceAdapter && null != mActivity.mRaceDatas
                && mActivity.mRaceDatas.size() > 0) {
            List<RaceData> tmpRaceData = new ArrayList<RaceData>();
            for (int i = 0; i < mActivity.mRaceDatas.size(); i++) {
                if (!TextUtils.isEmpty(mFcName) && (mFcName.equals(mActivity.mRaceDatas.get(i).visitingTeamName)
                        || mFcName.equals(mActivity.mRaceDatas.get(i).homeTeamName))) {
                    tmpRaceData.add(mActivity.mRaceDatas.get(i));
                }
            }
            mFcRaceAdapter.setData(tmpRaceData);
        }
    }

    private void initView(Context context) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout rootView  = (LinearLayout) inflater.inflate(R.layout.fc_popup_layout, null);

        mTvFcLogo = (TextView) rootView.findViewById(R.id.tv_popup_fc_logo);
        if (null != SoccerConstants.getInstance().getTeamLogoMap().get(mFcName))
            mTvFcLogo.setCompoundDrawables(mContext.getResources().getDrawable(SoccerConstants.getInstance()
                    .getTeamLogoMap().get(mFcName)), null, null, null);
//        mTvFcIntro = (TextView) rootView.findViewById(R.id.tv_popup_fc_intro);
        mLvFcRace = (ListView) rootView.findViewById(R.id.lv_popup_fc_race_schedules);

        if (null == mFcRaceAdapter) {
            mFcRaceAdapter = new FcRaceSchedulesAdapter(mContext);
        }
        mLvFcRace.setAdapter(mFcRaceAdapter);
        mLvFcRace.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RaceData raceData = (RaceData) parent.getAdapter().getItem(position);
                if (null != mActivity && null != raceData && !TextUtils.isEmpty(raceData.racePicLink)
                        && SoccerConstants.getInstance().getAllowGotoWebview(mContext)) {
                    // 直播间H5需优化,找到新浪手机直播间地址拼接
                    Bundle bundle = new Bundle();
                    if (("未开赛".equals(raceData.raceTimeDesc) || "进行中".equals(raceData.raceTimeDesc))
                            && raceData.racePicLink.length() > 6) {
                        String liveId = raceData.racePicLink.substring(raceData.racePicLink.length() - 6,
                                raceData.racePicLink.length());
                        bundle.putString("url", SoccerConstants.LIVE_URL_PREFIX + liveId);
                    } else {
                        bundle.putString("url", raceData.racePicLink);
                    }
                    MobclickAgent.onEvent(mContext, StatisticsConstants.STAT_ENTER_RACE_WEBVIEW_BY_POPUP);
                    mActivity.getUtilFragmentManager().showFragment(UtilFragmentManager.TYPE_WEBVIEW, bundle);
                    dismiss();
                }
            }
        });

        if (null != mActivity && null != mActivity.mRaceDatas && mActivity.mRaceDatas.size() > 0) {
            List<RaceData> tmpRaceData = new ArrayList<RaceData>();
            for (int i = 0; i < mActivity.mRaceDatas.size(); i++) {
                if (!TextUtils.isEmpty(mFcName) && (mFcName.equals(mActivity.mRaceDatas.get(i).visitingTeamName)
                        || mFcName.equals(mActivity.mRaceDatas.get(i).homeTeamName))) {
                    tmpRaceData.add(mActivity.mRaceDatas.get(i));
                }
            }
            mFcRaceAdapter.setData(tmpRaceData);
        }

        setContentView(rootView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        setFocusable(true);
        setTouchable(true);
        // 设置SelectPicPopupWindow弹出窗体动画效果
//        setAnimationStyle(R.style.AnimBottom);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        setBackgroundDrawable(dw);
    }

}


text:
package com.opengamma.analytics.financial.provider.sensitivity.parameter;

import it.unimi.dsi.fastutil.ints.IntArrayList;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor;
import com.opengamma.analytics.financial.provider.description.interestrate.ParameterProviderInterface;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.ForwardSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyMulticurveSensitivity;
import com.opengamma.analytics.financial.provider.sensitivity.multicurve.MultipleCurrencyParameterSensitivity;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.tuple.DoublesPair;
import com.opengamma.util.tuple.Pairs;

/**
 * For an instrument, computes the sensitivity of a multi-currency value (often the present value) to the
 * parameters used in the curve.
 * The meaning of "parameters" will depend of the way the curve is stored (interpolated zero-coupon rates,
 * function parameters, etc.).
 * The sensitivity is computed for the underlying curves up to one level deep, not further (see reference
 * documentation for more explanation).
 * The return format is a MultipleCurrencyParameterSensitivity object.
 * <p>
 * Reference: Sensitivity computation, OpenGamma Documentation n. 23, September 2014.
 * @param <DATA_TYPE> Data type extending ParameterProviderInterface.
 */
public class ParameterSensitivityUnderlyingParameterCalculator<DATA_TYPE extends ParameterProviderInterface>
  extends ParameterSensitivityParameterAbstractCalculator<DATA_TYPE> {

  /**
   * Constructor
   * @param curveSensitivityCalculator The curve sensitivity calculator.
   */
  public ParameterSensitivityUnderlyingParameterCalculator(
      final InstrumentDerivativeVisitor<DATA_TYPE, MultipleCurrencyMulticurveSensitivity> curveSensitivityCalculator) {
    super(curveSensitivityCalculator);
  }

  @Override
  public MultipleCurrencyParameterSensitivity pointToParameterSensitivity(final MultipleCurrencyMulticurveSensitivity sensitivity,
      final DATA_TYPE parameterMulticurves, final Set<String> sensicurveNamesSet) {
    ArgumentChecker.notNull(sensitivity, "sensitivity");
    ArgumentChecker.notNull(parameterMulticurves, "multicurves parameter");
    ArgumentChecker.notNull(sensicurveNamesSet, "curves set");
    // TODO: The first part depends only of the multicurves and curvesSet, not the sensitivity. Should it be refactored and done only once?
    final Set<String> multicurveNamesSet = parameterMulticurves.getMulticurveProvider().getAllNames();
    final String[] multicurveNamesArray = multicurveNamesSet.toArray(new String[0]);
    // Implementation note: Check sensicurve are in multicurve
    ArgumentChecker.isTrue(multicurveNamesSet.containsAll(sensicurveNamesSet), "curve in the names set not in the multi-curve provider");
    final int nbMultiCurve = multicurveNamesSet.size();
    // Populate the name names and numbers for the curves in the multicurve
    final LinkedHashMap<String, Integer> multicurveNum = new LinkedHashMap<>();
    for (int loopcur = 0; loopcur < nbMultiCurve; loopcur++) { // loop over all curves in multicurves
      multicurveNum.put(multicurveNamesArray[loopcur], loopcur);
    }
    final int[] nbNewParameters = new int[nbMultiCurve];
    final int[] nbParameters = new int[nbMultiCurve];
    // Implementation note: nbNewParameters - number of new parameters in the curve, parameters not
    //   from an underlying curve which is another curve of the bundle.
    for (int loopcur = 0; loopcur < nbMultiCurve; loopcur++) { // loop over all curves in multicurves
      nbParameters[loopcur] =
          parameterMulticurves.getMulticurveProvider().getNumberOfParameters(multicurveNamesArray[loopcur]);
      nbNewParameters[loopcur] = nbParameters[loopcur];
    }
    for (int loopcur = 0; loopcur < nbMultiCurve; loopcur++) { // loop over all curves in multicurves
      final List<String> underlyingCurveNames =
          parameterMulticurves.getMulticurveProvider().getUnderlyingCurvesNames(multicurveNamesArray[loopcur]);
      for (final String u : underlyingCurveNames) {
        final Integer i = multicurveNum.get(u);
        if (i != null) {
          nbNewParameters[loopcur] -= nbNewParameters[i]; // Only one level: a curve used as an underlying can not have an underlying itself.
        }
      }
    }
    final int[][] indexOtherMulticurve = new int[nbMultiCurve][];
    // Implementation note: indexOtherMultiCurve - for each curve in the multi-curve, the index of the underlying curves in the same set
    final int[] startOwnParameter = new int[nbMultiCurve];
    // Implementation note: The start index of the parameters of the own (new) parameters.
    final int[][] startUnderlyingParameter = new int[nbMultiCurve][];
    // Implementation note: The start index of the parameters of the underlying curves
    for (int loopcur = 0; loopcur < nbMultiCurve; loopcur++) { // loop over all curves in multicurves
      final List<String> underlyingCurveNames =
          parameterMulticurves.getMulticurveProvider().getUnderlyingCurvesNames(multicurveNamesArray[loopcur]);
      final IntArrayList indexOtherMulticurveList = new IntArrayList();
      for (final String u : underlyingCurveNames) {
        final Integer i = multicurveNum.get(u);
        if (i != null) {
          indexOtherMulticurveList.add(i);
        }
      }
      indexOtherMulticurve[loopcur] = indexOtherMulticurveList.toIntArray();
    }
    for (int loopcurve = 0; loopcurve < nbMultiCurve; loopcurve++) { // loop over all curves in multicurves
      int loopstart = 0;
      final int num = multicurveNum.get(multicurveNamesArray[loopcurve]);
      final IntArrayList startUnderlyingParamList = new IntArrayList();
      final List<String> underlyingCurveNames =
          parameterMulticurves.getMulticurveProvider().getUnderlyingCurvesNames(multicurveNamesArray[loopcurve]);
      for (final String u : underlyingCurveNames) {
        final Integer i = multicurveNum.get(u);
        if (i != null) {
          startUnderlyingParamList.add(loopstart);
          loopstart += nbNewParameters[i]; // Implementation note: Rely on underlying curves being first and then the new parameters
        }
      }
      startOwnParameter[num] = loopstart;
      startUnderlyingParameter[num] = startUnderlyingParamList.toIntArray();
    }
    // Implementation note: Compute the "dirty" sensitivity, i.e. the sensitivity to all the parameters in each curve.
    // The underlying are taken into account in the "clean" step.
    Set<Currency> ccySet = sensitivity.getCurrencies();
    Currency[] ccyArray = ccySet.toArray(new Currency[0]);
    int nbCcy = ccySet.size();
    double[][][] sensiDirty = new double[nbCcy][nbMultiCurve][];
    for (int loopccy = 0; loopccy < nbCcy; loopccy++) {
      final Map<String, List<DoublesPair>> sensitivityDsc =
          sensitivity.getSensitivity(ccyArray[loopccy]).getYieldDiscountingSensitivities();
      final Map<String, List<ForwardSensitivity>> sensitivityFwd =
          sensitivity.getSensitivity(ccyArray[loopccy]).getForwardSensitivities();
      for (int loopcurve = 0; loopcurve < nbMultiCurve; loopcurve++) { // loop over all curves
        sensiDirty[loopccy][loopcurve] = new double[nbParameters[loopcurve]];
        final double[] sDsc1Name = parameterMulticurves.parameterSensitivity(multicurveNamesArray[loopcurve],
            sensitivityDsc.get(multicurveNamesArray[loopcurve]));
        final double[] sFwd1Name = parameterMulticurves.parameterForwardSensitivity(multicurveNamesArray[loopcurve],
            sensitivityFwd.get(multicurveNamesArray[loopcurve]));
        for (int loopp = 0; loopp < nbParameters[loopcurve]; loopp++) {
          sensiDirty[loopccy][loopcurve][loopp] = sDsc1Name[loopp] + sFwd1Name[loopp];
        }
      }
    }
    // Implementation note: "clean" the sensitivity, i.e. add the parts on the same curves together.
    double[][][] sensiClean = new double[nbCcy][nbMultiCurve][];
    for (int loopccy = 0; loopccy < nbCcy; loopccy++) {
      for (int loopcurve = 0; loopcurve < nbMultiCurve; loopcurve++) { // loop over all curves
        sensiClean[loopccy][loopcurve] = new double[nbNewParameters[loopcurve]];
      }
    }
    for (int loopccy = 0; loopccy < nbCcy; loopccy++) {
      for (int loopcurve = 0; loopcurve < nbMultiCurve; loopcurve++) { // loop over all curves
        // Direct sensitivity
        for (int loopi = 0; loopi < nbNewParameters[loopcurve]; loopi++) {
          sensiClean[loopccy][loopcurve][loopi] += sensiDirty[loopccy][loopcurve][startOwnParameter[loopcurve] + loopi];
        }
        // Underlying (indirect) sensitivity
        for (int loopu = 0; loopu < startUnderlyingParameter[loopcurve].length; loopu++) {
          for (int loopi = 0; loopi < nbNewParameters[indexOtherMulticurve[loopcurve][loopu]]; loopi++) {
            sensiClean[loopccy][indexOtherMulticurve[loopcurve][loopu]][loopi] +=
                sensiDirty[loopccy][loopcurve][startUnderlyingParameter[loopcurve][loopu] + loopi];
          }
        }
      }
    }
    MultipleCurrencyParameterSensitivity result = new MultipleCurrencyParameterSensitivity();
    for (int loopccy = 0; loopccy < nbCcy; loopccy++) { // loop on all currencies
      for (int loopcurve = 0; loopcurve < nbMultiCurve; loopcurve++) { // loop over all curves
        result = result.plus(Pairs.of(multicurveNamesArray[loopcurve], ccyArray[loopccy]),
            new DoubleMatrix1D(sensiClean[loopccy][loopcurve]));
      }
    }
    return result;
  }

  @Override
  public MultipleCurrencyParameterSensitivity pointToParameterSensitivity(
      final MultipleCurrencyMulticurveSensitivity sensitivity, final DATA_TYPE parameterMulticurves) {
    ArgumentChecker.notNull(parameterMulticurves, "multicurves parameter");
    return pointToParameterSensitivity(sensitivity, parameterMulticurves,
        parameterMulticurves.getMulticurveProvider().getAllCurveNames());
  }
}


text:
[![Circle CI](https://circleci.com/gh/million12/docker-rackspace-cloud-backup.svg?style=svg)](https://circleci.com/gh/million12/docker-rackspace-cloud-backup)

Docker image [million12/rackspace-cloud-backup]() with Rackspace cloud backup agent, driveclient.

Contains installed `driveclient`. Once you run it and provide required ENV variables (see below), in the Rackspace Cloud Panel for given server, you should see **Backup Agent: Installed** status. Now you can configure your backup routines.

Few notes:
* driveclient randomly hits Rackspace HTTP(s) error 403 which results in lack of connection with Cloud Backup. The run script tries to handle that and checks logs for `HTTP(s) error code = 403` or `Could not post an event`. If it happens, it restarts the daemon automatically. And it does so until success.
* The script handles also error 400 which indicates connection problem (make sure you run this container with `--net=host` option!), errors with agent registration (bad credentials). In case of these errors, the container exists and you must fix the issue.

See [Rackspace Cloud Backup - Install the agent on Linux](http://www.rackspace.com/knowledge_center/article/rackspace-cloud-backup-install-the-agent-on-linux) for more info.

## Usage

You will need to set the following ENV variables:
> `API_HOST`: cloud backup API hostname for your region (check Rackspace website)
> `API_KEY`: 32-char length API key to your account
> `ACCOUNT_ID`: your Rackspace account ID
> `USERNAME`: Rackspace account username

```
docker pull million12/rackspace-cloud-backup:latest

docker run \
  --name=driveclient \
  --net=host \
  -v /:/mnt/host \
  --volumes-from=some-other-container \
  --env="API_HOST=lon.backup.api.rackspacecloud.com" \
  --env="API_KEY=32lengthApiKeyFromYourRaxAccount" \
  --env="ACCOUNT_ID=01234567" \
  --env="USERNAME=account-username" \
  million12/rackspace-cloud-backup
```

## Acknowledgments

* Author: Marcin Ryzycki <marcin@m12.io>
* Development sponsored by [Megabuyte](http://megabuyte.com/)

## License

Licensed under MIT, see LICENSE.


text:
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <protocol/TBinaryProtocol.h>
#include <transport/TSocket.h>
#include <transport/TTransportUtils.h>
#include <signal.h>

#include <getopt.h>
#include "ImageDownloadQueue.h"

#include "gd_helper.h"
#include "s3_helper.h"

#include "boost/filesystem.hpp"   // includes all needed Boost.Filesystem declarations
#include <boost/algorithm/string.hpp>

#include "svg_helper.h"

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
using namespace boost;
using namespace boost::filesystem;

/* Globals */
static shared_ptr<GDImage::Manager> __mim;
static shared_ptr<S3Helper> __sh;
static volatile sig_atomic_t gracefully_quit = 0;

static char* find_extension(const char* filename)
{
  char* extension = strrchr(filename,'.');
  if (!extension)
    extension = (char*) "jpg";
  else
    extension = extension + 1;
  return extension;
}

static  char* mime_type(const char* image_path)
{
  char* extension = strrchr(image_path,'.');
  if (!extension || strlen(extension) < 2)
    return (char*) "binary/octet-stream";
  else
    extension = extension + 1;
  if (!strncasecmp(extension,"jpg",3) || !strncasecmp(extension,"jpeg",4))
    return (char*) "image/jpeg";
  else if (!strncasecmp(extension,"png",3))
    return (char*) "image/png";
  else if (!strncasecmp(extension,"gif",3))
    return (char*) "image/gif";
  else if (!strncasecmp(extension,"svg",3)) // we actually return png because in this case we have converted it
    return (char*) "image/png";
  else {
    return (char*) "binary/octet-stream";
  }
}

/* Use boost filesystem to write it in the proper location */
static void write_image_to_filesystem(const char* image_path, const char* data, int len)
{
  vector<string> buckets;
  split(buckets,image_path,is_any_of("/"));
  if (buckets.size() == 3) {
    current_path("/tmp");
    string first_bucket = buckets[0];
    string second_bucket = buckets[1];
    path directory(first_bucket + "/" + second_bucket);
    string filename = buckets[2];
    create_directories(directory);
    ofstream file((directory / filename).string().c_str(),ios_base::binary);
    file << string(data,len);
    file.close();
  }
}

static void handle_sigint(int signal) {
  if (!gracefully_quit) {
    cout << "Sent Quit Signal" << endl;
    gracefully_quit = 1;
  } else {
    exit(0);
  }
}

int main(int argc, char **argv) {
  // Ignore SIGPIPES
  signal(SIGPIPE,SIG_IGN);
  signal(SIGINT,handle_sigint);
  char* host = (char*) "localhost";
  int port = 9091;
  int c;

  __sh = S3Helper::instance();
  __mim = GDImage::Manager::instance();

  while ((c = getopt(argc, argv, "h:p")) != -1) {
    switch (c) {
      case 'h':
        host = optarg;
        break;
      case 'p':
        port = atoi(optarg);
        if (port == 0) {
          cout << "Invalid port" << endl;
          exit(-1);
        }
        break;
    }
  }
  shared_ptr<TTransport> socket(new TSocket(host,port));
  shared_ptr<TTransport> transport(new TBufferedTransport(socket));
  shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
  ImageDownloadQueueClient client(protocol);

  for(;;) {
    try {
      if (gracefully_quit == 1) {
        cout << "Gracefully Quitting" << endl;
        exit(0);
      }
      transport->open();
      vector<ImageWorkUnit> work_units;
      client.dequeue(work_units);
      transport->close();
      if(work_units.size() > 0) {
        cout << "DEQUEUED: " << work_units.size() << endl;
        for(vector<ImageWorkUnit>::const_iterator ii = work_units.begin(); ii != work_units.end(); ii++) {
          ImageWorkUnit unit = *ii;
          char* data = NULL;
          uint32_t data_len;
          printf("START DOWNLOAD: %s\n", unit.link.c_str());
          data_len = __sh->get(unit.bucket.c_str(),unit.link.c_str(),&data);
          printf("FINISH DOWNLOAD: %s\n", unit.link.c_str());
          if (data_len > 0) {
            stringstream dest_bucket_strm;
            dest_bucket_strm << "climages" << unit.desired_size;
            string dest_bucket = dest_bucket_strm.str();
            char* extension = find_extension(unit.link.c_str());
            if (!strcasecmp("svg",extension)) {
              cout << "START SVG: " << unit.link << endl;
              char* converted_svg = NULL;
              int converted_size = svg_convert(data,data_len,&converted_svg,unit.desired_size);
              if (converted_svg) {
                cout << "DONE SVG: " << unit.link << endl;
                //__sh->put(dest_bucket.c_str(),unit.link.c_str(),converted_svg,converted_size,mime_type(unit.link.c_str()),true,true);
              } else {
                cout << "ERROR SVG: " << unit.link << endl;
              }
              free(converted_svg);
            } else {
              try {
                cout << "START GD: " << unit.link << endl;
                shared_ptr<GDImage> mi = __mim->new_image(extension,data,data_len);
                mi->floor(unit.desired_size);
                gd_image_data_t* gd_data = mi->data();
                if (gd_data && gd_data->data) {
                  cout << "DONE GD: " << unit.link << endl;
                  //__sh->put(dest_bucket.c_str(),unit.link.c_str(),gd_data->data,gd_data->size,mime_type(unit.link.c_str()),true,true);
                } else {
                  cout << "ERROR GD:" << unit.link << endl;
                }
                free_gd_image_data(gd_data);
              } catch (gd_exception& gde) {
                cout << "ERROR GD:" << unit.link << endl;
              }
            }
          } else {
            cout << "ERROR FILE: " << unit.link << endl;
          }
          free(data);
        }
      } else {
        cout << "Queue is Empty" << endl;
        sleep(10);
      }
    } catch (TException &tx) {
      printf("ERROR: %s\n", tx.what());
      printf("Sleeping for 10s before retry\n");
      sleep(10);
    }
  }
}


text:
@interface FuelResultVenderViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    NSArray *_results;
}

@property (nonatomic, strong) NSString *adminLevel1;
@property (nonatomic, strong) NSString *adminLevel2;

@property (nonatomic, readwrite) double lat;
@property (nonatomic, readwrite) double lon;

@end


text:
//========= Copyright 2016, HTC Corporation. All rights reserved. ===========

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

namespace HTC.UnityPlugin.Pointer3D
{
    public abstract class BaseRaycastMethod : MonoBehaviour, IRaycastMethod
    {
        private Pointer3DRaycaster m_raycaster;
        public Pointer3DRaycaster raycaster { get { return m_raycaster ?? (m_raycaster = GetComponent<Pointer3DRaycaster>()); } }

        protected virtual void Start()
        {
            raycaster.AddRaycastMethod(this);
        }

        protected virtual void OnEnable() { }

        protected virtual void OnDisable() { }

        protected virtual void OnDestroy()
        {
            raycaster.RemoveRaycastMethod(this);
        }

        public abstract void Raycast(Ray ray, float distance, List<RaycastResult> raycastResults);
    }
}


text:
/*
  Place all the styles related to the matching controller here.
  They will automatically be included in application.css.
*/

#loading {
  display: none;
}

.center_title {
  font-size: 60%;
}

.search_field {
  width: 130px !important;
}

#activity {
  padding-top: 50px;
}

.ltr {
  direction: ltr;
}

.rtl {
  direction: rtl;
}


text:
<?php

# Copyright 2015 Wayne D Grant (www.waynedgrant.com)
# Licensed under the MIT License

require_once('ObservationMap.php');

class LightningObservationMap extends ObservationMap {

    public function __construct($apiKey, $workingFolder) {
        parent::__construct($apiKey, $workingFolder);
    }

    protected function getName() {
        return 'Lightning Observation Map';
    }

    protected function getLayerName() {
        return 'ATDNET_Sferics';
    }

    protected function requiresTimestamp() {
        return true;
    }

    protected function getBaseMap() {
        return 'uk_base_greyscale.png';
    }

    protected function getOverlayMap() {
        return null;
    }
}

?>


text:
<?php

class PwNoticeApp extends PwNoticeAction
{
    public $aggregate = false;
    public $ignoreNotice = false;

    public function buildTitle($param = 0, $extendParams = null, $aggregatedNotice = null)
    {
        if ($extendParams['title']) {
            $title = $extendParams['title'];
        } else {
            $title = Pw::substrs($extendParams['content'], 60);
        }

        return $title;
    }

    /**
     * @see PwNoticeAction::formatExtendParams()
     */
    public function formatExtendParams($extendParams, $aggregatedNotice = null)
    {
        return $extendParams;
    }

    /**
     * 忽略一个回复通知.
     *
     * @param array $notice
     */
    public function ignoreNotice($notice, $ignore = 1)
    {
    }

    /**
     * @see PwNoticeAction::getDetailList()
     */
    public function getDetailList($notice)
    {
    }
}


text:
namespace TibiaData.Client.Models
{
    public enum AccountStatus
    {
        Free,
        Premium
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cortinarius albidoavellaneus Kauffman & A.H. Sm.

### Remarks
null


text:
package mcmod.nxs.minextension.render;

import java.util.Random;

import mcmod.nxs.minextension.MainClass;
import mcmod.nxs.minextension.entity.hostile.EntityNetherman;
import net.minecraft.block.material.Material;
import net.minecraft.client.model.ModelEnderman;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ResourceLocation;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public class RenderNetherman extends RenderLiving {
	private static final ResourceLocation endermanEyesTexture = new ResourceLocation("textures/entity/enderman/enderman_eyes.png");
	private static final ResourceLocation endermanTextures = new ResourceLocation(MainClass.TEXTURES_PATH + "textures/entity/netherman.png");
	/**
	 * The model of the enderman
	 */
	private ModelEnderman endermanModel;
	private Random rnd = new Random();
	private static final String __OBFID = "CL_00000989";

	public RenderNetherman()
	{
		super(new ModelEnderman(), 0.5F);
		this.endermanModel = (ModelEnderman) super.mainModel;
		this.setRenderPassModel(this.endermanModel);
	}

	/**
	 * Actually renders the given argument. This is a synthetic bridge method,
	 * always casting down its argument and then handing it off to a worker
	 * function which does the actual work. In all probabilty, the class Render
	 * is generic (Render<T extends Entity) and this method has signature public
	 * void doRender(T entity, double d, double d1, double d2, float f, float
	 * f1). But JAD is pre 1.5 so doesn't do that.
	 */
	public void doRender(EntityNetherman par1EntityNetherman, double par2, double par4, double par6, float par8, float par9)
	{
		this.endermanModel.isCarrying = par1EntityNetherman.func_146080_bZ().getMaterial() != Material.air;
		this.endermanModel.isAttacking = par1EntityNetherman.isScreaming();

		if (par1EntityNetherman.isScreaming())
		{
			double d3 = 0.02D;
			par2 += this.rnd.nextGaussian() * d3;
			par6 += this.rnd.nextGaussian() * d3;
		}

		super.doRender((EntityLiving) par1EntityNetherman, par2, par4, par6, par8, par9);
	}

	/**
	 * Returns the location of an entity's texture. Doesn't seem to be called
	 * unless you call Render.bindEntityTexture.
	 */
	protected ResourceLocation getEntityTexture(EntityNetherman par1EntityNetherman)
	{
		return endermanTextures;
	}

	protected void renderEquippedItems(EntityNetherman par1EntityNetherman, float par2)
	{
		super.renderEquippedItems(par1EntityNetherman, par2);

		if (par1EntityNetherman.func_146080_bZ().getMaterial() != Material.air)
		{
			GL11.glEnable(GL12.GL_RESCALE_NORMAL);
			GL11.glPushMatrix();
			float f1 = 0.5F;
			GL11.glTranslatef(0.0F, 0.6875F, -0.75F);
			f1 *= 1.0F;
			GL11.glRotatef(20.0F, 1.0F, 0.0F, 0.0F);
			GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);
			GL11.glScalef(-f1, -f1, f1);
			int i = par1EntityNetherman.getBrightnessForRender(par2);
			int j = i % 65536;
			int k = i / 65536;
			OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F);
			GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
			this.bindTexture(TextureMap.locationBlocksTexture);
			this.field_147909_c.renderBlockAsItem(par1EntityNetherman.func_146080_bZ(), par1EntityNetherman.getCarryingData(), 1.0F);
			GL11.glPopMatrix();
			GL11.glDisable(GL12.GL_RESCALE_NORMAL);
		}
	}

	/**
	 * Queries whether should render the specified pass or not.
	 */
	protected int shouldRenderPass(EntityNetherman par1EntityNetherman, int par2, float par3)
	{
		if (par2 != 0)
		{
			return -1;
		} else
		{
			this.bindTexture(endermanEyesTexture);
			float f1 = 1.0F;
			GL11.glEnable(GL11.GL_BLEND);
			GL11.glDisable(GL11.GL_ALPHA_TEST);
			GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE);
			GL11.glDisable(GL11.GL_LIGHTING);

			if (par1EntityNetherman.isInvisible())
			{
				GL11.glDepthMask(false);
			} else
			{
				GL11.glDepthMask(true);
			}

			char c0 = 61680;
			int j = c0 % 65536;
			int k = c0 / 65536;
			OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F);
			GL11.glEnable(GL11.GL_LIGHTING);
			GL11.glColor4f(1.0F, 1.0F, 1.0F, f1);
			return 1;
		}
	}

	/**
	 * Actually renders the given argument. This is a synthetic bridge method,
	 * always casting down its argument and then handing it off to a worker
	 * function which does the actual work. In all probabilty, the class Render
	 * is generic (Render<T extends Entity) and this method has signature public
	 * void doRender(T entity, double d, double d1, double d2, float f, float
	 * f1). But JAD is pre 1.5 so doesn't do that.
	 */
	public void doRender(EntityLiving par1EntityLiving, double par2, double par4, double par6, float par8, float par9)
	{
		this.doRender((EntityNetherman) par1EntityLiving, par2, par4, par6, par8, par9);
	}

	/**
	 * Queries whether should render the specified pass or not.
	 */
	protected int shouldRenderPass(EntityLivingBase par1EntityLivingBase, int par2, float par3)
	{
		return this.shouldRenderPass((EntityNetherman) par1EntityLivingBase, par2, par3);
	}

	protected void renderEquippedItems(EntityLivingBase par1EntityLivingBase, float par2)
	{
		this.renderEquippedItems((EntityNetherman) par1EntityLivingBase, par2);
	}

	/**
	 * Actually renders the given argument. This is a synthetic bridge method,
	 * always casting down its argument and then handing it off to a worker
	 * function which does the actual work. In all probabilty, the class Render
	 * is generic (Render<T extends Entity) and this method has signature public
	 * void doRender(T entity, double d, double d1, double d2, float f, float
	 * f1). But JAD is pre 1.5 so doesn't do that.
	 */
	public void doRender(EntityLivingBase par1Entity, double par2, double par4, double par6, float par8, float par9)
	{
		this.doRender((EntityNetherman) par1Entity, par2, par4, par6, par8, par9);
	}

	/**
	 * Returns the location of an entity's texture. Doesn't seem to be called
	 * unless you call Render.bindEntityTexture.
	 */
	protected ResourceLocation getEntityTexture(Entity par1Entity)
	{
		return this.getEntityTexture((EntityNetherman) par1Entity);
	}

	/**
	 * Actually renders the given argument. This is a synthetic bridge method,
	 * always casting down its argument and then handing it off to a worker
	 * function which does the actual work. In all probabilty, the class Render
	 * is generic (Render<T extends Entity) and this method has signature public
	 * void doRender(T entity, double d, double d1, double d2, float f, float
	 * f1). But JAD is pre 1.5 so doesn't do that.
	 */
	public void doRender(Entity par1Entity, double par2, double par4, double par6, float par8, float par9)
	{
		this.doRender((EntityNetherman) par1Entity, par2, par4, par6, par8, par9);
	}
}


text:
// Copyright 2021 Phyronnaz

#pragma once

#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "VoxelMathLibrary.generated.h"

USTRUCT(BlueprintType, meta = (HasNativeMake = "Voxel.VoxelMathLibrary.MakeHaltonStream"))
struct FVoxelHaltonStream
{
	GENERATED_BODY()

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Config")
	int32 InitialSeed = 0;

	UPROPERTY()
	mutable uint32 Seed = 0;
};

UCLASS()
class VOXEL_API UVoxelMathLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()

public:
	/**
	 * Generates a random position on the unit sphere, given some random input between 0 and 1
	 * @param	Random		Random values, between 0 and 1. Can use RandomFloat, but also more complex noises like Halton or Sobol
	 */
	UFUNCTION(BlueprintPure, Category = "Voxel|Math|Random")
	static FVector GetUnitVectorFromRandom(FVector2D Random);

public:
	UFUNCTION(BlueprintPure, meta = (Keywords = "construct build", NativeMakeFunc), Category = "Voxel|Math|Random")
	static FVoxelHaltonStream MakeHaltonStream(int32 InitialSeed);

	UFUNCTION(BlueprintCallable, Category = "Voxel|Math|Random")
	static void ResetHaltonStream(const FVoxelHaltonStream& Stream);

	UFUNCTION(BlueprintPure, Category = "Voxel|Math|Random")
	static float GetHalton1D(const FVoxelHaltonStream& Stream);

	UFUNCTION(BlueprintPure, Category = "Voxel|Math|Random")
	static FVector2D GetHalton2D(const FVoxelHaltonStream& Stream);

	UFUNCTION(BlueprintPure, Category = "Voxel|Math|Random")
	static FVector GetHalton3D(const FVoxelHaltonStream& Stream);
};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="edge_color">#FF000000</color>
    <color name="background_color_dark">#FF666666</color>
    <color name="background_color_light">#00FFFFFF</color>
</resources>


text:
@class JavaLangReflectField;
@protocol JavaUtilSet;

@interface OrgMockitoInternalConfigurationInjectionMockInjectionStrategy : NSObject

#pragma mark Public

- (instancetype)init;

+ (OrgMockitoInternalConfigurationInjectionMockInjectionStrategy *)nop;

- (jboolean)processWithJavaLangReflectField:(JavaLangReflectField *)onField
                                     withId:(id)fieldOwnedBy
                            withJavaUtilSet:(id<JavaUtilSet>)mockCandidates;

- (OrgMockitoInternalConfigurationInjectionMockInjectionStrategy *)thenTryWithOrgMockitoInternalConfigurationInjectionMockInjectionStrategy:(OrgMockitoInternalConfigurationInjectionMockInjectionStrategy *)strategy;

#pragma mark Protected

- (jboolean)processInjectionWithJavaLangReflectField:(JavaLangReflectField *)field
                                              withId:(id)fieldOwner
                                     withJavaUtilSet:(id<JavaUtilSet>)mockCandidates;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgMockitoInternalConfigurationInjectionMockInjectionStrategy)

FOUNDATION_EXPORT OrgMockitoInternalConfigurationInjectionMockInjectionStrategy *OrgMockitoInternalConfigurationInjectionMockInjectionStrategy_nop();

FOUNDATION_EXPORT void OrgMockitoInternalConfigurationInjectionMockInjectionStrategy_init(OrgMockitoInternalConfigurationInjectionMockInjectionStrategy *self);

J2OBJC_TYPE_LITERAL_HEADER(OrgMockitoInternalConfigurationInjectionMockInjectionStrategy)

#endif // _OrgMockitoInternalConfigurationInjectionMockInjectionStrategy_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">TouchwizMobileData</string>
    <string name="hello_world">Hello world!</string>

	<string name="app_description">Enables configuration for Samsung 4.1 Quick Settings.</string>

	<string name="edit">Edit</string>
</resources>


text:
layout: post
title:  "How to Install JDK 1.8 on Fedora 25"
date:   2017-03-05
published: false
tags:
    - general
categories:
    - article
---
{% highlight text %}
$
{% endhighlight %}


text:
package com.infinityraider.elementalinvocations.block;

import com.infinityraider.elementalinvocations.block.tile.TileSolidAir;
import com.infinityraider.elementalinvocations.reference.Reference;
import com.infinityraider.elementalinvocations.render.block.RenderBlockSolidAir;
import com.infinityraider.infinitylib.block.*;
import com.infinityraider.infinitylib.block.blockstate.InfinityProperty;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.entity.Entity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import javax.annotation.Nullable;
import java.util.Optional;
import java.util.Random;

public class BlockSolidAir extends BlockTileCustomRenderedBase<TileSolidAir> {
    public static final PropertyVisible PROPERTY_VISIBLE = new PropertyVisible();
    public static final AxisAlignedBB EMPTY_BB = new AxisAlignedBB(0, 0, 0, 0, 0, 0);

    public BlockSolidAir() {
        super("ei.block.solid_air", Material.BARRIER);
        this.setBlockUnbreakable();
        this.setResistance(6000000.0F);
    }

    @Override
    public TileSolidAir createNewTileEntity(World world, int meta) {
        return new TileSolidAir();
    }

    public Optional<TileSolidAir> getTile(IBlockAccess world, BlockPos pos) {
        TileEntity tile = world.getTileEntity(pos);
        return tile instanceof TileSolidAir ? Optional.of((TileSolidAir) tile) : Optional.empty();
    }

    @Override
    public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) {
        Optional<TileSolidAir> tile = getTile(world, pos);
        if (tile.isPresent()) {
            return ((IExtendedBlockState) state).withProperty(PROPERTY_VISIBLE, tile.get().isVisible());
        } else {
            return state;
        }
    }

    @Override
    public void onFallenUpon(World world, BlockPos pos, Entity entity, float fallDistance) {
        entity.fall(fallDistance, 0.0F);
    }

    @Override
    public void onLanded(World world, Entity entity) {
        if (entity.motionY < 0.0D) {
            entity.motionY = -0.3*entity.motionY;
        }
    }

    @Override
    public void onEntityCollidedWithBlock(World world, BlockPos pos, IBlockState state, Entity entity) {
        //TODO: render effect and play sound
    }

    @Override
    @SideOnly(Side.CLIENT)
    public boolean addHitEffects(IBlockState state, World worldObj, RayTraceResult target, net.minecraft.client.particle.ParticleManager manager) {
        //TODO: render effect and play sound
        return false;
    }

    @Override
    @Deprecated
    @SideOnly(Side.CLIENT)
    public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos) {
        return BlockSolidAir.EMPTY_BB;
    }

    @Override
    public int quantityDropped(Random random) {
        return 0;
    }

    @Override
    @Nullable
    public Item getItemDropped(IBlockState state, Random rand, int fortune) {
        return null;
    }

    @Override
    @SideOnly(Side.CLIENT)
    public ModelResourceLocation getBlockModelResourceLocation() {
        return new ModelResourceLocation(Reference.MOD_ID.toLowerCase() + ":" + getInternalName());
    }

    @Override
    protected InfinityProperty[] getPropertyArray() {
        return new InfinityProperty[]{};
    }

    @Override
    public IUnlistedProperty[] getUnlistedPropertyArray() {
        return new IUnlistedProperty[]{PROPERTY_VISIBLE};
    }

    @Override
    @SideOnly(Side.CLIENT)
    public RenderBlockSolidAir getRenderer() {
        return new RenderBlockSolidAir(this);
    }

    @Override
    @SideOnly(Side.CLIENT)
    public BlockRenderLayer getBlockLayer() {
        return BlockRenderLayer.CUTOUT;
    }

    @Override
    @SuppressWarnings("deprecation")
    public boolean isOpaqueCube(IBlockState state) {
        return false;
    }

    @Override
    @SuppressWarnings("deprecation")
    public boolean shouldSideBeRendered(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {
        IBlockState stateAt = world.getBlockState(pos.offset(side));
        return stateAt.getBlock() != this && super.shouldSideBeRendered(state, world, pos, side);
    }

    @Override
    public boolean doesSideBlockRendering(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {
        return false;
    }

    @Override
    @SuppressWarnings("deprecation")
    public boolean isFullCube(IBlockState state) {
        return true;
    }

    public static class PropertyVisible implements IUnlistedProperty<Boolean> {
        private PropertyVisible() {
        }

        @Override
        public String getName() {
            return "visible";
        }

        @Override
        public boolean isValid(Boolean value) {
            return true;
        }

        @Override
        public Class<Boolean> getType() {
            return Boolean.class;
        }

        @Override
        public String valueToString(Boolean value) {
            return value.toString();
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.easemob.rest</groupId>
    <artifactId>examples</artifactId>
    <packaging>pom</packaging>
    <version>0.0.1</version>
    <name>Easemob REST Example</name>
    <description>Easemob REST Example</description>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.easemob</groupId>
            <artifactId>rest-java-sdk</artifactId>
            <version>1.0.5</version>
        </dependency>
    </dependencies>
</project>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.thinkgem.jeesite.modules.sys.dao.SysDefinedAppDao">

	<sql id="sysDefinedAppColumns">
		a.id,
		a.app_type AS "appType",
		a.app_name AS "appName"
	</sql>

	<sql id="sysDefinedAppJoins">
	</sql>

	<select id="get" resultType="SysDefinedApp">
		SELECT
			<include refid="sysDefinedAppColumns"/>
		FROM sys_defined_app a
		<include refid="sysDefinedAppJoins"/>
		WHERE a.id = #{id}
	</select>

	<select id="findList" resultType="SysDefinedApp">
		SELECT
			<include refid="sysDefinedAppColumns"/>
		FROM sys_defined_app a
		<include refid="sysDefinedAppJoins"/>
		<where>
		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
			</otherwise>
		</choose>
	</select>

	<select id="findAllList" resultType="SysDefinedApp">
		SELECT
			<include refid="sysDefinedAppColumns"/>
		FROM sys_defined_app a
		<include refid="sysDefinedAppJoins"/>
		<where>

		</where>
		<choose>
			<when test="page !=null and page.orderBy != null and page.orderBy != ''">
				ORDER BY ${page.orderBy}
			</when>
			<otherwise>
			</otherwise>
		</choose>
	</select>

	<insert id="insert">
		INSERT INTO sys_defined_app(
			app_type,
			app_name
		) VALUES (
			#{appType},
			#{appName}
		)
	</insert>

	<update id="update">
		UPDATE sys_defined_app SET
			app_type = #{appType},
			app_name = #{appName}
		WHERE id = #{id}
	</update>

	<update id="delete">
		DELETE FROM sys_defined_app
		WHERE id = #{id}
	</update>

</mapper>


text:
{{ portfolio.tags }}

{{ tag.name }}

  {{ portfolio.getPostTags }}

{{ post.title.rendered }}

{{ post.title.rendered }}

                    <button ng-click="portfolio.open(post.id)" class="btn btn-primary">Read More</button>


text:
<?xml version="1.0" ?>

<!--

 This file is part of the Sylius package.

 (c) Paweł Jędrzejewski

 For the full copyright and license information, please view the LICENSE
 file that was distributed with this source code.

-->

<resources xmlns="https://api-platform.com/schema/metadata"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="https://api-platform.com/schema/metadata https://api-platform.com/schema/metadata/metadata-2.0.xsd"
>
    <resource class="%sylius.model.admin_user.class%" shortName="Administrator">
        <attribute name="normalization_context">
            <attribute name="groups">
                <attribute>admin_user:read</attribute>
            </attribute>
        </attribute>

        <attribute name="denormalization_context">
            <attribute name="groups">
                <attribute>admin_user:create</attribute>
            </attribute>
        </attribute>

        <attribute name="validation_groups">sylius</attribute>

        <collectionOperations>
            <collectionOperation name="get">
                <attribute name="security">is_granted('ROLE_API_ACCESS')</attribute>
            </collectionOperation>
            <collectionOperation name="post">
                <attribute name="security">is_granted('ROLE_API_ACCESS')</attribute>
                <attribute name="validation_groups">
                    <attribute>sylius</attribute>
                    <attribute>sylius_user_create</attribute>
                </attribute>
            </collectionOperation>
        </collectionOperations>

        <itemOperations>
            <itemOperation name="get">
                <attribute name="security">is_granted('ROLE_API_ACCESS')</attribute>
            </itemOperation>
            <itemOperation name="put">
                <attribute name="security">is_granted('ROLE_API_ACCESS')</attribute>
                <attribute name="denormalization_context">
                    <attribute name="groups">admin_user:update</attribute>
                </attribute>
            </itemOperation>
            <itemOperation name="delete">
                <attribute name="security">is_granted('ROLE_API_ACCESS')</attribute>
            </itemOperation>
        </itemOperations>

        <property name="id" identifier="true" writable="false" />
        <property name="email" required="true" />
        <property name="username" />
        <property name="plainPassword" readable="false" />
        <property name="enabled" />
        <property name="firstName" />
        <property name="lastName" />
        <property name="localeCode" />
        <property name="avatar" writable="true" />
        <property name="updatedAt" writable="false" />
        <property name="verifiedAt" writable="false" />
        <property name="lastLogin" writable="false" />
    </resource>
</resources>


text:
from __future__ import division
from __future__ import print_function

from random import randint
from collections import OrderedDict as odict
import traceback

from myhdl import (Signal, intbv, always, instance, concat,
                   now, delay, StopSimulation)

from support import Clock, Reset
from support import run_testbench, monitor, dump_monitor_log
from support import shifty

# initial_value check error message
errmsg1 = """initial_value output bit check failed, expected {} got {}
    initial_value    {:X}
    cycle (# shifts) {:d}
"""

# load value shift check error message
errmsg2 = """output bit check failed, expected {} got {}
    load_value       {:X}
    cycle (# shifts) {:d}
"""

def stimulator(mod=None):
    """ Basic stimulus for waveform viewing
    Arguments:
        mod: myhdl module to be stimulated

    This module will exercise a fixed number of clock cycles and
    will not verify for correctness.
    """
    if mod is None:
        mod = shifty

    clock = Clock(0)
    reset = Reset(1, active=1, async=True)
    load = Signal(bool(0))
    load_value = Signal(intbv(0, max=256, min=0))
    output_bit = Signal(bool(0))
    initial_value = 0x80

    sigs = odict()
    sigs['load'], sigs['load_value'] = load, load_value
    sigs['output_bit'] = output_bit

    def _bench():
        tbdut = mod(clock, reset, load, load_value, output_bit,
                    initial_value=initial_value)
        sigs['shiftreg'] = mod.shiftreg
        tbclk = clock.gen()
        tbmon = monitor(clock, sigs)

        @instance
        def tbstim():
            timestart = now()
            yield reset.pulse(10)
            yield clock.posedge
            try:
                for _ in range(8):
                    yield clock.posedge
                load_value.next = 0x01
                load.next = True
                yield clock.posedge
                load.next = False
                for _ in range(17):
                    yield clock.posedge
            except Exception as err:
                print("Error occurred: {}".format(err))
                traceback.print_exc()
                yield delay(now()-270)
            dump_monitor_log(format='hex')
            raise StopSimulation

        return tbdut, tbclk, tbmon, tbstim

    portmap = {"clock": clock, "reset": reset, "load": load,
               "load_value": load_value, "output_bit": output_bit,
               "initial_value": initial_value}
    run_testbench(_bench, "01_mex_stim", mod, portmap)

def test(mod=None):
    """ Verification test
    Arguments:
        mod: myhdl module to be verified
    """
    if mod is None:
        mod = shifty

    clock = Clock(0)
    reset = Reset(1, active=1, async=True)
    load = Signal(bool(0))
    load_value = Signal(intbv(0, max=256, min=0))
    output_bit = Signal(bool(0))
    initial_value = randint(0, load_value.max-1)

    sigs = odict()
    sigs['load'], sigs['load_value'] = load, load_value
    sigs['output_bit'] = output_bit

    def _bench():
        _bench.error = True
        tbdut = mod(clock, reset, load, load_value, output_bit,
                    initial_value=initial_value)
        sigs['shiftreg'] = mod.shiftreg
        tbclk = clock.gen()
        tbmon = monitor(clock, sigs)

        expected_shift = Signal(intbv(0, max=256, min=0))

        @instance
        def tbstim():
            try:
                expected_shift.next = initial_value
                yield reset.pulse(10)
                yield clock.posedge

                # check the `initial_value`
                for ii in range(1000):
                    assert expected_shift[7] == output_bit, \
                        errmsg1.format(expected_shift[7], output_bit,
                                       initial_value, ii)
                    expected_shift.next = concat(expected_shift[7:0],
                                                 expected_shift[7])
                    yield clock.posedge

                for ii in range(7):
                    rr = randint(1, load_value.max-1)
                    load_value.next = rr
                    load.next = True
                    expected_shift.next = rr
                    yield clock.posedge
                    load.next = False
                    yield clock.posedge
                    for ii in range(100):
                        assert expected_shift[7] == output_bit, \
                        errmsg2.format(expected_shift[7], output_bit,
                                       load_value, ii)
                        expected_shift.next = concat(expected_shift[7:0],
                                                     expected_shift[7])
                        yield clock.posedge

                _bench.error = False
                print("Test Successful")
            except Exception as err:
                yield delay(10*5)
                print("Test Error")
                dump_monitor_log(format='hex')
                _bench.error = True
                print(err)

            raise StopSimulation

        return tbclk, tbdut, tbstim, tbmon

    portmap = {"clock": clock, "reset": reset, "load": load,
               "load_value": load_value, "output_bit": output_bit,
               "initial_value": initial_value}
    run_testbench(_bench, "01_mex_test", mod, portmap)

if __name__ == '__main__':
    test(shifty)


text:
'''
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id: lib_glx.py 597 2007-02-03 16:13:07Z Alex.Holkner $'

import ctypes
from ctypes import *

import pyglet
from pyglet.gl.lib import missing_function, decorate_function

__all__ = ['link_GL', 'link_GLU', 'link_WGL']

_debug_trace = pyglet.options['debug_trace']

gl_lib = ctypes.windll.opengl32
glu_lib = ctypes.windll.glu32
wgl_lib = gl_lib

if _debug_trace:
    from pyglet.lib import _TraceLibrary
    gl_lib = _TraceLibrary(gl_lib)
    glu_lib = _TraceLibrary(glu_lib)
    wgl_lib = _TraceLibrary(wgl_lib)

try:
    wglGetProcAddress = wgl_lib.wglGetProcAddress
    wglGetProcAddress.restype = CFUNCTYPE(POINTER(c_int))
    wglGetProcAddress.argtypes = [c_char_p]
    _have_get_proc_address = True
except AttributeError:
    _have_get_proc_address = False

class WGLFunctionProxy(object):
    __slots__ = ['name', 'requires', 'suggestions', 'ftype', 'func']
    def __init__(self, name, ftype, requires, suggestions):
        assert _have_get_proc_address
        self.name = name
        self.ftype = ftype
        self.requires = requires
        self.suggestions = suggestions
        self.func = None

    def __call__(self, *args, **kwargs):
        if self.func:
            return self.func(*args, **kwargs)

        from pyglet.gl import current_context
        if not current_context:
            raise Exception(
                'Call to function "%s" before GL context created' % self.name)
        address = wglGetProcAddress(self.name)
        if cast(address, POINTER(c_int)):  # check cast because address is func
            self.func = cast(address, self.ftype)
            decorate_function(self.func, self.name)
        else:
            self.func = missing_function(
                self.name, self.requires, self.suggestions)
        result = self.func(*args, **kwargs)
        return result

def link_GL(name, restype, argtypes, requires=None, suggestions=None):
    try:
        func = getattr(gl_lib, name)
        func.restype = restype
        func.argtypes = argtypes
        decorate_function(func, name)
        return func
    except AttributeError, e:
        # Not in opengl32.dll. Try and get a pointer from WGL.
        try:
            fargs = (restype,) + tuple(argtypes)
            ftype = ctypes.WINFUNCTYPE(*fargs)
            if _have_get_proc_address:
                from pyglet.gl import gl_info
                if gl_info.have_context():
                    address = wglGetProcAddress(name)
                    if address:
                        func = cast(address, ftype)
                        decorate_function(func, name)
                        return func
                else:
                    # Insert proxy until we have a context
                    return WGLFunctionProxy(name, ftype, requires, suggestions)
        except:
            pass

        return missing_function(name, requires, suggestions)

def link_GLU(name, restype, argtypes, requires=None, suggestions=None):
    try:
        func = getattr(glu_lib, name)
        func.restype = restype
        func.argtypes = argtypes
        decorate_function(func, name)
        return func
    except AttributeError, e:
        # Not in glu32.dll. Try and get a pointer from WGL.
        try:
            fargs = (restype,) + tuple(argtypes)
            ftype = ctypes.WINFUNCTYPE(*fargs)
            if _have_get_proc_address:
                from pyglet.gl import gl_info
                if gl_info.have_context():
                    address = wglGetProcAddress(name)
                    if address:
                        func = cast(address, ftype)
                        decorate_function(func, name)
                        return func
                else:
                    # Insert proxy until we have a context
                    return WGLFunctionProxy(name, ftype, requires, suggestions)
        except:
            pass

        return missing_function(name, requires, suggestions)

link_WGL = link_GL


text:
package io.quarkus.kafka.client.serialization;

import org.apache.kafka.common.serialization.Deserializer;

import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;

/**
 * Kafka deserializer for raw bytes in a buffer
 */
public class JsonArrayDeserializer implements Deserializer<JsonArray> {

    @Override
    public JsonArray deserialize(String topic, byte[] data) {
        if (data == null)
            return null;

        return Buffer.buffer(data).toJsonArray();
    }

}


text:
// Licensed under the BSD license. See LICENSE.txt for more details.

/* C or C++ standard headers */
#include <cstdio>

/* physis-OpenCL specific */
#include "runtime/rpc_opencl.h"

namespace physis {
namespace runtime {

// PSGrid3DRealNew(NX, NX, NX); is translated into
// int dims[3] = {((index_t )NX), ((index_t )NX), ((index_t )NX)};
// g = __PSGridNew(sizeof(float), 3, dims, 0);

__PSGrid* CLinfo::GridNew(int elm_size, int num_dims, PSVectorInt dim, int grid_attribute) {
  /*
    1. Allocate grid
    2. Initialize grid
    3. Allocate memory on the device
    4. Set the on-device data (g->devptr)

    99. return allocated grid
  */

  int i = 0;
  cl_int status = -1;
  size_t size = 0;
  __PSGrid *g = NULL;
  err_status = 1;

  do {
    // Allocate grid
    g = (__PSGrid *)malloc(sizeof(__PSGrid));
    if (!g) {
      fprintf(stderr, "Allocating memory failed for __PSGrid.\n");
      break;
    }

    // Initialize grid
    g->elm_size = elm_size;
    g->num_dims = num_dims;
    PSVectorIntCopy(g->dim, dim);
    g->devptr = NULL;
    g->num_elms = 1;
    g->gridattr = grid_attribute;
    g->buf = NULL;

    for (i = 0; i < g->num_dims; i++) {
      g->num_elms *= dim[i];
    }

    // Allocate memory on the device
    do {
      cl_mem dev_mem = (cl_mem) NULL;
      g->buf = NULL;
      size = g->num_elms * g->elm_size;

      // 4th argument can be NULL here: we won't share memory on CPU and device
      dev_mem = clCreateBuffer(clcontext, CL_MEM_READ_WRITE, size, NULL, &status);
      if (status != CL_SUCCESS) {
        fprintf(stderr, "Calling clCreateBuffer failed for buffer %i: status %i\n", i, status);
        break;
      }
      g->buf = dev_mem;
    } while(0);

    if (status != CL_SUCCESS) break;

    // Set the on-device data. g->devptr data will be copied when calling
    // OpenCL global functions.
    status = -1;
    switch (g->num_dims) {
      case 1:
        g->devptr = malloc(sizeof(__PSGrid1DDev));
        if (!g->devptr) {
          fprintf(stderr, "Allocating memory failed for __PSGrid1DDev.\n");
          break;
        }
        ((__PSGrid1DDev*)g->devptr)->buf = g->buf;
        for (i = 0; i < g->num_dims; i++)
          ((__PSGrid1DDev*)g->devptr)->dim[i] = g->dim[i];
        status = CL_SUCCESS;
        break;

      case 2:
        g->devptr = malloc(sizeof(__PSGrid2DDev));
        if (!g->devptr) {
          fprintf(stderr, "Allocating memory failed for __PSGrid2DDev.\n");
          break;
        }
        ((__PSGrid2DDev*)g->devptr)->buf = g->buf;
        for (i = 0; i < g->num_dims; i++)
          ((__PSGrid2DDev*)g->devptr)->dim[i] = g->dim[i];
        status = CL_SUCCESS;
        break;

      case 3:
        g->devptr = malloc(sizeof(__PSGrid3DDev));
        if (!g->devptr) {
          fprintf(stderr, "Allocating memory failed for __PSGrid3DDev.\n");
          break;
        }
        ((__PSGrid3DDev*)g->devptr)->buf = g->buf;
        for (i = 0; i < g->num_dims; i++)
          ((__PSGrid3DDev*)g->devptr)->dim[i] = g->dim[i];
        status = CL_SUCCESS;
        break;

      default:
        LOG_ERROR() << "Unsupported dimension: " << g->num_dims << "\n";
        PSAbort(1);
    } // switch (g->num_dims)

    if (status != CL_SUCCESS) break;

    // Initialization finished
    err_status = 0;
  } while (0);

  return g;

} // GridNew()

void CLinfo::GridFree(__PSGrid *g) {
  cl_mem dev_mem = (cl_mem) NULL;

  if (!g) return;

  // Release memory objects on devices
  dev_mem = (cl_mem) g->buf;
  if (dev_mem) clReleaseMemObject(dev_mem);

  // Free g itself
  free(g->devptr);
  free(g);

} // GridFree

} // namespace physis
} // namespace runtime


text:
package org.openehealth.ipf.commons.ihe.xds.iti63;

import org.openehealth.ipf.commons.ihe.core.atna.AuditorManager;
import org.openehealth.ipf.commons.ihe.xds.core.audit.XdsQueryAuditDataset;
import org.openehealth.ipf.commons.ihe.xds.core.audit.XdsQueryAuditStrategy30;

/**
 * Audit strategy for the XCF ITI-63 transaction.
 * @author Dmytro Rud
 */
public class Iti63AuditStrategy extends XdsQueryAuditStrategy30 {

    private static final String[] NECESSARY_AUDIT_FIELDS = new String[] {
        "EventOutcomeCode",
        "ServiceEndpointUrl",
        "QueryUuid",
        "RequestPayload",
        "HomeCommunityId",
        "PatientId"};

    public Iti63AuditStrategy(boolean serverSide, boolean allowIncompleteAudit) {
        super(serverSide, allowIncompleteAudit);
    }

    @Override
    public void doAudit(XdsQueryAuditDataset auditDataset) throws Exception {
        AuditorManager.getCustomXdsAuditor().auditIti63(
                isServerSide(),
                auditDataset.getEventOutcomeCode(),
                auditDataset.getUserId(),
                auditDataset.getUserName(),
                auditDataset.getServiceEndpointUrl(),
                auditDataset.getClientIpAddress(),
                auditDataset.getQueryUuid(),
                auditDataset.getRequestPayload(),
                auditDataset.getHomeCommunityId(),
                auditDataset.getPatientId());
    }

    @Override
    public String[] getNecessaryAuditFieldNames() {
        return NECESSARY_AUDIT_FIELDS;
    }
}


text:
package com.stepstone.stepper.internal.widget;

import android.support.annotation.NonNull;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

/**
 * Checks if {@link StepTab} is in a correct state.
 *
 * @author Piotr Zawadzki
 */
public class StepTabStateMatcher extends TypeSafeMatcher<StepTab> {

    @NonNull
    private final TabState expectedState;

    public StepTabStateMatcher(@NonNull TabState expectedState) {
        this.expectedState = expectedState;
    }

    @Override
    protected boolean matchesSafely(StepTab item) {
        StepTab.AbstractState currentState = item.mCurrentState;
        switch (expectedState) {
            case ACTIVE:
                return currentState instanceof StepTab.ActiveNumberState;
            case INACTIVE:
                return currentState instanceof StepTab.InactiveNumberState;
            case DONE:
                return currentState instanceof StepTab.DoneState;
            case WARNING:
                return currentState instanceof StepTab.WarningState;
        }
        return false;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText(" with state: ").appendValue(expectedState);
    }

    public enum TabState {
        ACTIVE,
        INACTIVE,
        DONE,
        WARNING
    }
}


text:
'use strict';

app.controller('RestCtrl', function TodoCtrl($scope, $modal, sailsSocket, $http, $log) {

  function responseAlert(httpOrSocket, url, response, status) {
    // NOTE:
    // Socket calls do not return HTTP status in the `status` argument.
    // Though, a `response.status` is returned when the socket experiences an error.
    // When successful, the `response.status` will likely not exist unless you
    // explicitly include it in your controller responses.
    if (!status) {
      status = (response && response.status) ? response.status : 200;
    }

    $log.debug('REST::' + url, status, response);
    var alertType = (status === 200) ? 'success' : 'danger';
    return [{
      msg: response, status: status, type: alertType, httpOrSocket: httpOrSocket, timestamp: new Date()
    }];
  }

  //
  // Echo Test
  //
  $scope.echoTestAlerts = [];
  $scope.echoText = 'Test 1, 2, 3...';
  $scope.closeEchoAlert = function() { $scope.echoTestAlerts = []; };

  $scope.callEcho = function(httpOrSocket) {
    var message = $scope.echoText;

    var processResponse = function(response, status) {
      $scope.echoTestAlerts = responseAlert(httpOrSocket, '/echo', response, status);
    };

    if (httpOrSocket === 'socket') {
      message = 'SOCKET: ' + message;
      //sailsSocket.get('/echo', { message: message}, processResponse);
      sailsSocket.post('/echo', { message: message}, processResponse);
    } else {
      message = 'HTTP: ' + message;
      //$http.get('/echo?message=' + message)
      // .success(processResponse).error(processResponse);
      $http.post('/echo', { message: message})
        .success(processResponse).error(processResponse);
    }
  };

  //
  // Error Tests
  //
  $scope.errorScenarios = [
    {
      key:   'positive',
      title: 'Positive Test',
      url:   '/resterror/isworking',
      method: 'post'
    },
    {
      key:   'unauthorized',
      title: '401 : Unauthorized',
      url:   '/resterror/unauthorized',
      method: 'post'
    },
    {
      key:   'forbidden',
      title: '403 : Forbidden',
      url:   '/resterror/forbidden',
      method: 'post'
    },
    {
      key:   'not-found',
      title: '404 : Not Found',
      url:   '/resterror/not-found',
      method: 'post'
    },
    {
      key:   'throws',
      title: '500 : Internal Server Error',
      url:   '/resterror/throws',
      method: 'post'
    }
  ];
  // Initialize alerts for each scenario
  $scope.errorAlerts = {};
  angular.forEach($scope.errorScenarios, function(scenario) {
    $scope.errorAlerts[scenario.key] = [];
  });
  $scope.closeErrorAlert = function(key) { $scope.errorAlerts[key] = []; };

  $scope.callErrorScenario = function(httpOrSocket, scenario) {
    var processErrorResponse = function(response, status) {
      $scope.errorAlerts[scenario.key] = responseAlert(httpOrSocket, scenario.url, response, status);
    };

    if (httpOrSocket === 'socket') {
      sailsSocket[scenario.method](scenario.url, {}, processErrorResponse);
    } else {
      $http[scenario.method](scenario.url, {})
        .success(processErrorResponse).error(processErrorResponse);
    }
  };
});


text:
require './lib/configuration/team'
require './lib/configuration/service'
require './lib/configuration/postgres_connection'
require './lib/configuration/redis_connection'
require './lib/configuration/beanstalk_connection'
require './lib/configuration/contest_flow'
require './lib/configuration/network'

module Themis
    module Configuration
        def self.get_stream_config
            config = {
                network: {
                    internal: [],
                    other: [],
                    teams: []
                },
                postgres_connection: {
                },
                redis_connection: {
                }
            }

            network_opts = get_network
            config[:network][:internal] = network_opts.internal
            config[:network][:other] = network_opts.other

            Themis::Configuration::get_teams.each do |team_opts|
                config[:network][:teams] << team_opts.network
            end

            config[:redis_connection] = get_redis_options
            config[:postgres_connection] = get_postgres_options

            config
        end
    end
end