text:
"""
behave environment module for testing behave-django
"""

def before_feature(context, feature):
    if feature.name == 'Fixture loading':
        context.fixtures = ['behave-fixtures.json']

    elif feature.name == 'Fixture loading with decorator':
        # Including empty fixture to test that #92 is fixed
        context.fixtures = ['empty-fixture.json']

def before_scenario(context, scenario):
    if scenario.name == 'Load fixtures for this scenario and feature':
        context.fixtures.append('behave-second-fixture.json')

    if scenario.name == 'Load fixtures then reset sequences':
        context.fixtures.append('behave-second-fixture.json')
        context.reset_sequences = True

    if scenario.name == 'Load fixtures with databases option':
        context.databases = '__all__'

def django_ready(context):
    context.django = True

redpajama_set_name: RedPajamaGithub


text:
**Start Date**: December 14th, 2015
**Teacher**: [Nick Cannariato](http://github.com/nickcannariato)
**Curriculum**: [Code School's HTML, CSS, and JavaScript Paths](http://codeschool.com)
**Objective**: To learn HTML, CSS, and JavaScript and build a website from scratch

----

## About
This will be an ongoing project that will change and get better as time goes on.

## How the pieces work together
- Assignments, Questions, and student/teacher interaction will take place in Issues
- Class Notes and other resources can be found in the Wiki and will be updated as needed by either the student or the teacher.


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="keywords" content="Daisy's 22nd birthday" />
  <meta name="description" content="Happy Birthday!">
  <meta property="og:description" content="Happy Birthday!" />

  <meta property="og:url" content="https://daisygao.love/" />
  <meta property="og:title" content="Daisy's Birthday Present" />
  <meta property="og:image" content="http://daisygao.herokuapp.com/img/Daisy.jpg"/>
  <meta property="og:type" content="website" />
  <meta name="keywords" content="Daisy's Twenty second birthday!" />
  <title>Daisy's Website</title>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="css/styles.scss">

  <link href='https://fonts.googleapis.com/css?family=Roboto:300' rel='stylesheet' type='text/css'>

       <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>

Hover Me When You Finish Reading


text:
const { Model } = require('objection');

class Token extends Model {
  static get tableName () {
    return 'token';
  }
}

module.exports = Token;


text:
<?php

declare(strict_types=1);

namespace Mwop\Blog\Console;

use Psr\Container\ContainerInterface;
use Psr\Http\Message\RequestFactoryInterface;

class TweetPostFactory
{
    public function __invoke(ContainerInterface $container): TweetPost
    {
        $config = $container->get('config-blog.api');
        return new TweetPost(
            $container->get(RequestFactoryInterface::class),
            $config['token_header'],
        );
    }
}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/test/test_doh_server.h"

#include <string.h>

#include <memory>

#include "base/base64url.h"
#include "base/bind.h"
#include "base/check.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/synchronization/lock.h"
#include "net/base/io_buffer.h"
#include "net/base/url_util.h"
#include "net/dns/dns_query.h"
#include "net/dns/dns_response.h"
#include "net/dns/dns_test_util.h"
#include "net/dns/dns_util.h"
#include "net/dns/public/dns_protocol.h"
#include "net/http/http_status_code.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "net/test/embedded_test_server/http_request.h"
#include "net/test/embedded_test_server/http_response.h"
#include "url/gurl.h"

namespace net {

namespace {

const char kPath[] = "/dns-query";

std::unique_ptr<test_server::HttpResponse> MakeHttpErrorResponse(
    HttpStatusCode status,
    base::StringPiece error) {
  auto response = std::make_unique<test_server::BasicHttpResponse>();
  response->set_code(status);
  response->set_content(std::string(error));
  response->set_content_type("text/plain;charset=utf-8");
  return response;
}

std::unique_ptr<test_server::HttpResponse> MakeHttpResponseFromDns(
    const DnsResponse& dns_response) {
  if (!dns_response.IsValid()) {
    return MakeHttpErrorResponse(HTTP_INTERNAL_SERVER_ERROR,
                                 "error making DNS response");
  }

  auto response = std::make_unique<test_server::BasicHttpResponse>();
  response->set_code(HTTP_OK);
  response->set_content(std::string(dns_response.io_buffer()->data(),
                                    dns_response.io_buffer_size()));
  response->set_content_type("application/dns-message");
  return response;
}

}  // namespace

TestDohServer::TestDohServer() {
  server_.RegisterRequestHandler(base::BindRepeating(
      &TestDohServer::HandleRequest, base::Unretained(this)));
}

TestDohServer::~TestDohServer() = default;

void TestDohServer::SetHostname(base::StringPiece name) {
  DCHECK(!server_.Started());
  hostname_ = std::string(name);
}

void TestDohServer::SetFailRequests(bool fail_requests) {
  base::AutoLock lock(lock_);
  fail_requests_ = fail_requests;
}

void TestDohServer::AddAddressRecord(base::StringPiece name,
                                     const IPAddress& address,
                                     base::TimeDelta ttl) {
  AddRecord(BuildTestAddressRecord(std::string(name), address, ttl));
}

void TestDohServer::AddRecord(const DnsResourceRecord& record) {
  base::AutoLock lock(lock_);
  records_.insert(
      std::make_pair(std::make_pair(record.name, record.type), record));
}

bool TestDohServer::Start() {
  if (!InitializeAndListen()) {
    return false;
  }
  StartAcceptingConnections();
  return true;
}

bool TestDohServer::InitializeAndListen() {
  if (hostname_) {
    EmbeddedTestServer::ServerCertificateConfig cert_config;
    cert_config.dns_names = {*hostname_};
    server_.SetSSLConfig(cert_config);
  } else {
    // `CERT_OK` is valid for 127.0.0.1.
    server_.SetSSLConfig(EmbeddedTestServer::CERT_OK);
  }
  return server_.InitializeAndListen();
}

void TestDohServer::StartAcceptingConnections() {
  server_.StartAcceptingConnections();
}

bool TestDohServer::ShutdownAndWaitUntilComplete() {
  return server_.ShutdownAndWaitUntilComplete();
}

std::string TestDohServer::GetTemplate() {
  GURL url =
      hostname_ ? server_.GetURL(*hostname_, kPath) : server_.GetURL(kPath);
  return url.spec() + "{?dns}";
}

std::string TestDohServer::GetPostOnlyTemplate() {
  GURL url =
      hostname_ ? server_.GetURL(*hostname_, kPath) : server_.GetURL(kPath);
  return url.spec();
}

int TestDohServer::QueriesServed() {
  base::AutoLock lock(lock_);
  return queries_served_;
}

std::unique_ptr<test_server::HttpResponse> TestDohServer::HandleRequest(
    const test_server::HttpRequest& request) {
  GURL request_url = request.GetURL();
  if (request_url.path_piece() != kPath) {
    return nullptr;
  }

  base::AutoLock lock(lock_);
  queries_served_++;

  if (fail_requests_) {
    return MakeHttpErrorResponse(HTTP_NOT_FOUND, "failed request");
  }

  // See RFC 8484, Section 4.1.
  std::string query;
  if (request.method == test_server::METHOD_GET) {
    std::string query_b64;
    if (!GetValueForKeyInQuery(request_url, "dns", &query_b64) ||
        !base::Base64UrlDecode(
            query_b64, base::Base64UrlDecodePolicy::IGNORE_PADDING, &query)) {
      return MakeHttpErrorResponse(HTTP_BAD_REQUEST,
                                   "could not decode query string");
    }
  } else if (request.method == test_server::METHOD_POST) {
    auto content_type = request.headers.find("content-type");
    if (content_type == request.headers.end() ||
        content_type->second != "application/dns-message") {
      return MakeHttpErrorResponse(HTTP_BAD_REQUEST,
                                   "unsupported content type");
    }
    query = request.content;
  } else {
    return MakeHttpErrorResponse(HTTP_BAD_REQUEST, "invalid method");
  }

  // Parse the DNS query.
  auto query_buf = base::MakeRefCounted<IOBufferWithSize>(query.size());
  memcpy(query_buf->data(), query.data(), query.size());
  DnsQuery dns_query(std::move(query_buf));
  if (!dns_query.Parse(query.size())) {
    return MakeHttpErrorResponse(HTTP_BAD_REQUEST, "invalid DNS query");
  }

  absl::optional<std::string> name =
      DnsDomainToString(dns_query.qname(), /*require_complete=*/true);
  if (!name) {
    DnsResponse response(dns_query.id(), /*is_authoritative=*/false,
                         /*answers=*/{}, /*authority_records=*/{},
                         /*additional_records=*/{}, dns_query,
                         dns_protocol::kRcodeFORMERR);
    return MakeHttpResponseFromDns(response);
  }

  auto range = records_.equal_range(std::make_pair(*name, dns_query.qtype()));
  std::vector<DnsResourceRecord> answers;
  for (auto i = range.first; i != range.second; ++i) {
    answers.push_back(i->second);
  }

  VLOG(1) << "Serving " << answers.size() << " records for " << *name
          << ", qtype " << dns_query.qtype();

  // Note `answers` may be empty. NOERROR with no answers is how to express
  // NODATA, so there is no need handle it specially.
  //
  // For now, this server does not support configuring additional records. When
  // testing more complex HTTPS record cases, this will need to be extended.
  //
  // TODO(crbug.com/1251204): Add SOA records to test the default TTL.
  DnsResponse response(dns_query.id(), /*is_authoritative=*/true,
                       /*answers=*/answers, /*authority_records=*/{},
                       /*additional_records=*/{}, dns_query);
  return MakeHttpResponseFromDns(response);
}

}  // namespace net


text:
import Vue from 'vue';
import VueRouter from 'vue-router';
import VueResource from 'vue-resource';

import './images/favicon.png';
import './images/headerLogo.png';
import './scss/index.scss';

import App from './App.vue';

import routes from './routes';
import store from './store/index';
import firebaseApp, { getAccessToken } from './firebase';

if (NODE_ENV === 'production') {
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-80557105-2', 'auto');
  ga('send', 'pageview');
}

Vue.use(VueRouter);
Vue.use(VueResource);

firebaseApp.auth().onAuthStateChanged((user) => {
  store.dispatch('setUser', user);
  if (user) {
    getAccessToken(user).then((token) => {
      store.dispatch('setAccessToken', token);
    });
  }
});

const router = new VueRouter({ routes });

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Report of the Department of Indutry, Government Research Institute, Formosa 86: 158 (1943)

#### Original name
Pestalotia ecdysantherae Sawada

### Remarks
null


text:
//package tv.sisi.live.lean;
//
//import android.content.Intent;
//import android.support.design.widget.TabLayout;
//import android.support.v4.app.Fragment;
//import android.support.v4.app.FragmentManager;
//import android.support.v4.app.FragmentStatePagerAdapter;
//import android.support.v4.view.ViewPager;
//import android.support.v7.app.AppCompatActivity;
//import android.os.Bundle;
//import android.support.v7.widget.Toolbar;
//import android.view.Menu;
//import android.view.MenuItem;
//import android.widget.Toast;
//
//import com.avos.avoscloud.im.v2.AVIMConversation;
//import com.avos.avoscloud.im.v2.AVIMException;
//import com.avos.avoscloud.im.v2.callback.AVIMConversationCreatedCallback;
//
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.List;
//
//import cn.leancloud.chatkit.LCChatKit;
//import cn.leancloud.chatkit.LCChatKitUser;
//import cn.leancloud.chatkit.activity.LCIMConversationActivity;
//import cn.leancloud.chatkit.activity.LCIMConversationListFragment;
//import cn.leancloud.chatkit.utils.LCIMConstants;
//import tv.sisi.live.R;
//
//public class MainActivity extends AppCompatActivity {
//
//  private Toolbar toolbar;
//  private ViewPager viewPager;
//  private TabLayout tabLayout;
//
//  /**
//   * 上一次点击 back 键的时间
//   * 用于双击退出的判断
//   */
//  private static long lastBackTime = 0;
//
//  /**
//   * 当双击 back 键在此间隔内是直接触发 onBackPressed
//   */
//  private final int BACK_INTERVAL = 1000;
//
//  @Override
//  protected void onCreate(Bundle savedInstanceState) {
//    super.onCreate(savedInstanceState);
//    setContentView(R.layout.activity_main);
//    toolbar = (Toolbar) findViewById(R.id.toolbar);
//    viewPager = (ViewPager)findViewById(R.id.pager);
//    tabLayout = (TabLayout)findViewById(R.id.tablayout);
//    setTitle(R.string.app_name);
//    setSupportActionBar(toolbar);
//    initTabLayout();
//  }
//
//  @Override
//  public boolean onCreateOptionsMenu(Menu menu) {
//    getMenuInflater().inflate(R.menu.menu_square, menu);
//    return true;
//  }
//
//  @Override
//  public boolean onOptionsItemSelected(MenuItem item) {
//    int menuId = item.getItemId();
//    if (menuId == R.id.menu_square_members) {
//      gotoSquareConversation();
//    }
//    return super.onOptionsItemSelected(item);
//  }
//
//  private void initTabLayout() {
//    String[] tabList = new String[]{"会话", "联系人"};
//    final Fragment[] fragmentList = new Fragment[] {new LCIMConversationListFragment(),
//      new ContactFragment()};
//
//    tabLayout.setTabMode(TabLayout.MODE_FIXED);
//    for (int i = 0; i < tabList.length; i++) {
//      tabLayout.addTab(tabLayout.newTab().setText(tabList[i]));
//    }
//
//    TabFragmentAdapter adapter = new TabFragmentAdapter(getSupportFragmentManager(),
//      Arrays.asList(fragmentList), Arrays.asList(tabList));
//    viewPager.setAdapter(adapter);
//    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//      @Override
//      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//      }
//
//      @Override
//      public void onPageSelected(int position) {
//        if (0 == position) {
////          EventBus.getDefault().post(new ConversationFragmentUpdateEvent());
//        }
//      }
//
//      @Override
//      public void onPageScrollStateChanged(int state) {
//      }
//    });
//    tabLayout.setupWithViewPager(viewPager);
//    tabLayout.setTabsFromPagerAdapter(adapter);
//  }
//
//  @Override
//  public void onBackPressed() {
//    long currentTime = System.currentTimeMillis();
//    if (currentTime - lastBackTime < BACK_INTERVAL) {
//      super.onBackPressed();
//    } else {
//      Toast.makeText(this, "双击 back 退出", Toast.LENGTH_SHORT).show();
//    }
//    lastBackTime = currentTime;
//  }
//
//  public class TabFragmentAdapter extends FragmentStatePagerAdapter {
//
//    private List<Fragment> mFragments;
//    private List<String> mTitles;
//
//    public TabFragmentAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titles) {
//      super(fm);
//      mFragments = fragments;
//      mTitles = titles;
//    }
//
//    @Override
//    public Fragment getItem(int position) {
//      return mFragments.get(position);
//    }
//
//    @Override
//    public int getCount() {
//      return mFragments.size();
//    }
//
//    @Override
//    public CharSequence getPageTitle(int position) {
//      return mTitles.get(position);
//    }
//  }
//
//  private void gotoSquareConversation() {
//    List<LCChatKitUser> userList = CustomUserProvider.getInstance().getAllUsers();
//    List<String> idList = new ArrayList<>();
//    for (LCChatKitUser user : userList) {
//      idList.add(user.getUserId());
//    }
//    LCChatKit.getInstance().getClient().createConversation(
//      idList, getString(R.string.square), null, false, true, new AVIMConversationCreatedCallback() {
//        @Override
//        public void done(AVIMConversation avimConversation, AVIMException e) {
//          Intent intent = new Intent(MainActivity.this, LCIMConversationActivity.class);
//          intent.putExtra(LCIMConstants.CONVERSATION_ID, avimConversation.getConversationId());
//          startActivity(intent);
//        }
//      });
//  }
//}


text:
package org.motechproject.mockma.service.impl;

import org.motechproject.mockma.service.MockmaService;
import org.motechproject.mtraining.domain.Bookmark;
import org.motechproject.mtraining.domain.Course;
import org.motechproject.mtraining.domain.CourseUnitState;
import org.motechproject.mtraining.service.ActivityService;
import org.motechproject.mtraining.service.BookmarkService;
import org.motechproject.mtraining.service.MTrainingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Simple implementation of the {@link org.motechproject.mockma.service.MockmaService} interface.
 */
@Service("mockmaService")
public class MockmaServiceImpl implements MockmaService {

    private MTrainingService mTrainingService;
    private BookmarkService bookmarkService;
    private ActivityService activityService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public MockmaServiceImpl(MTrainingService mTrainingService, BookmarkService bookmarkService, ActivityService activityService) {
        this.mTrainingService = mTrainingService;
        this.bookmarkService = bookmarkService;
        this.activityService = activityService;
    }

    @Override
    public String sayHello() {
        logger.info("They said hello and I said world?");
        return "Hello World";
    }

    @Override
    public String getNextUnit(String userId) {

        Bookmark latest = this.bookmarkService.getLatestBookmarkByUserId(userId);
        if (latest != null) {
            return mTrainingService.getCourseById(Long.parseLong(latest.getCourseIdentifier())).toString();
        } else {
            return null;
        }
    }

    @Override
    public void setBookmark(Bookmark bookmark) {

        bookmarkService.updateBookmark(bookmark);
    }

    @Override
    public boolean checkNewUser(String userId) {
        logger.info(String.format("You asked me to check for userId: %s", userId));
        return this.activityService.getAllActivityForUser(userId).isEmpty() &&
                this.bookmarkService.getAllBookmarksForUser(userId).isEmpty();
    }

    @Override
    public String GetCourseString(String courseName) {
        logger.info(String.format("asked for course with name: %s", courseName));
        String courseString = "";
        List<Course> courses = mTrainingService.getCourseByName("courseName");
        for (Course current : courses) {
            if (current.getState() == CourseUnitState.Active) {
                return current.toString();
            }
        }
        return "";
    }

}


text:
<md-card>
  <md-card-content class="content">
    <md-input-container class="input">
      <input type="text" mdInput (keyup)="onKeyup(query.value)" #query>
      <md-placeholder>Search for an Artist, Song or Album</md-placeholder>
    </md-input-container>

    <md-spinner *ngIf="isLoading|async" class="spinner"></md-spinner>
  </md-card-content>
</md-card>

<spot-result-list></spot-result-list>


text:
class GURL;
struct FontDescriptor;

namespace base {
class SharedMemory;
}

namespace gfx {
struct GpuMemoryBufferHandle;
}

namespace gpu {
struct SyncToken;
}

namespace media {
struct MediaLogEvent;
}

namespace net {
class IOBuffer;
class KeygenHandler;
class URLRequestContext;
class URLRequestContextGetter;
}

namespace url {
class Origin;
}

namespace content {
class BrowserContext;
class CacheStorageContextImpl;
class CacheStorageCacheHandle;
class DOMStorageContextWrapper;
class MediaInternals;
class RenderWidgetHelper;
class ResourceContext;
class ResourceDispatcherHostImpl;

// This class filters out incoming IPC messages for the renderer process on the
// IPC thread.
class CONTENT_EXPORT RenderMessageFilter
    : public BrowserMessageFilter,
      public BrowserAssociatedInterface<mojom::RenderMessageFilter>,
      public mojom::RenderMessageFilter {
 public:
  // Create the filter.
  RenderMessageFilter(int render_process_id,
                      BrowserContext* browser_context,
                      net::URLRequestContextGetter* request_context,
                      RenderWidgetHelper* render_widget_helper,
                      MediaInternals* media_internals,
                      DOMStorageContextWrapper* dom_storage_context,
                      CacheStorageContextImpl* cache_storage_context);

  // BrowserMessageFilter methods:
  bool OnMessageReceived(const IPC::Message& message) override;
  void OnDestruct() const override;
  void OverrideThreadForMessage(const IPC::Message& message,
                                BrowserThread::ID* thread) override;

  int render_process_id() const { return render_process_id_; }

 protected:
  ~RenderMessageFilter() override;

 private:
  friend class BrowserThread;
  friend class base::DeleteHelper<RenderMessageFilter>;

  void OnGetProcessMemorySizes(size_t* private_bytes, size_t* shared_bytes);

#if defined(OS_MACOSX)
  // Messages for OOP font loading.
  void OnLoadFont(const FontDescriptor& font, IPC::Message* reply_msg);
  void SendLoadFontReply(IPC::Message* reply, FontLoader::Result* result);
#endif

  // mojom::RenderMessageFilter:
  void GenerateRoutingID(const GenerateRoutingIDCallback& routing_id) override;
  void CreateNewWindow(mojom::CreateNewWindowParamsPtr params,
                       const CreateNewWindowCallback& callback) override;
  void CreateNewWidget(int32_t opener_id,
                       blink::WebPopupType popup_type,
                       const CreateNewWidgetCallback& callback) override;
  void CreateFullscreenWidget(
      int opener_id,
      const CreateFullscreenWidgetCallback& callback) override;

  // Message handlers called on the browser IO thread:
  void OnEstablishGpuChannel(IPC::Message* reply);
  void OnHasGpuProcess(IPC::Message* reply);
  // Helper callbacks for the message handlers.
  void EstablishChannelCallback(std::unique_ptr<IPC::Message> reply,
                                const IPC::ChannelHandle& channel,
                                const gpu::GPUInfo& gpu_info);
  void GetGpuProcessHandlesCallback(
      std::unique_ptr<IPC::Message> reply,
      const std::list<base::ProcessHandle>& handles);
  // Used to ask the browser to allocate a block of shared memory for the
  // renderer to send back data in, since shared memory can't be created
  // in the renderer on POSIX due to the sandbox.
  void AllocateSharedBitmapOnFileThread(uint32_t buffer_size,
                                        const cc::SharedBitmapId& id,
                                        IPC::Message* reply_msg);
  void OnAllocateSharedBitmap(uint32_t buffer_size,
                              const cc::SharedBitmapId& id,
                              IPC::Message* reply_msg);
  void OnAllocatedSharedBitmap(size_t buffer_size,
                               const base::SharedMemoryHandle& handle,
                               const cc::SharedBitmapId& id);
  void OnDeletedSharedBitmap(const cc::SharedBitmapId& id);
  void OnResolveProxy(const GURL& url, IPC::Message* reply_msg);

  // Browser side discardable shared memory allocation.
  void AllocateLockedDiscardableSharedMemoryOnFileThread(
      uint32_t size,
      discardable_memory::DiscardableSharedMemoryId id,
      IPC::Message* reply_message);
  void OnAllocateLockedDiscardableSharedMemory(
      uint32_t size,
      discardable_memory::DiscardableSharedMemoryId id,
      IPC::Message* reply_message);
  void DeletedDiscardableSharedMemoryOnFileThread(
      discardable_memory::DiscardableSharedMemoryId id);
  void OnDeletedDiscardableSharedMemory(
      discardable_memory::DiscardableSharedMemoryId id);

#if defined(OS_LINUX)
  void SetThreadPriorityOnFileThread(base::PlatformThreadId ns_tid,
                                     base::ThreadPriority priority);
  void OnSetThreadPriority(base::PlatformThreadId ns_tid,
                           base::ThreadPriority priority);
#endif

  void OnCacheableMetadataAvailable(const GURL& url,
                                    base::Time expected_response_time,
                                    const std::vector<char>& data);
  void OnCacheableMetadataAvailableForCacheStorage(
      const GURL& url,
      base::Time expected_response_time,
      const std::vector<char>& data,
      const url::Origin& cache_storage_origin,
      const std::string& cache_storage_cache_name);
  void OnCacheStorageOpenCallback(
      const GURL& url,
      base::Time expected_response_time,
      scoped_refptr<net::IOBuffer> buf,
      int buf_len,
      std::unique_ptr<CacheStorageCacheHandle> cache_handle,
      CacheStorageError error);
  void OnKeygen(uint32_t key_size_index,
                const std::string& challenge_string,
                const GURL& url,
                const GURL& top_origin,
                IPC::Message* reply_msg);
  void PostKeygenToWorkerThread(
      IPC::Message* reply_msg,
      std::unique_ptr<net::KeygenHandler> keygen_handler);
  void OnKeygenOnWorkerThread(
      std::unique_ptr<net::KeygenHandler> keygen_handler,
      IPC::Message* reply_msg);
  void OnMediaLogEvents(const std::vector<media::MediaLogEvent>&);

  bool CheckBenchmarkingEnabled() const;
  bool CheckPreparsedJsCachingEnabled() const;

  void OnAllocateGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
                                 uint32_t width,
                                 uint32_t height,
                                 gfx::BufferFormat format,
                                 gfx::BufferUsage usage,
                                 IPC::Message* reply);
  void GpuMemoryBufferAllocated(IPC::Message* reply,
                                const gfx::GpuMemoryBufferHandle& handle);
  void OnDeletedGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
                                const gpu::SyncToken& sync_token);

  // Cached resource request dispatcher host, guaranteed to be non-null. We do
  // not own it; it is managed by the BrowserProcess, which has a wider scope
  // than we do.
  ResourceDispatcherHostImpl* resource_dispatcher_host_;

  HostSharedBitmapManagerClient bitmap_manager_client_;

  // Contextual information to be used for requests created here.
  scoped_refptr<net::URLRequestContextGetter> request_context_;

  // The ResourceContext which is to be used on the IO thread.
  ResourceContext* resource_context_;

  scoped_refptr<RenderWidgetHelper> render_widget_helper_;

  scoped_refptr<DOMStorageContextWrapper> dom_storage_context_;

  int render_process_id_;

  MediaInternals* media_internals_;
  CacheStorageContextImpl* cache_storage_context_;

  base::WeakPtrFactory<RenderMessageFilter> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(RenderMessageFilter);
};

}  // namespace content

