from unittest import TestCase
from types import SimpleNamespace
import gc
import weakref

from pgzero.animation import animate
from pgzero import clock

class TestObject:
    """A simple object subclass"""

class AnimationTest(TestCase):
    def test_basic_animation(self):
        """Test that animation works"""
        obj = SimpleNamespace()
        obj.attribute = 0
        animate(obj, attribute=2, duration=2)
        self.assertEqual(obj.attribute, 0)
        clock.tick(1)
        self.assertEqual(obj.attribute, 1)
        clock.tick(1)
        self.assertEqual(obj.attribute, 2)
        clock.tick(1)
        self.assertEqual(obj.attribute, 2)

    def test_some_tween(self):
        """Test that tweening does something"""
        obj = SimpleNamespace()
        obj.attribute = 0
        animate(obj, attribute=2, tween='accelerate', duration=2)
        self.assertEqual(obj.attribute, 0)
        clock.tick(1)
        assert 0 < obj.attribute < 1
        clock.tick(1)
        self.assertEqual(obj.attribute, 2)
        clock.tick(1)
        self.assertEqual(obj.attribute, 2)

    def test_tuple_animation(self):
        """Test that you can animate a tuple"""
        obj = SimpleNamespace()
        obj.attribute = 0, 2
        animate(obj, attribute=(2, 0), duration=2)
        self.assertEqual(obj.attribute, (0, 2))
        clock.tick(1)
        self.assertEqual(obj.attribute, (1, 1))
        clock.tick(1)
        self.assertEqual(obj.attribute, (2, 0))
        clock.tick(1)
        self.assertEqual(obj.attribute, (2, 0))

    def test_list_animation(self):
        """Test that you can animate a list"""
        obj = SimpleNamespace()
        obj.attribute = [0, 2]
        animate(obj, attribute=[2, 0], duration=2)
        self.assertEqual(obj.attribute, [0, 2])
        clock.tick(1)
        self.assertEqual(obj.attribute, [1, 1])
        clock.tick(1)
        self.assertEqual(obj.attribute, [2, 0])
        clock.tick(1)
        self.assertEqual(obj.attribute, [2, 0])

    def test_on_finished(self):
        """Test the on_finished callback works"""
        obj = SimpleNamespace()
        obj.attribute = 0
        endlist = ['in progress']
        animate(obj, attribute=2, duration=2, on_finished=endlist.clear)
        self.assertEqual(obj.attribute, 0)
        self.assertEqual(endlist, ['in progress'])
        clock.tick(1)
        self.assertEqual(obj.attribute, 1)
        self.assertEqual(endlist, ['in progress'])
        clock.tick(1)
        self.assertEqual(obj.attribute, 2)
        clock.tick(1)
        self.assertEqual(obj.attribute, 2)
        self.assertEqual(endlist, [])

    def test_cancel_old(self):
        """Test an old animation is cancelled when overwritten"""
        obj = SimpleNamespace()
        obj.attribute = 0
        animate(obj, attribute=-4, duration=4)
        animate(obj, attribute=2, duration=2)
        self.assertEqual(obj.attribute, 0)
        clock.tick(1)
        self.assertEqual(obj.attribute, 1)
        clock.tick(1)
        self.assertEqual(obj.attribute, 2)
        clock.tick(1)
        self.assertEqual(obj.attribute, 2)

    def test_cancel_some(self):
        """Test only the overwritten target of an old animation is cancelled"""
        obj = SimpleNamespace()
        obj.attr1 = 0
        obj.attr2 = 0
        animate(obj, attr1=-4, attr2=-4, duration=4)
        animate(obj, attr1=2, duration=2)
        self.assertEqual(obj.attr1, 0)
        self.assertEqual(obj.attr2, 0)
        clock.tick(1)
        self.assertEqual(obj.attr1, 1)
        self.assertEqual(obj.attr2, -1)
        clock.tick(1)
        self.assertEqual(obj.attr1, 2)
        self.assertEqual(obj.attr2, -2)
        clock.tick(1)
        self.assertEqual(obj.attr1, 2)
        self.assertEqual(obj.attr2, -3)

    def test_no_linger(self):
        """Test that deleted animations are garbage-collected"""
        anim1_alivelist = ['animation 1 alive']
        anim2_alivelist = ['animation 2 alive']
        obj_alivelist = ['object alive']
        # cannot use SimpleNamespace because it doesn't support weakref
        obj = TestObject()
        obj.attribute = 0
        anim1 = animate(obj, attribute=1, duration=5)
        anim2 = animate(obj, attribute=2, duration=1)
        weakref.finalize(anim1, anim1_alivelist.clear)
        weakref.finalize(anim2, anim2_alivelist.clear)
        weakref.finalize(obj, obj_alivelist.clear)

        del anim1
        del anim2
        del obj
        gc.collect()
        self.assertEqual(anim1_alivelist, [])

        clock.tick(3)
        gc.collect()
        self.assertEqual(anim2_alivelist, [])
        self.assertEqual(obj_alivelist, [])

    def test_running_after_animation_creation(self):
        """Ensure the running attribute is True on creation."""
        anim = animate(None)

        self.assertTrue(anim.running)

    def test_running_before_animation_finished(self):
        """Ensure the running attribute is True before animation finished."""
        anim = animate(None, duration=2)

        clock.tick(1)

        self.assertTrue(anim.running)

    def test_running_after_animation_finished(self):
        """Ensure the running attribute is False after animation finished."""
        anim = animate(None, duration=2)
        clock.tick(1)

        clock.tick(1.1)  # Add extra time to ensure it's done.

        self.assertFalse(anim.running)

    def test_running_read_only(self):
        """Ensure the running attribute is read only."""
        anim = animate(None)

        with self.assertRaises(AttributeError, msg="can't set attribute"):
            anim.running = False

    def test_stop_with_complete_false_after_creation(self):
        """Stop, with complete False, an animation after creation."""
        attr_start_val = 0
        attr_finish_val = 1
        test_obj = SimpleNamespace(attr=attr_start_val)
        anim = animate(test_obj, attr=attr_finish_val)
        expected_attr_val = attr_start_val

        anim.stop(complete=False)

        # Ensure animation stopped and attr as expected.
        self.assertFalse(anim.running)
        self.assertEqual(test_obj.attr, expected_attr_val)

    def test_stop_with_complete_true_after_creation(self):
        """Stop, with complete True, an animation after creation."""
        attr_start_val = 0
        attr_finish_val = 1
        test_obj = SimpleNamespace(attr=attr_start_val)
        anim = animate(test_obj, attr=attr_finish_val)
        expected_attr_val = attr_finish_val

        anim.stop(complete=True)

        # Ensure animation stopped and attr as expected.
        self.assertFalse(anim.running)
        self.assertEqual(test_obj.attr, expected_attr_val)

    def test_stop_with_complete_false_after_stopped(self):
        """Stop, with complete False, an animation that is already stopped."""
        attr_start_val = 0
        attr_finish_val = 1
        test_obj = SimpleNamespace(attr=attr_start_val)
        anim = animate(test_obj, attr=attr_finish_val)
        anim.stop(complete=False)
        expected_attr_val = attr_start_val

        anim.stop(complete=False)

        # Ensure animation stopped and attr as expected.
        self.assertFalse(anim.running)
        self.assertEqual(test_obj.attr, expected_attr_val)

    def test_stop_with_complete_true_after_stopped(self):
        """Stop, with complete True, an animation that is already stopped."""
        attr_start_val = 0
        attr_finish_val = 1
        test_obj = SimpleNamespace(attr=attr_start_val)
        anim = animate(test_obj, attr=attr_finish_val)
        anim.stop(complete=True)
        expected_attr_val = attr_finish_val

        anim.stop(complete=True)

        # Ensure animation stopped and attr as expected.
        self.assertFalse(anim.running)
        self.assertEqual(test_obj.attr, expected_attr_val)

    def test_stop_with_complete_false_after_finished(self):
        """Stop, with complete False, an animation after it has finished."""
        attr_start_val = 0
        attr_finish_val = 1
        anim_duration = 1.0
        test_obj = SimpleNamespace(attr=attr_start_val)
        anim = animate(test_obj, duration=anim_duration, attr=attr_finish_val)
        clock.tick(anim_duration + 0.1)  # Add extra time to ensure it's done.
        expected_attr_val = attr_finish_val

        anim.stop(complete=False)

        # Ensure animation stopped and attr as expected.
        self.assertFalse(anim.running)
        self.assertEqual(test_obj.attr, expected_attr_val)

    def test_stop_with_complete_true_after_finished(self):
        """Stop, with complete True, an animation after it has finished."""
        attr_start_val = 0
        attr_finish_val = 1
        anim_duration = 1.0
        test_obj = SimpleNamespace(attr=attr_start_val)
        anim = animate(test_obj, duration=anim_duration, attr=attr_finish_val)
        clock.tick(anim_duration + 0.1)  # Add extra time to ensure it's done.
        expected_attr_val = attr_finish_val

        anim.stop(complete=True)

        # Ensure animation stopped and attr as expected.
        self.assertFalse(anim.running)
        self.assertEqual(test_obj.attr, expected_attr_val)

    def test_stop_with_complete_false_after_running(self):
        """Stop, with complete False, an animation after it has run a bit."""
        attr_start_val = 0
        attr_finish_val = 1
        anim_duration = 5.0
        tick_duration = 1.0
        test_obj = SimpleNamespace(attr=attr_start_val)
        anim = animate(test_obj, duration=anim_duration, attr=attr_finish_val)
        clock.tick(tick_duration)
        expected_attr_val = attr_finish_val * tick_duration / anim_duration

        anim.stop(complete=False)

        # Ensure animation stopped and attr as expected.
        self.assertFalse(anim.running)
        self.assertEqual(test_obj.attr, expected_attr_val)

    def test_stop_with_complete_true_after_running(self):
        """Stop, with complete True, an animation after it has run a bit."""
        attr_start_val = 0
        attr_finish_val = 1
        anim_duration = 5.0
        tick_duration = 1.0
        test_obj = SimpleNamespace(attr=attr_start_val)
        anim = animate(test_obj, duration=anim_duration, attr=attr_finish_val)
        clock.tick(tick_duration)
        expected_attr_val = attr_finish_val

        anim.stop(complete=True)

        # Ensure animation stopped and attr as expected.
        self.assertFalse(anim.running)
        self.assertEqual(test_obj.attr, expected_attr_val)

{'repo_name': 'lordmauve/pgzero', 'stars': '237', 'repo_language': 'Python', 'file_name': 'update_colors.py', 'mime_type': 'text/x-python', 'hash': -19552531262727012, 'source_dataset': 'data'}


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

<title>C 中心、点、角度</title>
<link rel="stylesheet" type="text/css" href="../../../../../style.css" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

C 中心、点、角度

ツールバー/アイコン:

メニュー: D 描画 > A 弧 > C 中心、点、角度

ショートカット: A, R

コマンド: arcc | ar

説明

中心点、弧上のポイント、スタート角度および終了角度から弧を作成します。

Usage

オプション・ツールバー中の弧の方向を選んでください。

マウスあるいはコマンドラインの中で座標を入力して、弧の中心をセットしてください。

弧の上のポイントのクリックにより、あるいはコマンドラインへ座標を入力することにより半径を定義します。

もしくは、コマンドラインに半径を入力します。

マウス、あるいは座標を入力することでスタート角度を入力。あるいはコマンドラインで角度をセットします。

スタート角度と同じ方法で、終了角度をセットします。

{'repo_name': 'qcad/qcad', 'stars': '634', 'repo_language': 'C++', 'file_name': 'readme.txt', 'mime_type': 'text/plain', 'hash': 869775731693868378, 'source_dataset': 'data'}


% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/model_text.R, R/model_text_regression.R
\name{model_text}
\alias{model_text}
\alias{model_text.default}
\alias{model_text.stanreg}
\title{Text summary}
\usage{
model_text(model, ...)

\method{model_text}{default}(model, ...)

\method{model_text}{stanreg}(model, ci_method = "hdi", ...)
}
\arguments{
\item{model}{A statistical model.}

\item{...}{Arguments passed to other methods, in particular \code{\link[parameters:model_parameters]{model_parameters()}}.}

\item{ci_method}{The type of index used for Credible Interval. Can be
\code{"HDI"} (default, see \code{\link[bayestestR:hdi]{hdi}}), \code{"ETI"}
(see \code{\link[bayestestR:eti]{eti}}) or \code{"SI"}
(see \code{\link[bayestestR:si]{si}}).}
}
\value{
A list with elements of class \code{report_text} (which are character
vectors), containing a short and long version of the textual output of the
model summary.
}
\description{
Create a reportable textual output for your model.
}
\note{
Arguments in \code{...} are described in the \code{\link{report}} function help.

Arguments in \code{...} are described in the \code{\link{report}} function help.
}
\examples{
model <- t.test(Sepal.Length ~ Species, data = iris[1:100, ])
model_text(model)
summary(model_text(model))
model <- lm(Sepal.Length ~ Petal.Length * Species, data = iris)
model_text(model)
summary(model_text(model))
}

