text:
#include "third_party/blink/renderer/core/dom/text_link_colors.h"

#include "third_party/blink/renderer/core/css/css_color.h"
#include "third_party/blink/renderer/core/css/css_color_mix_value.h"
#include "third_party/blink/renderer/core/css/css_identifier_value.h"
#include "third_party/blink/renderer/core/css/css_light_dark_value_pair.h"
#include "third_party/blink/renderer/core/css/style_color.h"
#include "third_party/blink/renderer/core/layout/layout_theme.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"

namespace blink {

constexpr Color kDefaultLinkColorLight = Color::FromRGB(0, 0, 238);
constexpr Color kDefaultLinkColorDark = Color::FromRGB(158, 158, 255);
constexpr Color kDefaultVisitedLinkColorLight = Color::FromRGB(85, 26, 139);
constexpr Color kDefaultVisitedLinkColorDark = Color::FromRGB(208, 173, 240);
constexpr Color kDefaultActiveLinkColorLight = Color::FromRGB(255, 0, 0);
constexpr Color kDefaultActiveLinkColorDark = Color::FromRGB(255, 158, 158);

TextLinkColors::TextLinkColors() : text_color_(Color::kBlack) {
  ResetLinkColor();
  ResetVisitedLinkColor();
  ResetActiveLinkColor();
}

void TextLinkColors::SetTextColor(const Color& color) {
  text_color_ = color;
  has_custom_text_color_ = true;
}

Color TextLinkColors::TextColor() const {
  return TextColor(mojom::blink::ColorScheme::kLight);
}

Color TextLinkColors::TextColor(mojom::blink::ColorScheme color_scheme) const {
  return has_custom_text_color_
             ? text_color_
             : color_scheme == mojom::blink::ColorScheme::kLight
                   ? Color::kBlack
                   : Color::kWhite;
}

void TextLinkColors::SetLinkColor(const Color& color) {
  link_color_ = color;
  has_custom_link_color_ = true;
}

const Color& TextLinkColors::LinkColor() const {
  return LinkColor(mojom::blink::ColorScheme::kLight);
}

const Color& TextLinkColors::LinkColor(
    mojom::blink::ColorScheme color_scheme) const {
  return has_custom_link_color_
             ? link_color_
             : color_scheme == mojom::blink::ColorScheme::kLight
                   ? kDefaultLinkColorLight
                   : kDefaultLinkColorDark;
}

void TextLinkColors::SetVisitedLinkColor(const Color& color) {
  visited_link_color_ = color;
  has_custom_visited_link_color_ = true;
}

const Color& TextLinkColors::VisitedLinkColor() const {
  return VisitedLinkColor(mojom::blink::ColorScheme::kLight);
}

const Color& TextLinkColors::VisitedLinkColor(
    mojom::blink::ColorScheme color_scheme) const {
  return has_custom_visited_link_color_
             ? visited_link_color_
             : color_scheme == mojom::blink::ColorScheme::kLight
                   ? kDefaultVisitedLinkColorLight
                   : kDefaultVisitedLinkColorDark;
}

void TextLinkColors::SetActiveLinkColor(const Color& color) {
  active_link_color_ = color;
  has_custom_active_link_color_ = true;
}

const Color& TextLinkColors::ActiveLinkColor() const {
  return ActiveLinkColor(mojom::blink::ColorScheme::kLight);
}

const Color& TextLinkColors::ActiveLinkColor(
    mojom::blink::ColorScheme color_scheme) const {
  return has_custom_active_link_color_
             ? active_link_color_
             : color_scheme == mojom::blink::ColorScheme::kLight
                   ? kDefaultActiveLinkColorLight
                   : kDefaultActiveLinkColorDark;
}

Color TextLinkColors::ColorFromCSSValue(const CSSValue& value,
                                        Color current_color,
                                        mojom::blink::ColorScheme color_scheme,
                                        bool for_visited_link) const {
  if (auto* color_value = DynamicTo<cssvalue::CSSColor>(value))
    return color_value->Value();

  if (auto* color_mix_value = DynamicTo<cssvalue::CSSColorMixValue>(value)) {
    // TODO(crbug.com/1362022): This is not correct for CurrentColor
    Color c1 = ColorFromCSSValue(color_mix_value->Color1(), current_color,
                                 color_scheme, for_visited_link);
    Color c2 = ColorFromCSSValue(color_mix_value->Color2(), current_color,
                                 color_scheme, for_visited_link);

    double alpha_multiplier;
    double mix_amount;
    if (cssvalue::CSSColorMixValue::NormalizePercentages(
            color_mix_value->Percentage1(), color_mix_value->Percentage2(),
            mix_amount, alpha_multiplier)) {
      return Color::FromColorMix(color_mix_value->ColorInterpolationSpace(),
                                 color_mix_value->HueInterpolationMethod(), c1,
                                 c2, mix_amount, alpha_multiplier);
    } else {
      // TODO(crbug.com/1362022): Not sure what is appropriate to return when
      // both mix amounts are zero.
      return Color();
    }
  }

  if (auto* pair = DynamicTo<CSSLightDarkValuePair>(value)) {
    const CSSValue& color_value =
        color_scheme == mojom::blink::ColorScheme::kLight ? pair->First()
                                                          : pair->Second();
    return ColorFromCSSValue(color_value, current_color, color_scheme,
                             for_visited_link);
  }

  CSSValueID value_id = To<CSSIdentifierValue>(value).GetValueID();
  switch (value_id) {
    case CSSValueID::kInvalid:
      NOTREACHED();
      return Color();
    case CSSValueID::kInternalQuirkInherit:
      return TextColor(color_scheme);
    case CSSValueID::kWebkitLink:
      return for_visited_link ? VisitedLinkColor(color_scheme)
                              : LinkColor(color_scheme);
    case CSSValueID::kWebkitActivelink:
      return ActiveLinkColor(color_scheme);
    case CSSValueID::kWebkitFocusRingColor:
      return LayoutTheme::GetTheme().FocusRingColor(color_scheme);
    case CSSValueID::kCurrentcolor:
      return current_color;
    default:
      return StyleColor::ColorFromKeyword(value_id, color_scheme);
  }
}

}  // namespace blink


text:
obj-m += task_l.o

all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Smt\OpenPopo\Tester\Impl;

use PHPUnit_Framework_Assert as Assert;
use Smt\OpenPopo\Generator\TestDataGenerator;
use Smt\OpenPopo\Reflection\PopoClass;

/**
 * Test fluent setter
 * @package Smt\OpenPopo\Tester\Impl
 * @author Kirill Saksin <kirillsaksin@yandex.ru>
 * @api
 */
class FluentSetterTester extends AbstractPropertyTester
{
    /** {@inheritdoc} */
    protected function validate($object, \ReflectionProperty $property, PopoClass $class)
    {
        if (!$class->hasSetter($property->getName())) {
            return;
        }
        $setter = $class->getSetter($property->getName());
        $testData = TestDataGenerator::forParameter($setter->getParameters()[0]);
        Assert::assertEquals($object, $setter->invoke($object, $testData), sprintf(
            '%s::%s() is not fluent', get_class($object),
            $setter->getName()
        ));
        Assert::assertEquals($testData, $property->getValue($object), sprintf(
            'Failed on %s::%s() - written value doesn`t appear in property',
            get_class($object),
            $setter->getName()
        ));
    }
}


text:
        <hall-reservator-control-panel hall="$ctrl.hall" event-id="{{ ::$ctrl.event.Id }}" reservations="$ctrl.reservations"></hall-reservator-control-panel>

        <svg-wrapper svg-size="$ctrl.svg" hall="$ctrl.hall" mode="reservate"></svg-wrapper>


text:
App that checks Swiss trains and notifies you in HipChat if any of them have some delay.

## Features