#endif  // CONTENT_BROWSER_RENDERER_HOST_RENDER_MESSAGE_FILTER_H_


text:
package com.puzzletimer.statistics;

import com.puzzletimer.models.Solution;
import com.puzzletimer.util.SolutionUtils;

public class Average implements StatisticalMeasure {
    private int minimumWindowSize;
    private int maximumWindowSize;
    private long value;

    public Average(int minimumWindowSize, int maximumWindowSize) {
        this.minimumWindowSize = minimumWindowSize;
        this.maximumWindowSize = maximumWindowSize;
    }

    @Override
    public int getMinimumWindowSize() {
        return this.minimumWindowSize;
    }

    @Override
    public int getMaximumWindowSize() {
        return this.maximumWindowSize;
    }

    @Override
    public int getWindowPosition() {
        return 0;
    }

    @Override
    public long getValue() {
        return this.value;
    }

    @Override
    public void setSolutions(Solution[] solutions) {
        long[] times = SolutionUtils.realTimes(solutions, false);

        // if number of DNFs is greater than one, return DNF
        int nDNFs = 0;
        for (long time : times) {
            if (time == Long.MAX_VALUE) {
                nDNFs++;
                if (nDNFs > 1) {
                    this.value = Long.MAX_VALUE;
                    return;
                }
            }
        }

        long worst = Long.MIN_VALUE;
        long best = Long.MAX_VALUE;

        long sum = 0L;
        for (long time : times) {
            if (time > worst) {
                worst = time;
            }

            if (time < best) {
                best = time;
            }

            sum += time;
        }

        this.value = (sum - worst - best) / (solutions.length - 2);
    }
}