{'repo_name': 'easystats/report', 'stars': '233', 'repo_language': 'R', 'file_name': 'text_long.Rd', 'mime_type': 'text/plain', 'hash': -6230230324447035582, 'source_dataset': 'data'}


/*
 * Copyright (C) 2003 Robert Shearman
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

import "objidl.idl";

/* trick widl into thinking that it knows the DirectDraw types
 * as there is no IDL file for them (yet) */
cpp_quote("#if 0")
interface IDirectDraw;
typedef void DDSURFACEDESC,DDCAPS;
typedef DWORD RGBQUAD;
typedef LONGLONG REFERENCE_TIME;
typedef struct
{
    DWORD 	biSize;
    LONG  	biWidth;
    LONG  	biHeight;
    WORD 	biPlanes;
    WORD 	biBitCount;
    DWORD 	biCompression;
    DWORD 	biSizeImage;
    LONG  	biXPelsPerMeter;
    LONG  	biYPelsPerMeter;
    DWORD 	biClrUsed;
    DWORD 	biClrImportant;
} BITMAPINFOHEADER, *PBITMAPINFOHEADER, *LPBITMAPINFOHEADER;
cpp_quote("#endif")

cpp_quote("#include <ddraw.h>")

cpp_quote("#define AMDDS_NONE 0x00")
cpp_quote("#define AMDDS_DCIPS 0x01")
cpp_quote("#define AMDDS_PS 0x02")
cpp_quote("#define AMDDS_RGBOVR 0x04")
cpp_quote("#define AMDDS_YUVOVR 0x08")
cpp_quote("#define AMDDS_RGBOFF 0x10")
cpp_quote("#define AMDDS_YUVOFF 0x20")
cpp_quote("#define AMDDS_RGBFLP 0x40")
cpp_quote("#define AMDDS_YUVFLP 0x80")
cpp_quote("#define AMDDS_ALL 0xFF")
cpp_quote("#define AMDDS_DEFAULT AMDDS_ALL")

cpp_quote("#define AMDDS_YUV (AMDDS_YUVOFF | AMDDS_YUVOVR | AMDDS_YUVFLP)")
cpp_quote("#define AMDDS_RGB (AMDDS_RGBOFF | AMDDS_RGBOVR | AMDDS_RGBFLP)")
cpp_quote("#define AMDSS_PRIMARY (AMDDS_DCIPS | AMDDS_PS)")

[
    object,
    /* uuid(36d39eb0-dd75-11ce-bf0e-00aa0055595a)  conflicts with uuids.h */
    pointer_default(unique),
    local
]
interface IDirectDrawVideo : IUnknown
{
    HRESULT GetSwitches([out] DWORD * pSwitches);
    HRESULT SetSwitches([in] DWORD Switches);
    HRESULT GetCaps([out] DDCAPS * pCaps);
    HRESULT GetEmulatedCaps([out] DDCAPS *pCaps);
    HRESULT GetSurfaceDesc([out] DDSURFACEDESC * pSurfaceDesc);
    HRESULT GetFourCCCodes([out] DWORD * pCount, [out] DWORD * pCodes);
    HRESULT SetDirectDraw([in] IDirectDraw *ddraw);
    HRESULT GetDirectDraw([out] IDirectDraw **ddraw);
    HRESULT GetSurfaceType([out] DWORD * pSurfaceType);
    HRESULT SetDefault();
    HRESULT UseScanLine([in] long UseScanLine);
    HRESULT CanUseScanLine([out] long * UseScanLine);
    HRESULT UseOverlayStretch([in] long UseOverlayStretch);
    HRESULT CanUseOverlayStretch([out] long * UseOverlayStretch);
    HRESULT UseWhenFullScreen([in] long UseWhenFullScreen);
    HRESULT WillUseFullScreen([out] long * UseWhenFullScreen);
}

[
    object,
    /* uuid(1bd0ecb0-f8e2-11ce-aac6-0020af0b99a3)  conflicts with uuids.h */
    pointer_default(unique),
    local
]
interface IQualProp : IUnknown
{
    [propget] HRESULT FramesDroppedInRenderer([out] int * pcFrames);
    [propget] HRESULT FramesDrawn([out] int * pcFramesDrawn);
    [propget] HRESULT AvgFrameRate([out] int * piAvgFrameRate);
    [propget] HRESULT Jitter([out] int * iJitter);
    [propget] HRESULT AvgSyncOffset([out] int * piAvg);
    [propget] HRESULT DevSyncOffset([out] int * piDev);
}

[
    object,
    /* uuid(dd1d7110-7836-11cf-bf47-00aa0055595a)  conflicts with uuids.h */
    pointer_default(unique)
]
interface IFullScreenVideo : IUnknown
{
    HRESULT CountModes([out] long * pModes);
    HRESULT GetModeInfo([in] long Mode, [out] long * pWidth, [out] long * pHeight, [out] long * pDepth);
    HRESULT GetCurrentMode([out] long * pMode);
    HRESULT IsModeAvailable([in] long Mode);
    HRESULT IsModeEnabled([in] long Mode);
    HRESULT SetEnabled([in] long Mode, [in] long bEnabled);
    HRESULT GetClipFactor([out] long * pClipFactor);
    HRESULT SetClipFactor([in] long ClipFactor);
    HRESULT SetMessageDrain([in] HWND hwnd);
    HRESULT GetMessageDrain([out] HWND * hwnd);
    HRESULT SetMonitor([in] long Monitor);
    HRESULT GetMonitor([out] long * Monitor);
    HRESULT HideOnDeactivate([in] long Hide);
    HRESULT IsHideOnDeactivate();
    HRESULT SetCaption([in] BSTR strCaption);
    HRESULT GetCaption([out] BSTR * pstrCaption);
    HRESULT SetDefault();
}

[
    object,
    /* uuid(53479470-f1dd-11cf-bc42-00aa00ac74f6)  conflicts with uuids.h */
    pointer_default(unique),
    local
]
interface IFullScreenVideoEx : IFullScreenVideo
{
    HRESULT SetAcceleratorTable([in] HWND hwnd, [in] HACCEL hAccel);
    HRESULT GetAcceleratorTable([out] HWND * phwnd, [out] HACCEL * phAccel);
    HRESULT KeepPixelAspectRatio([in] long KeepAspect);
    /* FIXME: not sure is this next method is an [out] */
    HRESULT IsKeepPixelAspectRatio([out] long * pKeepAspect);
}

[
    object,
    /* uuid(61ded640-e912-11ce-a099-00aa00479a58)  conflicts with uuids.h */
    pointer_default(unique),
    local
]
interface IBaseVideoMixer : IUnknown
{
    HRESULT SetLeadPin([in] int iPin);
    HRESULT GetLeadPin([out] int * piPin);
    HRESULT GetInputPinCount([out] int * piPinCount);
    HRESULT IsUsingClock([out] int * pbValue);
    HRESULT SetUsingClock([in] int bValue);
    HRESULT GetClockPeriod([out] int * pbValue);
    HRESULT SetClockPeriod([in] int bValue);
}

#define iPALETTE_COLORS 256
#define iMASK_COLORS 3

cpp_quote("#define iPALETTE_COLORS 256")
cpp_quote("#define iEGA_COLORS 16")
cpp_quote("#define iMASK_COLORS 3")
cpp_quote("#define iTRUECOLOR 16")
cpp_quote("#define iRED 0")
cpp_quote("#define iGREEN 1")
cpp_quote("#define iBLUE 2")
cpp_quote("#define iPALETTE 8")
cpp_quote("#define iMAXBITS 8")

typedef struct tag_TRUECOLORINFO
{
    DWORD dwBitMasks[iMASK_COLORS];
    RGBQUAD bmiColors[iPALETTE_COLORS];
} TRUECOLORINFO;

typedef struct tagVIDEOINFOHEADER
{
    RECT rcSource;
    RECT rcTarget;
    DWORD dwBitRate;
    DWORD dwBitErrorRate;
    REFERENCE_TIME AvgTimePerFrame;

    BITMAPINFOHEADER bmiHeader;
} VIDEOINFOHEADER;

typedef struct tagVIDEOINFO
{
    RECT rcSource;
    RECT rcTarget;
    DWORD dwBitRate;
    DWORD dwBitErrorRate;
    REFERENCE_TIME AvgTimePerFrame;

    BITMAPINFOHEADER bmiHeader;

    union
    {
        RGBQUAD bmiColors[iPALETTE_COLORS];
        DWORD dwBitMasks[iMASK_COLORS];
        TRUECOLORINFO TrueColorInfo;
    };
} VIDEOINFO;

typedef struct tagMPEG1VIDEOINFO
{
    VIDEOINFOHEADER hdr;
    DWORD dwStartTimeCode;
    DWORD cbSequenceHeader;
    BYTE bSequenceHeader[1];
} MPEG1VIDEOINFO;

cpp_quote("#define MAX_SIZE_MPEG1_SEQUENCE_INFO 140")
cpp_quote("#define MPEG1_SEQUENCE_INFO(pv) ((const BYTE *)(pv)->bSequenceHeader)")

typedef struct tagAnalogVideoInfo
{
    RECT rcSource;
    RECT rcTarget;
    DWORD dwActiveWidth;
    DWORD dwActiveHeight;
    REFERENCE_TIME AvgTimePerFrame;
} ANALOGVIDEOINFO;

typedef enum
{
    AM_PROPERTY_FRAMESTEP_STEP = 0x01,
    AM_PROPERTY_FRAMESTEP_CANCEL = 0x02,
    AM_PROPERTY_FRAMESTEP_CANSTEP = 0x03,
    AM_PROPERTY_FRAMESTEP_CANSTEPMULTIPLE = 0x04
} AM_PROPERTY_FRAMESTEP;

typedef struct _AM_FRAMESTEP_STEP
{
    DWORD dwFramesToStep;
} AM_FRAMESTEP_STEP;

{'repo_name': 'ziglang/zig', 'stars': '6084', 'repo_language': 'Zig', 'file_name': 'c_flag_overrides.cmake', 'mime_type': 'text/plain', 'hash': -4333025393899528003, 'source_dataset': 'data'}


[metadata]
description-file = README.md

[pep8]
max-line-length = 120

[nosetests]
## advanced debug
#verbosity=1
#detailed-errors=1
#debug=nose.loader
## jump into pdb on errors
#pdb=1
#pdb-failures=1
## cobertura style coverage with nosexcover.
## we're calling this from ci-runtests.sh in order to not require having nosexcover in requirements.txt
#with-xcoverage=1
#cover-package=scapy_ssl_tls
#cover-html=1
#cover-html-dir=cover
#xcoverage-file=cover/cobertura.xml

{'repo_name': 'tintinweb/scapy-ssl_tls', 'stars': '330', 'repo_language': 'Python', 'file_name': 'key.pem', 'mime_type': 'text/plain', 'hash': 729156697042065509, 'source_dataset': 'data'}


package com.tencent.mm.plugin.sns.ui.a;