- Check trains delays from official [Swiss transport APIs](http://transport.opendata.ch/).
- Notify in a HipChat room if some train have some delay.

## Getting Started

- Add `prod.env` file in the project root.

```
export HIPCHAT_TOKEN='YOUR HIPCHAT ROOM TOKEN';
export HIPCHAT_ROOM_ID='YOUR HIPCHAT ROOM ID';
export SLACK_WEBHOOK_URL='YOUR SLACK INCOMING WEBHOOK URL';
```
- Change constants inside `./libs/core/config.js` to satisfy your needs.
- `npm install`
- `npm start`
- Never run to catch a delayed train again!

## Run docker

`docker run -e HIPCHAT_TOKEN='<YOUR_HIPCHAT_ROOM_TOKEN>' -e HIPCHAT_ROOM_ID='<YOUR_HIPCHAT_ROOM_ID>' -e SLACK_WEBHOOK_URL='YOUR SLACK WEBHOOK URL' --init -d matitalatina/ffs-delay`


text:
package com.rey.material.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rey.material.R;
import com.rey.material.drawable.RippleDrawable;
import com.rey.material.util.ThemeUtil;
import com.rey.material.util.ViewUtil;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class TabPageIndicator extends HorizontalScrollView implements ViewPager.OnPageChangeListener, android.view.View.OnClickListener{

	private LinearLayout mTabContainer;
	private ViewPager mViewPager;

	private int mMode;
	private int mTabPadding;
	private int mTabRippleStyle;
	private int mTextAppearance;

	private int mIndicatorOffset;
	private int mIndicatorWidth;
	private int mIndicatorHeight;

	private Paint mPaint;

	public static final int MODE_SCROLL = 0;
	public static final int MODE_FIXED = 1;

	private int mSelectedPosition;
	private boolean mScrolling = false;

	private Runnable mTabAnimSelector;

	private ViewPager.OnPageChangeListener mListener;

	private DataSetObserver mObserver = new DataSetObserver(){

		@Override
		public void onChanged() {
			notifyDataSetChanged();
		}

		@Override
		public void onInvalidated() {
			notifyDataSetInvalidated();
		}

	};

	public TabPageIndicator(Context context) {
		super(context);

		init(context, null, 0, 0);
	}

	public TabPageIndicator(Context context, AttributeSet attrs) {
		super(context, attrs);

		init(context, attrs, 0, 0);
	}

	public TabPageIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);

		init(context, attrs, defStyleAttr, 0);
	}

    public TabPageIndicator(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr);

        init(context, attrs, defStyleAttr, defStyleRes);
    }

	private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){
		setHorizontalScrollBarEnabled(false);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);

        mTabContainer = new LinearLayout(context);
        mTabContainer.setOrientation(LinearLayout.HORIZONTAL);
        mTabContainer.setGravity(Gravity.CENTER);

        applyStyle(context, attrs, defStyleAttr, defStyleRes);

		if(isInEditMode())
			addTemporaryTab();
	}

    public void applyStyle(int resId){
        applyStyle(getContext(), null, 0, resId);
    }

    private void applyStyle(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TabPageIndicator, defStyleAttr, defStyleRes);

        mTabPadding = a.getDimensionPixelSize(R.styleable.TabPageIndicator_tpi_tabPadding, ThemeUtil.dpToPx(context, 12));
        mTabRippleStyle = a.getResourceId(R.styleable.TabPageIndicator_tpi_tabRipple, 0);
        int indicatorColor = a.getColor(R.styleable.TabPageIndicator_tpi_indicatorColor, ThemeUtil.colorAccent(context, 0xFFFFFFFF));
        mIndicatorHeight = a.getDimensionPixelSize(R.styleable.TabPageIndicator_tpi_indicatorHeight, ThemeUtil.dpToPx(context, 2));
        mTextAppearance = a.getResourceId(R.styleable.TabPageIndicator_android_textAppearance, 0);
        mMode = a.getInteger(R.styleable.TabPageIndicator_tpi_mode, MODE_SCROLL);

        a.recycle();

        removeAllViews();
        if(mMode == MODE_SCROLL) {
            addView(mTabContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
            setFillViewport(false);
        }
        else if(mMode == MODE_FIXED){
            addView(mTabContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            setFillViewport(true);
        }

        mPaint.setColor(indicatorColor);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        // Re-post the selector we saved
        if (mTabAnimSelector != null)
            post(mTabAnimSelector);
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mTabAnimSelector != null)
            removeCallbacks(mTabAnimSelector);
    }

    private CheckedTextView getTabView(int position){
    	return (CheckedTextView)mTabContainer.getChildAt(position);
    }

    private void animateToTab(final int position) {
    	final CheckedTextView tv = getTabView(position);
    	if(tv == null)
    		return;

        if (mTabAnimSelector != null)
            removeCallbacks(mTabAnimSelector);

        mTabAnimSelector = new Runnable() {
            public void run() {
            	if(!mScrolling)
                	updateIndicator(tv.getLeft(), tv.getWidth());

                smoothScrollTo(tv.getLeft() - (getWidth() - tv.getWidth()) / 2 + getPaddingLeft(), 0);
                mTabAnimSelector = null;
            }
        };

        post(mTabAnimSelector);
    }

    /**
     * Set a listener will be called when the current page is changed.
     * @param listener The {@link android.support.v4.view.ViewPager.OnPageChangeListener} will be called.
     */
	public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mListener = listener;
    }

    /**
     * Set the ViewPager associate with this indicator view.
     * @param view The ViewPager view.
     */
    public void setViewPager(ViewPager view) {
        if (mViewPager == view)
            return;

        if (mViewPager != null){
            mViewPager.setOnPageChangeListener(null);
            PagerAdapter adapter = view.getAdapter();
            if(adapter != null)
            	adapter.unregisterDataSetObserver(mObserver);
        }

        PagerAdapter adapter = view.getAdapter();
        if (adapter == null)
            throw new IllegalStateException("ViewPager does not have adapter instance.");

        adapter.registerDataSetObserver(mObserver);

        mViewPager = view;
        view.setOnPageChangeListener(this);

        notifyDataSetChanged();
    }

    /**
     * Set the ViewPager associate with this indicator view and the current position;
     * @param view The ViewPager view.
     * @param initialPosition The current position.
     */
    public void setViewPager(ViewPager view, int initialPosition) {
    	setViewPager(view);
        setCurrentItem(initialPosition);
    }

    private void updateIndicator(int offset, int width){
		mIndicatorOffset = offset;
		mIndicatorWidth = width;
		invalidate();
	}

	@Override
	public void draw(@NonNull Canvas canvas) {
		super.draw(canvas);

		int x = mIndicatorOffset + getPaddingLeft();
		canvas.drawRect(x, getHeight() - mIndicatorHeight, x + mIndicatorWidth, getHeight(), mPaint);

		if(isInEditMode())
			canvas.drawRect(getPaddingLeft(), getHeight() - mIndicatorHeight, getPaddingLeft() + mTabContainer.getChildAt(0).getWidth(), getHeight(), mPaint);
	}

	@Override
	public void onPageScrollStateChanged(int state) {
		if(state == ViewPager.SCROLL_STATE_IDLE){
			mScrolling = false;
			TextView tv = getTabView(mSelectedPosition);
			if(tv != null)
				updateIndicator(tv.getLeft(), tv.getMeasuredWidth());
		}
		else
			mScrolling = true;

		if (mListener != null)
			mListener.onPageScrollStateChanged(state);
	}

	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		if (mListener != null)
            mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);

		CheckedTextView tv_scroll = getTabView(position);
		CheckedTextView tv_next = getTabView(position + 1);

		if(tv_scroll != null && tv_next != null){
			int width_scroll = tv_scroll.getWidth();
			int width_next = tv_next.getWidth();
			float distance = (width_scroll + width_next) / 2f;

			int width =  (int)(width_scroll + (width_next - width_scroll) * positionOffset + 0.5f);
			int offset = (int)(tv_scroll.getLeft() + width_scroll / 2f + distance * positionOffset - width / 2f + 0.5f);
			updateIndicator(offset, width);
		}
	}

	@Override
	public void onPageSelected(int position) {
		setCurrentItem(position);
        if (mListener != null)
            mListener.onPageSelected(position);
	}

	@Override
	public void onClick(android.view.View v) {
		int position = (Integer)v.getTag();
		if(position == mSelectedPosition && mListener != null)
			mListener.onPageSelected(position);

		mViewPager.setCurrentItem(position, true);
	}

    /**
     * Set the current page of this TabPageIndicator.
     * @param position The position of current page.
     */
	public void setCurrentItem(int position) {
		if(mSelectedPosition != position){
			CheckedTextView tv = getTabView(mSelectedPosition);
			if(tv != null)
				tv.setChecked(false);
		}

		mSelectedPosition = position;
		CheckedTextView tv = getTabView(mSelectedPosition);
		if(tv != null)
			tv.setChecked(true);

		animateToTab(position);
	}

	private void notifyDataSetChanged() {
		mTabContainer.removeAllViews();

		PagerAdapter adapter = mViewPager.getAdapter();
		final int count = adapter.getCount();

		if (mSelectedPosition > count)
        	mSelectedPosition = count - 1;

        for (int i = 0; i < count; i++) {
            CharSequence title = adapter.getPageTitle(i);
            if (title == null)
                title = "NULL";

            CheckedTextView tv = new CheckedTextView(getContext());
            tv.setCheckMarkDrawable(null);
            tv.setText(title);
            tv.setGravity(Gravity.CENTER);
            tv.setTextAppearance(getContext(), mTextAppearance);
            tv.setSingleLine(true);
            tv.setEllipsize(TruncateAt.END);
            tv.setOnClickListener(this);
            tv.setTag(i);
            if(mTabRippleStyle > 0)
                ViewUtil.setBackground(tv, new RippleDrawable.Builder(getContext(), mTabRippleStyle).build());

            if(mMode == MODE_SCROLL){
            	tv.setPadding(mTabPadding, 0, mTabPadding, 0);
            	mTabContainer.addView(tv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
            }
            else if(mMode == MODE_FIXED){
            	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
            	params.weight = 1f;
            	mTabContainer.addView(tv, params);
            }

        }

        setCurrentItem(mSelectedPosition);
        requestLayout();
	}

	private void notifyDataSetInvalidated() {
		PagerAdapter adapter = mViewPager.getAdapter();
		final int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
        	TextView tv = getTabView(i);

        	CharSequence title = adapter.getPageTitle(i);
            if (title == null)
                title = "NULL";

            tv.setText(title);
        }

        requestLayout();
	}

	private void addTemporaryTab(){
		for (int i = 0; i < 3; i++) {
            CharSequence title = null;
            if (i == 0)
                title = "TAB ONE";
            else if (i == 1)
                title = "TAB TWO";
            else if (i == 2)
                title = "TAB THREE";

            CheckedTextView tv = new CheckedTextView(getContext());
            tv.setCheckMarkDrawable(null);
            tv.setText(title);
            tv.setGravity(Gravity.CENTER);
            tv.setTextAppearance(getContext(), mTextAppearance);
            tv.setSingleLine(true);
            tv.setEllipsize(TruncateAt.END);
            tv.setTag(i);
            tv.setChecked(i == 0);
            if(mMode == MODE_SCROLL){
            	tv.setPadding(mTabPadding, 0, mTabPadding, 0);
            	mTabContainer.addView(tv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
            }
            else if(mMode == MODE_FIXED){
            	LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
            	params.weight = 1f;
            	mTabContainer.addView(tv, params);
            }
        }
	}
}


text:
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