text:
title: Liputan Khusus dan advokasi litigasi kasus makar Forkorus Cs
date: 2012-05-04
categories:
- laporan
- Aldepe.com- Advokasi Hak Asasi Manusia (HAM) di Papua Via Media Online, Mobile Phone dan Social Media
---
![200px-Mei_04_2012_Pendampingan_Hukum_kasus_Makar_Fokrkurus_cs.JPG](/uploads/200px-Mei_04_2012_Pendampingan_Hukum_kasus_Makar_Fokrkurus_cs.JPG){: .img-responsive .center-block }

**Tujuan** : Liputan Khusus dan advokasi litigasi kasus makar Forkorus Cs

**Lokasi** : Jayapura

**Alamat** : Pengadilan Negeri Kelas 1A Jayapura

**Jam** : 3 jam

**Hadir** :
* Koalisi LSM HAM untuk Penegakan HAM di tanah Papua
* Hakim, jaksa
* Masyarakat
* Jurnalis
* Pihak Aparat kepolisian

**Ringkasan** :
* Melakukan pendampingan hukum di mana ALDP terlibat dalam koalisi LSM HAM Papua
* Putusan 3 tahun terhadap Forkorus CS di kenakan pasal-penghasutan KUHP
* melakukan peliputan khusus untuk persidangan kasus makar Forkorus Cs
* informasi selengkapnya bisa di akses pada website kami [http://www.aldp-papua.com](http://www.aldp-papua.com)


text:
package org.hisp.dhis.dd.action.category;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

import java.util.Collections;
import java.util.List;

import org.hisp.dhis.common.comparator.IdentifiableObjectNameComparator;
import org.hisp.dhis.dataelement.DataElementCategory;
import org.hisp.dhis.dataelement.DataElementCategoryService;
import org.hisp.dhis.paging.ActionPagingSupport;

/**
 * @author Abyot Asalefew
 * @version $Id$
 */
public class GetDataElementCategoryListAction
    extends ActionPagingSupport<DataElementCategory>
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private DataElementCategoryService dataElementCategoryService;

    public void setDataElementCategoryService( DataElementCategoryService dataElementCategoryService )
    {
        this.dataElementCategoryService = dataElementCategoryService;
    }

    // -------------------------------------------------------------------------
    // Getters & Setters
    // -------------------------------------------------------------------------

    private List<DataElementCategory> dataElementCategories;

    public List<DataElementCategory> getDataElementCategories()
    {
        return dataElementCategories;
    }

    private DataElementCategory defaultCategory;

    public DataElementCategory getDefaultCategory()
    {
        return defaultCategory;
    }

    private String key;

    public String getKey()
    {
        return key;
    }

    public void setKey( String key )
    {
        this.key = key;
    }

    // -------------------------------------------------------------------------
    // Action implementation
    // -------------------------------------------------------------------------

    @Override
    public String execute()
    {
        defaultCategory = dataElementCategoryService.getDataElementCategoryByName( DataElementCategory.DEFAULT_NAME );

        if ( isNotBlank( key ) ) // Filter on key only if set
        {
            this.paging = createPaging( dataElementCategoryService.getDataElementCategoryCountByName( key ) );

            dataElementCategories = dataElementCategoryService.getDataElementCategoriesBetweenByName( key, paging.getStartPos(), paging.getPageSize() );
        }
        else
        {
            this.paging = createPaging( dataElementCategoryService.getDataElementCategoryCount() );

            dataElementCategories = dataElementCategoryService.getDataElementCategoriesBetween( paging.getStartPos(), paging.getPageSize() );
        }

        Collections.sort( dataElementCategories, IdentifiableObjectNameComparator.INSTANCE );

        return SUCCESS;
    }
}


text:
/**
 * @author Alexander V. Astapchuk
 */
package org.apache.harmony.auth;

/**
 * A principal which holds information about user's primary group basing on
 * group's sid.
 */
public class NTSidPrimaryGroupPrincipal extends NTSid {

    private static final long serialVersionUID = 1652712324814773197L;

    /**
     * A constructor which takes group SID as its only argument.
     * @param sid group SID
     */
    public NTSidPrimaryGroupPrincipal(String sid) {
        super(sid);
    }

    /**
     * A constructor which takes an extended set of information - group SID,
     * its name and its domain name
     * @param sid group SID
     * @param objName group name
     * @param objDomain name of group's domain
     */
    public NTSidPrimaryGroupPrincipal(String sid, String objName,
            String objDomain) {
        super(sid, objName, objDomain);
    }
}


text:
using AIMP.SDK.UI.MenuItem;