import android.content.Context;
import com.tencent.mm.protocal.b.auf;
import com.tencent.mm.protocal.b.gd;
import com.tencent.mm.protocal.b.gi;
import com.tencent.mm.protocal.b.gk;
import com.tencent.mm.sdk.platformtools.v;
import com.tencent.mm.ui.f.h.b;
import com.tencent.mm.ui.f.h.c;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public final class c
  extends com.tencent.mm.ui.f.d
{
  public c(Context paramContext, h.c paramc, int paramInt)
  {
    super(paramContext, paramc, paramInt);
  }

  public final long LZ()
  {
    return 8L;
  }

  protected final com.tencent.mm.ui.f.a.a a(int paramInt, h.b paramb)
  {
    int i = paramInt - lTz - 1;
    gi localgi = null;
    Object localObject = localgi;
    if (i < lTE)
    {
      localObject = localgi;
      if (i >= 0)
      {
        localgi = (gi)lTF.jBi.get(i);
        localObject = new a(paramInt);
        hDB = jBA;
        cKI = lTF.jBh;
        lTK = jBy;
      }
    }
    if (localObject != null) {
      lTI = (i + 1);
    }
    return (com.tencent.mm.ui.f.a.a)localObject;
  }

  protected final void b(gd paramgd)
  {
    if (lTt.size() > 0)
    {
      localb = (h.b)lTt.get(0);
      lTF.jBi.addAll(jBi);
      v.i("MicroMsg.FTS.FTSTimeLineDetailUIUnit", "before time line post process size=%d", new Object[] { Integer.valueOf(lTF.jBi.size()) });
      gd localgd = lTF;
      LinkedList localLinkedList = lTF.jBi;
      Object localObject2 = new HashSet();
      Object localObject1 = new LinkedList();
      int i = localLinkedList.size() - 1;
      while (i >= 0)
      {
        if (((HashSet)localObject2).add(Long.valueOf(getjBA.jBF)))
        {
          a.c localc = new a.c((byte)0);
          index = i;
          id = getjBA.jBF;
          cbi = jCgetjBA.jBG).fyR;
          ((LinkedList)localObject1).add(localc);
        }
        i -= 1;
      }
      Collections.sort((List)localObject1, new a.1());
      localObject2 = new LinkedList();
      localObject1 = ((LinkedList)localObject1).iterator();
      while (((Iterator)localObject1).hasNext()) {
        ((LinkedList)localObject2).add(localLinkedList.get(nextindex));
      }
      v.i("MicroMsg.FTS.FTSTimeLineDataItem", "filter: before=%d | after=%d", new Object[] { Integer.valueOf(localLinkedList.size()), Integer.valueOf(((LinkedList)localObject2).size()) });
      jBi = ((LinkedList)localObject2);
      v.i("MicroMsg.FTS.FTSTimeLineDetailUIUnit", "after time line post process size=%d", new Object[] { Integer.valueOf(lTF.jBi.size()) });
      lTF.jxP = jxP;
      lTF.jBg = jBg;
      lTF.jBh = jBh;
      lTF.jBj = jBj;
      lTE = lTF.jBi.size();
      return;
    }
    h.b localb = new h.b();
    lTF = paramgd;
    lTE = lTF.jBi.size();
    iBL = 8;
    lTt.add(localb);
  }

  public final int getType()
  {
    return 4416;
  }
}

/* Location:
 * Qualified Name:     com.tencent.mm.plugin.sns.ui.a.c
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */

{'repo_name': 'reverseengineeringer/com.tencent.mm', 'stars': '201', 'repo_language': 'Smali', 'file_name': 'LibCardRecog.smali', 'mime_type': 'text/plain', 'hash': -1946952169312454056, 'source_dataset': 'data'}


#!/usr/bin/env bash

# Get the path to this script in SCRIPT_DIR, preserving cwd
ORIG_DIR=$(pwd)
cd "$(dirname "$0")"
SCRIPT_DIR=$(pwd -P)
cd "$ORIG_DIR"

# Find the top of the tools tree (not to be confused with the 'tools'
# directory in that tree)
TOOLS_DIR="$SCRIPT_DIR/../../.."

# Find our binary dependencies (node).
DEV_BUNDLE="$TOOLS_DIR/dev_bundle"

# Have at it!
export NODE_PATH="$DEV_BUNDLE/lib/node_modules"
exec "$DEV_BUNDLE/bin/node" "$SCRIPT_DIR/fake-mongod.js" "$@"