default_args = {
    'owner': 'airflow',
    'depends_on_past': False,
    'start_date': datetime.now(),
    'email': ['chris@fregly.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 0,
    'retry_delay': timedelta(minutes=5),
    # 'queue': 'bash_queue',
    # 'pool': 'backfill',
    # 'priority_weight': 10,
    # 'end_date': datetime(2016, 4, 24),
}

dag = DAG('update_sparksubmit_pyspark', default_args=default_args)
#, schedule_interval=timedelta(0))

pull_git = BashOperator(
    task_id='pull_git',
    bash_command='cd /root/pipeline && git pull',
    dag=dag)

# t1 is an example of tasks created by instatiating operators
sparksubmit_pyspark = BashOperator(
    task_id='sparksubmit_pyspark',
    bash_command='spark-submit --master local[*] /root/pipeline/jupyterhub.ml/scripts/pi.py 10',
    dag=dag)

# Setup Airflow DAG
sparksubmit_pyspark.set_upstream(pull_git)


text:
var app = angular.module('GroupStore');

app.service('orderService', function($http, $q){

	this.createOrder = function(order) {
		return $http({
			method: 'POST',
			url: '/api/user/order',
			data: order
		})
	};

	this.getOrderDetails = function(id) {
		return $http({
			method: 'GET',
			url: '/api/admin/order/' + id
		})
	};

	this.getAllOrders = function() {
		return $http({
			method: 'GET',
			url: '/api/admin/orders'
		})
	};

	this.updateOrder = function(id, orderObj) {
		return $http({
			method: 'PUT',
			url: '/api/admin/order/' + id,
			data: orderObj
		})
	};

	this.updateOrderByPaymentId = function(orderObj){
		console.log('what is this', orderObj)
		return $http({
			method: 'PUT',
			url: '/api/user/order/' + orderObj.paymentId,
			data: orderObj
		})
	};

	this.emptyCart = function() {
		return $http({
			method: 'DELETE',
			url: '/api/user/cart'
		})
	}

});


text:
require 'spec_helper'

module Arel
  describe Join do
    before do
      @relation1 = Table.new(:users)
      @relation2 = Table.new(:photos)
      @predicate = @relation1[:id].eq(@relation2[:user_id])
    end

    describe '#attributes' do
      it 'combines the attributes of the two relations' do
        join = InnerJoin.new(@relation1, @relation2, @predicate)
        join.attributes.should == (@relation1.attributes | @relation2.attributes).bind(join)
      end
    end
  end
end


text:
package com.effektif.workflow.test.timer;

import static org.junit.Assert.assertEquals;

import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDateTime;
import org.junit.Test;

import com.effektif.workflow.api.model.NextRelativeTime;
import com.effektif.workflow.api.model.RelativeTime;
import com.effektif.workflow.test.WorkflowTest;

/**
 * @author Tom Baeyens
 */
public class RelativeTimeTest extends WorkflowTest {

  @Test
  public void testIn5Minutes() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = RelativeTime.minutes(5).resolve(base);
    assertEquals(base.plusMinutes(5), absoluteTime);
  }

  @Test
  public void testIn7Hours() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = RelativeTime.hours(7).resolve(base);
    assertEquals(base.plusHours(7), absoluteTime);
  }

  @Test
  public void testIn20Days() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = RelativeTime.days(20).resolve(base);
    assertEquals(endOfDay(base.plusDays(20)), absoluteTime);
  }

  @Test
  public void testIn3Weeks() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = RelativeTime.weeks(3).resolve(base);
    assertEquals(endOfDay(base.plusWeeks(3)), absoluteTime);
  }

  @Test
  public void testIn9Months() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = RelativeTime.months(9).resolve(base);
    assertEquals(endOfDay(base.plusMonths(9)), absoluteTime);
  }

  @Test
  public void testIn4Years() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = RelativeTime.years(4).resolve(base);
    assertEquals(endOfDay(base.plusYears(4)), absoluteTime);
  }

  @Test
  public void testTomorrowAt11() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = RelativeTime.days(1).at(11,00).resolve(base);
    assertEquals(base
            .plusDays(1)
            .withTime(11, 0, 0, 0), absoluteTime);
  }

  @Test
  public void testNextThursday() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = NextRelativeTime
      .dayOfWeek(DateTimeConstants.THURSDAY)
      .resolve(base);
    assertEquals(base
            .withDayOfWeek(DateTimeConstants.THURSDAY)
            .withTime(0, 0, 0, 0), absoluteTime);
  }

  @Test
  public void testNextThursdayAt15() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = NextRelativeTime
      .dayOfWeek(DateTimeConstants.THURSDAY)
      .at(15,30)
      .resolve(base);
    assertEquals(base
            .withDayOfWeek(DateTimeConstants.THURSDAY)
            .withTime(15, 30, 0, 0), absoluteTime);
  }

  @Test
  public void testNextFirstOfTheMonth() {
    LocalDateTime base = new LocalDateTime(2015, 12, 28, 9, 0, 0, 0);
    LocalDateTime absoluteTime = NextRelativeTime
      .dayOfMonth(1)
      .resolve(base);
    assertEquals(new LocalDateTime(2016, 1, 1, 0, 0, 0, 0), absoluteTime);
  }

  private Object endOfDay(LocalDateTime time) {
    return time.withTime(23, 59, 59, 999);
  }
}