namespace AIMP.SDK.Services.MenuManager
{
    /// <summary>
    ///
    /// </summary>
    public enum MenuItemPropertyType
    {
        AIMP_MENUITEM_PROPID_CUSTOM = 0,
        AIMP_MENUITEM_PROPID_ACTION,
        AIMP_MENUITEM_PROPID_ID,
        AIMP_MENUITEM_PROPID_NAME,
        AIMP_MENUITEM_PROPID_ENABLED,
        AIMP_MENUITEM_PROPID_STYLE,
        AIMP_MENUITEM_PROPID_EVENT,
        AIMP_MENUITEM_PROPID_EVENT_ONSHOW,
        AIMP_MENUITEM_PROPID_GLYPH,
        AIMP_MENUITEM_PROPID_PARENT,
        AIMP_MENUITEM_PROPID_VISIBLE,
        AIMP_MENUITEM_PROPID_CHECKED
    }

    public enum MenuItemStyleType
    {
        AIMP_MENUITEM_STYLE_NORMAL = 0,
        AIMP_MENUITEM_STYLE_CHECKBOX,
        AIMP_MENUITEM_STYLE_RADIOBOX
    }

    /// <summary>
    /// AIMP Parent menu item.
    /// </summary>
    public enum ParentMenuType
    {
        AIMP_MENUID_COMMON_UTILITIES = 0,
        AIMP_MENUID_PLAYER_MAIN_FUNCTIONS = 10,
        AIMP_MENUID_PLAYER_MAIN_OPEN = 11,
        AIMP_MENUID_PLAYER_MAIN_OPTIONS = 12,

        AIMP_MENUID_PLAYER_PLAYLIST_ADDING = 20,
        AIMP_MENUID_PLAYER_PLAYLIST_DELETION = 21,
        AIMP_MENUID_PLAYER_PLAYLIST_SORTING = 22,
        AIMP_MENUID_PLAYER_PLAYLIST_MISCELLANEOUS = 23,
        AIMP_MENUID_PLAYER_PLAYLIST_MANAGE = 24,
        AIMP_MENUID_PLAYER_PLAYLIST_CONTEXT_ADDING = 30,
        AIMP_MENUID_PLAYER_PLAYLIST_CONTEXT_QUEUE = 31,
        AIMP_MENUID_PLAYER_PLAYLIST_CONTEXT_FUNCTIONS = 32,
        AIMP_MENUID_PLAYER_PLAYLIST_CONTEXT_SENDING = 33,
        AIMP_MENUID_PLAYER_PLAYLIST_CONTEXT_DELETION = 34,

        AIMP_MENUID_PLAYER_TRAY = 40,
        AIMP_MENUID_PLAYER_EQ_LIB = 41
    }

    /// <summary>
    /// Menu manager interface.
    /// </summary>
    public interface IMenuManager
    {
        /// <summary>
        /// Adds the menu item.
        /// </summary>
        /// <param name="parentMenuType">Type of the parent menu.</param>
        /// <param name="items">The menu item <see cref="MenuItem" />.</param>
        void AddRange(ParentMenuType parentMenuType, MenuItemCollection items);

        /// <summary>
        /// Adds new menu item.
        /// </summary>
        /// <param name="parentMenuType"></param>       b
        /// <param name="item"></param>
        void Add(ParentMenuType parentMenuType, MenuItem item);

        /// <summary>
        /// Deletes the menu item.
        /// </summary>
        /// <param name="item">The menu item.</param>
        void Delete(MenuItem item);

        /// <summary>
        /// Deletes the menu item.
        /// </summary>
        /// <param name="id">The identifier.</param>
        void Delete(string id);

        /// <summary>
        /// Deletes the specified items.
        /// </summary>
        /// <param name="items">The items.</param>
        void Delete(MenuItemCollection items);

        /// <summary>
        /// Gets the by identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        MenuItem GetById(string id);

        /// <summary>
        /// Gets the standart menu item.
        /// </summary>
        /// <param name="menuType">Type of the menu.</param>
        MenuItem GetBuiltIn(ParentMenuType menuType);
    }
}


text:
package com.bumptech.glide.tests;

import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.RETURNS_DEFAULTS;
import static org.mockito.Mockito.mock;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.engine.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.robolectric.util.ReflectionHelpers;

// FIXME move to testutil module
public class Util {

  public static String getExpectedClassId(Class<?> clazz) {
    return clazz.getSimpleName() + "." + clazz.getPackage().getName();
  }

  /**
   * Gives the proper generic type to the {@link ArgumentCaptor}.
   * Only useful when the captor's {@code T} is also a generic type.
   * Without this it's really ugly to have a properly typed captor object.
   */
  @SuppressWarnings("unchecked")
  public static <T> ArgumentCaptor<T> cast(ArgumentCaptor<?> captor) {
    return (ArgumentCaptor<T>) captor;
  }

  public static DataSource isADataSource() {
    return isA(DataSource.class);
  }

  public static Context anyContext() {
    return any(Context.class);
  }

  /**
   * Creates a Mockito argument matcher to be used in verify.
   * It returns a generic typed {@link Resource} to prevent unchecked warnings.
   */
  @SuppressWarnings("unchecked")
  public static <T> Resource<T> anyResource() {
    return any(Resource.class);
  }

  /**
   * Creates a Mockito mock object.
   * It returns a generic typed {@link Resource} to prevent unchecked warnings.
   */
  @SuppressWarnings("unchecked")
  public static <T> Resource<T> mockResource() {
    return mock(Resource.class);
  }

  public static boolean isWindows() {
    return System.getProperty("os.name").startsWith("Windows");
  }

  public static void writeFile(File file, byte[] data) throws IOException {
    OutputStream out = new FileOutputStream(file);
    try {
      out.write(data);
      out.flush();
      out.close();
    } finally {
      try {
        out.close();
      } catch (IOException ex) {
        // Do nothing.
      }
    }
  }

  public static byte[] readFile(File file, int expectedLength) throws IOException {
    InputStream is = new FileInputStream(file);
    byte[] result = new byte[expectedLength];
    try {
      assertEquals(expectedLength, is.read(result));
      assertEquals(-1, is.read());
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        // Do nothing.
      }
    }
    return result;
  }

  public static void setSdkVersionInt(int version) {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", version);
  }

  public static class WriteDigest implements Answer<Void> {
    private String toWrite;

    public WriteDigest(String toWrite) {
      this.toWrite = toWrite;
    }

    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      MessageDigest md = (MessageDigest) invocationOnMock.getArguments()[0];
      md.update(toWrite.getBytes());
      return null;
    }
  }

  public static class ReturnsSelfAnswer implements Answer<Object> {

    public Object answer(InvocationOnMock invocation) throws Throwable {
      Object mock = invocation.getMock();
      if (invocation.getMethod().getReturnType().isInstance(mock)) {
        return mock;
      } else {
        return RETURNS_DEFAULTS.answer(invocation);
      }
    }
  }

  public static class CallDataReady<T> implements Answer<Void> {

    private T data;

    public CallDataReady(T data) {
      this.data = data;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      DataFetcher.DataCallback<T> callback =
          (DataFetcher.DataCallback<T>) invocationOnMock.getArguments()[1];
      callback.onDataReady(data);
      return null;
    }
  }

  public static class CreateBitmap implements Answer<Bitmap> {

    @Override
    public Bitmap answer(InvocationOnMock invocation) throws Throwable {
      int width = (Integer) invocation.getArguments()[0];
      int height = (Integer) invocation.getArguments()[1];
      Bitmap.Config config = (Bitmap.Config) invocation.getArguments()[2];
      return Bitmap.createBitmap(width, height, config);
    }
  }
}


text:
using OLEDB.Test.ModuleCore;