{'repo_name': 'meteor/meteor', 'stars': '41844', 'repo_language': 'JavaScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 909649517617998103, 'source_dataset': 'data'}


---
title: "Copying Linked Files and Intercepting Local Links"
date: "2017-03-21"
draft: false
author: Daisy Buchanan
tags:
  - remark
  - linked files
  - local links
---

![](denys-nevozhai-184452.jpg) _Photo by
[Denys Nevozhai](https://unsplash.com/@dnevozhai) via
[Unsplash](https://unsplash.com/@dnevozhai?photo=DlnK1KOREds)_

## Copying Linked Files

[gatsby-remark-copy-linked-files][1] copies files linked to from Markdown to
your `public` folder.

Let's try with a PDF, that you should be able to preview and/or download by
clicking this link:
[Creative Commons Informational Flyer.pdf](Creativecommons-informational-flyer_eng.pdf)

## Intercepting Local Links

[gatsby-plugin-catch-links][2] intercepts local links from Markdown and other
non-react pages and does a client-side `pushState` to avoid the browser having
to refresh the page.

Let's try linking to the
"[Code and Syntax Highlighting with PrismJS](/code-and-syntax-highlighting/)"
article using a relative path.

Also, let's link to "[Rendering math equations with KaTeX](https://using-remark.gatsbyjs.org/katex/)" article using an absolute path.

And this [link will be excluded](/excluded-link).

[1]: https://www.gatsbyjs.com/plugins/gatsby-remark-copy-linked-files/
[2]: https://www.gatsbyjs.com/plugins/gatsby-plugin-catch-links/

{'repo_name': 'gatsbyjs/gatsby', 'stars': '45786', 'repo_language': 'JavaScript', 'file_name': 'index.js', 'mime_type': 'text/plain', 'hash': -3744010754968566655, 'source_dataset': 'data'}


package com.habitrpg.android.habitica;

import org.junit.Before;
import org.mockito.MockitoAnnotations;

public class BaseTestCase {

    @Before
    public void initMocks() {
        MockitoAnnotations.initMocks(this);
    }
}

{'repo_name': 'HabitRPG/habitica-android', 'stars': '755', 'repo_language': 'Kotlin', 'file_name': 'store_strings-es.xml', 'mime_type': 'text/xml', 'hash': 4894963048849297591, 'source_dataset': 'data'}


<?php

namespace League\Flysystem\Adapter;

use DateTime;
use League\Flysystem\AdapterInterface;
use League\Flysystem\Config;
use League\Flysystem\NotSupportedException;
use League\Flysystem\SafeStorage;
use RuntimeException;

abstract class AbstractFtpAdapter extends AbstractAdapter
{
    /**
     * @var mixed
     */
    protected $connection;

    /**
     * @var string
     */
    protected $host;

    /**
     * @var int
     */
    protected $port = 21;

    /**
     * @var bool
     */
    protected $ssl = false;

    /**
     * @var int
     */
    protected $timeout = 90;

    /**
     * @var bool
     */
    protected $passive = true;

    /**
     * @var string
     */
    protected $separator = '/';

    /**
     * @var string|null
     */
    protected $root;

    /**
     * @var int
     */
    protected $permPublic = 0744;

    /**
     * @var int
     */
    protected $permPrivate = 0700;

    /**
     * @var array
     */
    protected $configurable = [];

    /**
     * @var string
     */
    protected $systemType;

    /**
     * @var bool
     */
    protected $alternativeRecursion = false;

    /**
     * @var SafeStorage
     */
    protected $safeStorage;

    /**
     * Constructor.
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->safeStorage = new SafeStorage();
        $this->setConfig($config);
    }

    /**
     * Set the config.
     *
     * @param array $config
     *
     * @return $this
     */
    public function setConfig(array $config)
    {
        foreach ($this->configurable as $setting) {
            if ( ! isset($config[$setting])) {
                continue;
            }

            $method = 'set' . ucfirst($setting);

            if (method_exists($this, $method)) {
                $this->$method($config[$setting]);
            }
        }

        return $this;
    }

    /**
     * Returns the host.
     *
     * @return string
     */
    public function getHost()
    {
        return $this->host;
    }

    /**
     * Set the host.
     *
     * @param string $host
     *
     * @return $this
     */
    public function setHost($host)
    {
        $this->host = $host;

        return $this;
    }

    /**
     * Set the public permission value.
     *
     * @param int $permPublic
     *
     * @return $this
     */
    public function setPermPublic($permPublic)
    {
        $this->permPublic = $permPublic;

        return $this;
    }

    /**
     * Set the private permission value.
     *
     * @param int $permPrivate
     *
     * @return $this
     */
    public function setPermPrivate($permPrivate)
    {
        $this->permPrivate = $permPrivate;

        return $this;
    }

    /**
     * Returns the ftp port.
     *
     * @return int
     */
    public function getPort()
    {
        return $this->port;
    }

    /**
     * Returns the root folder to work from.
     *
     * @return string
     */
    public function getRoot()
    {
        return $this->root;
    }

    /**
     * Set the ftp port.
     *
     * @param int|string $port
     *
     * @return $this
     */
    public function setPort($port)
    {
        $this->port = (int) $port;

        return $this;
    }

    /**
     * Set the root folder to work from.
     *
     * @param string $root
     *
     * @return $this
     */
    public function setRoot($root)
    {
        $this->root = rtrim($root, '\\/') . $this->separator;

        return $this;
    }

    /**
     * Returns the ftp username.
     *
     * @return string username
     */
    public function getUsername()
    {
        $username = $this->safeStorage->retrieveSafely('username');

        return $username !== null ? $username : 'anonymous';
    }

    /**
     * Set ftp username.
     *
     * @param string $username
     *
     * @return $this
     */
    public function setUsername($username)
    {
        $this->safeStorage->storeSafely('username', $username);

        return $this;
    }

    /**
     * Returns the password.
     *
     * @return string password
     */
    public function getPassword()
    {
        return $this->safeStorage->retrieveSafely('password');
    }

    /**
     * Set the ftp password.
     *
     * @param string $password
     *
     * @return $this
     */
    public function setPassword($password)
    {
        $this->safeStorage->storeSafely('password', $password);

        return $this;
    }

    /**
     * Returns the amount of seconds before the connection will timeout.
     *
     * @return int
     */
    public function getTimeout()
    {
        return $this->timeout;
    }

    /**
     * Set the amount of seconds before the connection should timeout.
     *
     * @param int $timeout
     *
     * @return $this
     */
    public function setTimeout($timeout)
    {
        $this->timeout = (int) $timeout;

        return $this;
    }

    /**
     * Return the FTP system type.
     *
     * @return string
     */
    public function getSystemType()
    {
        return $this->systemType;
    }

    /**
     * Set the FTP system type (windows or unix).
     *
     * @param string $systemType
     *
     * @return $this
     */
    public function setSystemType($systemType)
    {
        $this->systemType = strtolower($systemType);

        return $this;
    }

    /**
     * @inheritdoc
     */
    public function listContents($directory = '', $recursive = false)
    {
        return $this->listDirectoryContents($directory, $recursive);
    }

    abstract protected function listDirectoryContents($directory, $recursive = false);

    /**
     * Normalize a directory listing.
     *
     * @param array  $listing
     * @param string $prefix
     *
     * @return array directory listing
     */
    protected function normalizeListing(array $listing, $prefix = '')
    {
        $base = $prefix;
        $result = [];
        $listing = $this->removeDotDirectories($listing);

        while ($item = array_shift($listing)) {
            if (preg_match('#^.*:$#', $item)) {
                $base = trim($item, ':');
                continue;
            }

            $result[] = $this->normalizeObject($item, $base);
        }

        return $this->sortListing($result);
    }

    /**
     * Sort a directory listing.
     *
     * @param array $result
     *
     * @return array sorted listing
     */
    protected function sortListing(array $result)
    {
        $compare = function ($one, $two) {
            return strnatcmp($one['path'], $two['path']);
        };

        usort($result, $compare);

        return $result;
    }

    /**
     * Normalize a file entry.
     *
     * @param string $item
     * @param string $base
     *
     * @return array normalized file array
     *
     * @throws NotSupportedException
     */
    protected function normalizeObject($item, $base)
    {
        $systemType = $this->systemType ?: $this->detectSystemType($item);

        if ($systemType === 'unix') {
            return $this->normalizeUnixObject($item, $base);
        } elseif ($systemType === 'windows') {
            return $this->normalizeWindowsObject($item, $base);
        }

        throw NotSupportedException::forFtpSystemType($systemType);
    }

    /**
     * Normalize a Unix file entry.
     *
     * @param string $item
     * @param string $base
     *
     * @return array normalized file array
     */
    protected function normalizeUnixObject($item, $base)
    {
        $item = preg_replace('#\s+#', ' ', trim($item), 7);

        if (count(explode(' ', $item, 9)) !== 9) {
            throw new RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
        }

        list($permissions, /* $number */, /* $owner */, /* $group */, $size, /* $month */, /* $day */, /* $time*/, $name) = explode(' ', $item, 9);
        $type = $this->detectType($permissions);
        $path = empty($base) ? $name : $base . $this->separator . $name;

        if ($type === 'dir') {
            return compact('type', 'path');
        }

        $permissions = $this->normalizePermissions($permissions);
        $visibility = $permissions & 0044 ? AdapterInterface::VISIBILITY_PUBLIC : AdapterInterface::VISIBILITY_PRIVATE;
        $size = (int) $size;

        return compact('type', 'path', 'visibility', 'size');
    }

    /**
     * Normalize a Windows/DOS file entry.
     *
     * @param string $item
     * @param string $base
     *
     * @return array normalized file array
     */
    protected function normalizeWindowsObject($item, $base)
    {
        $item = preg_replace('#\s+#', ' ', trim($item), 3);

        if (count(explode(' ', $item, 4)) !== 4) {
            throw new RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
        }

        list($date, $time, $size, $name) = explode(' ', $item, 4);
        $path = empty($base) ? $name : $base . $this->separator . $name;

        // Check for the correct date/time format
        $format = strlen($date) === 8 ? 'm-d-yH:iA' : 'Y-m-dH:i';
        $dt = DateTime::createFromFormat($format, $date . $time);
        $timestamp = $dt ? $dt->getTimestamp() : (int) strtotime("$date $time");

        if ($size === '<DIR>') {
            $type = 'dir';

            return compact('type', 'path', 'timestamp');
        }

        $type = 'file';
        $visibility = AdapterInterface::VISIBILITY_PUBLIC;
        $size = (int) $size;

        return compact('type', 'path', 'visibility', 'size', 'timestamp');
    }

    /**
     * Get the system type from a listing item.
     *
     * @param string $item
     *
     * @return string the system type
     */
    protected function detectSystemType($item)
    {
        return preg_match('/^[0-9]{2,4}-[0-9]{2}-[0-9]{2}/', $item) ? 'windows' : 'unix';
    }

    /**
     * Get the file type from the permissions.
     *
     * @param string $permissions
     *
     * @return string file type
     */
    protected function detectType($permissions)
    {
        return substr($permissions, 0, 1) === 'd' ? 'dir' : 'file';
    }

    /**
     * Normalize a permissions string.
     *
     * @param string $permissions
     *
     * @return int
     */
    protected function normalizePermissions($permissions)
    {
        // remove the type identifier
        $permissions = substr($permissions, 1);

        // map the string rights to the numeric counterparts
        $map = ['-' => '0', 'r' => '4', 'w' => '2', 'x' => '1'];
        $permissions = strtr($permissions, $map);

        // split up the permission groups
        $parts = str_split($permissions, 3);

        // convert the groups
        $mapper = function ($part) {
            return array_sum(str_split($part));
        };

        // get the sum of the groups
        return array_sum(array_map($mapper, $parts));
    }

    /**
     * Filter out dot-directories.
     *
     * @param array $list
     *
     * @return array
     */
    public function removeDotDirectories(array $list)
    {
        $filter = function ($line) {
            if ( ! empty($line) && ! preg_match('#.* \.(\.)?$|^total#', $line)) {
                return true;
            }

            return false;
        };

        return array_filter($list, $filter);
    }

    /**
     * @inheritdoc
     */
    public function has($path)
    {
        return $this->getMetadata($path);
    }

    /**
     * @inheritdoc
     */
    public function getSize($path)
    {
        return $this->getMetadata($path);
    }

    /**
     * @inheritdoc
     */
    public function getVisibility($path)
    {
        return $this->getMetadata($path);
    }

    /**
     * Ensure a directory exists.
     *
     * @param string $dirname
     */
    public function ensureDirectory($dirname)
    {
        if ( ! empty($dirname) && ! $this->has($dirname)) {
            $this->createDir($dirname, new Config());
        }
    }

    /**
     * @return mixed
     */
    public function getConnection()
    {
        $tries = 0;

        while ( ! $this->isConnected() && $tries < 3) {
            $tries++;
            $this->disconnect();
            $this->connect();
        }

        return $this->connection;
    }

    /**
     * Get the public permission value.
     *
     * @return int
     */
    public function getPermPublic()
    {
        return $this->permPublic;
    }

    /**
     * Get the private permission value.
     *
     * @return int
     */
    public function getPermPrivate()
    {
        return $this->permPrivate;
    }

    /**
     * Disconnect on destruction.
     */
    public function __destruct()
    {
        $this->disconnect();
    }

    /**
     * Establish a connection.
     */
    abstract public function connect();

    /**
     * Close the connection.
     */
    abstract public function disconnect();

    /**
     * Check if a connection is active.
     *
     * @return bool
     */
    abstract public function isConnected();
}

{'repo_name': 'lvntayn/laravel-social-network', 'stars': '103', 'repo_language': 'JavaScript', 'file_name': 'bootstrap.js', 'mime_type': 'text/plain', 'hash': 5075637743666452931, 'source_dataset': 'data'}


// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

load("test/mjsunit/wasm/wasm-module-builder.js");

try {
  (function () {
    let m = new WasmModuleBuilder();
    m.addFunction("sub", kSig_i_ii)
    m.instantiate();
  })();
} catch (e) {
  console.info("caught exception");
  console.info(e);
}
for (let i = 0; i < 150; i++) {
  var m = new WasmModuleBuilder();
  m.addMemory(2);
  m.instantiate();
}

{'repo_name': 'tc39/test262', 'stars': '1439', 'repo_language': 'JavaScript', 'file_name': 'S11.8.4_A3.2_T1.1.js', 'mime_type': 'text/plain', 'hash': -3543581912564339935, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>API_KEY</key>
	<string>correct_api_key</string>
	<key>TRACKING_ID</key>
	<string>correct_tracking_id</string>
	<key>CLIENT_ID</key>
	<string>correct_client_id</string>
	<key>REVERSED_CLIENT_ID</key>
	<string>correct_reversed_client_id</string>
	<key>GOOGLE_APP_ID</key>
	<string>1:123:ios:123abc</string>
	<key>GCM_SENDER_ID</key>
	<string>correct_gcm_sender_id</string>
	<key>PLIST_VERSION</key>
	<string>1</string>
	<key>BUNDLE_ID</key>
	<string>com.google.FirebaseSDKTests</string>
	<key>PROJECT_ID</key>
	<string>abc-xyz-123</string>
	<key>DATABASE_URL</key>
	<string>https://abc-xyz-123.firebaseio.com</string>
	<key>STORAGE_BUCKET</key>
	<string>project-id-123.storage.firebase.com</string>
</dict>
</plist>

{'repo_name': 'firebase/firebase-ios-sdk', 'stars': '1976', 'repo_language': 'Objective-C', 'file_name': 'GoogleService-Info.plist', 'mime_type': 'text/xml', 'hash': 3353790122315629727, 'source_dataset': 'data'}


// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2009-2012 Vicente J. Botet Escriba

#ifndef BOOST_THREAD_LOCK_TRAITS_HPP
#define BOOST_THREAD_LOCK_TRAITS_HPP

#include <boost/thread/detail/config.hpp>
//#include <boost/thread/detail/move.hpp>
//#include <boost/thread/exceptions.hpp>
//
//#ifdef BOOST_THREAD_USES_CHRONO
//#include <boost/chrono/time_point.hpp>
//#include <boost/chrono/duration.hpp>
//#endif

#include <boost/type_traits/integral_constant.hpp>

#include <boost/config/abi_prefix.hpp>

namespace boost
{

/**
 * An strict lock is a lock ensuring the mutex is locked on the scope of the lock
 * There is no single way to define a strict lock as the strict_lock and
 * nesteed_strict_lock shows. So we need a metafunction that states if a
 * lock is a strict lock "sur parole".
 */

template <typename Lock>
struct is_strict_lock_sur_parolle : false_type {};

template <typename Lock>
struct is_strict_lock_sur_parole : is_strict_lock_sur_parolle<Lock> {};

template <typename Lock>
struct is_strict_lock : is_strict_lock_sur_parole<Lock> {};

}
#include <boost/config/abi_suffix.hpp>

#endif

{'repo_name': 'discourse/DiscourseMobile', 'stars': '153', 'repo_language': 'JavaScript', 'file_name': 'App-test.js', 'mime_type': 'text/x-java', 'hash': -1349921756527144969, 'source_dataset': 'data'}


package dns

// Dedup removes identical RRs from rrs. It preserves the original ordering.
// The lowest TTL of any duplicates is used in the remaining one. Dedup modifies
// rrs.
// m is used to store the RRs temporary. If it is nil a new map will be allocated.
func Dedup(rrs []RR, m map[string]RR) []RR {

	if m == nil {
		m = make(map[string]RR)
	}
	// Save the keys, so we don't have to call normalizedString twice.
	keys := make([]*string, 0, len(rrs))

	for _, r := range rrs {
		key := normalizedString(r)
		keys = append(keys, &key)
		if mr, ok := m[key]; ok {
			// Shortest TTL wins.
			rh, mrh := r.Header(), mr.Header()
			if mrh.Ttl > rh.Ttl {
				mrh.Ttl = rh.Ttl
			}
			continue
		}

		m[key] = r
	}
	// If the length of the result map equals the amount of RRs we got,
	// it means they were all different. We can then just return the original rrset.
	if len(m) == len(rrs) {
		return rrs
	}

	j := 0
	for i, r := range rrs {
		// If keys[i] lives in the map, we should copy and remove it.
		if _, ok := m[*keys[i]]; ok {
			delete(m, *keys[i])
			rrs[j] = r
			j++
		}

		if len(m) == 0 {
			break
		}
	}

	return rrs[:j]
}

// normalizedString returns a normalized string from r. The TTL
// is removed and the domain name is lowercased. We go from this:
// DomainName<TAB>TTL<TAB>CLASS<TAB>TYPE<TAB>RDATA to:
// lowercasename<TAB>CLASS<TAB>TYPE...
func normalizedString(r RR) string {
	// A string Go DNS makes has: domainname<TAB>TTL<TAB>...
	b := []byte(r.String())

	// find the first non-escaped tab, then another, so we capture where the TTL lives.
	esc := false
	ttlStart, ttlEnd := 0, 0
	for i := 0; i < len(b) && ttlEnd == 0; i++ {
		switch {
		case b[i] == '\\':
			esc = !esc
		case b[i] == '\t' && !esc:
			if ttlStart == 0 {
				ttlStart = i
				continue
			}
			if ttlEnd == 0 {
				ttlEnd = i
			}
		case b[i] >= 'A' && b[i] <= 'Z' && !esc:
			b[i] += 32
		default:
			esc = false
		}
	}

	// remove TTL.
	copy(b[ttlStart:], b[ttlEnd:])
	cut := ttlEnd - ttlStart
	return string(b[:len(b)-cut])
}

{'repo_name': 'prometheus/alertmanager', 'stars': '3306', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': 6287950624686105094, 'source_dataset': 'data'}


# Author: Rishabh Chauhan
# License: BSD
# Location for tests  of FreeNAS new GUI
# Test case count: 1

import sys
import os
cwd = str(os.getcwd())
sys.path.append(cwd)
from function import take_screenshot

skip_mesages = "Skipping first run"
script_name = os.path.basename(__file__).partition('.')[0]

xpaths = {
    'navSystem': "//span[contains(.,'System')]",
    'submenuCertificates': "//a[contains(text(),'Certificates')]",
    'breadcrumbBar1': "//div[@id='breadcrumb-bar']/ul/li/a",
    'breadcrumbBar2': "//*[@id='breadcrumb-bar']/ul/li[2]/a"
}

def test_01_nav_system_certificates(browser):
    browser.find_element_by_xpath(xpaths['submenuCertificates']).click()
    # get the ui element
    ui_element = browser.find_element_by_xpath(xpaths['breadcrumbBar1'])
    # get the weather data
    page_data = ui_element.text
    # assert response
    assert "System" in page_data, page_data
    # get the ui element
    ui_element = browser.find_element_by_xpath(xpaths['breadcrumbBar2'])
    # get the weather data
    page_data = ui_element.text
    # assert response
    assert "Certificates" in page_data, page_data
    # taking screenshot
    test_name = sys._getframe().f_code.co_name
    take_screenshot(browser, script_name, test_name)

{'repo_name': 'freenas/webui', 'stars': '113', 'repo_language': 'TypeScript', 'file_name': 'format', 'mime_type': 'text/plain', 'hash': -1949121477532959449, 'source_dataset': 'data'}


import tornado
from tornado import escape, gen, websocket

try:
    from urllib.parse import urlparse # py3
except ImportError:
    from urlparse import urlparse # py2

class SockJSWebSocketHandler(websocket.WebSocketHandler):
    if tornado.version_info[0] == 4 and tornado.version_info[1] > 1:
        def get_compression_options(self):
            # let tornado use compression when Sec-WebSocket-Extensions:permessage-deflate is provided
            return {}

    def check_origin(self, origin):
        # let tornado first check if connection from the same domain
        same_domain = super(SockJSWebSocketHandler, self).check_origin(origin)
        if same_domain:
            return True

        # this is cross-origin connection - check using SockJS server settings
        allow_origin = self.server.settings.get("websocket_allow_origin", "*")
        if allow_origin == "*":
            return True
        else:
            parsed_origin = urlparse(origin)
            origin = parsed_origin.netloc
            origin = origin.lower()
            return origin in allow_origin

    def abort_connection(self):
        if self.ws_connection:
            self.ws_connection._abort()

    @gen.coroutine
    def _execute(self, transforms, *args, **kwargs):
        self._transforms = transforms
        # Websocket only supports GET method
        if self.request.method != "GET":
            self.set_status(405)
            self.set_header("Allow", "GET")
            self.set_header("Connection", "Close")
            self.finish("WebSocket only supports GET requests.")
            return

        # Upgrade header should be present and should be equal to WebSocket
        if self.request.headers.get("Upgrade", "").lower() != "websocket":
            self.set_status(400)
            self.set_header("Connection", "Close")
            self.finish("Can \"Upgrade\" only to \"WebSocket\".")
            return

        # Connection header should be upgrade. Some proxy servers/load balancers
        # might mess with it.
        headers = self.request.headers
        connection = map(lambda s: s.strip().lower(), headers.get("Connection", "").split(","))
        if "upgrade" not in connection:
            self.set_status(400)
            self.set_header("Connection", "Close")
            self.finish("\"Connection\" must be \"Upgrade\".")
            return

        yield super(SockJSWebSocketHandler, self)._execute(transforms, *args, **kwargs)

{'repo_name': 'AstroPrint/AstroBox', 'stars': '138', 'repo_language': 'Python', 'file_name': '__init__.py', 'mime_type': 'text/x-python', 'hash': -9192362148376998071, 'source_dataset': 'data'}


/*****************************************************************************
 * Copyright (C) 2007-2012 Pierre d'Herbemont and VideoLAN
 *
 * Authors: Pierre d'Herbemont
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#import "Controller.h"

/**********************************************************
 * First off, some value transformer to easily play with
 * bindings
 */
@interface VLCFloat10000FoldTransformer : NSObject
@end

@implementation VLCFloat10000FoldTransformer

+ (Class)transformedValueClass
{
    return [NSNumber class];
}

+ (BOOL)allowsReverseTransformation
{
    return YES;
}

- (id)transformedValue:(id)value
{
    if( !value ) return nil;

    if(![value respondsToSelector: @selector(floatValue)])
    {
        [NSException raise: NSInternalInconsistencyException
                    format: @"Value (%@) does not respond to -floatValue.",
        [value class]];
        return nil;
    }

    return [NSNumber numberWithFloat: [value floatValue]*10000.];
}

- (id)reverseTransformedValue:(id)value
{
    if( !value ) return nil;

    if(![value respondsToSelector: @selector(floatValue)])
    {
        [NSException raise: NSInternalInconsistencyException
                    format: @"Value (%@) does not respond to -floatValue.",
        [value class]];
        return nil;
    }

    return [NSNumber numberWithFloat: [value floatValue]/10000.];
}
@end

/**********************************************************
 * @implementation Controller
 */
@interface Controller ()
@property (retain,readwrite) NSString * outputFolderPath;
@end

@implementation Controller
- (id)init
{
    if(self = [super init])
    {
        [self bind:@"outputFolderPath" toObject:[NSUserDefaultsController sharedUserDefaultsController]
              withKeyPath:@"values.outputFolderPath" options:nil];
        [[[NSUserDefaultsController sharedUserDefaultsController] values] bind:@"outputFolderPath" toObject:self
              withKeyPath:@"outputFolderPath" options:nil];
        VLCFloat10000FoldTransformer *float100fold;
        float100fold = [[[VLCFloat10000FoldTransformer alloc] init] autorelease];
        [NSValueTransformer setValueTransformer:(id)float100fold forName:@"Float10000FoldTransformer"];
        self.media = nil;
        self.streamSession = nil;
        selectedStreamOutput = [[NSNumber alloc] initWithInt:0];
        self.remoteURLAsString = @"http://youtube.com/watch?v=IXpx2OEWBdA&feature=bz303";
        outputFilePath = nil;
        if( !self.outputFolderPath || [self.outputFolderPath isKindOfClass:[NSNull class]])
            self.outputFolderPath = [@"~/Movies/Flash Video Converted" stringByExpandingTildeInPath];
    }
    return self;
}

- (void)dealloc
{
    [outputFilePath release];
    [remoteURLAsString release];
    [streamSession release];
    [media release];
    [super dealloc];
}

@synthesize streamSession;
@synthesize selectedStreamOutput;
@synthesize media;
@synthesize outputFolderPath;

- (void)awakeFromNib
{
    [window setShowsResizeIndicator:NO];
    [NSApp setDelegate: self];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [VLCLibrary sharedLibrary];
}

- (NSString *)remoteURLAsString
{
    return remoteURLAsString;
}

- (void)setRemoteURLAsString:(NSString *)newURLAsString
{
    [remoteURLAsString release];
    remoteURLAsString = [[newURLAsString copy] retain];
    media = [[newURLAsString copy] retain];
    [self setMedia:[VLCMedia mediaWithPath:newURLAsString]];
}

+ (NSSet *)keyPathsForValuesAffectingOutputFilePath
{
    return [NSSet setWithObjects:@"media.metaDictionary.title", nil];
}

- (void)freezeOutputFilePath
{
    [outputFilePath release];
    outputFilePath = nil;
    outputFilePath = [self outputFilePath];
    [outputFilePath retain];
}

- (NSString *)outputFilePath
{
    if(outputFilePath)
        return [outputFilePath copy];
    VLCMedia * aMedia = self.streamSession ? self.streamSession.media ? self.streamSession.media : self.media : self.media;
    NSString * name = [[[aMedia metaDictionary] objectForKey:@"title"] lastPathComponent];
    NSString * extension = [selectedStreamOutput intValue] == 2 ? @"mpeg" : @"mp4";
    NSString * path = [NSString stringWithFormat:@"%@/%@.%@", self.outputFolderPath, name, extension ];
    int i;
    for( i = 0; [[NSFileManager defaultManager] fileExistsAtPath:path]; i ++)
    {
        path = [NSString stringWithFormat:@"%@/%@ %d.%@", self.outputFolderPath, name, i, extension ];
        if( i > 256 )
        {
            /* Don't got too far */
            /* FIXME: Be nicer with the user and give him a choice for the new name */
            NSRunAlertPanelRelativeToWindow(@"File already exists",
                [NSString stringWithFormat:
                    @"File '%@', already exists. The old one will be deleted when the OK button will be pressed", path],
                @"OK", nil, nil, window);
            break;
        }
    }
    return path;
}

- (IBAction)convert:(id)sender
{
    VLCStreamOutput * streamOutput;
    [self.streamSession removeObserver:self forKeyPath:@"isComplete"];

    self.streamSession = [VLCStreamSession streamSession];
    [self freezeOutputFilePath];

    if([selectedStreamOutput intValue] == 2)
    {
        streamOutput = [VLCStreamOutput mpeg2StreamOutputWithFilePath:[self outputFilePath]];
    }
    else if([selectedStreamOutput intValue] == 1)
    {
        streamOutput = [VLCStreamOutput mpeg4StreamOutputWithFilePath:[self outputFilePath]];
    }
    else
        streamOutput = [VLCStreamOutput ipodStreamOutputWithFilePath:[self outputFilePath]];

    /* Make sure we are exporting to a well known directory */
    [[NSFileManager defaultManager] createDirectoryAtPath:self.outputFolderPath attributes:nil];

    [self.streamSession setStreamOutput:streamOutput];
    [self.streamSession setMedia:self.media];
    [self.streamSession startStreaming];

    [self.streamSession addObserver:self forKeyPath:@"isComplete" options:NSKeyValueObservingOptionNew context:nil];

    /* Show the new view */
    [[window contentView] addSubview:workingView];
    NSRect frame = [workingView frame];
    frame.origin.y -= NSHeight([window contentRectForFrameRect:[window frame]]) + 20.f;
    [workingView setFrame:frame];
    [[window animator] setFrame:NSMakeRect([window frame].origin.x, [window frame].origin.y-NSHeight([workingView frame]), NSWidth([window frame]), NSHeight([window frame])+NSHeight([workingView frame])) display:YES];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"isComplete"])
    {
        if([self.streamSession isComplete])
        {
            /* Notify the user */
            [[NSSound soundNamed:@"Glass"] play];

            /* Set the icon */
            [openConvertedFileButton setImage:[[NSWorkspace sharedWorkspace] iconForFile:[self outputFilePath]]];

            /* Rename the link with a nicer name */
            NSString * oldPath = [self outputFilePath];
            [self freezeOutputFilePath];
            [[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:[self outputFilePath] error:NULL];
        }
        return;
    }
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}

- (IBAction)openConvertedFile:(id)sender
{
    [[NSWorkspace sharedWorkspace] openFile:[self outputFilePath]];
}

- (IBAction)pickOutputFolderPath:(id)sender;
{
    NSOpenPanel * panel = [NSOpenPanel openPanel];
    [panel setCanChooseFiles:NO];
    [panel setCanChooseDirectories:YES];
    [panel setAllowsMultipleSelection:NO];
    [panel beginSheetForDirectory:self.outputFolderPath file:nil types:nil modalForWindow:[sender window] modalDelegate:self didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

- (void)openPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode  contextInfo:(void  *)contextInfo
{
    if(returnCode != NSOKButton || ![[panel filenames] count])
        return;
    self.outputFolderPath = [[panel filenames] objectAtIndex:0];
}

- (IBAction)openConvertedEnclosingFolder:(id)sender
{
    [[NSWorkspace sharedWorkspace] selectFile:[self outputFilePath] inFileViewerRootedAtPath:[[self outputFilePath] stringByDeletingLastPathComponent]];
}

- (IBAction)cancel:(id)sender
{
    [self.streamSession stop];
}

@end

{'repo_name': 'videolan/vlckit', 'stars': '194', 'repo_language': 'Objective-C', 'file_name': 'MobileVLCKit.podspec', 'mime_type': 'text/plain', 'hash': 6544419066114518287, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: 057269281faafa24c883dd0187910002
TextureImporter:
  internalIDToNameTable:
  - first:
      213: 21300000
    second: monkey_r_arm_10_0
  - first:
      213: 21300002
    second: monkey_r_arm_10_1
  - first:
      213: 21300004
    second: monkey_r_arm_10_2
  - first:
      213: 21300006
    second: monkey_r_arm_10_3
  externalObjects: {}
  serializedVersion: 10
  mipmaps:
    mipMapMode: 0
    enableMipMap: 0
    sRGBTexture: 1
    linearTexture: 0
    fadeOut: 0
    borderMipMap: 0
    mipMapsPreserveCoverage: 0
    alphaTestReferenceValue: 0.5
    mipMapFadeDistanceStart: 1
    mipMapFadeDistanceEnd: 3
  bumpmap:
    convertToNormalMap: 0
    externalNormalMap: 0
    heightScale: 0.25
    normalMapFilter: 0
  isReadable: 1
  streamingMipmaps: 0
  streamingMipmapsPriority: 0
  grayScaleToAlpha: 0
  generateCubemap: 6
  cubemapConvolution: 0
  seamlessCubemap: 0
  textureFormat: 1
  maxTextureSize: 2048
  textureSettings:
    serializedVersion: 2
    filterMode: 0
    aniso: -1
    mipBias: -100
    wrapU: 1
    wrapV: 1
    wrapW: 1
  nPOTScale: 0
  lightmap: 0
  compressionQuality: 50
  spriteMode: 2
  spriteExtrude: 1
  spriteMeshType: 0
  alignment: 0
  spritePivot: {x: 0.5, y: 0.5}
  spritePixelsToUnits: 32
  spriteBorder: {x: 0, y: 0, z: 0, w: 0}
  spriteGenerateFallbackPhysicsShape: 1
  alphaUsage: 1
  alphaIsTransparency: 1
  spriteTessellationDetail: -1
  textureType: 8
  textureShape: 1
  singleChannelComponent: 0
  maxTextureSizeSet: 0
  compressionQualitySet: 0
  textureFormatSet: 0
  platformSettings:
  - serializedVersion: 3
    buildTarget: DefaultTexturePlatform
    maxTextureSize: 2048
    resizeAlgorithm: 0
    textureFormat: 4
    textureCompression: 1
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 0
    androidETC2FallbackOverride: 0
    forceMaximumCompressionQuality_BC6H_BC7: 1
  - serializedVersion: 3
    buildTarget: Standalone
    maxTextureSize: 2048
    resizeAlgorithm: 0
    textureFormat: 4
    textureCompression: 1
    compressionQuality: 50
    crunchedCompression: 0
    allowsAlphaSplitting: 0
    overridden: 0
    androidETC2FallbackOverride: 0
    forceMaximumCompressionQuality_BC6H_BC7: 1
  spriteSheet:
    serializedVersion: 2
    sprites:
    - serializedVersion: 2
      name: monkey_r_arm_10_0
      rect:
        serializedVersion: 2
        x: 0
        y: 0
        width: 32
        height: 32
      alignment: 0
      pivot: {x: 0, y: 0}
      border: {x: 0, y: 0, z: 0, w: 0}
      outline: []
      physicsShape: []
      tessellationDetail: 0
      bones: []
      spriteID: b16489681e753a24ab39d1f4a26cd82a
      internalID: 21300000
      vertices: []
      indices:
      edges: []
      weights: []
    - serializedVersion: 2
      name: monkey_r_arm_10_1
      rect:
        serializedVersion: 2
        x: 32
        y: 0
        width: 32
        height: 32
      alignment: 0
      pivot: {x: 0, y: 0}
      border: {x: 0, y: 0, z: 0, w: 0}
      outline: []
      physicsShape: []
      tessellationDetail: 0
      bones: []
      spriteID: b16489681e753a24ab39d1f4a26cd82a
      internalID: 21300002
      vertices: []
      indices:
      edges: []
      weights: []
    - serializedVersion: 2
      name: monkey_r_arm_10_2
      rect:
        serializedVersion: 2
        x: 64
        y: 0
        width: 32
        height: 32
      alignment: 0
      pivot: {x: 0, y: 0}
      border: {x: 0, y: 0, z: 0, w: 0}
      outline: []
      physicsShape: []
      tessellationDetail: 0
      bones: []
      spriteID: b16489681e753a24ab39d1f4a26cd82a
      internalID: 21300004
      vertices: []
      indices:
      edges: []
      weights: []
    - serializedVersion: 2
      name: monkey_r_arm_10_3
      rect:
        serializedVersion: 2
        x: 96
        y: 0
        width: 32
        height: 32
      alignment: 0
      pivot: {x: 0, y: 0}
      border: {x: 0, y: 0, z: 0, w: 0}
      outline: []
      physicsShape: []
      tessellationDetail: 0
      bones: []
      spriteID: b16489681e753a24ab39d1f4a26cd82a
      internalID: 21300006
      vertices: []
      indices:
      edges: []
      weights: []
    outline: []
    physicsShape: []
    bones: []
    spriteID: 280b93732caf29f42b334a277f625760
    internalID: 0
    vertices: []
    indices:
    edges: []
    weights: []
    secondaryTextures: []
  spritePackingTag:
  pSDRemoveMatte: 0
  pSDShowRemoveMatteOption: 0
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'unitystation/unitystation', 'stars': '507', 'repo_language': 'C#', 'file_name': 'misc.meta', 'mime_type': 'text/plain', 'hash': 8851562075888531046, 'source_dataset': 'data'}


;;;Copyright (c) 2008 Matthew Flatt
;;;Modified by Marco Maggi <marco.maggi-ipsu@poste.it>
;;;
;;;This library is free software;  you can redistribute it and/or modify
;;;it  under the  terms of  the GNU  Library General  Public  License as
;;;published by  the Free Software  Foundation; either version 2  of the
;;;License, or (at your option) any later version.
;;;
;;;This library is  distributed in the hope that it  will be useful, but
;;;WITHOUT  ANY   WARRANTY;  without   even  the  implied   warranty  of
;;;MERCHANTABILITY  or FITNESS FOR  A PARTICULAR  PURPOSE.  See  the GNU
;;;Library General Public License for more details.
;;;
;;;You should  have received  a copy of  the GNU Library  General Public
;;;License along with  this library; if not, write  to the Free Software
;;;Foundation,  Inc.,  51  Franklin  Street,  Fifth  Floor,  Boston,  MA
;;;02110-1301 USA.

#!r6rs
(import (r6rs syntax-case)
  (r6rs test)
  (rnrs io simple)
  (only (vicare checks)
	check-display))
(check-display "*** Flatt's R6RS tests for (rnrs syntax-case)\n\n")
(run-syntax-case-tests)
(report-test-results)

;;; end of file

{'repo_name': 'marcomaggi/vicare', 'stars': '183', 'repo_language': 'Scheme', 'file_name': 'rfc4291.ipv6-address-achitecture.txt', 'mime_type': 'text/plain', 'hash': -6186704254142617065, 'source_dataset': 'data'}


// This file is part of CaesarIA.
//
// CaesarIA is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// CaesarIA is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with CaesarIA.  If not, see <http://www.gnu.org/licenses/>.
//
// Copyright 2012-2014 Dalerank, dalerankn8@gmail.com

#include "prefecture.hpp"
#include "gfx/picture.hpp"
#include "game/resourcegroup.hpp"
#include "core/position.hpp"
#include "walker/prefect.hpp"
#include "pathway/pathway_helper.hpp"
#include "gfx/tile.hpp"
#include "city/city.hpp"
#include "pathway/path_finding.hpp"
#include "city/statistic.hpp"
#include "gfx/tilemap.hpp"
#include "city/cityservice_fire.hpp"
#include "objects/constants.hpp"
#include "objects_factory.hpp"

using namespace gfx;

REGISTER_CLASS_IN_OVERLAYFACTORY(object::prefecture, Prefecture)

class Prefecture::Impl
{
public:
  TilePos fireDetect;

public:
  TilePos checkFireDetect(PlayerCityPtr city , const TilePos& pos);
};

Prefecture::Prefecture()
  : ServiceBuilding(Service::prefect, object::prefecture, Size::square(1)),
    _d( new Impl )
{
  _d->fireDetect = TilePos::invalid();

  setPicture( info().randomPicture( size() ) );
  _fgPictures().resize(1);
}

Prefecture::~Prefecture() {}

void Prefecture::timeStep(const unsigned long time)
{
  ServiceBuilding::timeStep( time );
}

void Prefecture::deliverService()
{
  if( !isActive() )
    return;

  if( numberWorkers() > 0 && walkers().size() == 0 )
  {
    TilePos fireDetectPos = _d->checkFireDetect( _city(), pos() );
    bool fireDetect = fireDetectPos.i() >= 0;
    PrefectPtr prefect = Walker::create<Prefect>( _city() );
    prefect->setMaxDistance( walkerDistance() );

    if( fireDetect )
    {
      TilePos startPos = roadside().front()->pos();

      OverlayPtr ruin = _map().overlay( _d->fireDetect );
      Pathway pathway = PathwayHelper::create( startPos, ruin, PathwayHelper::allTerrain );

      bool fireInOutWorkArea = pathway.length() <= walkerDistance();
      if( pathway.isValid() && fireInOutWorkArea )
      {
        pathway.setNextTile( ruin->tile() );
        prefect->setPos( pathway.startPos() );
        prefect->setBase( this );
        prefect->setPathway( pathway );
        prefect->go();
      }
      else
      {
        fireDetect = false;
      }

      _d->fireDetect = TilePos::invalid();
    }

    prefect->send2City( this, Prefect::patrol, fireDetect ? 1000 : 0 );

    addWalker( prefect.object() );
  }
}

unsigned int Prefecture::walkerDistance() const { return 26; }
void Prefecture::fireDetect( const TilePos& pos ){ _d->fireDetect = pos; }

TilePos Prefecture::Impl::checkFireDetect( PlayerCityPtr city, const TilePos& pos )
{
  if( fireDetect.i() >= 0 )
    return fireDetect;

  city::FirePtr fire = city->statistic().services.find<city::Fire>();

  fireDetect = TilePos::invalid();
  int minDistance = 9999;
  for( auto& location : fire->locations() )
  {
    int currentDistance = pos.distanceFrom( location );
    if( currentDistance < minDistance )
    {
      minDistance = currentDistance;
      fireDetect = location;
    }
  }

  return fireDetect;
}

{'repo_name': 'dalerank/caesaria-game', 'stars': '191', 'repo_language': 'C', 'file_name': 'Android.mk', 'mime_type': 'text/plain', 'hash': -2857792657962293771, 'source_dataset': 'data'}


/*
 * linux/fs/nls/nls_koi8-ru.c
 *
 * Charset koi8-ru translation based on charset koi8-u.
 * The Unicode to charset table has only exact mappings.
 */

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/nls.h>
#include <linux/errno.h>

static struct nls_table *p_nls;

static int uni2char(const wchar_t uni,
		    unsigned char *out, int boundlen)
{
	if (boundlen <= 0)
		return -ENAMETOOLONG;

	if ((uni & 0xffaf) == 0x040e || (uni & 0xffce) == 0x254c) {
		/* koi8-ru and koi8-u differ only on two characters */
		if (uni == 0x040e)
			out[0] = 0xbe;
		else if (uni == 0x045e)
			out[0] = 0xae;
		else if (uni == 0x255d || uni == 0x256c)
			return 0;
		else
			return p_nls->uni2char(uni, out, boundlen);
		return 1;
	}
	else
		/* fast path */
		return p_nls->uni2char(uni, out, boundlen);
}

static int char2uni(const unsigned char *rawstring, int boundlen,
		    wchar_t *uni)
{
	int n;

	if ((*rawstring & 0xef) != 0xae) {
		/* koi8-ru and koi8-u differ only on two characters */
		*uni = (*rawstring & 0x10) ? 0x040e : 0x045e;
		return 1;
	}

	n = p_nls->char2uni(rawstring, boundlen, uni);
	return n;
}

static struct nls_table table = {
	.charset	= "koi8-ru",
	.uni2char	= uni2char,
	.char2uni	= char2uni,
	.owner		= THIS_MODULE,
};

static int __init init_nls_koi8_ru(void)
{
	p_nls = load_nls("koi8-u");

	if (p_nls) {
		table.charset2upper = p_nls->charset2upper;
		table.charset2lower = p_nls->charset2lower;
		return register_nls(&table);
	}

	return -EINVAL;
}

static void __exit exit_nls_koi8_ru(void)
{
	unregister_nls(&table);
	unload_nls(p_nls);
}

module_init(init_nls_koi8_ru)
module_exit(exit_nls_koi8_ru)

MODULE_LICENSE("Dual BSD/GPL");

{'repo_name': 'longsleep/linux-pine64', 'stars': '103', 'repo_language': 'C', 'file_name': 'HalBtc8192d2Ant.c', 'mime_type': 'text/x-c', 'hash': 380802569502481251, 'source_dataset': 'data'}


// script.aculo.us scriptaculous.js v1.8.0, Tue Nov 06 15:01:40 +0300 2007

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Scriptaculous = {
  Version: '1.8.0',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
  },
  REQUIRED_PROTOTYPE: '1.6.0',
  load: function() {
    function convertVersionString(versionString){
      var r = versionString.split('.');
      return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
    }

    if((typeof Prototype=='undefined') ||
       (typeof Element == 'undefined') ||
       (typeof Element.Methods=='undefined') ||
       (convertVersionString(Prototype.Version) <
        convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
       throw("script.aculo.us requires the Prototype JavaScript framework >= " +
        Scriptaculous.REQUIRED_PROTOTYPE);

    $A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
       function(include) { Scriptaculous.require(path+include+'.js') });
    });
  }
}

Scriptaculous.load();

{'repo_name': 'jcnetdev/jobberrails', 'stars': '117', 'repo_language': 'JavaScript', 'file_name': 'jquery.form.js', 'mime_type': 'text/plain', 'hash': 3482510495108115704, 'source_dataset': 'data'}


// © 2014 - 2017 Soverance Studios
// http://www.soverance.com

// 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, softHunterse
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT HuntersRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "Ethereal.h"
#include "HuntersBoots.h"

#define LOCTEXT_NAMESPACE "EtherealText"

// Sets default values
AHuntersBoots::AHuntersBoots(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	// Get Assets, References Obtained Via Right Click in Editor
	static ConstructorHelpers::FObjectFinder<UTexture2D> LargeIconObject(TEXT("Texture2D'/Game/Blueprints/Widgets/UI-Images/Icons_Gear/ArmorIcon_HuntersBoots.ArmorIcon_HuntersBoots'"));
	static ConstructorHelpers::FObjectFinder<UTexture2D> SmallIconObject(TEXT("Texture2D'/Game/Blueprints/Widgets/UI-Images/Icons_Gear/ArmorIcon_HuntersBoots-small.ArmorIcon_HuntersBoots-small'"));
	static ConstructorHelpers::FObjectFinder<USkeletalMesh> ArmorMeshObject(TEXT("SkeletalMesh'/Game/EtherealParty/Morgan/Clothes/HuntersGarb/HuntersBoots/HuntersBoots.HuntersBoots'"));

	// Set Default Objects
	LargeIcon = LargeIconObject.Object;
	SmallIcon = SmallIconObject.Object;

	SK_ArmorMesh = ArmorMeshObject.Object;
	ArmorMesh = ObjectInitializer.CreateDefaultSubobject<USkeletalMeshComponent>(this, TEXT("ArmorMesh"));
	ArmorMesh->SetSkeletalMesh(SK_ArmorMesh);
	ArmorMesh->SetupAttachment(RootComponent);
	UCommonLibrary::SetupSKComponentsWithCollision(ArmorMesh);

	// Set Default Values
	Name = EMasterGearList::GL_HuntersBoots;
	NameText = LOCTEXT("HuntersBootsName", "Hunters Boots");
	Type = EMasterGearTypes::GT_Feet;
	TypeText = LOCTEXT("HuntersBootsType", "Feet");
	Description = "Armor of Ethereal Hunters.";
	Price = 45000;
	MPCost = 0;
	ATK = 17;
	DEF = 5;
	SPD = 5;
	HP = 50;
	MP = 25;
	SpecialEffectText = LOCTEXT("HuntersBootsSpecialEffect", "+ Lightfooted");
}

// Called when the game starts or when spawned
void AHuntersBoots::BeginPlay()
{
	Super::BeginPlay();

	// Bind this function to the event dispatcher for Bind Gear
	OnBindGear.AddDynamic(this, &AHuntersBoots::DoSpecialEffect);
	OnRemoveGear.AddDynamic(this, &AHuntersBoots::RemoveSpecialEffect);
}

// Custom code for Special Effect
void AHuntersBoots::DoSpecialEffect()
{
	OwnerReference->HasLightfoot = true;
}

// Custom code for Special Effect
void AHuntersBoots::RemoveSpecialEffect()
{
	OwnerReference->HasLightfoot = false;
}

#undef LOCTEXT_NAMESPACE

{'repo_name': 'Soverance/EtherealLegends', 'stars': '164', 'repo_language': 'C++', 'file_name': 'DropFire.h', 'mime_type': 'text/x-c++', 'hash': 8586978467446056138, 'source_dataset': 'data'}


// SPDX-License-Identifier: GPL-2.0

/*
 * media_device_open.c - Media Controller Device Open Test
 *
 * Copyright (c) 2016 Shuah Khan <shuahkh@osg.samsung.com>
 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
 *
 */

/*
 * This file adds a test for Media Controller API.
 * This test should be run as root and should not be
 * included in the Kselftest run. This test should be
 * run when hardware and driver that makes use Media
 * Controller API are present in the system.
 *
 * This test opens user specified Media Device and calls
 * MEDIA_IOC_DEVICE_INFO ioctl, closes the file, and exits.
 *
 * Usage:
 *	sudo ./media_device_open -d /dev/mediaX
 *
 *	Run this test is a loop and run bind/unbind on the driver.
*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <linux/media.h>

#include "../kselftest.h"

int main(int argc, char **argv)
{
	int opt;
	char media_device[256];
	int count = 0;
	struct media_device_info mdi;
	int ret;
	int fd;

	if (argc < 2) {
		printf("Usage: %s [-d </dev/mediaX>]\n", argv[0]);
		exit(-1);
	}

	/* Process arguments */
	while ((opt = getopt(argc, argv, "d:")) != -1) {
		switch (opt) {
		case 'd':
			strncpy(media_device, optarg, sizeof(media_device) - 1);
			media_device[sizeof(media_device)-1] = '\0';
			break;
		default:
			printf("Usage: %s [-d </dev/mediaX>]\n", argv[0]);
			exit(-1);
		}
	}

	if (getuid() != 0)
		ksft_exit_skip("Please run the test as root - Exiting.\n");

	/* Open Media device and keep it open */
	fd = open(media_device, O_RDWR);
	if (fd == -1) {
		printf("Media Device open errno %s\n", strerror(errno));
		exit(-1);
	}

	ret = ioctl(fd, MEDIA_IOC_DEVICE_INFO, &mdi);
	if (ret < 0)
		printf("Media Device Info errno %s\n", strerror(errno));
	else
		printf("Media device model %s driver %s\n",
			mdi.model, mdi.driver);
}

{'repo_name': 'RadeonOpenCompute/ROCK-Kernel-Driver', 'stars': '135', 'repo_language': 'C', 'file_name': 'pinctrl-zx.c', 'mime_type': 'text/x-c', 'hash': 3286927284698063151, 'source_dataset': 'data'}


pragma solidity >=0.5.0 <0.6.0;

contract IEscrow {

  enum EscrowStatus {CREATED, FUNDED, PAID, RELEASED, CANCELED}

  struct EscrowTransaction {
      uint256 offerId;
      address token;
      uint256 tokenAmount;
      uint256 expirationTime;
      uint256 sellerRating;
      uint256 buyerRating;
      uint256 fiatAmount;
      address payable buyer;
      address payable seller;
      address payable arbitrator;
      address payable destination;
      EscrowStatus status;
  }

  function createEscrow_relayed(
        address payable _sender,
        uint _offerId,
        uint _tokenAmount,
        uint _fiatAmount,
        address payable _destination,
        string calldata _contactData,
        string calldata _location,
        string calldata _username
    ) external returns(uint escrowId);

  function updateDestination(uint _escrowId, address payable _destination) external;

  function pay(uint _escrowId) external;

  function pay_relayed(address _sender, uint _escrowId) external;

  function cancel(uint _escrowId) external;

  function cancel_relayed(address _sender, uint _escrowId) external;

  function openCase(uint  _escrowId, uint8 _motive) external;

  function openCase_relayed(address _sender, uint256 _escrowId, uint8 _motive) external;

  function rateTransaction(uint _escrowId, uint _rate) external;

  function rateTransaction_relayed(address _sender, uint _escrowId, uint _rate) external;

  function getBasicTradeData(uint _escrowId) external view returns(address payable buyer, address payable seller, address token, uint tokenAmount);

}

{'repo_name': 'embarklabs/embark', 'stars': '3047', 'repo_language': 'JavaScript', 'file_name': 'globalize.js', 'mime_type': 'text/plain', 'hash': 6731738028538258347, 'source_dataset': 'data'}


package crontab

import (
	"time"
)

type Expression interface {
	Next(fromTime time.Time) time.Time
}

type CrontabLine struct {
	Expression Expression
	Schedule   string
	Command    string
}

type Job struct {
	CrontabLine
	Position int
}

type Context struct {
	Shell   string
	Environ map[string]string
}

type Crontab struct {
	Jobs    []*Job
	Context *Context
}

{'repo_name': 'aptible/supercronic', 'stars': '753', 'repo_language': 'Go', 'file_name': 'cron_test.go', 'mime_type': 'text/plain', 'hash': 3843843018948049094, 'source_dataset': 'data'}


{{# def.definitions }}
{{# def.errors }}
{{# def.setupKeyword }}
{{# def.setupNextLevel }}

{{
  var $currentBaseId = $it.baseId
    , $allSchemasEmpty = true;
}}

{{~ $schema:$sch:$i }}
  {{? {{# def.nonEmptySchema:$sch }} }}
    {{
      $allSchemasEmpty = false;
      $it.schema = $sch;
      $it.schemaPath = $schemaPath + '[' + $i + ']';
      $it.errSchemaPath = $errSchemaPath + '/' + $i;
    }}

    {{# def.insertSubschemaCode }}

    {{# def.ifResultValid }}
  {{?}}
{{~}}

{{? $breakOnError }}
  {{? $allSchemasEmpty }}
    if (true) {
  {{??}}
    {{= $closingBraces.slice(0,-1) }}
  {{?}}
{{?}}

{{# def.cleanUp }}

{'repo_name': 'sx1989827/DOClever', 'stars': '2669', 'repo_language': 'JavaScript', 'file_name': 'parse.js', 'mime_type': 'text/plain', 'hash': 1166574617925430991, 'source_dataset': 'data'}


[manifest]
name = katran
fbsource_path = fbcode/katran
shipit_project = katran
shipit_fbcode_builder = true

[git]
repo_url = https://github.com/facebookincubator/katran.git

[build.not(os=linux)]
builder = nop

[build.os=linux]
builder = cmake
subdir = .

[cmake.defines.test=on]
BUILD_TESTS=ON

[cmake.defines.test=off]
BUILD_TESTS=OFF

[dependencies]
folly
fizz
libbpf
libmnl
zlib
googletest

[shipit.pathmap]
fbcode/katran/public_root = .
fbcode/katran = katran

[shipit.strip]
^fbcode/katran/facebook
^fbcode/katran/OSS_SYNC

{'repo_name': 'facebook/proxygen', 'stars': '6739', 'repo_language': 'C++', 'file_name': 'proxygen-config.cmake.in', 'mime_type': 'text/plain', 'hash': -5409226430377396071, 'source_dataset': 'data'}


//
//  ALPHATCC.h
//  Alpha
//
//  Created by Dal Rupnik on 18/10/15.
//  Copyright © 2015 Unified Sense. All rights reserved.
//

@import Foundation;

int TCCAccessRequest(NSString *service, NSString *message, int completion); // Triggers permission request
int TCCAccessPreflight(NSString *service); // Checks for permission settings
int TCCAccessRestricted(NSString *service); //

//
// Methods for system processes
//
// Note: calling them on a non-privileged process will emit a notice in OS console:
//  tccd[102] <Notice>: Refusing <Method name> from unprivileged client (pid <PID>)
//
/*int TCCAccessCheckAuditToken(int a1, char a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10);
int TCCAccessCopyInformation(NSString* service, SEL a2); // This one is called by Preferences
int TCCAccessCopyInformationInternal(int a1);
int TCCAccessCopyInformationForBundle(NSString *bundleIdentifier);
int TCCAccessCopyBundleIdentifiersForService(int a1);
int TCCAccessCopyBundleIdentifiersDisabledForService(int a1);
int TCCAccessSetOverride(int a1, char a2);
int TCCAccessSetForBundle(NSString *service, CFBundleRef bundle, BOOL access); // This is called by Preferences
int TCCAccessSetInternal(int a1, int a2, int a3, int a4, char a5);
int TCCAccessSet(int a1, int a2, char a3);
int TCCAccessSetForPath(int a1, int a2, int a3, char a4);
int TCCAccessSetForAuditToken(int a1, int a2, char a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, char a11);
int TCCAccessOverride(int a1, char a2);
int TCCAccessGetOverride(int a1, int a2); // This is called by Preferences to get value
int TCCAccessReset(int a1);
int TCCAccessResetForBundle(int a1, int a2);
int TCCAccessResetForPath(int a1, int a2);
int TCCAccessResetInternal(int a1, int a2, int a3);
int TCCAccessDeclarePolicy(int a1, int a2);
int TCCAccessSelectPolicyForExtensionWithIdentifier(int a1, int a2);
int TCCAccessResetPoliciesExcept(int a1);
int TCCTestInternal(int a1, int a2, int a3);

// Sends to daemon
int tccd(void); // weak
int tccd_send(int a1, int a2, int a3);*/

{'repo_name': 'Legoless/Alpha', 'stars': '727', 'repo_language': 'Objective-C', 'file_name': 'ALPHAFailureRecorder.m', 'mime_type': 'text/x-objective-c', 'hash': -1395065813315725864, 'source_dataset': 'data'}


//          Copyright Emil Fresk 2017.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE.md or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#pragma once

#include "crect/crect.hpp"
#include "crect/async/async_queue.hpp"

#include <chrono>

extern crect::async_queue<__CRECT_ASYNC_QUEUE_SIZE> crect_async_queue;

namespace crect
{
namespace details
{

/*
 * @brief Asynchronous pend of a job with duration (implementation).
 *
 * @param[in] duration  The time until the job shall be executed.
 * @param[in] isr       The Job's ISR value.
 */
static void async_impl_dur(time::system_clock::duration dur, unsigned isr)
{
  /* Always get the current time. */
  auto current_time = claim<Rsystem_clock>([](auto &now){
    return now();
  });

  /* Claim the async queue and manipulate. */
  claim<Rasync>([&](auto &async_queue){
    async_queue.push(current_time + dur, isr);
  });
}

/*
 * @brief Asynchronous pend of a job at specific time (implementation).
 *
 * @param[in] time      The absolute time the job shall be executed.
 * @param[in] isr       The Job's ISR value.
 */
static void async_impl_time(time::system_clock::time_point time, unsigned isr)
{
  /* Claim the async queue and manipulate. */
  claim<Rasync>([&](auto &async_queue){
    async_queue.push(time, isr);
  });
}

} /* END namespace details */

/**
 * @brief Asynchronous pend of a job.
 *
 * @tparam Job          The job to pend in the future.
 * @tparam Rep          Representation of the duration.
 * @tparam Period       Period of the duration.
 *
 * @param[in] duration  The time until the job shall be executed.
 */

template <typename Job, typename Rep, typename Period>
constexpr void async(std::chrono::duration<Rep, Period> duration)
{
  using namespace std::chrono;
  using idx = typename Job::isr::index;

  auto dur = duration_cast<time::system_clock::duration>(duration);

  details::async_impl_dur(dur, idx::value);
}

/**
 * @brief Asynchronous pend of a job, manually specifying the ISR ID.
 *
 * @tparam Rep          Representation of the duration.
 * @tparam Period       Period of the duration.
 *
 * @param[in] duration  The time until the job shall be executed.
 * @param[in] isr       The ISR ID to pend.
 */

template <typename Rep, typename Period>
constexpr void async(std::chrono::duration<Rep, Period> duration, unsigned isr)
{
  using namespace std::chrono;

  auto dur = duration_cast<time::system_clock::duration>(duration);

  details::async_impl_dur(dur, isr);
}

/**
 * @brief Asynchronous pend of a job.
 *
 * @tparam Job          The job to pend in the future.
 *
 * @param[in] time      The time the job shall be executed.
 */

template <typename Job>
constexpr void async(time::system_clock::time_point time)
{
  using idx = typename Job::isr::index;
  details::async_impl_time(time, idx::value);
}

/**
 * @brief Asynchronous pend of a job, manually specifying the ISR ID.
 *
 * @tparam Job          The job to pend in the future.
 *
 * @param[in] time      The time the job shall be executed.
 * @param[in] isr       The ISR ID to pend.
 */

inline void async(time::system_clock::time_point time, unsigned isr)
{
  details::async_impl_time(time, isr);
}

} /* END namespace crect */

{'repo_name': 'korken89/crect', 'stars': '158', 'repo_language': 'C++', 'file_name': 'Makefile', 'mime_type': 'text/x-makefile', 'hash': 2980407731666098439, 'source_dataset': 'data'}


{'repo_name': 'revapi/revapi', 'stars': '107', 'repo_language': 'Java', 'file_name': 'SemverIgnoreTransformTest.java', 'mime_type': 'text/x-java', 'hash': -5287054215156163258, 'source_dataset': 'data'}


// +build !ci

// +build android

#include <android/log.h>
#include <jni.h>
#include <stdbool.h>
#include <stdlib.h>

#define LOG_FATAL(...) __android_log_print(ANDROID_LOG_FATAL, "GoLog", __VA_ARGS__)

static jclass find_class(JNIEnv *env, const char *class_name) {
	jclass clazz = (*env)->FindClass(env, class_name);
	if (clazz == NULL) {
		(*env)->ExceptionClear(env);
		LOG_FATAL("cannot find %s", class_name);
		return NULL;
	}
	return clazz;
}

static jmethodID find_method(JNIEnv *env, jclass clazz, const char *name, const char *sig) {
	jmethodID m = (*env)->GetMethodID(env, clazz, name, sig);
	if (m == 0) {
		(*env)->ExceptionClear(env);
		LOG_FATAL("cannot find method %s %s", name, sig);
		return 0;
	}
	return m;
}

static jmethodID find_static_method(JNIEnv *env, jclass clazz, const char *name, const char *sig) {
	jmethodID m = (*env)->GetStaticMethodID(env, clazz, name, sig);
	if (m == 0) {
		(*env)->ExceptionClear(env);
		LOG_FATAL("cannot find method %s %s", name, sig);
		return 0;
	}
	return m;
}

jobject getSystemService(uintptr_t jni_env, uintptr_t ctx, char *service) {
	JNIEnv *env = (JNIEnv*)jni_env;
	jstring serviceStr = (*env)->NewStringUTF(env, service);

	jclass ctxClass = (*env)->GetObjectClass(env, ctx);
	jmethodID getSystemService = find_method(env, ctxClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");

	return (jobject)(*env)->CallObjectMethod(env, ctx, getSystemService, serviceStr);
}

int nextId = 1;

bool isOreoOrLater(JNIEnv *env) {
    jclass versionClass = find_class(env, "android/os/Build$VERSION" );
    jfieldID sdkIntFieldID = (*env)->GetStaticFieldID(env, versionClass, "SDK_INT", "I" );
    int sdkVersion = (*env)->GetStaticIntField(env, versionClass, sdkIntFieldID );

    return sdkVersion >= 26; // O = Oreo, will not be defined for older builds
}

void sendNotification(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx, char *title, char *body) {
	JNIEnv *env = (JNIEnv*)jni_env;
	jstring titleStr = (*env)->NewStringUTF(env, title);
	jstring bodyStr = (*env)->NewStringUTF(env, body);

	jclass cls = find_class(env, "android/app/Notification$Builder");
	jmethodID constructor = find_method(env, cls, "<init>", "(Landroid/content/Context;)V");
	jobject builder = (*env)->NewObject(env, cls, constructor, ctx);

	jclass mgrCls = find_class(env, "android/app/NotificationManager");
	jobject mgr = getSystemService(env, ctx, "notification");

	if (isOreoOrLater(env)) {
		jstring channelId = (*env)->NewStringUTF(env, "fyne-notif");
		jstring name = (*env)->NewStringUTF(env, "Fyne Notification");
        int importance = 4; // IMPORTANCE_HIGH

		jclass chanCls = find_class(env, "android/app/NotificationChannel");
		jmethodID constructor = find_method(env, chanCls, "<init>", "(Ljava/lang/String;Ljava/lang/CharSequence;I)V");
		jobject channel = (*env)->NewObject(env, chanCls, constructor, channelId, name, importance);

		jmethodID createChannel = find_method(env, mgrCls, "createNotificationChannel", "(Landroid/app/NotificationChannel;)V");
		(*env)->CallVoidMethod(env, mgr, createChannel, channel);

		jmethodID setChannelId = find_method(env, cls, "setChannelId", "(Ljava/lang/String;)Landroid/app/Notification$Builder;");
		(*env)->CallObjectMethod(env, builder, setChannelId, channelId);
	}

	jmethodID setContentTitle = find_method(env, cls, "setContentTitle", "(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;");
	(*env)->CallObjectMethod(env, builder, setContentTitle, titleStr);

	jmethodID setContentText = find_method(env, cls, "setContentText", "(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;");
	(*env)->CallObjectMethod(env, builder, setContentText, bodyStr);

	int iconID = 17629184; // constant of "unknown app icon"
	jmethodID setSmallIcon = find_method(env, cls, "setSmallIcon", "(I)Landroid/app/Notification$Builder;");
	(*env)->CallObjectMethod(env, builder, setSmallIcon, iconID);

	jmethodID build = find_method(env, cls, "build", "()Landroid/app/Notification;");
	jobject notif = (*env)->CallObjectMethod(env, builder, build);

	jmethodID notify = find_method(env, mgrCls, "notify", "(ILandroid/app/Notification;)V");
	(*env)->CallVoidMethod(env, mgr, notify, nextId, notif);
	nextId++;
}

{'repo_name': 'airplayx/gormat', 'stars': '149', 'repo_language': 'Go', 'file_name': 'build.go', 'mime_type': 'text/x-c', 'hash': 3955122342164235162, 'source_dataset': 'data'}


# Bounded_int_table

A `Bounded_int_table` is a table whose keys can be mapped to integers
in a fixed range, `0` ... `num_keys - 1`, where `num_keys` is
specified at table-creation time.  The purpose of `Bounded_int_table`
is to be faster than `Hashtbl` in situations where one is willing to
pay a space cost for the speed.

{'repo_name': 'realworldocaml/book', 'stars': '652', 'repo_language': 'OCaml', 'file_name': 'dune', 'mime_type': 'text/plain', 'hash': -8998651448484112495, 'source_dataset': 'data'}


/*
Copyright Charly Chevalier 2015
Copyright Joel Falcou 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/

#include <boost/predef/hardware/simd/x86.h>
#include <boost/predef/hardware/simd/x86_amd.h>
#include <boost/predef/hardware/simd/arm.h>
#include <boost/predef/hardware/simd/ppc.h>

#ifndef BOOST_PREDEF_HARDWARE_SIMD_H
#define BOOST_PREDEF_HARDWARE_SIMD_H

#include <boost/predef/version_number.h>

/*`
 [section Using the `BOOST_HW_SIMD_*` predefs]
 [include ../doc/hardware_simd.qbk]
 [endsect]

 [/ --------------------------- ]

 [section `BOOST_HW_SIMD_*`]

 [heading `BOOST_HW_SIMD`]

 The SIMD extension detected for a specific architectures.
 Version number depends on the detected extension.

 [table
     [[__predef_symbol__] [__predef_version__]]

     [[`BOOST_HW_SIMD_X86_AVAILABLE`] [__predef_detection__]]
     [[`BOOST_HW_SIMD_X86_AMD_AVAILABLE`] [__predef_detection__]]
     [[`BOOST_HW_SIMD_ARM_AVAILABLE`] [__predef_detection__]]
     [[`BOOST_HW_SIMD_PPC_AVAILABLE`] [__predef_detection__]]
     ]

 [include ../include/boost/predef/hardware/simd/x86.h]
 [include ../include/boost/predef/hardware/simd/x86_amd.h]
 [include ../include/boost/predef/hardware/simd/arm.h]
 [include ../include/boost/predef/hardware/simd/ppc.h]

 [endsect]

 [/ --------------------------- ]

 [section `BOOST_HW_SIMD_X86_*_VERSION`]
 [include ../include/boost/predef/hardware/simd/x86/versions.h]
 [endsect]

 [section `BOOST_HW_SIMD_X86_AMD_*_VERSION`]
 [include ../include/boost/predef/hardware/simd/x86_amd/versions.h]
 [endsect]

 [section `BOOST_HW_SIMD_ARM_*_VERSION`]
 [include ../include/boost/predef/hardware/simd/arm/versions.h]
 [endsect]

 [section `BOOST_HW_SIMD_PPC_*_VERSION`]
 [include ../include/boost/predef/hardware/simd/ppc/versions.h]
 [endsect]

 */

// We check if SIMD extension of multiples architectures have been detected,
// if yes, then this is an error!
//
// NOTE: _X86_AMD implies _X86, so there is no need to check for it here!
//
#if defined(BOOST_HW_SIMD_ARM_AVAILABLE) && defined(BOOST_HW_SIMD_PPC_AVAILABLE) ||\
    defined(BOOST_HW_SIMD_ARM_AVAILABLE) && defined(BOOST_HW_SIMD_X86_AVAILABLE) ||\
    defined(BOOST_HW_SIMD_PPC_AVAILABLE) && defined(BOOST_HW_SIMD_X86_AVAILABLE)
#   error "Multiple SIMD architectures detected, this cannot happen!"
#endif

#if defined(BOOST_HW_SIMD_X86_AVAILABLE)
#   define BOOST_HW_SIMD BOOST_HW_SIMD_X86
#endif

#if defined(BOOST_HW_SIMD_X86_AMD_AVAILABLE)
#   define BOOST_HW_SIMD BOOST_HW_SIMD_X86_AMD
#endif

#if defined(BOOST_HW_SIMD_ARM_AVAILABLE)
#   define BOOST_HW_SIMD BOOST_HW_SIMD_ARM
#endif

#if defined(BOOST_HW_SIMD_PPC_AVAILABLE)
#   define BOOST_HW_SIMD BOOST_HW_SIMD_PPC
#endif

#if defined(BOOST_HW_SIMD)
#   define BOOST_HW_SIMD_AVAILABLE
#else
#   define BOOST_HW_SIMD BOOST_VERSION_NUMBER_NOT_AVAILABLE
#endif

#define BOOST_HW_SIMD_NAME "Hardware SIMD"

#endif

#include <boost/predef/detail/test.h>
BOOST_PREDEF_DECLARE_TEST(BOOST_HW_SIMD, BOOST_HW_SIMD_NAME)

{'repo_name': 'danoli3/ofxiOSBoost', 'stars': '266', 'repo_language': 'C++', 'file_name': 'stack.hpp', 'mime_type': 'text/x-c', 'hash': 7521089777813707252, 'source_dataset': 'data'}