text:
This page summarizes common error scenarios when running the pipeline and
provide recommanded workarounds. If you are still unable to successfully load
or export your VCF files, please post on the
[google-genomics-discuss](https://groups.google.com/forum/#!forum/google-genomics-discuss)
group or file a GitHub issue if you believe that there is a bug in the pipeline.

## Pipeline is too slow

* Try increasing `--max_num_workers`.
* Try changing `--worker_machine_type` to a larger machine (e.g.
  `n1-standard-32`). See
  [predefined machine types](https://cloud.google.com/compute/pricing#predefined_machine_types)
  for the full list.
* Ensure you have enough [quota](https://cloud.google.com/compute/quotas) in the
  region running the pipeline. You need to [set a region](./setting_region.md)
  for running the pipeline by specifying `--region <region>`. You can check for
  quota issues by navigating to the [Compute Engine quotas page](https://console.cloud.google.com/iam-admin/quotas?service=compute.googleapis.com)
  while the pipeline is running, which shows saturated quotas at the top of the
  page (highlighted in red).
* Ensure your source GCS bucket is located in the same region as where you are
  running your Dataflow pipeline. According to [data
  locality](https://cloud.google.com/dataflow/docs/concepts/regional-endpoints#data_locality)
  guidelines the GCS bucket containing your VCF files as well as the temporary
  directory of your pipeline should be located in the same region as your
  Dataflow pipeline.
* `gzip` and `bzip2` file formats cannot be sharded, which considerably slows
  down the pipeline. Consider decompressing the files prior to running the
  pipeline. You may use [dsub](https://github.com/googlegenomics/dsub) to write
  a script to decompress the files in scalable manner. Note that this is only an
  issue if running the pipeline with a small number of large files (i.e. running
  with a large number of small files is usually fine as each file can be read by
  a separate process).

See [handling large inputs](./large_inputs.md) for more details.

## Pipeline crashes due to out of disk error

Try increasing the disk size allocated to each worker by specifying
`--disk_size_gb <disk_size>` and/or increasing the number of workers by
specifying `--max_num_workers <num_workers>`. By default, each worker gets 250GB
of disk, and the aggregate disk size available to all workers should be at least
as large as the uncompressed size of the VCF files being loaded. However, to
accomoddate for intermediate stages of the pipeline and also to account for
the additional overhead introduced by the transforms, the aggregate disk size
among all workers should be at least 3 to 4 times the total size of raw VCF
files.

See [handling large inputs](./large_inputs.md) for more details.

## Error: "JSON parsing error ... No such field: <field_name>"

If you see an error in the form,
`Error while reading data, error message: JSON parsing error in row starting at
position 0: No such field: <field_name>`, it means that the `<field_name>`
is missing from the BigQuery schema, which is caused by its definition missing
from a VCF header file.

You can fix this by:

* Changing the VCF file containing the field and adding an entry in the header
  with proper definition. For instance, if the error is for the field `AF`, you
  can add the following to the VCF file:

  ```
  ##INFO=<ID=AF,Number=A,Type=Float,Description="Allele Frequency">
  ```

  Note that it's important to provide valid `Type` and `Number` for the field.
  If unsure, you can provide `Type=String` and `Number=.` (i.e. a generic list
  of strings), which will match any field. Please also check whether the
  missing field is for `##INFO` or `##FORMAT`.

* If changing the file(s) is not an option, you can also run the pipeline with
  `--representative_header_file <file_path>`, where you provide a merged view
  of all headers in all files. You can add any missing fields to that file.
  We are working on a tool to make this process easier and provide
  recommendations for missing fields.

* Run the pipeline with `--infer_headers`. This will do two passes on the data
  and will infer definition for undefined headers and mismatched headers (header
  field definition does not match the field value). You do not need to make any
  changes to the VCF files or provide a representative header file. However,
  running with this option adds ~30% more compute to the pipeline.

## Error: "BigQuery schema has no such field"

Same as [above](#error-json-parsing-error--no-such-field-field_name).

## BigQuery to VCF fails: "A work item was attempted 4 times without success."

The error "Each time the worker eventually lost contact with the service." may
relate to insufficient memory.

* Try changing `--worker_machine_type` to a larger machine (e.g.
  `n1-standard-64`). See
  [predefined machine types](https://cloud.google.com/compute/pricing#predefined_machine_types)
  for the full list.

* Try lowering the value of `--number_of_bases_per_shard` (e.g. `10000`)


text:
package org.openqa.selenium.remote;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.common.collect.ImmutableMap;

import org.junit.Test;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.Platform;

import java.io.IOException;
import java.util.UUID;

public class RemoteWebDriverInitializationTest {
  private boolean quitCalled = false;

  @Test
  public void testQuitsIfStartSessionFails() {
    assertThatExceptionOfType(RuntimeException.class)
        .isThrownBy(() -> new BadStartSessionRemoteWebDriver(mock(CommandExecutor.class), new ImmutableCapabilities()))
        .withMessageContaining("Stub session that should fail");

    assertThat(quitCalled).isTrue();
  }

  @Test
  public void canHandleNonStandardCapabilitiesReturnedByRemoteEnd() throws IOException {
    Response resp = new Response();
    resp.setSessionId(UUID.randomUUID().toString());
    resp.setValue(ImmutableMap.of("platformName", "xxx"));
    CommandExecutor executor = mock(CommandExecutor.class);
    when(executor.execute(any())).thenReturn(resp);
    RemoteWebDriver driver = new RemoteWebDriver(executor, new ImmutableCapabilities());
    assertThat(driver.getCapabilities().getCapability("platform")).isEqualTo(Platform.UNIX);
  }

  private class BadStartSessionRemoteWebDriver extends RemoteWebDriver {
    public BadStartSessionRemoteWebDriver(CommandExecutor executor,
                                          Capabilities desiredCapabilities) {
      super(executor, desiredCapabilities);
    }

    @Override
    protected void startSession(Capabilities desiredCapabilities) {
      throw new RuntimeException("Stub session that should fail");
    }

    @Override
    public void quit() {
      quitCalled = true;
    }
  }
}


text:
package org.consumersunion.stories.common.shared.model;

import java.util.List;

import org.consumersunion.stories.common.shared.model.document.Block;

public interface HasBlocks {
    List<Block> getBlocks();

    void setBlocks(List<Block> blocks);
}


text:
namespace Gearset.Components {
    /// <summary>
    ///     Shows labels of text in 2D positions or 3d (TODO)s unprojected positions.
    /// </summary>
    public sealed class Labeler : InternalLabeler {
        public Labeler()
            : base(GearsetSettings.Instance.LabelerConfig) {}
    }
}


text:
package program;

public class Program {

	public void run() {
		// TODO Auto-generated method stub
		init();
		while (running) {
			loop();
		}
	}

}


text:
@interface BoundFetchedResultsDataSourceDelegate : NSObject<UITableViewDataSource, UITableViewDelegate>

#pragma mark - Properties

@property(nonatomic) NSManagedObjectContext     *managedObjectContext;
@property(nonatomic) NSFetchedResultsController *fetchedResultsController;

// If no fetchedResultsController is specified, the following properties will be used to create one.
@property(nonatomic) Class                entityClass;         // | or
@property(nonatomic) NSString            *entityName;          // |
@property(nonatomic) NSString            *cellReuseIdentifier; // Default: entity name
@property(nonatomic) NSString            *sectionNameKeyPath;  // Optional

@property(copy) void(^doOnError)(NSError*); //defaults to log and abort
@property(nonatomic, readonly) NSArray         *selectedObjects;
@property(nonatomic, readonly) NSManagedObject *selectedObject;

#pragma mark - Object Access

-(NSManagedObject*)objectAtIndexPath:(NSIndexPath*)i;
-(NSIndexPath*)indexPathForObject:(id)o;

-(void)selectObject:(id)o scrollPosition:(UITableViewScrollPosition)scrollPosition;
-(void)deselectObject:(id)o;

//Configure these:
-(void)didSelectObject:(id)o;
-(void)didDeselectObject:(id)o;

-(void)configureCell:(UITableViewCell*)cell atIndexPath:(NSIndexPath*)indexPath with:(id)object;
-(void)configureCell:(UITableViewCell*)cell atIndexPath:(NSIndexPath*)indexPath;
@end


text:
//
//  TableViewController.m
//  pmEvent
//

#import "TableViewController.h"
#import "CalendarEvent.h"
#import "Model.h"
#import "DateCategory.h"
#import "CustomSheet.h"

@implementation TableViewController

@synthesize dateOfEvents;
@synthesize window;

- (id)init
{
    self = [super init];
    if (self) {
        dateOfEvents = [[NSDate date]retain];

        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

        [nc addObserver:self selector:@selector(eventsChanged:) name:CalEventsChangedExternallyNotification object:nil];
        [nc addObserver:self selector:@selector(eventsChanged:) name:CalEventsChangedNotification object:nil];
        [nc addObserver:self selector:@selector(eventsChanged:) name:CalCalendarsChangedExternallyNotification object:nil];
        [nc addObserver:self selector:@selector(dateChanged:)   name:PMDateChangedNotification object:nil];
    }

    return self;
}

- (void)awakeFromNib
{
    [self setNextResponder:[window contentView]];
    [tableView setNextResponder:self];
    [tableView setDoubleAction:@selector(doubleClickAction)];
}

- (void)eventsChanged:(NSNotification *)notification
{
    [self willChangeValueForKey:@"events"];
    [self didChangeValueForKey:@"events"];
}

- (void)dateChanged:(NSNotification *)notification
{
    [self willChangeValueForKey:@"events"];
    self.dateOfEvents = [[notification userInfo] objectForKey:@"startDate"];
    [self didChangeValueForKey:@"events"];
}

- (NSArray*)events
{
	return [CalendarEvent eventsOnDate:self.dateOfEvents];
}

#pragma mark -
#pragma mark Key Events

-(void)keyDown:(NSEvent *)event
{
    NSInteger row = [tableView selectedRow];

    if (row >= 0) {
        NSString *str = [event charactersIgnoringModifiers];
        if ([str isEqualToString: @" "]){
            [popoverController togglePopover:tableView];
            return;
        }

        unichar keyChar = [str characterAtIndex:0];
        if (keyChar == NSDeleteCharacter || keyChar == NSDeleteFunctionKey) {
            [self deleteEvent:tableView];
            if ([tableView numberOfRows] < 1) {
                [popoverController closePopover:tableView];
                [window makeFirstResponder:[window initialFirstResponder]];
            }
            return;
        }
    }
    if ([event type] == NSKeyDown) {
        if ([event keyCode] == 53) {
            // Escape
            [popoverController closePopover:tableView];
            return;
        }
    }
    [super keyDown:event];
}

- (void)cancelOperation:(id)sender
{
    [popoverController closePopover:tableView];
}

#pragma mark -
#pragma mark Mouse Events

- (void)doubleClickAction
{
    [popoverController togglePopover:tableView];
}

- (void)rightMouseDown:(NSEvent *)event
{
    [popoverController togglePopover:tableView];
}

#pragma mark -
#pragma mark IBActions

- (IBAction)deleteEvent:(id)sender
{
    CalEvent *evt = [[eventArrayController selectedObjects]objectAtIndex:0];

    // check if the event covers multiple days
    NSInteger pastDays = [evt.endDate pastDaysSinceDate:evt.startDate];
    if ([evt.endDate isEqualToDate:[evt.endDate dateAtMidnight]]) {
        //  end day that ends at midnight does not count
        pastDays--;
    }
    if (pastDays > 0) {
        // Event covers multiple days
        CustomSheet *sheet = [CustomSheet sheetWithTitle:[NSString stringWithFormat:@"Event covers %d days.", (int)pastDays +1]
                                         informativeText:@"Do you really want to delete this event?"
                                           defaultButton:@"Delete"
                                         alternateButton:@"Cancel"];
        if ([sheet runModalForWindow:[sender window]] != CSDefaultReturn) {
            return;
        }
    }

    /* ToDo: enhance deleting a multi-occurence event
     *
     *      4y ago ------------------>| start ------------------ end |<-------------------------- distant future
     */
    NSArray *pastEvents   = [CalendarEvent eventsWithUID:[evt uid] startDate:[evt.startDate dateFourYearsAgo] endDate:evt.startDate];
    NSArray *futureEvents = [CalendarEvent eventsWithUID:[evt uid] startDate:evt.endDate endDate:[NSDate distantFuture]];

    //DLog(@"past:%ld  future:%ld",[pastEvents count], [futureEvents count]);

    CalSpan span = CalSpanThisEvent;

    if ([pastEvents lastObject] || [futureEvents lastObject]) {
        CustomSheet *sheet = [CustomSheet sheetWithTitle:@"This is a multi-occurrence event."
                                         informativeText:@"Delete all occurrences of this event?"
                                           defaultButton:@"Delete"
                                         alternateButton:@"Cancel"];
        if ([sheet runModalForWindow:[sender window]] == CSDefaultReturn) {
            span = CalSpanAllEvents;
        } else {
            return;
        }
    }

    NSUndoManager *undoManager = [sender undoManager];
    [undoManager setActionName:@"Remove Event"];
    [[undoManager prepareWithInvocationTarget:[CalendarEvent class]] saveEvent:evt span:span];
    [CalendarEvent removeEvent:evt span:span];
    if ([[eventArrayController arrangedObjects]lastObject] == nil) {
        [[sender window] makeFirstResponder:[[sender window] initialFirstResponder]];
    }
}

- (IBAction)launchIcal:(id)sender
{
    NSString *source;
    if ([[eventArrayController selectedObjects]lastObject]) {
        // open iCal, show existing event
        CalEvent *calEvent = [[eventArrayController selectedObjects]objectAtIndex:0];

        source = [NSString stringWithFormat:@"tell application \"iCal\" \n activate\n"
                            "tell calendar \"%@\" \n set MyEvent to first event whose uid=\"%@\" \n end tell\n"
                            "if MyEvent is not null then \n show MyEvent\n end if\n"
                            "end tell", calEvent.calendar.title, calEvent.uid];

    } else {
        // open iCal on date
        source = [NSString stringWithFormat:@"tell application \"iCal\"\n"
                            "view calendar at date \"%@\" \n activate\n end tell", [dateOfEvents descriptionIcalDate]];
    }

    NSDictionary *errorInfo = [NSDictionary dictionary];
    NSAppleScript *script = [[NSAppleScript alloc] initWithSource:source];

    if ([script executeAndReturnError:&errorInfo] == nil) {

        NSString *msg  = [NSString stringWithFormat:@"%@ (Error %@)",
                            [errorInfo objectForKey:@"NSAppleScriptErrorMessage"],
                            [errorInfo objectForKey:@"NSAppleScriptErrorNumber"]];
        NSAlert *alert = [NSAlert alertWithMessageText:msg
                                         defaultButton:@"OK"
                                       alternateButton:nil
                                           otherButton:nil
                             informativeTextWithFormat:@""];
        [alert setAlertStyle:NSCriticalAlertStyle];
        [alert runModal];
    }
    [script release];
}

#pragma mark -

- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [super dealloc];
}
@end


text:
TEST_FILES=('data' 'notebooks' 'scripts' 'test_workflow' 'data.csv' 'example.jsonl' 'quilt_summarize.json' 'vega.json')
echo "Removing files and directories created by tests..."
for x in $TEST_FILES; do
  echo " - " $x
  rm -rf $x
done


text:
package ca.shoaib.searchcontacts;

import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;

public class SearchContactsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_contacts);
        initSearchView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search_contacts, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void initSearchView() {
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        final SearchView searchView = (SearchView) findViewById(R.id.searchView);
        SearchableInfo searchableInfo = searchManager.getSearchableInfo(getComponentName());
        searchView.setSearchableInfo(searchableInfo);
    }
}


text:
@section('meta')
<meta property="og:title" content="{{ $ad->content->title }}" />
<meta property="og:url" content="{{ route('ad.show', array($ad->id, str_slug($ad->content->title))) }}" />
<meta property="og:description" content="{{ str_limit($ad->content->body, 150) }}" />
{{--*/ $mainPhoto = $ad->photos()->main()->first();  /*--}}
@if ($mainPhoto)
<meta property="og:image" content="{{ image_route('large', $mainPhoto->path) }}" />
<meta property="og:image:alt" content="{{ $ad->content->title }}" />
@endif
@append

    @if (Route::is('ad.preview'))

 {!! trans('frontend.ad.preview_mode') !!}

      @if ($ad->adstatus->title == 'validate')
         {!! trans('frontend.ad.validated_ad') !!}
      @elseif ($ad->adstatus->title == 'pending')
         {!! trans('frontend.ad.pending_ad') !!}
      @elseif ($ad->adstatus->title == 'expired')
         {!! trans('frontend.ad.expired_ad') !!}
      @elseif ($ad->adstatus->title == 'banned')
         {!! trans('frontend.ad.banished_ad') !!}
      @elseif ($ad->adstatus->title == 'trashed')
         {!! trans('frontend.ad.trashed_ad') !!}
      @endif

    @endif

{{ $ad->content->title }}

              @if ($ad->adstatus->title == 'validate')
              {!! trans('frontend.user.ad.published_at', ['time' => $ad->published_at->diffForHumans()]) !!}
              @elseif ($ad->adstatus->title == 'expired')
              {!! trans('frontend.user.ad.expired_at', ['time' => $ad->expired_at->diffForHumans()]) !!}
              @else
              {!! trans('frontend.user.ad.created_at', ['time' => $ad->created_at->diffForHumans()]) !!}
              @endif

            @if (($price = $ad->price()) && isset($price->pivot))

              {{ number_format($price->pivot->value, trans('frontend.format.number.decimals') , trans('frontend.format.number.dec_point'), trans('frontend.format.number.thousands_sep')) }}

              {{ getAdCurrency($ad, $price->unit) }}

            @endif

        {{--*/ $photos = $ad->photos;  /*--}}
        @if ($photos->count())

              @foreach ($photos as $photo)

path) }}" alt="{{ $ad->content->title }}" title="{{ $ad->content->title }}" />

              @endforeach

        @if ($photos->count() > 1)

            @foreach ($photos as $key => $photo)
              path) }}" alt="{{ $ad->content->title }}" title="{{ $ad->content->title }}" />
            @endforeach

        @endif
        @endif

        @if ($ad->videos()->count())

videos }}">

        @endif

        @if ($fields->count())

category->id) }}">

        @endif

{{ $ad->content->body }}


text:
<?php

//DO NOT test this code on production
//it will merge leads permanently
$delete = new MergeLead();
$delete->id = 40000;
$delete->leadIds = array(10000, 20000, 30000);
print_r($delete->postData());

class MergeLead{
	private $host = "";//CHANGE ME
	private $clientId = "";//CHANGE ME
	private $clientSecret = "";//CHANGE ME
	public $id;//winning lead id
	public $leadIds; //array of one or more losing IDs

	public function postData(){
		$url = $this->host . "/rest/v1/leads/" . $this->id ."/merge.json?access_token=" . $this->getToken() . "&leadIds=" . $this::csvString($this->leadIds);
		$ch = curl_init($url);
		curl_setopt($ch,  CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json','Content-Type: application/json'));
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_getinfo($ch);
		$response = curl_exec($ch);
		return $response;
	}

	private function getToken(){
		$ch = curl_init($this->host . "/identity/oauth/token?grant_type=client_credentials&client_id=" . $this->clientId . "&client_secret=" . $this->clientSecret);
		curl_setopt($ch,  CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('accept: application/json',));
		$response = json_decode(curl_exec($ch));
		curl_close($ch);
		$token = $response->access_token;
		return $token;
	}
	private static function csvString($fields){
		$csvString = implode(",", $fields);
		return $csvString;
	}
}


text:
package com.cc.custom.calender.demo;

import android.support.annotation.IntDef;

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

public class TXCalendarConst {

    public static final String INTENT_START_DATE = "intent.start.day";
    public static final String INTENT_END_DATE = "intent.end.day";
    public static final String INTENT_TYPE = "intent.type";

    /**
     * 类型
     */
    public static class Type {
        // 日
        public static final int DAY = 0;
        // 周
        public static final int WEEK = 1;
        // 月
        public static final int MONTH = 2;
        // 年
        public static final int YEAR = 3;

        @IntDef({ DAY, WEEK, MONTH, YEAR })
        @Retention(RetentionPolicy.SOURCE)
        public @interface TYPE {
        }
    }

    /**
     * 显示类型
     */
    public static class ShowType {
        // 普通数据
        public static final int TYPE_NORMAL = 0;
        // 占位数据
        public static final int TYPE_HOLDER = 1;

        @IntDef({ TYPE_NORMAL, TYPE_HOLDER })
        @Retention(RetentionPolicy.SOURCE)
        public @interface TYPE {
        }
    }
}


text:
<?php

namespace Ansas\Component\Locale;

use Exception;

/**
 * Class Localization
 *
 * Extends locales container class and enables localization via gettext(). Also this class can find all supported
 * translated locales dynamically.
 *
 * @package Ansas\Component\Locale
 * @author  Ansas Meyer <mail@ansas-meyer.de>
 */
class Localization extends Locales
{
    /**
     * Locale code set
     */
    const CODE_SET = 'UTF-8';

    /**
     * @var Locale Default (fallback) locale
     */
    protected $default;

    /**
     * @var string Locale path
     */
    protected $path;

    /**
     * @var string Locale domain
     */
    protected $domain;

    /**
     * @var array Translation map for virtual locale and domain
     */
    protected $maps;

    /**
     * Add map for a virtual locale.
     *
     * @param string $locale
     * @param array  $map
     *
     * @return $this
     */
    public function addMap($locale, $map)
    {
        // Get sanitized locale
        $locale = Locale::sanitizeLocale($locale);

        $this->maps[$locale] = $map;

        return $this;
    }

    /**
     * Add maps for virtual locales.
     *
     * @param array[] $maps
     *
     * @return $this
     */
    public function addMaps(array $maps)
    {
        foreach ($maps as $locale => $map) {
            $this->addMap($locale, $map);
        }

        return $this;
    }

    /**
     * Dynamically find all available locales.
     *
     * This class supports "virtual locales" because often not all locales are installed on the server. If you want to
     * use gettext() the used locale MUST be installed. This class uses the workaround via default internal
     * locale "C" and determining the locale via filename. The mapping is done automatically.
     *
     * All locales must be stored in a "locale" folder (specified via setPath() in this structure:
     * - <pathToLocale>/<locale>/LC_MESSAGES/<domain>.mo or
     * - <pathToLocale>/C/LC_MESSAGES/<domain>.<locale>.mo
     *
     * Examples:
     * - de_DE/LC_MESSAGES/default.mo or
     * - C/LC_MESSAGES/app.en_GB.mo
     *
     * @throws Exception
     */
    public function findAvailableLocales()
    {
        // Check for needed data
        $path   = $this->getPath();
        $domain = $this->getDomain();
        if (!$path || !$domain) {
            throw new Exception("Values for 'path' and 'domain' must be set.");
        }

        // Build regular expressions for finding domains and locales
        $regexLocale  = Locale::REGEX_LOCALE;
        $regexDefault = "/^{$regexLocale}\/LC_MESSAGES\/{$domain}\.mo$/ui";
        $regexVirtual = "/^(?<virtualLocale>C)\/LC_MESSAGES\/(?<virtualDomain>{$domain}[^a-z]{$regexLocale})\.mo$/ui";

        $glob = "{$path}/*/LC_MESSAGES/{$domain}*.mo";
        foreach (glob($glob) as $parse) {
            // Strip path prefix to fit regex
            $parse = str_replace($path . '/', '', $parse);

            // Check for default or virtual localized files
            if (preg_match($regexDefault, $parse, $found) || preg_match($regexVirtual, $parse, $found)) {
                $this->addLocale($found['locale']);
                if (!empty($found['virtualLocale'])) {
                    $map = [
                        'domain' => $found['virtualDomain'],
                        'locale' => $found['virtualLocale'],
                    ];
                    $this->addMap($found['locale'], $map);
                }
            }
        }

        return $this;
    }

    /**
     * Get default (fallback) locale.
     *
     * @return Locale|null
     */
    public function getDefault()
    {
        return $this->default;
    }

    /**
     * Get locale domain.
     *
     * @param bool $realDomain [optional] Get mapped value (if exists)
     *
     * @return string
     */
    public function getDomain($realDomain = false)
    {
        if ($realDomain) {
            return $this->getMap($this->getActive(), 'domain') ?: $this->domain;
        }

        return $this->domain;
    }

    /**
     * Get locale.
     *
     * @param bool $realLocale [optional] Get mapped value (if exists)
     *
     * @return string
     */
    public function getLocale($realLocale = false)
    {
        $active = $this->getActive();

        if (!$active) {
            return null;
        }

        if ($realLocale) {
            return $this->getMap($active, 'locale') ?: $active->getLocale();
        }

        return $active->getLocale();
    }

    /**
     * Get map for specified name.
     *
     * @param string|Locale $locale
     * @param string        $key
     *
     * @return array|null
     */
    public function getMap($locale, $key = null)
    {
        // Get sanitized locale
        $locale = Locale::sanitizeLocale($locale);

        if ($key) {
            return isset($this->maps[$locale][$key]) ? $this->maps[$locale][$key] : null;
        }

        return isset($this->maps[$locale]) ? $this->maps[$locale] : null;
    }

    /**
     * Get maps.
     *
     * @return array
     */
    public function getMaps()
    {
        return $this->maps;
    }

    /**
     * Get locale path.
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * {@inheritDoc}
     */
    public function setActive($locale)
    {
        parent::setActive($locale);

        // Check for needed data
        $domain = $this->getDomain(true);
        $path   = $this->getPath();
        $locale = $this->getLocale(true);

        if (!$path || !$domain) {
            throw new Exception("Values for 'path' and 'domain' must be set.");
        }

        // Set locale (must be incl. code set!)
        $locale = $locale . '.' . self::CODE_SET;
        setlocale(LC_ALL, $locale);
        setlocale(LC_NUMERIC, 'C');

        // Bind (virtual) locale and domain for gettext() usage
        bindtextdomain($domain, $path);
        bind_textdomain_codeset($domain, self::CODE_SET);
        textdomain($domain);

        return $this;
    }

    /**
     * Set the default locale.
     *
     * @param string|Locale $locale
     *
     * @return $this
     */
    public function setDefault($locale)
    {
        // Make sure locale is available (set it on list if not set yet)
        $this->addLocale($locale);

        // Mark as default locale
        $this->default = $this->findByLocale($locale);

        // Mark as current locale (if none set yet)
        if (!$this->getActive()) {
            $this->setActive($this->default);
        }

        return $this;
    }

    /**
     * Set domain.
     *
     * @param string $domain
     *
     * @return $this
     */
    public function setDomain($domain)
    {
        $this->domain = $domain;

        return $this;
    }

    /**
     * Set path.
     *
     * @param string $path
     *
     * @return $this
     */
    public function setPath($path)
    {
        $this->path = realpath($path);

        return $this;
    }
}


text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Increase Jasmine timeout.
jasmine.DEFAULT_TIMEOUT_INTERVAL = 180000;

/**
 * Before each it().
 */
beforeEach(function() {

    if (ISBROWSER) {
        // Set the window.
        if (ISTABLET) {
          browser.driver.manage().window().setSize(1024, 768);
        } else {
          browser.driver.manage().window().setSize(400, 640);
        }

        // Open the main URL.
        browser.driver.get(DEVICEURL);
    }

    // Wait for the login page.
    return browser.driver.wait(function() {
      return browser.driver.isElementPresent(by.id('mm-login-site')).then(function(e) {
        return e === true;
      });
    }, 50000);
});


text:
package org.apache.bookkeeper.client.api;

import org.apache.bookkeeper.common.annotation.InterfaceAudience.Public;
import org.apache.bookkeeper.common.annotation.InterfaceStability.Unstable;

/**
 * Builder-style interface to create new ledgers.
 *
 * @since 4.6
 * @see BookKeeper#newCreateLedgerOp()
 */
@Public
@Unstable
public interface CreateAdvBuilder extends OpBuilder<WriteAdvHandle> {

    /**
     * Set a fixed ledgerId for the newly created ledger. If no explicit ledgerId is passed a new ledger id will be
     * assigned automatically.
     *
     * @param ledgerId
     *
     * @return the builder itself
     */
    CreateAdvBuilder withLedgerId(long ledgerId);
}


text:
package org.apache.camel.component.zookeeper.cluster;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.camel.component.zookeeper.ZooKeeperCuratorConfiguration;
import org.apache.camel.component.zookeeper.ZooKeeperCuratorHelper;
import org.apache.camel.support.cluster.AbstractCamelClusterService;
import org.apache.camel.util.ObjectHelper;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.AuthInfo;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ZooKeeperClusterService extends AbstractCamelClusterService<ZooKeeperClusterView> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperClusterService.class);

    private CuratorFramework curator;
    private ZooKeeperCuratorConfiguration configuration;
    private boolean managedInstance;

    public ZooKeeperClusterService() {
        this.configuration = new ZooKeeperCuratorConfiguration();
        this.managedInstance = true;
    }

    public ZooKeeperClusterService(ZooKeeperCuratorConfiguration configuration) {
        this.configuration = configuration.copy();
        this.managedInstance = true;
    }

    // *********************************************
    // Properties
    // *********************************************

    public ZooKeeperCuratorConfiguration getConfiguration() {
        return configuration;
    }

    public void setConfiguration(ZooKeeperCuratorConfiguration configuration) {
        this.configuration = configuration.copy();
    }

    public CuratorFramework getCuratorFramework() {
        return configuration.getCuratorFramework();
    }

    public void setCuratorFramework(CuratorFramework curatorFramework) {
        configuration.setCuratorFramework(curatorFramework);
    }

    public List<String> getNodes() {
        return configuration.getNodes();
    }

    public void setNodes(String nodes) {
        configuration.setNodes(nodes);
    }

    public void setNodes(List<String> nodes) {
        configuration.setNodes(nodes);
    }

    public String getNamespace() {
        return configuration.getNamespace();
    }

    public void setNamespace(String namespace) {
        configuration.setNamespace(namespace);
    }

    public long getReconnectBaseSleepTime() {
        return configuration.getReconnectBaseSleepTime();
    }

    public void setReconnectBaseSleepTime(long reconnectBaseSleepTime) {
        configuration.setReconnectBaseSleepTime(reconnectBaseSleepTime);
    }

    public void setReconnectBaseSleepTime(long reconnectBaseSleepTime, TimeUnit reconnectBaseSleepTimeUnit) {
        configuration.setReconnectBaseSleepTime(reconnectBaseSleepTime, reconnectBaseSleepTimeUnit);
    }

    public TimeUnit getReconnectBaseSleepTimeUnit() {
        return configuration.getReconnectBaseSleepTimeUnit();
    }

    public void setReconnectBaseSleepTimeUnit(TimeUnit reconnectBaseSleepTimeUnit) {
        configuration.setReconnectBaseSleepTimeUnit(reconnectBaseSleepTimeUnit);
    }

    public int getReconnectMaxRetries() {
        return configuration.getReconnectMaxRetries();
    }

    public void setReconnectMaxRetries(int reconnectMaxRetries) {
        configuration.setReconnectMaxRetries(reconnectMaxRetries);
    }

    public long getSessionTimeout() {
        return configuration.getSessionTimeout();
    }

    public void setSessionTimeout(long sessionTimeout) {
        configuration.setSessionTimeout(sessionTimeout);
    }

    public void setSessionTimeout(long sessionTimeout, TimeUnit sessionTimeoutUnit) {
        configuration.setSessionTimeout(sessionTimeout, sessionTimeoutUnit);
    }

    public TimeUnit getSessionTimeoutUnit() {
        return configuration.getSessionTimeoutUnit();
    }

    public void setSessionTimeoutUnit(TimeUnit sessionTimeoutUnit) {
        configuration.setSessionTimeoutUnit(sessionTimeoutUnit);
    }

    public long getConnectionTimeout() {
        return configuration.getConnectionTimeout();
    }

    public void setConnectionTimeout(long connectionTimeout) {
        configuration.setConnectionTimeout(connectionTimeout);
    }

    public void setConnectionTimeout(long connectionTimeout, TimeUnit connectionTimeotUnit) {
        configuration.setConnectionTimeout(connectionTimeout, connectionTimeotUnit);
    }

    public TimeUnit getConnectionTimeoutUnit() {
        return configuration.getConnectionTimeoutUnit();
    }

    public void setConnectionTimeoutUnit(TimeUnit connectionTimeotUnit) {
        configuration.setConnectionTimeoutUnit(connectionTimeotUnit);
    }

    public List<AuthInfo> getAuthInfoList() {
        return configuration.getAuthInfoList();
    }

    public void setAuthInfoList(List<AuthInfo> authInfoList) {
        configuration.setAuthInfoList(authInfoList);
    }

    public long getMaxCloseWait() {
        return configuration.getMaxCloseWait();
    }

    public void setMaxCloseWait(long maxCloseWait) {
        configuration.setMaxCloseWait(maxCloseWait);
    }

    public TimeUnit getMaxCloseWaitUnit() {
        return configuration.getMaxCloseWaitUnit();
    }

    public void setMaxCloseWaitUnit(TimeUnit maxCloseWaitUnit) {
        configuration.setMaxCloseWaitUnit(maxCloseWaitUnit);
    }

    public RetryPolicy getRetryPolicy() {
        return configuration.getRetryPolicy();
    }

    public void setRetryPolicy(RetryPolicy retryPolicy) {
        configuration.setRetryPolicy(retryPolicy);
    }

    public String getBasePath() {
        return configuration.getBasePath();
    }

    public void setBasePath(String basePath) {
        configuration.setBasePath(basePath);
    }

    // *********************************************
    //
    // *********************************************

    @Override
    protected ZooKeeperClusterView createView(String namespace) throws Exception {

        // Validation
        ObjectHelper.notNull(getCamelContext(), "Camel Context");
        ObjectHelper.notNull(configuration.getBasePath(), "ZooKeeper base path");

        return new ZooKeeperClusterView(this, configuration, getOrCreateCurator(), namespace);
    }

    @Override
    protected void doStart() throws Exception {
        // instantiate a new CuratorFramework
        getOrCreateCurator();

        super.doStart();
    }

    @Override
    protected void doStop() throws Exception {
        super.doStop();

        if (curator != null && managedInstance) {
            curator.close();
        }
    }

    private CuratorFramework getOrCreateCurator() throws Exception {
        if (curator == null) {
            curator = configuration.getCuratorFramework();

            if (curator == null) {
                managedInstance = true;

                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Starting ZooKeeper Curator with namespace '{}',  nodes: '{}'",
                            configuration.getNamespace(),
                            String.join(",", configuration.getNodes()));
                }

                curator = ZooKeeperCuratorHelper.createCurator(configuration);
                curator.start();
            } else {
                managedInstance = false;
            }
        }

        return curator;
    }
}


text:
layout: article
title: "Éliminer les téléchargements inutiles"
description: "La ressource la plus rapide et la mieux optimisée est une ressource qui n`est pas envoyée. Avez-vous audité vos ressources récemment ? Vous devez le faire régulièrement pour vous assurer que chaque ressource permet d`offrir une meilleure expérience à l`utilisateur."
introduction: "La ressource la plus rapide et la mieux optimisée est une ressource qui n`est pas envoyée. Avez-vous audité vos ressources récemment ? Vous devez le faire régulièrement pour vous assurer que chaque ressource permet d`offrir une meilleure expérience à l`utilisateur."
article:
  written_on: 2014-04-01
  updated_on: 2014-04-29
  order: 1
collection: optimizing-content-efficiency
authors:
  - ilyagrigorik
key-takeaways:
  eliminate-downloads:
    - "Inventorier tous vos éléments et tous les éléments tiers sur vos pages"
    - "Mesurer les performances de chaque élément : sa valeur et ses performances techniques"
    - "Déterminer si les ressources offrent une valeur suffisante"
---

{% wrap content%}

{% include modules/toc.liquid %}

{% include modules/takeaway.liquid list=page.key-takeaways.eliminate-downloads %}

La ressource la plus rapide et la mieux optimisée est une ressource qui n`est pas envoyée. Cela peut sembler évident, mais en pratique, ce principe est trop souvent oublié : en tant que technicien en performances, il vous incombe de toujours garder un regard critique afin de saisir chaque opportunité d`éliminer les ressources inutiles de votre application. La remise en question et le réexamen périodique des suppositions implicites et explicites avec votre équipe font partie des bonnes pratiques. Quelques exemples :

* Nous avons toujours inclus la ressource X sur nos pages, mais le coût de son téléchargement et de son affichage est-il compensé par la valeur apportée à l`utilisateur ? Pouvons-nous mesurer et prouver sa valeur ?
* La ressource, en particulier s`il s`agit d`une ressource tierce, offre-t-elle des performances constantes ? La ressource se trouve-t-elle dans le chemin critique, ou a-t-elle besoin de s`y trouver ? Si la ressource se trouve dans le chemin critique, pourrait-elle constituer un point faible pour notre site ? C`est-à-dire que si la ressource n`est pas disponible, cela affecte-t-il l`expérience de nos pages pour l`utilisateur ?
* Cette ressource a-t-elle besoin ou dispose-t-elle d`un contrat de niveau de service ? Cette ressource respecte-t-elle les bonnes pratiques en matière de performances : compression, mise en cache, etc. ?

Nos pages contiennent trop souvent des ressources inutiles, ou pire, qui réduisent les performances de la page sans offrir beaucoup de valeur au visiteur ou au site sur lequel elles sont hébergées. Cela s`applique également aux ressources et widgets propriétaires et tiers :

* Le site A a décidé d`afficher un un carrousel de photos sur sa page d`accueil, pour permettre au visiteur de prévisualiser plusieurs photos en un clic. Toutes les photos sont chargées en même temps que la page, et l`utilisateur les fait défiler.
    * **Question** : Avez-vous calculé combien d`utilisateurs affichent plusieurs photos dans la galerie carrousel ? Vous pouvez augmenter de façon importante le temps système en téléchargeant des ressources inutiles que la plupart des visiteurs ne consultent jamais.
* Le site B a décidé d`installer un widget tiers pour afficher le contenu connexe, augmenter les interactions sociales ou fournir un autre service.
    * **Question** : Avez-vous contrôlé combien de visiteurs utilisent le widget ou cliquent pour accéder au contenu fourni par celui-ci ? Les interactions générées par ce widget sont-elles suffisantes pour justifier le temps système ?

Comme vous pouvez le voir, si le fait d`éliminer les téléchargements inutiles peut sembler sans intérêt, en pratique c`est tout le contraire, car cela demande souvent beaucoup de réflexion et de mesures pour prendre la décision adaptée. En fait, pour obtenir les meilleurs résultats possibles, vous devez inventorier et vous reposer ces questions régulièrement pour chaque élément sur vos pages.

{% include modules/nextarticle.liquid %}

{% endwrap %}


text:
gompatible
==========

Gompatible is a tool to show Go package's API changes between two (git) revisions. The API changes are categorized into unchanged, added, removed, breaking, and compatible.

## Installation

    go get -u github.com/motemen/gompatible/cmd/gompat

## Usage

    gompat [-a] [-d] [-r] <rev1>[..[<rev2>]] [<import path>[/...]]

Extracts type information of target package (or the current directory if not specified) at two revisions _rev1_, _rev2_ and shows changes between them.

Flags:

    -a    show also unchanged APIs
    -d    run diff on multi-line changes
    -r    recurse into subdirectories
          (can be specified by "/..." suffix to the import path)

### Specifying revisions

- `<rev1>..<rev2>` ... Shows changes between revisions _rev1_ and _rev2_
- `<rev1>..` ... Shows changes between revisions _rev1_ and `HEAD` (same as `<rev1>..HEAD`)
- `<rev1>` .. Shows changes introduced by the commit _rev1_ (same as `<rev1>~1..<rev1>`)

## Example

~~~
% gompat 665374f1c86631cf73f4729095d4cf4313670 golang.org/x/tools/go/types
! func Eval(str string, pkg *Package, scope *Scope) (TypeAndValue, error)
. func Eval(fset *token.FileSet, pkg *Package, pos token.Pos, expr string) (tv TypeAndValue, err error)
- func EvalNode(fset *token.FileSet, node ast.Expr, pkg *Package, scope *Scope) (tv TypeAndValue, err error)
- func New(str string) Type
! func NewScope(parent *Scope, comment string) *Scope
. func NewScope(parent *Scope, pos, end token.Pos, comment string) *Scope
...
~~~

## Details

### API entities

API entities, in the sense of Gompatible recognizes,
are package-level and exported

- Functions and methods (`func`),
- Types (`type`), and
- Variables (`var`) and constants (`const`).

### API changes

The obvious API change kinds are:

- Unchanged (`=`)
  - The API entity kept unchanged
- Added (`+`)
  - The API entity was newly added
- Removed (`-`)
  - The API entity was removed

And below are the less-obvious ones:

#### Breaking (`!`)

The API signature has been changed and the users must change their usages.

Example:

~~~
// before
func F(n, m int) error

// after
func F(n, m int, b bool) error
~~~

~~~
// before
type T struct {
  Foo string
  Bar bool
}

// after
type T struct {
  Foo float64
  Bar bool
}
~~~

#### Compatible (`*`)

The API signature has been changed, but the users do not have to change their usages.

Example:

~~~
// before
func F(n, m int) error

// after
func F(n, m int, opt ...interface{}) error
~~~

~~~
// before
func F(b *bytes.Buffer)

// after
func F(r io.Reader)
~~~

## Author

motemen <https://motemen.github.io/>


text:
from django.conf import settings
from datetime import datetime
import os
import logging
logger = logging.getLogger(__name__)

# convert dict to object
class DictToObject(object):
    def __init__(self, d):
        self.__dict__['d'] = d

    def __getattr__(self, key):
        value = self.__dict__['d'][key]
        if type(value) == type({}):
            return DictToObject(value)
        return value

"""
example settings file
FILESERVICE_CONFIG = {
    'store_dir': '/webapps/vida/fileservice_store'
}
"""

def get_fileservice_dir():
    conf = getattr(settings, 'FILESERVICE_CONFIG', {})
    return conf.get('store_dir', './fileservice_store')

def get_fileservice_server_route_internal():
    conf = getattr(settings, 'FILESERVICE_CONFIG', {})
    return conf.get('server_route_internal', '/server_route_internal/')

def u_to_str(string):
    return string.encode('ascii', 'ignore')

def is_int_str(v):
    v = str(v).strip()
    return v == '0' or (v if v.find('..') > -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit()

def add_file_attribs(target_object, filename):
    if os.path.isfile(filename):
        stat = os.stat(filename)
        if stat:
            target_object['file_size'] = stat.st_size
            target_object['file_updated'] = datetime.fromtimestamp(stat.st_ctime)

def get_fileservice_files():
    return os.listdir(get_fileservice_dir())

def file_exists(filename):
    if os.path.isfile(get_filename_absolute(filename)):
        return True
    return False

def get_filename_absolute(filename):
    return '{}/{}'.format(get_fileservice_dir(), filename)

def get_gallery_file():
    conf = getattr(settings, 'FILESERVICE_CONFIG', {})
    return conf.get('gallery_file', get_fileservice_dir() + '/gallery.gal')

def get_fileservice_files_abs():
    result = []
    for i in get_fileservice_files():
        if 'thumb' in i:
            continue
        if i == "gallery.gal":
            continue
        logger.debug(i)
        result.append(get_filename_absolute(i))
    return result


text:
using System;
using System.ComponentModel;

namespace Azure.MixedReality.ObjectAnchors.Conversion.Models
{
    /// <summary>
    /// The Quaternion.
    /// </summary>
    internal partial class Quaternion : IEquatable<Quaternion>
    {
        private System.Numerics.Quaternion data;

        /// <summary>
        /// Creates a autorest-defined Quaternion given its Numerics equivalent.
        /// </summary>
        /// <param name="quaternion">The numerics quaternion.</param>
        internal Quaternion(System.Numerics.Quaternion quaternion)
        {
            data = quaternion;
        }

        /// <summary>
        /// Creates a autorest-defined Quaternion given its fields.
        /// </summary>
        /// <param name="x">X component.</param>
        /// <param name="y">Y component.</param>
        /// <param name="z">Z component.</param>
        /// <param name="w">W component.</param>
        /// <param name="isIdentity">Unused.</param>
#pragma warning disable CA1801 // Review unused parameters
        internal Quaternion(float x, float y, float z, float w, bool isIdentity) : this(x, y, z, w)
#pragma warning restore CA1801 // Review unused parameters
        {
        }

        /// <summary>
        /// Creates a autorest-defined Quaternion given its fields.
        /// </summary>
        /// <param name="x">X component.</param>
        /// <param name="y">Y component.</param>
        /// <param name="z">Z component.</param>
        /// <param name="w">W component.</param>
        internal Quaternion(float x, float y, float z, float w)
        {
            data = new System.Numerics.Quaternion(x, y, z, w);
        }

        /// <summary>
        /// X component.
        /// </summary>
        public float X { get { return data.X; } set { data.X = value; } }

        /// <summary>
        /// Y component.
        /// </summary>
        public float Y { get { return data.Y; } set { data.Y = value; } }

        /// <summary>
        /// Z component.
        /// </summary>
        public float Z { get { return data.Z; } set { data.Z = value; } }

        /// <summary>
        /// W component.
        /// </summary>
        public float W { get { return data.W; } set { data.W = value; } }

        /// <summary>
        /// Gets a value that indicates whether the current instance is the identity quaternion.
        /// </summary>
        public bool IsIdentity { get => data.IsIdentity; }

        /// <summary>
        /// Assesses equality with another quaternion.
        /// </summary>
        /// <param name="other">The other quaternion being compared to.</param>
        /// <returns>Whether the two are equal.</returns>
        public bool Equals(Quaternion other)
        {
            return this.data.Equals(other.data);
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj)
        {
            return obj is Quaternion && this.Equals(obj as Quaternion);
        }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode()
        {
            return data.GetHashCode();
        }

        public static implicit operator System.Numerics.Quaternion(Quaternion q) => q.data;
        public static implicit operator Quaternion(System.Numerics.Quaternion q) => new Quaternion(q);
    }
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'app-form',
    templateUrl: './form.component.html',
    styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
    constructor() { }
    ngOnInit() {}
}


text:
package net.etalia.crepuscolo.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.ApplicationContext;

@Configurable
public class ServiceHack {

	@Autowired
	private ApplicationContext appctx;

	private static ServiceHack instance = null;

	public static ServiceHack getInstance() {
		if (instance == null) {
			instance = new ServiceHack();
		}
		return instance;
	}

	public static ServiceHack createNewInstance() {
		instance = new ServiceHack();
		return instance;
	}

	@Autowired(required=false)
	private StorageService storageService;

	@Autowired(required=false)
	private CreationService creationService;

	@Autowired(required=false)
	private AuthService authService;

	@Deprecated
	public StorageService getStorageService() {
		return storageService;
	}

	@Deprecated
	public CreationService getCreationService() {
		return creationService;
	}

	@Deprecated
	public AuthService getAuthService() {
		return authService;
	}

	public <T> T getBean(Class<T> clazz) {
		if (appctx == null) return null;
		return appctx.getBean(clazz);
	}

	public Object getBean(String name) {
		if (appctx == null) return null;
		return appctx.getBean(name);
	}

}


text:
lychee.define('lychee.ui.entity.Text').includes([
	'lychee.ui.Entity'
]).exports((lychee, global, attachments) => {

	const _Entity = lychee.import('lychee.ui.Entity');
	const _FONT   = attachments['fnt'];

	/*
	 * HELPERS
	 */

	const _render_buffer = function(renderer) {

		let font = this.font;
		if (font !== null && font.texture !== null) {

			if (this.__buffer !== null) {
				this.__buffer.resize(this.width, this.height);
			} else {
				this.__buffer = renderer.createBuffer(this.width, this.height);
			}

			renderer.clear(this.__buffer);
			renderer.setBuffer(this.__buffer);
			renderer.setAlpha(1.0);

			let lines = this.__lines;
			let lh    = font.lineheight;
			let ll    = lines.length;
			if (ll > 0) {

				for (let l = 0; l < ll; l++) {

					renderer.drawText(
						0,
						0 + lh * l,
						lines[l],
						font,
						false
					);

				}

			}

			renderer.setBuffer(null);
			this.__isDirty = false;

		}

	};

	/*
	 * IMPLEMENTATION
	 */

	const Composite = function(data) {

		let states = Object.assign({}, data);

		this.font  = _FONT;
		this.value = '';

		this.__buffer  = null;
		this.__lines   = [];
		this.__isDirty = true;

		this.setFont(states.font);
		this.setValue(states.value);

		delete states.font;
		delete states.value;

		states.width  = this.width;
		states.height = this.height;
		states.shape  = _Entity.SHAPE.rectangle;

		_Entity.call(this, states);

		states = null;

		/*
		 * INITIALIZATION
		 */

		this.bind('relayout', function() {
			this.__isDirty = true;
		}, this);

		// this.bind('touch', function() {
		// 	this.trigger('change', [ this.value ]);
		// }, this);

	};

	Composite.prototype = {

		/*
		 * ENTITY API
		 */

		deserialize: function(blob) {

			let font = lychee.deserialize(blob.font);
			if (font !== null) {
				this.setFont(font);
			}

		},

		serialize: function() {

			let data = _Entity.prototype.serialize.call(this);
			data['constructor'] = 'lychee.ui.entity.Text';

			let states = data['arguments'][0];
			let blob   = (data['blob'] || {});

			if (this.value !== '') states.value = this.value;

			if (this.font !== null) blob.font = lychee.serialize(this.font);

			data['blob'] = Object.keys(blob).length > 0 ? blob : null;

			return data;

		},

		render: function(renderer, offsetX, offsetY) {

			if (this.visible === false) return;

			let alpha    = this.alpha;
			let position = this.position;
			let x        = position.x + offsetX;
			let y        = position.y + offsetY;
			let hwidth   = this.width  / 2;
			let hheight  = this.height / 2;

			if (this.__isDirty === true) {
				_render_buffer.call(this, renderer);
			}

			if (alpha !== 1) {
				renderer.setAlpha(alpha);
			}

			if (this.__buffer !== null) {

				renderer.drawBuffer(
					x - hwidth,
					y - hheight,
					this.__buffer
				);

			}

			if (alpha !== 1) {
				renderer.setAlpha(1.0);
			}

		},

		/*
		 * CUSTOM API
		 */

		setFont: function(font) {

			font = font instanceof Font ? font : null;

			if (font !== null) {

				this.font = font;

				// refresh the layout
				if (this.value !== '') {
					this.setValue(this.value);
				}

				return true;

			}

			return false;

		},

		setValue: function(value) {

			value = typeof value === 'string' ? value : null;

			if (value !== null) {

				let font = this.font;
				if (font !== null) {

					let realwidth  = 0;
					let realheight = 0;
					let lines      = value.split('\n');

					lines.map(line => font.measure(line)).forEach(dim => {
						if (dim.realwidth  > realwidth)  realwidth  = dim.realwidth;
						if (dim.realheight > realheight) realheight = dim.realheight;
					});

					this.width  = realwidth;
					this.height = realheight * lines.length;

				}

				this.value = value;

				this.__lines   = value.split('\n');
				this.__isDirty = true;

				return true;

			}

			return false;

		}

	};

	return Composite;

});


text:
<?php

namespace AppBundle\Entity\Report;

use JMS\Serializer\Annotation as JMS;
use Symfony\Component\Validator\Constraints as Assert;

class MoneyTransactionShort
{
    /**
     * @var int
     * @JMS\Type("integer")
     *
     * @JMS\Groups({"moneyTransactionShort"})
     */
    private $id;

    /**
     * @JMS\Type("AppBundle\Entity\Report\Report")
     * @var Report
     */
    private $report;

    /**
     * @var float
     *
     * @JMS\Type("string")
     * @JMS\Groups({"moneyTransactionShort"})
     *
     * @Assert\NotBlank(message="moneyTransactionShort.amount.notBlank", groups={"money-transaction-short"})
     * @Assert\Type(type="numeric", message="moneyTransactionShort.amount.type", groups={"money-transaction-short"})
     * @Assert\Range(min=1000, max=10000000, minMessage = "moneyTransactionShort.amount.minMessage", maxMessage = "moneyTransactionShort.amount.maxMessage", groups={"money-transaction-short"})
     *
     */
    private $amount;

    /**
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\Groups({"moneyTransactionShort"})
     *
     * @Assert\NotBlank(message="moneyTransactionShort.description.notBlank", groups={"money-transaction-short"})
     */
    private $description;

    /**
     * @var DateTime
     *
     * @JMS\Type("DateTime<'Y-m-d'>")
     * @JMS\Groups({"moneyTransactionShort"})
     *
     * @Assert\Date(message="moneyTransactionShort.date.notValid", groups={"money-transaction-short"})
     */
    private $date;

    /**
     * Discriminator field
     *
     * @var string
     *
     * @JMS\Type("string")
     * @JMS\Groups({"moneyTransactionShort"})
     */
    private $type;

    /**
     * MoneyTransactionShort constructor.
     * @param string $type
     */
    public function __construct($type)
    {
        $this->type = $type;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     *
     * @return MoneyTransactionShort
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return Report
     */
    public function getReport()
    {
        return $this->report;
    }

    /**
     * @param Report $report
     *
     * @return MoneyTransactionShort
     */
    public function setReport($report)
    {
        $this->report = $report;

        return $this;
    }

    /**
     * @return float
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * @param float $amount
     *
     * @return MoneyTransactionShort
     */
    public function setAmount($amount)
    {
        $this->amount = $amount;

        return $this;
    }

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

    /**
     * @param string $description
     *
     * @return MoneyTransactionShort
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @return DateTime
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * @param DateTime $date
     *
     * @return MoneyTransactionShort
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

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

    /**
     * @param string $type
     */
    public function setType($type)
    {
        $this->type = $type;
    }
}


text:
#ifndef QNET_UNIX_P_H
#define QNET_UNIX_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of Qt code on Unix. This header file may change from version to
// version to version without notice, or even be removed.
//
// We mean it.
//

#include "private/qcore_unix_p.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#if defined(Q_OS_VXWORKS)
#  include <sockLib.h>
#endif

// for inet_addr
#include <netdb.h>
#include <arpa/inet.h>
#if defined(Q_OS_VXWORKS)
#  include <hostLib.h>
#else
#  include <resolv.h>
#endif

QT_BEGIN_NAMESPACE

// Almost always the same. If not, specify in qplatformdefs.h.
#if !defined(QT_SOCKOPTLEN_T)
# define QT_SOCKOPTLEN_T QT_SOCKLEN_T
#endif

// UnixWare 7 redefines socket -> _socket
static inline int qt_safe_socket(int domain, int type, int protocol, int flags = 0)
{
    Q_ASSERT((flags & ~O_NONBLOCK) == 0);

    int fd;
#ifdef QT_THREADSAFE_CLOEXEC
    int newtype = type | SOCK_CLOEXEC;
    if (flags & O_NONBLOCK)
        newtype |= SOCK_NONBLOCK;
    fd = ::socket(domain, newtype, protocol);
    return fd;
#else
    fd = ::socket(domain, type, protocol);
    if (fd == -1)
        return -1;

    ::fcntl(fd, F_SETFD, FD_CLOEXEC);

    // set non-block too?
    if (flags & O_NONBLOCK)
        ::fcntl(fd, F_SETFL, ::fcntl(fd, F_GETFL) | O_NONBLOCK);

    return fd;
#endif
}

// Tru64 redefines accept -> _accept with _XOPEN_SOURCE_EXTENDED
static inline int qt_safe_accept(int s, struct sockaddr *addr, QT_SOCKLEN_T *addrlen, int flags = 0)
{
    Q_ASSERT((flags & ~O_NONBLOCK) == 0);

    int fd;
#ifdef QT_THREADSAFE_CLOEXEC
    // use accept4
    int sockflags = SOCK_CLOEXEC;
    if (flags & O_NONBLOCK)
        sockflags |= SOCK_NONBLOCK;
    fd = ::accept4(s, addr, static_cast<QT_SOCKLEN_T *>(addrlen), sockflags);
    return fd;
#else
    fd = ::accept(s, addr, static_cast<QT_SOCKLEN_T *>(addrlen));
    if (fd == -1)
        return -1;

    ::fcntl(fd, F_SETFD, FD_CLOEXEC);

    // set non-block too?
    if (flags & O_NONBLOCK)
        ::fcntl(fd, F_SETFL, ::fcntl(fd, F_GETFL) | O_NONBLOCK);

    return fd;
#endif
}

// UnixWare 7 redefines listen -> _listen
static inline int qt_safe_listen(int s, int backlog)
{
    return ::listen(s, backlog);
}

static inline int qt_safe_connect(int sockfd, const struct sockaddr *addr, QT_SOCKLEN_T addrlen)
{
    int ret;
    // Solaris e.g. expects a non-const 2nd parameter
    EINTR_LOOP(ret, QT_SOCKET_CONNECT(sockfd, const_cast<struct sockaddr *>(addr), addrlen));
    return ret;
}
#undef QT_SOCKET_CONNECT
#define QT_SOCKET_CONNECT qt_safe_connect

#if defined(socket)
# undef socket
#endif
#if defined(accept)
# undef accept
#endif
#if defined(listen)
# undef listen
#endif

// VxWorks' headers specify 'int' instead of '...' for the 3rd ioctl() parameter.
template <typename T>
static inline int qt_safe_ioctl(int sockfd, int request, T arg)
{
#ifdef Q_OS_VXWORKS
    return ::ioctl(sockfd, request, (int) arg);
#else
    return ::ioctl(sockfd, request, arg);
#endif
}

// VxWorks' headers do not specify any const modifiers
static inline in_addr_t qt_safe_inet_addr(const char *cp)
{
#ifdef Q_OS_VXWORKS
    return ::inet_addr((char *) cp);
#else
    return ::inet_addr(cp);
#endif
}

static inline int qt_safe_sendmsg(int sockfd, const struct msghdr *msg, int flags)
{
#ifdef MSG_NOSIGNAL
    flags |= MSG_NOSIGNAL;
#else
    qt_ignore_sigpipe();
#endif

    int ret;
    EINTR_LOOP(ret, ::sendmsg(sockfd, msg, flags));
    return ret;
}

static inline int qt_safe_recvmsg(int sockfd, struct msghdr *msg, int flags)
{
    int ret;

    EINTR_LOOP(ret, ::recvmsg(sockfd, msg, flags));
    return ret;
}

QT_END_NAMESPACE

#endif // QNET_UNIX_P_H


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Diagnostics.SymbolStore
{
  public partial interface ISymbolReader
  {
    #region Methods and constructors
    ISymbolDocument GetDocument(string url, Guid language, Guid languageVendor, Guid documentType);

    ISymbolDocument[] GetDocuments();

    ISymbolVariable[] GetGlobalVariables();

    ISymbolMethod GetMethod(SymbolToken method, int version);

    ISymbolMethod GetMethod(SymbolToken method);

    ISymbolMethod GetMethodFromDocumentPosition(ISymbolDocument document, int line, int column);

    ISymbolNamespace[] GetNamespaces();

    byte[] GetSymAttribute(SymbolToken parent, string name);

    ISymbolVariable[] GetVariables(SymbolToken parent);
    #endregion

    #region Properties and indexers
    SymbolToken UserEntryPoint
    {
      get;
    }
    #endregion
  }
}


text:
/* --------------------------------

Primary style

-------------------------------- */
*, *::after, *::before {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
}

body {
  font-size: 1.6rem;
  font-family: sans-serif;
  color: #ffffff;
  background: #001426 url("../img/bg-pattern.png");
}

a {
  color: #196a74;
  text-decoration: none;
}

/* --------------------------------

Main Components

-------------------------------- */
.cd-background-wrapper {
  background-color: #001426;
  position: relative;
  overflow: hidden;
}
.no-touch .cd-background-wrapper {
  -webkit-perspective: 4000px;
  -moz-perspective: 4000px;
  perspective: 4000px;
}
.cd-background-wrapper::before {
  /* never visible - this is used in jQuery to check the device type */
  content: 'web';
  display: none;
}
.touch .cd-background-wrapper::before {
  /* never visible - this is used in jQuery to check the device type */
  content: 'mobile';
}

.cd-floating-background {
  position: relative;
}
.cd-floating-background img {
  display: block;
  width: 100%;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  /* fixes a Firefox bug - images not correctly rendered*/
  background-color: rgba(255, 255, 255, 0.01);
}
.cd-floating-background img:not(:first-child) {
  position: absolute;
  top: 0;
  left: 0;
}
.no-touch .cd-floating-background {
  top: 0;
  left: 0;
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  -ms-transform-style: preserve-3d;
  -o-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-transform: translateZ(0);
  -moz-transform: translateZ(0);
  -ms-transform: translateZ(0);
  -o-transform: translateZ(0);
  transform: translateZ(0);
}
.no-touch .cd-floating-background.is-absolute {
  position: absolute;
}
.no-touch .cd-floating-background img:first-child {
  -webkit-transform: translateZ(50px);
  -moz-transform: translateZ(50px);
  -ms-transform: translateZ(50px);
  -o-transform: translateZ(50px);
  transform: translateZ(50px);
}
.no-touch .cd-floating-background img:nth-child(2) {
  -webkit-transform: translateZ(290px);
  -moz-transform: translateZ(290px);
  -ms-transform: translateZ(290px);
  -o-transform: translateZ(290px);
  transform: translateZ(290px);
}
.no-touch .cd-floating-background img:nth-child(3) {
  -webkit-transform: translateZ(400px);
  -moz-transform: translateZ(400px);
  -ms-transform: translateZ(400px);
  -o-transform: translateZ(400px);
  transform: translateZ(400px);
}
.no-touch.no-preserve-3d .cd-floating-background {
  /* we target browsers that don't support preserve-3d and show just a standard image - no effect visible */
  position: relative;
}