namespace System.Xml.Tests
{
    public partial class TCReadToNextSibling : TCXMLReaderBaseGeneral
    {
        // Type is System.Xml.Tests.TCReadToNextSibling
        // Test Case
        public override void AddChildren()
        {
            // for function v
            {
                this.AddChild(new CVariation(v) { Attribute = new Variation("Simple positive test 1") { Params = new object[] { "NNS" }, Pri = 0 } });
                this.AddChild(new CVariation(v) { Attribute = new Variation("Simple positive test 2") { Params = new object[] { "DNS" }, Pri = 0 } });
                this.AddChild(new CVariation(v) { Attribute = new Variation("Simple positive test 3") { Params = new object[] { "NS" }, Pri = 0 } });
            }

            // for function v2
            {
                this.AddChild(new CVariation(v2) { Attribute = new Variation("Read on a deep tree atleast more than 4K boundary") { Pri = 2 } });
            }

            // for function v2_1
            {
                this.AddChild(new CVariation(v2_1) { Attribute = new Variation("Read on a deep tree with more than 65536 elems") { Pri = 2 } });
            }

            // for function v3
            {
                this.AddChild(new CVariation(v3) { Attribute = new Variation("Read on next sibling with same names 3") { Params = new object[] { "NS", "<root xmlns:a='a'></root>" }, Pri = 1 } });
                this.AddChild(new CVariation(v3) { Attribute = new Variation("Read on next sibling with same names 2") { Params = new object[] { "DNS", "<root xmlns='a'></root>" }, Pri = 1 } });
                this.AddChild(new CVariation(v3) { Attribute = new Variation("Read to next sibling with same names 1") { Params = new object[] { "NNS", "<root></root>" }, Pri = 1 } });
            }

            // for function v4
            {
                this.AddChild(new CVariation(v4) { Attribute = new Variation("If name not found, stop at end element of the subtree") { Pri = 1 } });
            }

            // for function v5
            {
                this.AddChild(new CVariation(v5) { Attribute = new Variation("Positioning on a level and try to find the name which is on a level higher") { Pri = 1 } });
            }

            // for function v6
            {
                this.AddChild(new CVariation(v6) { Attribute = new Variation("Read to next sibling on one level and again to level below it") { Pri = 1 } });
            }

            // for function v12
            {
                this.AddChild(new CVariation(v12) { Attribute = new Variation("Call from different nodetypes") { Pri = 1 } });
            }

            // for function v16
            {
                this.AddChild(new CVariation(v16) { Attribute = new Variation("Pass null to both arguments throws ArgumentException") { Pri = 2 } });
            }

            // for function v17
            {
                this.AddChild(new CVariation(v17) { Attribute = new Variation("Different names, same uri works correctly") { Pri = 2 } });
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Hosting;
using Lucene.Net.Linq;
using Ninject;
using Ninject.Components;
using Ninject.Modules;
using Ninject.Selection.Heuristics;
using NuGet.Lucene.Web.Authentication;
using NuGet.Lucene.Web.Models;
using NuGet.Lucene.Web.Modules;

namespace NuGet.Lucene.Web
{
    public class NuGetWebApiModule : NinjectModule
    {
        public const string AppSettingNamesapce = "NuGet.Lucene.Web:";
        public const string DefaultRoutePathPrefix = "api/";

        public override void Load()
        {
            var cfg = new LuceneRepositoryConfigurator
                {
                    EnablePackageFileWatcher = GetFlagFromAppSetting("enablePackageFileWatcher", true),
                    GroupPackageFilesById = GetFlagFromAppSetting("groupPackageFilesById", true),
                    LuceneIndexPath = MapPathFromAppSetting("lucenePath", "~/App_Data/Lucene"),
                    PackagePath = MapPathFromAppSetting("packagesPath", "~/App_Data/Packages")
                };

            cfg.Initialize();

            Kernel.Components.Add<IInjectionHeuristic, NonDecoratedPropertyInjectionHeuristic>();

            var routeMapper = new NuGetWebApiRouteMapper(RoutePathPrefix);
            var mirroringPackageRepository = MirroringPackageRepositoryFactory.Create(cfg.Repository, PackageMirrorTargetUrl, PackageMirrorTimeout);

            Bind<NuGetWebApiRouteMapper>().ToConstant(routeMapper);
            Bind<ILucenePackageRepository>().ToConstant(cfg.Repository).OnDeactivation(_ => cfg.Dispose());
            Bind<IMirroringPackageRepository>().ToConstant(mirroringPackageRepository);
            Bind<LuceneDataProvider>().ToConstant(cfg.Provider);
            Bind<IQueryable<ApiUser>>().ToConstant(cfg.Provider.AsQueryable<ApiUser>());
            Bind<IApiKeyAuthentication>().To<LuceneApiKeyAuthentication>();

            Bind<IHttpModule>().To<ApiKeyAuthenticationModule>();

            var tokenSource = new ReusableCancellationTokenSource();
            Bind<ReusableCancellationTokenSource>().ToConstant(tokenSource);

            var repository = base.Kernel.Get<ILucenePackageRepository>();

            if (GetFlagFromAppSetting("synchronizeOnStart", true))
            {
                repository.SynchronizeWithFileSystem(tokenSource.Token);
            }
        }

        public static bool ShowExceptionDetails
        {
            get { return GetFlagFromAppSetting("showExceptionDetails", false); }
        }

        public static bool EnableCrossDomainRequests
        {
            get { return GetFlagFromAppSetting("enableCrossDomainRequests", false); }
        }

        public static string RoutePathPrefix
        {
            get { return GetAppSetting("routePathPrefix", DefaultRoutePathPrefix); }
        }

        public static string PackageMirrorTargetUrl
        {
            get { return GetAppSetting("packageMirrorTargetUrl", string.Empty); }
        }

        public static TimeSpan PackageMirrorTimeout
        {
            get
            {
                var str = GetAppSetting("packageMirrorTimeout", "0:00:15");
                TimeSpan ts;
                return TimeSpan.TryParse(str, out ts) ? ts : TimeSpan.FromSeconds(15);
            }
        }
        internal static bool GetFlagFromAppSetting(string key, bool defaultValue)
        {
            var flag = GetAppSetting(key, string.Empty);

            bool result;
            return bool.TryParse(flag ?? string.Empty, out result) ? result : defaultValue;
        }

        internal static string MapPathFromAppSetting(string key, string defaultValue)
        {
            var path = GetAppSetting(key, defaultValue);

            if (path.StartsWith("~/"))
            {
                return HostingEnvironment.MapPath(path);
            }

            return path;
        }

        internal static string GetAppSetting(string key, string defaultValue)
        {
            var value = ConfigurationManager.AppSettings[GetAppSettingKey(key)];
            return string.IsNullOrWhiteSpace(value) ? defaultValue : value;
        }

        private static string GetAppSettingKey(string key)
        {
            return AppSettingNamesapce + key;
        }
    }

    public class NonDecoratedPropertyInjectionHeuristic : NinjectComponent, IInjectionHeuristic
    {
        private readonly IKernel kernel;

        private static readonly ISet<Assembly> knownAssemblies = new HashSet<Assembly> { typeof(NonDecoratedPropertyInjectionHeuristic).Assembly };

        public NonDecoratedPropertyInjectionHeuristic(IKernel kernel)
        {
            this.kernel = kernel;
        }

        public bool ShouldInject(MemberInfo memberInfo)
        {
            var propertyInfo = memberInfo as PropertyInfo;
            return ShouldInject(propertyInfo);
        }

        private bool ShouldInject(PropertyInfo propertyInfo)
        {
            if (propertyInfo == null)
                return false;

            if (!propertyInfo.CanWrite)
                return false;

            var targetType = propertyInfo.ReflectedType;
            var assembly = targetType.Assembly;
            if (!knownAssemblies.Contains(assembly))
                return false;

            var instance = kernel.TryGet(propertyInfo.PropertyType);
            return instance != null;
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.5"/>
<title>Core Plot (iOS): CPTAxis(AbstractMethods) Category Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Core Plot (iOS)

Cocoa plotting framework for Mac OS X and iOS

Main Page

Related Pages

Animation & Constants

Classes

Files

Class List

Class Index

Class Hierarchy

Class Members

List of all members

CPTAxis(AbstractMethods) Category Reference

CPTAxis abstract methods—must be overridden by subclasses.
 More...

#import <CPTAxis.h>

Public Instance Methods

Coordinate Space Conversions

(CGPoint) 	- viewPointForCoordinateDecimalNumber:

 	Converts a position on the axis to drawing coordinates.  More...

Grid Lines

(void) 	- drawGridLinesInContext:isMajor:

 	Draws grid lines into the provided graphics context.  More...

Background Bands

(void) 	- drawBackgroundBandsInContext:

 	Draws alternating background bands into the provided graphics context.  More...

(void) 	- drawBackgroundLimitsInContext:

 	Draws background limit ranges into the provided graphics context.  More...

Detailed Description

CPTAxis abstract methods—must be overridden by subclasses.

Method Documentation

          - (void) drawBackgroundBandsInContext:

          (CGContextRef)
          context

Draws alternating background bands into the provided graphics context.

Parameters

context	The graphics context to draw into.

Extends class CPTAxis.

          - (void) drawBackgroundLimitsInContext:

          (CGContextRef)
          context

Draws background limit ranges into the provided graphics context.

Parameters

context	The graphics context to draw into.

Extends class CPTAxis.

          - (void) drawGridLinesInContext:

          (CGContextRef)
          context

          isMajor:

          (BOOL)
          major

Draws grid lines into the provided graphics context.

Parameters

context	The graphics context to draw into.

major	Draw the major grid lines If YES, minor grid lines otherwise.

Extends class CPTAxis.

          - (CGPoint) viewPointForCoordinateDecimalNumber:

          (NSDecimal)
          coordinateDecimalNumber

Converts a position on the axis to drawing coordinates.

Parameters

coordinateDecimalNumber	The axis value in data coordinate space.

Returns

The drawing coordinates of the point.

Extends class CPTAxis.

The documentation for this category was generated from the following files:

Source/CPTAxis.h

Source/CPTAxis.m

CPTAxis(AbstractMethods)

Generated by

     1.8.5


text:
/*!
 * \file mxnet_op.h
 * \brief
 * \author Junyuan Xie
*/
#ifndef MXNET_OPERATOR_MXNET_OP_H_
#define MXNET_OPERATOR_MXNET_OP_H_

#include <dmlc/omp.h>
#include <mxnet/base.h>
#include <mxnet/engine.h>
#include <mxnet/op_attr_types.h>
#include <algorithm>

#ifdef __CUDACC__
#include "../common/cuda_utils.h"
#endif  // __CUDACC__

namespace mxnet {
namespace op {
namespace mxnet_op {
using namespace mshadow;

#ifdef __CUDA_ARCH__
__constant__ const float PI = 3.14159265358979323846;
#else
const float PI = 3.14159265358979323846;
using std::isnan;
#endif

template<typename xpu>
int get_num_threads(const int N);

#ifdef __CUDACC__
#define CUDA_KERNEL_LOOP(i, n) \
  for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
      i < (n); \
      i += blockDim.x * gridDim.x)

inline cudaDeviceProp cuda_get_device_prop() {
  int device;
  CUDA_CALL(cudaGetDevice(&device));
  cudaDeviceProp deviceProp;
  CUDA_CALL(cudaGetDeviceProperties(&deviceProp, device));
  return deviceProp;
}

/*!
 * \brief Get the number of blocks for cuda kernel given N
 */
inline int cuda_get_num_blocks(const int N) {
  using namespace mshadow::cuda;
  return std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum);
}

template<>
inline int get_num_threads<gpu>(const int N) {
  using namespace mshadow::cuda;
  return kBaseThreadNum * cuda_get_num_blocks(N);
}
#endif  // __CUDACC__

template<>
inline int get_num_threads<cpu>(const int N) {
  return omp_get_max_threads();
}

/*! \brief operator request type switch */
#define MXNET_ASSIGN_REQ_SWITCH(req, ReqType, ...)  \
  switch (req) {                                    \
  case kNullOp:                                     \
    break;                                          \
  case kWriteInplace:                               \
  case kWriteTo:                                    \
    {                                               \
      const OpReqType ReqType = kWriteTo;           \
      {__VA_ARGS__}                                 \
    }                                               \
    break;                                          \
  case kAddTo:                                      \
    {                                               \
      const OpReqType ReqType = kAddTo;             \
      {__VA_ARGS__}                                 \
    }                                               \
    break;                                          \
  default:                                          \
    break;                                          \
  }

/*!
 * \brief assign the val to out according
 * to request in Kernel::Launch
 * \param out the data to be assigned
 * \param req the assignment request
 * \param val the value to be assigned to out
 * \tparam OType output type
 * \tparam VType value type
 */
#define KERNEL_ASSIGN(out, req, val)  \
  {                                   \
    switch (req) {                    \
      case kNullOp:                   \
        break;                        \
      case kWriteTo:                  \
      case kWriteInplace:             \
        (out) = (val);                \
        break;                        \
      case kAddTo:                    \
        (out) += (val);               \
        break;                        \
      default:                        \
        break;                        \
    }                                 \
  }

/* \brief Compute flattened index given coordinates and shape. */
template<int ndim>
MSHADOW_XINLINE int ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) {
  int ret = 0;
  #pragma unroll
  for (int i = 0; i < ndim; ++i) {
    ret = ret * shape[i] + (shape[i] > coord[i]) * coord[i];
  }
  return ret;
}

/* Compute coordinates from flattened index given shape */
template<int ndim>
MSHADOW_XINLINE Shape<ndim> unravel(const int idx, const Shape<ndim>& shape) {
  Shape<ndim> ret;
  #pragma unroll
  for (int i = ndim-1, j = idx; i >=0; --i) {
    int tmp = j / shape[i];
    ret[i] = j - tmp*shape[i];
    j = tmp;
  }
  return ret;
}

/* Compute dot product of two vector */
template<int ndim>
MSHADOW_XINLINE int dot(const Shape<ndim>& coord, const Shape<ndim>& stride) {
  int ret = 0;
  #pragma unroll
  for (int i = 0; i < ndim; ++i)
    ret += coord[i] * stride[i];
  return ret;
}

/* Combining unravel and dot */
template<int ndim>
MSHADOW_XINLINE int unravel_dot(const int idx, const Shape<ndim>& shape,
  const Shape<ndim>& stride) {
  int ret = 0;
  #pragma unroll
  for (int i = ndim-1, j = idx; i >=0; --i) {
    int tmp = j / shape[i];
    ret += (j - tmp*shape[i])*stride[i];
    j = tmp;
  }
  return ret;
}

/* Calculate stride of each dim from shape */
template<int ndim>
MSHADOW_XINLINE Shape<ndim> calc_stride(const Shape<ndim>& shape) {
  Shape<ndim> stride;
  index_t cumprod = 1;
  #pragma unroll
  for (int i = ndim - 1; i >= 0; --i) {
    stride[i] = (shape[i] > 1) ? cumprod : 0;
    cumprod *= shape[i];
  }
  return stride;
}

/*!
 * \brief Simple copy data from one blob to another
 * \param to Destination blob
 * \param from Source blob
 */
template <typename xpu>
MSHADOW_CINLINE void copy(mshadow::Stream<xpu> *s, const TBlob& to, const TBlob& from) {
  CHECK_EQ(from.Size(), to.Size());
  CHECK_EQ(from.dev_mask(), to.dev_mask());
  MSHADOW_TYPE_SWITCH(to.type_flag_, DType, {
    if (to.type_flag_ == from.type_flag_) {
      mshadow::Copy(to.FlatTo1D<xpu, DType>(), from.FlatTo1D<xpu, DType>(), s);
    } else {
      MSHADOW_TYPE_SWITCH(from.type_flag_, SrcDType, {
        to.FlatTo1D<xpu, DType>(s) = mshadow::expr::tcast<DType>(from.FlatTo1D<xpu, SrcDType>(s));
      })
    }
  })
}

/*! \brief Binary op backward gradient OP wrapper */
template<typename GRAD_OP>
struct backward_grad {
  /* \brief Backward calc with grad
   * \param a - output grad
   * \param args... - data to grad calculation op (what this is -- input, output, etc. -- varies)
   * \return input grad
   */
  template<typename DType, typename ...Args>
  MSHADOW_XINLINE static DType Map(DType a, Args... args) {
    return DType(a * GRAD_OP::Map(args...));
  }
};

/*! \brief Select assignment operation based upon the req value
 * Also useful for mapping mshadow Compute (F<OP>) to Kernel<OP>::Launch
 */
template<typename OP, int req>
struct op_with_req {
  typedef OP Operation;

  /*! \brief input is one tensor */
  template<typename DType>
  MSHADOW_XINLINE static void Map(int i, DType *out, const DType *in) {
    KERNEL_ASSIGN(out[i], req, OP::Map(in[i]));
  }

  /*! \brief inputs are two tensors */
  template<typename DType>
  MSHADOW_XINLINE static void Map(int i, DType *out, const DType *lhs, const DType *rhs) {
    KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i]));
  }

  /*! \brief input is tensor and a scalar value */
  template<typename DType>
  MSHADOW_XINLINE static void Map(int i, DType *out, const DType *in, const DType value) {
    KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value));
  }

  /*! \brief No inputs (ie fill to constant value) */
  template<typename DType>
  MSHADOW_XINLINE static void Map(int i, DType *out) {
    KERNEL_ASSIGN(out[i], req, OP::Map());
  }

  /*! \brief input is single scalar value */
  template<typename DType>
  MSHADOW_XINLINE static void Map(int i, DType *out, const DType value) {
    KERNEL_ASSIGN(out[i], req, OP::Map(value));
  }

  /*! \brief inputs are two tensors and a scalar value */
  template<typename DType>
  MSHADOW_XINLINE static void Map(int i, DType *out,
                                  const DType *input_1, const DType *input_2, const DType value) {
    KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], value));
  }

  /*! \brief inputs are three tensors (ie backward grad with binary grad function) */
  template<typename DType>
  MSHADOW_XINLINE static void Map(int i, DType *out,
                                  const DType *input_1,
                                  const DType *input_2,
                                  const DType *input_3) {
    KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], input_3[i]));
  }
};

/*!
 * \brief Set to immediate scalar value kernel
 * \tparam val Scalar immediate
 */
template<int val>
struct set_to_int {
  // mxnet_op version (when used directly with Kernel<>::Launch()) */
  template<typename DType>
  MSHADOW_XINLINE static void Map(int i, DType* out) {
    out[i] = DType(val);
  }
  // mshadow_op version (when used with op_with_req<>)
  MSHADOW_XINLINE static int Map() {
    return val;
  }
};

/*! \brief Special-case kernel shortcut for setting to zero */
using set_zero = set_to_int<0>;

template<typename OP, typename xpu>
struct Kernel;

template<typename OP>
struct Kernel<OP, cpu> {
  template<typename ...Args>
  inline static void Launch(mshadow::Stream<cpu> *s, const int N, Args... args) {
#ifdef _OPENMP
    const int omp_cores = Engine::Get()->num_omp_threads_per_worker();
    if (omp_cores <= 1) {
      // Zero means not to use OMP, but don't interfere with external OMP behavior
      for (int i = 0; i < N; ++i) {
        OP::Map(i, args...);
      }
    } else {
      #pragma omp parallel for num_threads(omp_cores)
      for (int i = 0; i < N; ++i) {
        OP::Map(i, args...);
      }
    }
#else
    for (int i = 0; i < N; ++i) {
        OP::Map(i, args...);
    }
#endif
  }
};

#ifdef __CUDACC__
template<typename OP, typename ...Args>
__global__ void mxnet_generic_kernel(int N, Args... args) {
  for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) {
    OP::Map(i, args...);
  }
}

template<typename OP>
struct Kernel<OP, gpu> {
  template<typename ...Args>
  inline static void Launch(mshadow::Stream<gpu> *s, int N, Args... args) {
    using namespace mshadow::cuda;
    int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum);
    mxnet_generic_kernel<OP, Args...>
      <<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>(
        N, args...);
  }
};
#endif  // __CUDACC__

}  // namespace mxnet_op
}  // namespace op
}  // namespace mxnet
#endif  // MXNET_OPERATOR_MXNET_OP_H_


text:
using System;
using System.Diagnostics;
using GSF.IO.Unmanaged;
using GSF.Snap.Types;
using NUnit.Framework;

namespace GSF.Snap.Tree
{
    public static class Extension_FixedSizeNode_uint_uint
    {
        public static uint Get(this FixedSizeNode<SnapUInt32, SnapUInt32> tree, uint key)
        {
            SnapUInt32 k = new SnapUInt32(key);
            SnapUInt32 v = new SnapUInt32();
            if (!tree.TryGet(k, v))
                throw new Exception();
            return v.Value;
        }

        public static bool TryGet(this FixedSizeNode<SnapUInt32, SnapUInt32> tree, uint key, out uint value)
        {
            SnapUInt32 k = new SnapUInt32(key);
            SnapUInt32 v = new SnapUInt32();
            bool rv = tree.TryGet(k, v);
            value = v.Value;
            return rv;
        }

        public static uint GetOrGetNext(this FixedSizeNode<SnapUInt32, SnapUInt32> tree, uint key)
        {
            SnapUInt32 k = new SnapUInt32(key);
            SnapUInt32 v = new SnapUInt32();
            tree.GetOrGetNext(k, v);
            return v.Value;
        }

        public static bool TryInsert(this FixedSizeNode<SnapUInt32, SnapUInt32> tree, uint key, uint value)
        {
            SnapUInt32 k = new SnapUInt32(key);
            SnapUInt32 v = new SnapUInt32(value);
            bool rv = tree.TryInsert(k, v);
            return rv;
        }

        public static void Insert(this FixedSizeNode<SnapUInt32, SnapUInt32> tree, uint key, uint value)
        {
            SnapUInt32 k = new SnapUInt32(key);
            SnapUInt32 v = new SnapUInt32(value);
            if (!tree.TryInsert(k, v))
                throw new Exception();
        }

        public static void GetFirstKeyValue(this FixedSizeNode<SnapUInt32, SnapUInt32> tree, out uint key, out uint value)
        {
            SnapUInt32 k = new SnapUInt32();
            SnapUInt32 v = new SnapUInt32();
            tree.TryGetFirstRecord(k, v);
            key = k.Value;
            value = v.Value;
        }

        public static uint GetFirstKey(this FixedSizeNode<SnapUInt32, SnapUInt32> tree)
        {
            SnapUInt32 k = new SnapUInt32();
            SnapUInt32 v = new SnapUInt32();
            tree.TryGetFirstRecord(k, v);
            return k.Value;
        }

        public static uint GetFirstValue(this FixedSizeNode<SnapUInt32, SnapUInt32> tree)
        {
            SnapUInt32 k = new SnapUInt32();
            SnapUInt32 v = new SnapUInt32();
            tree.TryGetFirstRecord(k, v);
            return v.Value;
        }

        public static void GetLastKeyValue(this FixedSizeNode<SnapUInt32, SnapUInt32> tree, out uint key, out uint value)
        {
            SnapUInt32 k = new SnapUInt32();
            SnapUInt32 v = new SnapUInt32();
            tree.TryGetLastRecord(k, v);
            key = k.Value;
            value = v.Value;
        }

        public static uint GetLastKey(this FixedSizeNode<SnapUInt32, SnapUInt32> tree)
        {
            SnapUInt32 k = new SnapUInt32();
            SnapUInt32 v = new SnapUInt32();
            tree.TryGetLastRecord(k, v);
            return k.Value;
        }

        public static uint GetLastValue(this FixedSizeNode<SnapUInt32, SnapUInt32> tree)
        {
            SnapUInt32 k = new SnapUInt32();
            SnapUInt32 v = new SnapUInt32();
            tree.TryGetLastRecord(k, v);
            return v.Value;
        }

        public static bool KeyInsideBounds(this FixedSizeNode<SnapUInt32, SnapUInt32> tree, uint key)
        {
            SnapUInt32 k = new SnapUInt32(key);
            return tree.IsKeyInsideBounds(k);
        }

        public static uint UpperKey(this FixedSizeNode<SnapUInt32, SnapUInt32> tree)
        {
            return tree.UpperKey.Value;
        }

        public static uint LowerKey(this FixedSizeNode<SnapUInt32, SnapUInt32> tree)
        {
            return tree.LowerKey.Value;
        }
    }

    [TestFixture]
    public class FixedSizeNode_Test
    {
        private const int Max = 1000000;

        [Test]
        public void Test_CreateRootNode_Get()
        {
            uint rootKey = 0;
            byte rootLevel = 0;

            uint nextKeyIndex = 0;
            Func<uint> getNextKey = () =>
            {
                nextKeyIndex++;
                return nextKeyIndex - 1;
            };
            Action<SnapUInt32, uint, byte> addToParent = (int32, u, arg3) => int32 = int32;
            Func<SnapUInt32, uint> findLeafNode = int32 => 0;

            Stopwatch swWrite = new Stopwatch();
            Stopwatch swRead = new Stopwatch();
            using (BinaryStream bs = new BinaryStream())
            {
                uint k, v;
                FixedSizeNode<SnapUInt32, SnapUInt32> node = new FixedSizeNode<SnapUInt32, SnapUInt32>(0);

                node.Initialize(bs, 1024, getNextKey, null);

                node.CreateEmptyNode(0);
                node.Insert(1, 100);
                node.Insert(2, 200);

                Assert.AreEqual(0u, node.NodeIndex);
                Assert.AreEqual(uint.MaxValue, node.LeftSiblingNodeIndex);
                Assert.AreEqual(uint.MaxValue, node.RightSiblingNodeIndex);

                Assert.AreEqual(1u, node.GetFirstKey());
                Assert.AreEqual(100u, node.GetFirstValue());
                Assert.AreEqual(2u, node.GetLastKey());
                Assert.AreEqual(200u, node.GetLastValue());

                Assert.AreEqual(100u, node.Get(1));
                Assert.AreEqual(200u, node.Get(2));
                Assert.AreEqual(100u, node.GetOrGetNext(1));
                Assert.AreEqual(200u, node.GetOrGetNext(2));
                Assert.AreEqual(200u, node.GetOrGetNext(3));

                node.SetNodeIndex(0);

                Assert.AreEqual(0u, node.NodeIndex);
                Assert.AreEqual(uint.MaxValue, node.LeftSiblingNodeIndex);
                Assert.AreEqual(uint.MaxValue, node.RightSiblingNodeIndex);

                Assert.AreEqual(1u, node.GetFirstKey());
                Assert.AreEqual(100u, node.GetFirstValue());
                Assert.AreEqual(2u, node.GetLastKey());
                Assert.AreEqual(200u, node.GetLastValue());

                Assert.AreEqual(100u, node.Get(1));
                Assert.AreEqual(200u, node.Get(2));
                Assert.AreEqual(100u, node.GetOrGetNext(1));
                Assert.AreEqual(200u, node.GetOrGetNext(2));
                Assert.AreEqual(200u, node.GetOrGetNext(3));
            }
        }

        //[Test]
        //public void Test_Split()
        //{
        //    uint rootKey = 0;
        //    byte rootLevel = 0;

        //    uint nextKeyIndex = 0;
        //    Func<uint> getNextKey = () =>
        //    {
        //        nextKeyIndex++;
        //        return nextKeyIndex - 1;
        //    };

        //    Stopwatch swWrite = new Stopwatch();
        //    Stopwatch swRead = new Stopwatch();
        //    using (var bs = new BinaryStream())
        //    {
        //        var node = new SparseIndex<KeyValue256, KeyValue256Methods>.Node(bs, 1024, 1);
        //        var k0 = new KeyValue256();
        //        var k1 = new KeyValue256();
        //        var k2 = new KeyValue256();
        //        var k3 = new KeyValue256();
        //        var k4 = new KeyValue256();
        //        var k5 = new KeyValue256();
        //        k0.Key1 = 1;
        //        k1.Key1 = 1000;
        //        k2.Key1 = 2000;
        //        k3.Key1 = 3000;
        //        k4.Key1 = 4000;
        //        k5.Key1 = 5000;

        //        node.CreateRootNode(0, 1, 100, k2, 2000);
        //        node.Insert(k5, 5000);
        //        node.Insert(k3, 3000);
        //        node.Insert(k1, 1000);
        //        node.Insert(k4, 4000);

        //        node.Split(1);

        //        Assert.AreEqual(uint.MaxValue, node.LeftSiblingNodeIndex);
        //        Assert.AreEqual(1u, node.RightSiblingNodeIndex);
        //        Assert.AreEqual((ushort)2, node.RecordCount);
        //        Assert.AreEqual(100u, node.GetFirstPointer());
        //        Assert.AreEqual(2000u, node.GetLastPointer());
        //        Assert.AreEqual(0ul, node.LowerKey.Key1);
        //        Assert.AreEqual(3000ul, node.UpperKey.Key1);

        //        Assert.AreEqual(100u, node.Get(k0));
        //        Assert.AreEqual(1000u, node.Get(k1));
        //        Assert.AreEqual(2000u, node.Get(k2));
        //        Assert.AreEqual(2000u, node.Get(k3));
        //        Assert.AreEqual(2000u, node.Get(k4));
        //        Assert.AreEqual(2000u, node.Get(k5));

        //        node.SeekToRightSibling();

        //        Assert.AreEqual(0u, node.LeftSiblingNodeIndex);
        //        Assert.AreEqual(uint.MaxValue, node.RightSiblingNodeIndex);
        //        Assert.AreEqual((ushort)2, node.RecordCount);
        //        Assert.AreEqual(3000u, node.GetFirstPointer());
        //        Assert.AreEqual(5000u, node.GetLastPointer());
        //        Assert.AreEqual(3000ul, node.LowerKey.Key1);
        //        Assert.AreEqual(0ul, node.UpperKey.Key1);

        //        Assert.AreEqual(3000u, node.Get(k0));
        //        Assert.AreEqual(3000u, node.Get(k1));
        //        Assert.AreEqual(3000u, node.Get(k2));
        //        Assert.AreEqual(3000u, node.Get(k3));
        //        Assert.AreEqual(4000u, node.Get(k4));
        //        Assert.AreEqual(5000u, node.Get(k5));

        //        node.SeekToLeftSibling();

        //        Assert.AreEqual(uint.MaxValue, node.LeftSiblingNodeIndex);
        //        Assert.AreEqual(1u, node.RightSiblingNodeIndex);
        //        Assert.AreEqual((ushort)2, node.RecordCount);
        //        Assert.AreEqual(100u, node.GetFirstPointer());
        //        Assert.AreEqual(2000u, node.GetLastPointer());
        //        Assert.AreEqual(0ul, node.LowerKey.Key1);
        //        Assert.AreEqual(3000ul, node.UpperKey.Key1);

        //        Assert.AreEqual(100u, node.Get(k0));
        //        Assert.AreEqual(1000u, node.Get(k1));
        //        Assert.AreEqual(2000u, node.Get(k2));
        //        Assert.AreEqual(2000u, node.Get(k3));
        //        Assert.AreEqual(2000u, node.Get(k4));
        //        Assert.AreEqual(2000u, node.Get(k5));

        //        node.Insert(k3, 303);
        //        node.Insert(k4, 404);
        //        node.Insert(k5, 505);

        //        node.Split(2);

        //        Assert.AreEqual(uint.MaxValue, node.LeftSiblingNodeIndex);
        //        Assert.AreEqual(2u, node.RightSiblingNodeIndex);
        //        Assert.AreEqual((ushort)2, node.RecordCount);
        //        Assert.AreEqual(100u, node.GetFirstPointer());
        //        Assert.AreEqual(2000u, node.GetLastPointer());
        //        Assert.AreEqual(0ul, node.LowerKey.Key1);
        //        Assert.AreEqual(3000ul, node.UpperKey.Key1);

        //        Assert.AreEqual(100u, node.Get(k0));
        //        Assert.AreEqual(1000u, node.Get(k1));
        //        Assert.AreEqual(2000u, node.Get(k2));
        //        Assert.AreEqual(2000u, node.Get(k3));
        //        Assert.AreEqual(2000u, node.Get(k4));
        //        Assert.AreEqual(2000u, node.Get(k5));

        //        node.SeekToRightSibling();

        //        Assert.AreEqual(0u, node.LeftSiblingNodeIndex);
        //        Assert.AreEqual(1u, node.RightSiblingNodeIndex);
        //        Assert.AreEqual((ushort)2, node.RecordCount);
        //        Assert.AreEqual(303u, node.GetFirstPointer());
        //        Assert.AreEqual(505u, node.GetLastPointer());
        //        Assert.AreEqual(3000ul, node.LowerKey.Key1);
        //        Assert.AreEqual(3000ul, node.UpperKey.Key1);

        //        Assert.AreEqual(303u, node.Get(k0));
        //        Assert.AreEqual(303u, node.Get(k1));
        //        Assert.AreEqual(303u, node.Get(k2));
        //        Assert.AreEqual(303u, node.Get(k3));
        //        Assert.AreEqual(404u, node.Get(k4));
        //        Assert.AreEqual(505u, node.Get(k5));

        //        node.SeekToRightSibling();

        //        Assert.AreEqual(2u, node.LeftSiblingNodeIndex);
        //        Assert.AreEqual(uint.MaxValue, node.RightSiblingNodeIndex);
        //        Assert.AreEqual((ushort)2, node.RecordCount);
        //        Assert.AreEqual(3000u, node.GetFirstPointer());
        //        Assert.AreEqual(5000u, node.GetLastPointer());
        //        Assert.AreEqual(3000ul, node.LowerKey.Key1);
        //        Assert.AreEqual(0ul, node.UpperKey.Key1);

        //        Assert.AreEqual(3000u, node.Get(k0));
        //        Assert.AreEqual(3000u, node.Get(k1));
        //        Assert.AreEqual(3000u, node.Get(k2));
        //        Assert.AreEqual(3000u, node.Get(k3));
        //        Assert.AreEqual(4000u, node.Get(k4));
        //        Assert.AreEqual(5000u, node.Get(k5));
        //    }
        //}
    }
}


text:
require 'helper'

describe Trufflepig::FeatureList do
  describe "load" do
    before do
      @features = Trufflepig::FeatureList.load
    end

    it "returns a list of features" do
      feature_keys = @features.collect{|f| f["id"] }
      feature_keys.must_include "video"
      feature_keys.must_include "audio"
      feature_keys.must_include "canvas"

      feature = @features.select{|f| f["id"] == "video"}.first
      feature["categories"].must_equal ["HTML5"]
      feature["title"].must_equal "Video element"
    end
  end

  describe "build" do
    before do
      Trufflepig::FeatureList.build
      @features = Trufflepig::FeatureList.load
    end

    it "adds detection patterns to the features" do
      feature = @features.select{|f| f["id"] == "video"}.first
      feature["detection_pattern"].must_equal "<video.*>.*<\\/video>"

      feature = @features.select{|f| f["id"] == "offline-apps"}.first
      feature["detection_pattern"].must_equal "<html.*\\smanifest=.*>"
    end
  end
end


text:
@interface FNNewsBaseController () <UIScrollViewDelegate>
// 顶部栏目标题scrollView
@property (nonatomic, weak) UIScrollView *titleScrollView;
// 内容的scrollView,存放tableView
@property (nonatomic, weak) UIScrollView *contentScrollView;
@property (nonatomic, strong) UIButton *selectedBtn;
@property (nonatomic, strong) NSMutableArray *titleBtnArray;

@property (nonatomic, assign) BOOL isSet;

@end

@implementation FNNewsBaseController

- (NSMutableArray *)titleBtnArray
{
    if (!_titleBtnArray){
        self.titleBtnArray = [[NSMutableArray alloc] init];
    }
    return _titleBtnArray;

}

- (void)setAllPrepare
{
    [self setContentScrollView];
    [self setTitleScrollView];
    [self setTitleScrollViewBtn];
    [self showTargetViewWithIndex:0];
}
#pragma mark - 设置标题scrollView
- (void)setTitleScrollView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    UIScrollView *titleScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, FNScreenW, 35)];
    titleScrollView.backgroundColor = FNColor(235, 235, 235);

    CGFloat W = self.childViewControllers.count * FNScreenW / 4;
    titleScrollView.contentSize = CGSizeMake(W, 0);
    titleScrollView.showsHorizontalScrollIndicator = NO;
    titleScrollView.showsVerticalScrollIndicator = NO;
    titleScrollView.scrollsToTop = NO;
    [self.view addSubview:titleScrollView];
    self.titleScrollView = titleScrollView;
}
#pragma mark - 设置标题按钮
- (void)setTitleScrollViewBtn
{
    for (int i = 0; i < self.childViewControllers.count; i++) {
        UIViewController *VC = self.childViewControllers[i];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        [self.titleBtnArray addObject:btn];
        CGFloat X = FNScreenW/4 * i;
        btn.frame = CGRectMake(X, 0, FNScreenW/4, 35);
        btn.tag = i;
        if (btn.tag == 0) {
            self.selectedBtn = btn;
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            btn.transform = CGAffineTransformMakeScale(1.3, 1.3);
        } else {
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
        [btn setTitle:VC.title forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(titleViewBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.titleScrollView addSubview:btn];
    }

}
#pragma mark - 监听标题按钮点击
- (void)titleViewBtnClick:(UIButton *)btn
{
    // 发布通知
    if (self.selectedBtn == btn) {
        // object = nil 匿名通知
        [[NSNotificationCenter defaultCenter] postNotificationName:FNNewsTitleButtonRepeatClickNotification object:nil];
    }
    // 1.标题状态改变
    self.selectedBtn.transform = CGAffineTransformIdentity;
    self.selectedBtn.selected = NO;
    [self.selectedBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    btn.selected = YES;
    self.selectedBtn = btn;
    [self.selectedBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    self.contentScrollView.contentOffset = CGPointMake(FNScreenW * btn.tag, 0);

    self.selectedBtn.transform = CGAffineTransformMakeScale(1.3, 1.3);
    CGFloat offSetX = 0;
    if (btn.center.x < FNScreenW/2) {
        offSetX = 0;
    }else if ((self.titleScrollView.contentSize.width - btn.center.x) < FNScreenW/2) {
        offSetX = self.titleScrollView.contentSize.width - FNScreenW;
    } else {
        offSetX = btn.center.x - FNScreenW/2;
    }
    [self.titleScrollView setContentOffset:CGPointMake(offSetX, 0) animated:YES];

    // 2.显示目标View
    [self showTargetViewWithIndex:btn.tag];
}
#pragma mark - 设置contentScrollView
- (void)setContentScrollView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    UIScrollView *contentScrollView = [[UIScrollView alloc] init];
    contentScrollView.delegate = self;
    contentScrollView.frame = CGRectMake(0, 0, FNScreenW, FNScreenH);
    contentScrollView.backgroundColor = [UIColor whiteColor];

    CGFloat contentW = self.childViewControllers.count * FNScreenW;
    contentScrollView.contentSize = CGSizeMake(contentW, 0);
    contentScrollView.showsHorizontalScrollIndicator = NO;
    contentScrollView.showsVerticalScrollIndicator = NO;
    contentScrollView.pagingEnabled = YES;
    contentScrollView.scrollsToTop = NO;
    [self.view addSubview:contentScrollView];

    self.contentScrollView = contentScrollView;
}

#pragma mark - UIScrollViewDelegate 标题颜色大小渐变

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x<0 | scrollView.contentOffset.x>=(self.titleBtnArray.count-1)*FNScreenW) return;

    NSInteger index = scrollView.contentOffset.x / FNScreenW;

    UIButton *leftbtnBtn = self.titleBtnArray[index];
    UIButton *rightBtn = self.titleBtnArray[index+1];

    CGFloat rightScale = (scrollView.contentOffset.x - index*FNScreenW)/FNScreenW;
    CGFloat leftScale = 1 - rightScale;

    rightBtn.transform = CGAffineTransformMakeScale(rightScale*0.3+1, rightScale*0.3+1);
    leftbtnBtn.transform = CGAffineTransformMakeScale(leftScale*0.3+1, leftScale*0.3+1);

    [rightBtn setTitleColor:[UIColor colorWithRed:rightScale green:0 blue:0 alpha:1] forState:UIControlStateNormal];
    [leftbtnBtn setTitleColor:[UIColor colorWithRed:leftScale green:0 blue:0 alpha:1] forState:UIControlStateNormal];

}
// 滑动结束时调用的代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x / FNScreenW;

    UIButton *btn = self.titleBtnArray[index];

    // 如果滑动减速后的页面还是当前页面,就不调用下面的方法,直接返回
    if (self.selectedBtn == btn) return;

    [self titleViewBtnClick:btn];

}

#pragma mark - 展示点击的目标View
- (void)showTargetViewWithIndex:(NSInteger)index
{
    UITableViewController *tableVC = (UITableViewController*)self.childViewControllers[index];
    // 如果已经添加了View,不做重复操作
    if (!tableVC.tableView.window) {
        [self setLayout:tableVC.tableView :index];
    }
    // 对左右两个新闻界面进行提前缓存
    if (index == 0) {
        UITableViewController *rightTableVC = (UITableViewController*)self.childViewControllers[index+1];
        if (!rightTableVC.tableView.window) {
            [self setLayout:rightTableVC.tableView :index+1];
        }
    } else if (index == self.childViewControllers.count-1) {
        UITableViewController *leftTableVC = (UITableViewController*)self.childViewControllers[index-1];
        if (!leftTableVC.tableView.window) {
            [self setLayout:leftTableVC.tableView :index-1];
        };
    } else {
        UITableViewController *rightTableVC = (UITableViewController*)self.childViewControllers[index+1];
        if (!rightTableVC.tableView.window) {

            [self setLayout:rightTableVC.tableView :index+1];
        }
        UITableViewController *leftTableVC = (UITableViewController*)self.childViewControllers[index-1];
        if (!leftTableVC.tableView.window) {
            [self setLayout:leftTableVC.tableView :index-1];
        }
    }

    // 保持最多5个控制器的View存在,性能优化

    for (int i = 0;i < self.childViewControllers.count ;i++) {
        UITableViewController *tableVC = self.childViewControllers[i];
    // 保持最多5个控制器的View存在,性能优化
        if (fabs((double)(i-index)) > 2 && tableVC.isViewLoaded) {
            [tableVC.view removeFromSuperview];
        }
//         当scrollsToTop属性为yes时,再点击顶部状态栏
//         解决懒加载失败的BUG
        if (tableVC.isViewLoaded) {
            tableVC.tableView.scrollsToTop = (i == index);
        }
    }

}
#pragma mark - 抽出设置tableView frame的方法
- (void)setLayout:(UITableView *)tableV :(NSInteger)XIndex{
    [self.contentScrollView addSubview:tableV];
    tableV.frame = CGRectMake(FNScreenW * (XIndex), 0, FNScreenW, FNScreenH);
    tableV.contentInset = UIEdgeInsetsMake(YJNavBarMaxY+YJTitlesViewH, 0, YJTabBarH, 0);
    tableV.contentOffset = CGPointMake(0, -YJNavBarMaxY-YJTitlesViewH);
}

@end


text:
from types import CodeType
from typing import Any, Optional
import typing

if typing.TYPE_CHECKING:
    from . import sketch  # noqa: F401
    from . import statements  # noqa: F401

__all__ = ["PythonPrinter"]

class PythonPrinter:
    """
    Print Python code with indentation gracefully.
    """

    def __init__(
        self,
        path: str = "<string>",
        end: str = "\n",
        indent_mark: str = " " * 4,
    ) -> None:
        self._path = path
        self._indent_num = 0
        self._committed_code = ""

        self._end = end
        self._indent_mark = indent_mark

        self._finished = False

    def writeline(
        self, line: str, stmt: Optional["statements.AppendMixIn"] = None
    ) -> None:
        """
        Write a line with indent.
        """
        assert not self._finished, "Code Generation has already been finished."

        if stmt:
            line += f"  # in file {self._path} at line {stmt.line_no}."

        final_line = self._indent_mark * self._indent_num + line + self._end
        self._committed_code += final_line

    def indent_block(self) -> "PythonPrinter":
        """
        Indent the code with `with` statement.

        Example::

              printer.writeline("def a():")
              with printer.indent_block():
                  printer.writeline("return \"Text from function a.\"")

              printer.writeline("a()")

        """
        assert not self._finished, "Code Generation has already been finished."
        return self

    def _inc_indent_num(self) -> None:
        assert not self._finished, "Code Generation has already been finished."
        self._indent_num += 1

    def _dec_indent_num(self) -> None:
        assert not self._finished, "Code Generation has already been finished."
        self.writeline("pass")
        self._indent_num -= 1

    def __enter__(self) -> None:
        self._inc_indent_num()

    def __exit__(self, *exc: Any) -> None:
        self._dec_indent_num()

    @property
    def finished(self) -> bool:  # pragma: no cover
        return self._finished

    @property
    def plain_code(self) -> str:
        """
        Return the plain, printed code.
        """
        self._finished = True
        return self._committed_code

    @property
    def compiled_code(self) -> CodeType:
        """
        Return compiled code.
        """
        if not hasattr(self, "_compiled_code"):
            self._compiled_code = compile(
                self.plain_code, self._path, "exec", dont_inherit=True
            )

        return self._compiled_code  # type: ignore

    @classmethod
    def print_sketch(cls, skt: "sketch.Sketch") -> CodeType:
        py_printer = cls(path=skt._path)
        skt._root.print_code(py_printer)
        return py_printer.compiled_code