text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (What are Ubuntu Repositories? How to enable or disable them?)
[#]: via: (https://itsfoss.com/ubuntu-repositories)
[#]: author: (Abhishek Prakash https://itsfoss.com/author/abhishek/)

What are Ubuntu Repositories? How to enable or disable them?
======

_**This detailed article tells you about various repositories like universe, multiverse in Ubuntu and how to enable or disable them.**_

So, you are trying to follow a tutorial from the web and installing a software using apt-get command and it throws you an error:

```
E: Unable to locate package xyz
```

You are surprised because others the package should be available. You search on the internet and come across a solution that you have to enable universe or multiverse repository to install that package.

**You can enable universe and multiverse repositories in Ubuntu using the commands below:**

```
sudo add-apt-repository universe multiverse
sudo apt update
```

You installed the universe and multiverse repository but do you know what are these repositories? How do they play a role in installing packages? Why there are several repositories?

I'll explain all these questions in detail here.

### The concept of repositories in Ubuntu

Okay, so you already know that to [install software in Ubuntu][1], you can use the [apt command][2]. This is the same [APT package manager][3] that Ubuntu Software Center utilizes underneath. So all the software (except Snap packages) that you see in the Software Center are basically from APT.

Have you ever wondered where does the apt program install the programs from? How does it know which packages are available and which are not?

Apt basically works on the repository. A repository is nothing but a server that contains a set of software. Ubuntu provides a set of repositories so that you won't have to search on the internet for the installation file of various software of your need. This centralized way of providing software is one of the main strong points of using Linux.

The APT package manager gets the repository information from the /etc/apt/sources.list file and files listed in /etc/apt/sources.list.d directory. Repository information is usually in the following format:

```
deb http://us.archive.ubuntu.com/ubuntu/ bionic main
```

In fact, you can [go to the above server address][4] and see how the repository is structured.

When you [update Ubuntu using the apt update command][5], the apt package manager gets the information about the available packages (and their version info) from the repositories and stores them in local cache. You can see this in /var/lib/apt/lists directory.

Keeping this information locally speeds up the search process because you don't have to go through the network and search the database of available packages just to check if a certain package is available or not.

Now you know how repositories play an important role, let's see why there are several repositories provided by Ubuntu.

### Ubuntu Repositories: Main, Universe, Multiverse, Restricted and Partner

![][6]

Software in Ubuntu repository are divided into five categories: main, universe, multiverse, restricted and partner.

Why Ubuntu does that? Why not put all the software into one single repository? To answer this question, let's see what are these repositories:

#### **Main**

When you install Ubuntu, this is the repository enabled by default. The main repository consists of only FOSS (free and open source software) that can be distributed freely without any restrictions.

Software in this repository are fully supported by the Ubuntu developers. This is what Ubuntu will provide with security updates until your system reaches end of life.

#### **Universe**

This repository also consists free and open source software but Ubuntu doesn't guarantee of regular security updates to software in this category.

Software in this category are packaged and maintained by the community. The Universe repository has a vast amount of open source software and thus it enables you to have access to a huge number of software via apt package manager.

#### **Multiverse**

Multiverse contains the software that are not FOSS. Due to licensing and legal issues, Ubuntu cannot enable this repository by default and cannot provide fix and updates.

It's up to you to decide if you want to use Multiverse repository and check if you have the right to use the software.

#### **Restricted**

Ubuntu tries to provide only free and open source software but that's not always possible specially when it comes to supporting hardware.

The restricted repositories consists of proprietary drivers.

#### **Partner**

This repository consist of proprietary software packaged by Ubuntu for their partners. Earlier, Ubuntu used to provide Skype trough this repository.

#### Third party repositories and PPA (Not provided by Ubuntu)

The above five repositories are provided by Ubuntu. You can also add third party repositories (it's up to you if you want to do it) to access more software or to access newer version of a software (as Ubuntu might provide old version of the same software).

For example, if you add the repository provided by [VirtualBox][7], you can get the latest version of VurtualBox. It will add a new entry in your sources.list.

You can also install additional application using PPA (Personal Package Archive). I have written about [what is PPA and how it works][8] in detail so please read that article.

Tip

Try NOT adding anything other than Ubuntu's repositories in your sources.list file. You should keep this file in pristine condition because if you mess it up, you won't be able to update your system or (at times) even install new packages.

### Add universe, multiverse and other repositories

As I had mentioned earlier, only the Main repository is enabled by default when you install Ubuntu. To access more software, you can add the additional repositories.

Let me show you how to do it in command line first and then I'll show you the GUI ways as well.

To enable Universe repository, use:

```
sudo add-apt-repository universe
```

To enable Restricted repository, use:

```
sudo add-apt-repository restricted
```

To enable Multiverse repository, use this command:

```
sudo add-apt-repository multiverse
```

You must use sudo apt update command after adding the repository so that you system creates the local cache with package information.

If you want to **remove a repository** , simply add -r like **sudo add-apt-repository -r universe**.

Graphically, go to Software & Updates and you can enable the repositories here:

![Adding Universe, Restricted and Multiverse repositories][9]

You'll find the option to enable partner repository in the Other Software tab.

![Adding Partner repository][10]

To disable a repository, simply uncheck the box.

### Bonus Tip: How to know which repository a package belongs to?

Ubuntu has a dedicated website that provides you with information about all the packages available in the Ubuntu archive. Go to Ubuntu Packages website.

[Ubuntu Packages][11]

You can search for a package name in the search field. You can select if you are looking for a particular Ubuntu release or a particular repository. I prefer using 'any' option in both fields.

![][12]

It will show you all the matching packages, Ubuntu releases and the repository information.

![][13]

As you can see above the package tor is available in the Universe repository for various Ubuntu releases.

**Conclusion**

I hope this article helped you in understanding the concept of repositories in Ubuntu.

If you have any questions or suggestions, please feel free to leave a comment below. If you liked the article, please share it on social media sites like Reddit and Hacker News.

--------------------------------------------------------------------------------

via: https://itsfoss.com/ubuntu-repositories

作者:[Abhishek Prakash][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://itsfoss.com/author/abhishek/
[b]: https://github.com/lujun9972
[1]: https://itsfoss.com/remove-install-software-ubuntu/
[2]: https://itsfoss.com/apt-command-guide/
[3]: https://wiki.debian.org/Apt
[4]: http://us.archive.ubuntu.com/ubuntu/
[5]: https://itsfoss.com/update-ubuntu/
[6]: https://i2.wp.com/itsfoss.com/wp-content/uploads/2019/03/ubuntu-repositories.png?resize=800%2C450&ssl=1
[7]: https://itsfoss.com/install-virtualbox-ubuntu/
[8]: https://itsfoss.com/ppa-guide/
[9]: https://i2.wp.com/itsfoss.com/wp-content/uploads/2019/03/enable-repositories-ubuntu.png?resize=800%2C490&ssl=1
[10]: https://i2.wp.com/itsfoss.com/wp-content/uploads/2019/03/enable-partner-repository-ubuntu.png?resize=800%2C490&ssl=1
[11]: https://packages.ubuntu.com
[12]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2019/03/search-packages-ubuntu-archive.png?ssl=1
[13]: https://i0.wp.com/itsfoss.com/wp-content/uploads/2019/03/search-packages-ubuntu-archive-1.png?resize=800%2C454&ssl=1


text:
{% extends "wmhub/base.html" %}
{% block body %}

    Skip to content

    {{box.name}}

    基本设置

	管理员修改

Loading…

		  {% if errmsg %}

{{errmsg}}

		  {% endif %}

盒子信息

      <form accept-charset="UTF-8" action="." class="columns js-uploadable-container js-upload-avatar-image is-default" data-alambic-organization="12134573" data-alambic-owner-id="12134573" data-alambic-owner-type="User" data-form-nonce="4d266008a5f14bf19fdfe013514ccd6ee0a170f2" data-upload-policy-url="/upload/policies/avatars" id="edit_organization_12134573" method="post">

新管理员目录

<input id="organization_profile_name" name="admin" size="30" value="{{box.admin.dir}}" type="text">

<button type="submit" class="btn btn-primary">修改管理员</button>

</form>

Status

API

Training

Shop

Blog

About

Pricing

© 2015 GitHub, Inc.

Terms

Privacy

Security

Contact

Help

      <button type="button" class="flash-close js-flash-close js-ajax-error-dismiss" aria-label="Dismiss error">

      </button>
      Something went wrong with that request. Please try again.

      You signed in with another tab or window. Reload to refresh your session.
      You signed out in another tab or window. Reload to refresh your session.

         <button type="button" class="facebox-close js-facebox-close" aria-label="Close modal">                    </button>

	{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
'''
Created on Aug 7, 2011

@author: eplaster
'''

from __builtin__ import object


text:
var path = require('path');
var highlightjs = require('highlight.js');
var webpack = require('webpack');

module.exports = [
  {
    name: "docs",
    entry: './docs/app/index.js',
    output: {
      path: './docs/js/',
      filename: 'app.js',
    },
    babel: {
      stage:0,
      optional: ['runtime'],
      resolveModuleSource: function (source, filename) {
        if (source.match(/^react-mf-modal/)) {
          source = path.relative(path.dirname(filename), source.replace('react-mf-modal',  __dirname + '/src'));
        }

        return source;
      },
    },
    markdownLoader: {
      langPrefix: 'hljs ',
      highlight: function (code, lang) {
        return highlightjs.highlightAuto(code, [lang]).value;
      },
    },
    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        mangle: true,
        compress: {
          warnings: false,
        },
      }),
    ],
    module: {
      loaders: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel',
        }, {
          test: /\.md$/,
          loader: "html!markdown",
        },
      ]
    },
  }
];


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
    <actionOverrides>
        <actionName>Accept</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>CancelEdit</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>Clone</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>Delete</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>Edit</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>List</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>New</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>SaveEdit</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>Tab</actionName>
        <type>Default</type>
    </actionOverrides>
    <actionOverrides>
        <actionName>View</actionName>
        <type>Default</type>
    </actionOverrides>
    <allowInChatterGroups>false</allowInChatterGroups>
    <compactLayoutAssignment>HEDA_Course_Offering_Compact_Layout</compactLayoutAssignment>
    <deploymentStatus>Deployed</deploymentStatus>
    <description>Joins Courses and Terms to contain information related to a single occurrence of a Course.</description>
    <enableActivities>false</enableActivities>
    <enableBulkApi>true</enableBulkApi>
    <enableFeeds>false</enableFeeds>
    <enableHistory>false</enableHistory>
    <enableLicensing>false</enableLicensing>
    <enableReports>true</enableReports>
    <enableSearch>true</enableSearch>
    <enableSharing>true</enableSharing>
    <enableStreamingApi>true</enableStreamingApi>
    Course Offering
    <nameField>
        Course Offering ID
        <type>Text</type>
    </nameField>
    <pluralLabel>Course Offerings</pluralLabel>
    <searchLayouts/>
    <sharingModel>ControlledByParent</sharingModel>
    <visibility>Public</visibility>
</CustomObject>


text:
using System;
using System.Linq;
using System.Net;
using System.Reflection;

using Orleans.Internals;
using Orleans.Runtime;
using Orleans.Runtime.Host;
using Orleans.Runtime.Configuration;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

using Orleans;
using Orleans.CodeGeneration;

namespace Orleankka.Cluster
{
    using Core;
    using Utility;

     public class ClusterActorSystem : ActorSystem, IDisposable
    {
        readonly Action<IServiceCollection> di;
        internal readonly ActorInvocationPipeline Pipeline;

        [ThreadStatic]
        static ClusterActorSystem current;

        internal ClusterActorSystem(ClusterConfiguration configuration, Action<IServiceCollection> di, ActorInvocationPipeline pipeline, IActorRefInvoker invoker)
            : base(invoker)
        {
            this.di = di;
            Pipeline = pipeline;

            current = this;
            configuration.UseStartupType<Startup>();

            using (Trace.Execution("Orleans silo initialization"))
            {
                Host = new SiloHost(Dns.GetHostName(), configuration);
                Host.LoadOrleansConfig();
                Host.InitializeOrleansSilo();
            }

            Silo = Host.GetSilo();
            Initialize(Silo.GetServiceProvider());
        }

        class Startup
        {
            public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                current.di?.Invoke(services);

                services.AddSingleton<IActorSystem>(current);
                services.AddSingleton(current);
                services.TryAddSingleton<IActorActivator>(x => new DefaultActorActivator(x));
                services.AddSingleton<Func<MethodInfo, InvokeMethodRequest, IGrain, string>>(DashboardIntegration.Format);

                return services.BuildServiceProvider();
            }
        }

        public bool Started => Host.IsStarted;

        public SiloHost Host { get; }
        public Silo Silo { get; }

        public void Start(bool wait = false)
        {
            if (Started)
                throw new InvalidOperationException("Cluster already started");

            using (Trace.Execution("Orleans silo startup"))
                if (!Host.StartOrleansSilo(catchExceptions: false))
                    throw new Exception("Silo failed to start. Check the logs");

            if (wait)
                Host.WaitForOrleansSiloShutdown();
        }

        public void Stop(bool force = false)
        {
            if (!Started)
                throw new InvalidOperationException("Cluster already stopped");

            if (force)
            {
                Host.StopOrleansSilo();
                return;
            }

            Host.ShutdownOrleansSilo();
        }

        public void Dispose()
        {
            Host?.UnInitializeOrleansSilo();
            Host?.Dispose();
        }
    }
}


text:
package com.graphhopper.routing.util.spatialrules;

import com.graphhopper.util.shapes.Polygon;

import java.util.List;

/**
 * Defines rules that are valid for a certain region, e.g. a country.
 * A rule defines access, max-speed, etc. dependent on this region.
 * <p>
 * Every SpatialRule has a set of borders. The rules are valid inside of these borders.
 *
 * @author Robin Boldt
 */
public interface SpatialRule {

    enum Access {
        YES,
        CONDITIONAL,
        NO
    }

    /**
     * Return the max speed for a certain highway type. If there is no max speed defined, _default will be returned.
     *
     * @param highway  The highway type, e.g. primary, secondary
     * @param _default The default max speed
     * @return max speed
     */
    double getMaxSpeed(String highway, double _default);

    /**
     * Returns the {@link Access} for a certain highway type and transportation mode. If nothing is defined,
     * _default will be returned.
     *
     * @param highwayTag         The highway type, e.g. primary, secondary
     * @param transportationMode The mode of transportation
     * @param _default           The default AccessValue
     */
    Access getAccess(String highwayTag, TransportationMode transportationMode, Access _default);

    /**
     * Returns the borders in which the SpatialRule is valid
     */
    List<Polygon> getBorders();

    /**
     * Returns the id for this rule, e.g. the ISO name of the country. The id has to be unique.
     */
    String getId();

    SpatialRule EMPTY = new SpatialRule() {
        @Override
        public double getMaxSpeed(String highwayTag, double _default) {
            return _default;
        }

        @Override
        public Access getAccess(String highwayTag, TransportationMode transportationMode, Access _default) {
            return _default;
        }

        @Override
        public String getId() {
            return "SpatialRule.EMPTY";
        }

        @Override
        public List<Polygon> getBorders() {
            throw new IllegalArgumentException("Empty rule does not have borders");
        }

        @Override
        public String toString() {
            return "SpatialRule.EMPTY";
        }
    };
}


text:
using HedgehogSoft.BackpackLogin.Models;
using HedgehogSoft.BackpackLogin.Rest;
using Newtonsoft.Json;

namespace HedgehogSoft.BackpackLogin.SteamLogin
{
    internal class OffsetGenerator
    {
        internal static OffsetResponse GetOffset()
        {
            var response = new RestClient().GetSteamOffset();
            return JsonConvert.DeserializeObject<OffsetResponse>(response.Content.ReadAsStringAsync().Result);
        }
    }
}


text:
<?php

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use GeoJson\GeoJson;
use GeoJson\Geometry\Point;
use GeoJson\Feature\FeatureCollection;
use GeoJson\Feature\Feature;
use SMYQ\Share\Template;
use SMYQ\Share\Manager;
use SMYQ\Document\SharePoint;

$console = new Application('Share My Earthquake', 'n/a');
$console->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', 'dev'));
$console->setDispatcher($app['dispatcher']);
$console
    ->register('fetch-and-share-earthquakes')
    ->setDefinition([
        new InputOption('period', 'p', InputOption::VALUE_REQUIRED, 'Period to be parsed (default all_hour)', 'all_hour')
    ])
    ->setDescription('Fetch and share all the earthquakes data found')
    ->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
        $period = $input->getOption('period');

        $url = sprintf("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/%s.geojson", $period);

        $output->writeln(sprintf("<info>Fetching earthquakes for '%s' period</info>", $period));
        $geoJsonData = @json_decode(@file_get_contents($url) ? : []) ? : [];

        /** @var FeatureCollection $featureCollection */
        $featureCollection = GeoJson::jsonUnserialize($geoJsonData);
        $iterator = $featureCollection->getIterator();
        $template = new Template();

        if($iterator->count() <= 0) {
            $output->writeln(sprintf("<info>There are no new earthquakes out there</info>", $period));
            return 0;
        }

        /** @var \Doctrine\ODM\MongoDB\DocumentManager $dm */
        $dm = $app['odm'];
        $dm->getSchemaManager()->ensureIndexes();

        /** @var Manager $sharer */
        $sharer = $app['sharer'];

        while($iterator->valid()) {
            /** @var Feature $feature */
            $feature = $iterator->current();
            $properties = $feature->getProperties();
            $geometry = $feature->getGeometry();
            list($latitude, $longitude) = $geometry->getCoordinates();

            $dm->clear();// hook to fix issue with distance mapping...
            $sharePoints = $dm->createQueryBuilder(SharePoint::class)
                ->field('coordinates')
                ->geoNear($latitude, $longitude)
                // todo: Figure out this
                ->distanceMultiplier(\SMYQ\Helper\Distance::KILOMETERS_MULTIPLIER)
                //->maxDistance(6000 * \SMYQ\Helper\Distance::KILOMETERS_MULTIPLIER) // what's a magic here =)
                ->getQuery();

            if(empty($sharePoints)) {
                $output->writeln(sprintf("<info>No share points found for event #%s</info>", $feature->getId()));
            } else {
                $event = (new \SMYQ\Event\Earthquake())->populate($properties);

                $output->writeln(sprintf(
                    "<info>Start matching event #%s... (%f:%f)</info>",
                    $feature->getId(),
                    $latitude,
                    $longitude
                ));

                echo "\nEV: $latitude, $longitude\n";

                /** @var SharePoint $sharePoint */
                foreach($sharePoints as $sharePoint) {
                    $output->writeln(sprintf(
                        "<info>Matching event #%s for share point #%s...</info>",
                        $feature->getId(),
                        $sharePoint->getId()
                    ));
echo "\nSP: {$sharePoint->getCoordinates()->getLatitude()}, {$sharePoint->getCoordinates()->getLongitude()}\n";
                    echo "\n{$sharePoint->getCalculatedDistance()} VS {$sharePoint->getDistance()}\n";
                    continue;
                    if($sharePoint->getCalculatedDistance() > $sharePoint->getDistance()) {
                        continue;
                    }

                    $sharedEvent = $dm->createQueryBuilder(\SMYQ\Document\SharedEvent::class)
                        ->field('eventId')->equals($feature->getId())
                        ->getQuery()->getSingleResult();

                    if($sharedEvent) {
                        $output->writeln(sprintf(
                            "<info>Event #%s already shared for share point #%s. Skipping...</info>",
                            $feature->getId(),
                            $sharePoint->getId()
                        ));
                        continue;
                    }

                    $output->writeln(sprintf(
                        "<info>Sharing event #%s for share point #%s!</info>",
                        $feature->getId(),
                        $sharePoint->getId()
                    ));

                    $text = $template->render($sharePoint, $event);
                    $socialAccount = $sharePoint->getSocialAccount();

                    if($sharer->share($socialAccount, $text)) {
                        $sharedEvent = new \SMYQ\Document\SharedEvent();
                        $sharedEvent->setDatetime(new \DateTime());
                        $sharedEvent->setEventId($feature->getId());
                        $sharedEvent->setOriginalData($properties);
                        $sharedEvent->setSharedText($text);
                        $sharedEvent->setType($event->getType());
                        $sharedEvent->setSharePoint($sharePoint);

                        $dm->persist($sharedEvent);
                        $dm->flush();

                        $output->writeln(sprintf(
                            "<info>Event #%s shared for account #%s</info>",
                            $feature->getId(),
                            $socialAccount->getId()
                        ));
                    } else {
                        $output->writeln(sprintf(
                            "<error>Unable to share event #%s for account #%s</error>",
                            $feature->getId(),
                            $socialAccount->getId()
                        ));
                    }
                }
            }

            $iterator->next();
        }

        $output->writeln(sprintf("<info>Parsed earthquakes successfully shared</info>", $period));
        return 0;
    })
;

return $console;


text:
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Compression;

namespace com.wjlc.util
{
    public class HttpHelper
    {

        ///
        ///访问网络
        ///
        ///<param name="URL">url地址</param>
        ///<param name="strPostdata">发送的数据</param>
        ///<returns></returns>
        public static string SendPostRequest(string url, string postData, string strEncoding)
        {
            try
            {

                Encoding encoding = Encoding.Default;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "post";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/x-www-form-urlencoded";
                byte[] buffer = encoding.GetBytes(postData);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding(strEncoding)))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #region  使用方法
        /*
          HttpHelper http = new HttpHelper();
         * HttpItem item = new HttpItem()
         * {
         *  URL = "http://www.sufeinet.com",//URL这里都是测试     必需项
         *  Method = "get",//URL     可选项 默认为Get
         *  };            //得到HTML代码
         *  HttpResult result = http.GetHtml(item);
         *  item = new HttpItem()
         *  {
         *  URL = "http://tool.sufeinet.com",//URL这里都是测试URl   必需项
         *  Encoding = null,//编码格式(utf-8,gb2312,gbk)     可选项 默认类会自动识别
         *  //Encoding = Encoding.Default,
         *  Method = "post",//URL     可选项 默认为Get
         *  Postdata = "user=123123&pwd=1231313"           };            //得到新的HTML代码
         *  result = http.GetHtml(item);
         */

        #endregion

        #region 预定义方法或者变更

        //默认的编码
        public Encoding encoding = Encoding.Default;
        //HttpWebRequest对象用来发起请求
        public HttpWebRequest request = null;
        //获取影响流的数据对象
        private HttpWebResponse response = null;
        //返回的Cookie
        public string cookie = "";
        //是否设置为全文小写
        public Boolean isToLower = true;
        //读取流的对象
        private StreamReader reader = null;
        //需要返回的数据对象
        private string returnData = "error";

        ///
        /// 根据相传入的数据,得到相应页面数据
        ///
        /// <param name="strPostdata">传入的数据Post方式,get方式传NUll或者空字符串都可以</param>
        /// <returns>string类型的响应数据</returns>
        private string GetHttpRequestData(string strPostdata)
        {
            try
            {
                //支持跳转页面,查询结果将是跳转后的页面
                request.AllowAutoRedirect = true;

                //验证在得到结果时是否有传入数据
                if (!string.IsNullOrEmpty(strPostdata) && request.Method.Trim().ToLower().Contains("post"))
                {
                    byte[] buffer = encoding.GetBytes(strPostdata);
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }

                ////最大连接数
                //request.ServicePoint.ConnectionLimit = 1024;

                #region 得到请求的response

                using (response = (HttpWebResponse)request.GetResponse())
                {
                    try
                    {
                        cookie = response.Headers["set-cookie"].ToString();
                    }
                    catch (Exception)
                    {

                    }
                    //从这里开始我们要无视编码了
                    if (encoding == null)
                    {
                        MemoryStream _stream = new MemoryStream();
                        if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //开始读取流并设置编码方式
                            //new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240);

                            //.net4.0以下写法
                            _stream = GetMemoryStream(response.GetResponseStream());
                        }
                        else
                        {
                            //response.GetResponseStream().CopyTo(_stream, 10240);
                            // .net4.0以下写法
                            _stream = GetMemoryStream(response.GetResponseStream());
                        }
                        byte[] RawResponse = _stream.ToArray();
                        string temp = Encoding.Default.GetString(RawResponse, 0, RawResponse.Length);
                        //<meta(.*?)charset([\s]?)=[^>](.*?)>
                        Match meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"']", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                        string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty;
                        charter = charter.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(";", string.Empty);
                        if (charter.Length > 0)
                        {
                            charter = charter.ToLower().Replace("iso-8859-1", "gbk");
                            encoding = Encoding.GetEncoding(charter);
                        }
                        else
                        {
                            if (response.CharacterSet.ToLower().Trim() == "iso-8859-1")
                            {
                                encoding = Encoding.GetEncoding("gbk");
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(response.CharacterSet.Trim()))
                                {
                                    encoding = Encoding.UTF8;
                                }
                                else
                                {
                                    encoding = Encoding.GetEncoding(response.CharacterSet);
                                }
                            }
                        }
                        returnData = encoding.GetString(RawResponse);
                    }
                    else
                    {
                        if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //开始读取流并设置编码方式
                            using (reader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encoding))
                            {
                                returnData = reader.ReadToEnd();
                            }
                        }
                        else
                        {
                            //开始读取流并设置编码方式
                            using (reader = new StreamReader(response.GetResponseStream(), encoding))
                            {
                                returnData = reader.ReadToEnd();
                            }
                        }
                    }
                }

                #endregion
            }
            catch (WebException ex)
            {
                //这里是在发生异常时返回的错误信息
                returnData = "error";
                response = (HttpWebResponse)ex.Response;
            }
            if (isToLower)
            {
                returnData = returnData.ToLower();
            }
            return returnData;
        }

        ///
        /// 4.0以下.net版本取水运
        ///
        /// <param name="streamResponse"></param>
        private static MemoryStream GetMemoryStream(Stream streamResponse)
        {
            MemoryStream _stream = new MemoryStream();
            int Length = 256;
            Byte[] buffer = new Byte[Length];
            int bytesRead = streamResponse.Read(buffer, 0, Length);
            // write the required bytes
            while (bytesRead > 0)
            {
                _stream.Write(buffer, 0, bytesRead);
                bytesRead = streamResponse.Read(buffer, 0, Length);
            }
            return _stream;
        }

        ///
        /// 为请求准备参数
        ///
        ///<param name="objhttpItem">参数列表</param>
        /// <param name="_Encoding">读取数据时的编码方式</param>
        private void SetRequest(HttpItem objhttpItem)
        {
            //初始化对像,并设置请求的URL地址
            request = (HttpWebRequest)WebRequest.Create(GetUrl(objhttpItem.URL));
            //请求方式Get或者Post
            request.Method = objhttpItem.Method;
            //Accept
            request.Accept = objhttpItem.Accept;
            //ContentType返回类型
            request.ContentType = objhttpItem.ContentType;
            //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息
            request.UserAgent = objhttpItem.UserAgent;
            if (objhttpItem.Encoding == "NULL")
            {
                //读取数据时的编码方式
                encoding = null;
            }
            else
            {
                //读取数据时的编码方式
                encoding = System.Text.Encoding.GetEncoding(objhttpItem.Encoding);
            }
            //Cookie
            request.Headers[HttpRequestHeader.Cookie] = objhttpItem.Cookie;

            //来源地址
            request.Referer = objhttpItem.Referer;
        }

        ///
        /// 设置当前访问使用的代理
        ///
        /// <param name="userName">代理 服务器用户名</param>
        /// <param name="passWord">代理 服务器密码</param>
        /// <param name="ip">代理 服务器地址</param>
        public void SetWebProxy(string userName, string passWord, string ip)
        {
            //设置代理服务器
            WebProxy myProxy = new WebProxy(ip, false);
            //建议连接
            myProxy.Credentials = new NetworkCredential(userName, passWord);
            //给当前请求对象
            request.Proxy = myProxy;
            //设置安全凭证
            request.Credentials = CredentialCache.DefaultNetworkCredentials;
        }

        #endregion

        #region 普通类型

        ///
        /// 传入一个正确或不正确的URl,返回正确的URL
        ///
        /// <param name="URL">url</param>
        /// <returns>
        /// </returns>
        public static string GetUrl(string URL)
        {
            if (!(URL.Contains("http://") || URL.Contains("https://")))
            {
                URL = "http://" + URL;
            }
            return URL;
        }

        ///
        ///采用https协议访问网络,根据传入的URl地址,得到响应的数据字符串。错误返回 "error"
        ///
        ///<param name="objhttpItem">参数列表</param>
        ///<returns>String类型的数据</returns>
        public string GetHtml(HttpItem objhttpItem)
        {
            //准备参数
            SetRequest(objhttpItem);

            //调用专门读取数据的类
            return GetHttpRequestData(objhttpItem.Postdata);
        }
        #endregion
    }

    ///
    /// Http请求参考类
    ///
    public class HttpItem
    {
        string _URL;
        ///
        /// 请求URL必须填写
        ///
        public string URL
        {
            get { return _URL; }
            set { _URL = value; }
        }

        string _Method = "GET";
        ///
        /// 请求方式默认为GET方式
        ///
        public string Method
        {
            get { return _Method; }
            set { _Method = value; }
        }

        string _Accept = "text/html, application/xhtml+xml, */*";
        ///
        /// 请求标头值 默认为text/html, application/xhtml+xml, */*
        ///
        public string Accept
        {
            get { return _Accept; }
            set { _Accept = value; }
        }

        string _ContentType = "text/html";
        ///
        /// 请求返回类型默认 text/html
        ///
        public string ContentType
        {
            get { return _ContentType; }
            set { _ContentType = value; }
        }

        string _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
        ///
        /// 客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
        ///
        public string UserAgent
        {
            get { return _UserAgent; }
            set { _UserAgent = value; }
        }

        string _Encoding = "NULL";
        ///
        /// 返回数据编码默认为NUll,可以自动识别
        ///
        public string Encoding
        {
            get { return _Encoding; }
            set { _Encoding = value; }
        }

        string _Postdata;
        ///
        /// Post请求时要发送的Post数据
        ///
        public string Postdata
        {
            get { return _Postdata; }
            set { _Postdata = value; }
        }

        string _Cookie;
        ///
        /// 请求时的Cookie
        ///
        public string Cookie
        {
            get { return _Cookie; }
            set { _Cookie = value; }
        }

        string _Referer;
        ///
        /// 来源地址,上次访问地址
        ///
        public string Referer
        {
            get { return _Referer; }
            set { _Referer = value; }
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cedeel</groupId>
    <artifactId>URIEnforcer</artifactId>
    <packaging>jar</packaging>
    <version>1.3</version>
    <name>URIEnforcer</name>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.build.number>DEV</project.build.number>
    </properties>
    <repositories>
        <!-- Bukkit Repository -->
        <repository>
            <id>bukkit-repo</id>
            <url>http://repo.bukkit.org/content/groups/public/</url>
        </repository>
    </repositories>
    <scm>
        <developerConnection>scm:git:git@github.com:darnell/URIEnforcer.git</developerConnection>
        <connection>scm:git:git://github.com/darnell/URIEnforcer.git</connection>
        <url>https://github.com/darnell/URIEnforcer</url>
    </scm>
    <profiles>
        <profile>
            <id>jenkins</id>
            <activation>
                <property>
                    <name>env.BUILD_NUMBER</name>
                </property>
            </activation>
            <properties>
                <project.build.number>${env.BUILD_NUMBER}</project.build.number>
            </properties>
        </profile>
    </profiles>
    <build>
        <finalName>${project.name}</finalName>
        <defaultGoal>clean package</defaultGoal>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
	    <plugin>
	        <groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-shade-plugin</artifactId>
		<version>2.1</version>
		<configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
		    <artifactSet>
		        <includes>
		            <include>org.mcstats.bukkit:metrics-lite</include>
			</includes>
		    </artifactSet>
		    <relocations>
		        <relocation>
			    <pattern>org.mcstats</pattern>
			    <shadedPattern>com.cedeel.urienforcer.util.mcstats</shadedPattern>
			</relocation>
		    </relocations>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <!-- Bukkit Dependency -->
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.8-R0.1-SNAPSHOT</version>
            <type>jar</type>
        </dependency>
        <!-- End Bukkit -->
    </dependencies>

</project>


text:
import os
from tqdm import tqdm
import logging
import argparse
import numpy as np
import multiprocessing as mp
from numpy.linalg import norm

try:
    import cPickle as pickle
except ImportError:
    import pickle

from keras.applications.vgg16 import VGG16
from keras.preprocessing.image import load_img, img_to_array
from keras.applications.vgg16 import preprocess_input

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

INPUT_SHAPE = (224, 224, 3)
# INPUT_SHAPE = (512, 512, 3)
model = VGG16(weights="imagenet",
              input_shape=(INPUT_SHAPE[0], INPUT_SHAPE[1], INPUT_SHAPE[2]),
              pooling="max",
              include_top=False)

def extract_feat(img_path):
    """
     Use vgg16 model to extract features
     Output normalized feature vector
    """
    img = img_to_array(load_img(img_path, target_size=(INPUT_SHAPE[0], INPUT_SHAPE[1])))
    img = preprocess_input(np.expand_dims(img, axis=0))
    feat = model.predict(img)
    norm_feat = feat[0] / norm(feat[0])
    return norm_feat

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("-f", "--file_list", dest="file_list_fn", required=True,
                        help="Name of directory which contains images to be indexed")
    parser.add_argument("-o", "--output", dest="index_fn", required=True,
                        help="Name of index file")
    return parser.parse_args()

def index_features(args):
    """
    Extract features and index the images.
    :param args:
        Namespace arguments.
    :return:
        No return value.
    """

    with open(args.file_list_fn) as fp:
        img_list = list(map(lambda line: line.strip("\n"), fp.readlines()))

    feats = []
    for i, img_path in tqdm(enumerate(img_list), total=len(img_list)):
        feats.append(extract_feat(img_path))
    feats = np.array(feats)

    logger.info("Writing extracted embeddings to disk.")
    with open(args.index_fn, "wb") as fp:
        pickle.dump({"features": feats, "names": img_list}, fp)

if __name__ == "__main__":
    index_features(parse_args())


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Seabatle 1.0</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="app.css">

Seabatle 1.0

{{ship.count}}


text:
package com.creditease.dbus.heartbeat.handler.impl;

import com.creditease.dbus.heartbeat.container.HeartBeatConfigContainer;
import com.creditease.dbus.heartbeat.container.LifeCycleContainer;
import com.creditease.dbus.heartbeat.event.IEvent;
import com.creditease.dbus.heartbeat.event.impl.LifeEvent;
import com.creditease.dbus.heartbeat.handler.AbstractHandler;

public class LifeCycleHandler extends AbstractHandler {

    @Override
    public void process() {
        long lifeInterval = HeartBeatConfigContainer.getInstance().getHbConf().getLifeInterval();
        IEvent lifeEvent = new LifeEvent(lifeInterval);
        Thread let = new Thread(lifeEvent, "life-event");
        let.start();
        LifeCycleContainer.getInstance().put(lifeEvent, let);
    }

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.init = init;
/**
 *
 */
function init(options) {
    var mqs = options.mediaqueries;

    var handleMediaChange = function handleMediaChange(mediaQueryList) {
        var media = mqs.filter(function (el) {
            return mediaQueryList.media.replace(/: /g, ':') === el.media;
        });

        if (media.length === 0) {
            return;
        }
        media = media[0];

        var event = document.createEvent("CustomEvent");
        event.initCustomEvent('mediaquery', false, false, {
            active: mediaQueryList.matches,
            media: media.name
        });

        document.dispatchEvent(event);
    };

    var _iteratorNormalCompletion = true;
    var _didIteratorError = false;
    var _iteratorError = undefined;

    try {
        for (var _iterator = mqs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var mq = _step.value;

            mq.media = mq.media.replace(/: /g, ':');
            var mql = window.matchMedia(mq.media);
            mql.addListener(handleMediaChange);
            handleMediaChange(mql);
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally {
        try {
            if (!_iteratorNormalCompletion && _iterator.return) {
                _iterator.return();
            }
        } finally {
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
}


text:
package nl.vu.cs.ajira.examples.aurora.data.exceptions;

public class UnsupportedOperatorException extends RuntimeException {
  private static final long serialVersionUID = 4524362051003237974L;

}


text:
int main(int argc, char * argv[]){
	WSADATA wsaData;
	SOCKET serverSocket, acceptSocket;
	SOCKADDR_IN serverAddr, clientAddr;
	int checkErr, sizeClientAddr, recvCount = 0;
	char recvBuf[MAX_DATA], recvBufSize;

	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0){
		perror("initiate winsock");
		return 0;
	}

	serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (serverSocket == INVALID_SOCKET){
		perror("socket");
		return 0;
	}

	serverAddr.sin_family = AF_INET;
	serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	serverAddr.sin_port = htons(PORT);

	checkErr = bind(serverSocket, (SOCKADDR *)&serverAddr, sizeof(serverAddr));
	if (checkErr == SOCKET_ERROR){
		perror("bind");
		return 0;
	}

	checkErr = listen(serverSocket, 1);
	if (checkErr == SOCKET_ERROR){
		perror("listen");
		return 0;
	}
	sizeClientAddr = sizeof(clientAddr);
	acceptSocket = accept(serverSocket, (SOCKADDR *)&clientAddr, &sizeClientAddr);
	if (acceptSocket == SOCKET_ERROR){
		perror("accept");
		return 0;
	}

	while (recvBufSize = recv(acceptSocket, &recvBuf[recvCount], 1, 0)){
		if (recvBufSize == SOCKET_ERROR){
			perror("recv");
			return 0;
		}
		++recvCount;
	}

	printf("%s\n", recvBuf);
	printf("recv count = %d\n", recvCount);
	closesocket(serverSocket);
	closesocket(acceptSocket);
	WSACleanup();
	getchar();
	return 0;
}


text:
using System;

namespace RetinaOverflow
{
    public class RetinaException : Exception
    {
        public RetinaException(){
            GlobalManager.instance.logging.error(GetType().ToString());
        }
        public RetinaException(string message) : base(message){
            GlobalManager.instance.logging.error(GetType() + ": " + message);
        }
    }

}


text:
/* objectmap.c  -  Foundation library  -  Public Domain  -  2013 Mattias Jansson / Rampant Pixels
 *
 * This library provides a cross-platform foundation library in C11 providing basic support data types and
 * functions to write applications and games in a platform-independent fashion. The latest source code is
 * always available at
 *
 * https://github.com/rampantpixels/foundation_lib
 *
 * This library is put in the public domain; you can redistribute it and/or modify it without any restrictions.
 *
 */

#include <foundation/foundation.h>
#include <foundation/internal.h>

FOUNDATION_STATIC_ASSERT( FOUNDATION_ALIGNOF(object_base_t) >= 8, "object_base_t alignment" );
FOUNDATION_STATIC_ASSERT( FOUNDATION_ALIGNOF(objectmap_t) >= 8, "objectmap_t alignment" );

void _object_initialize( object_base_t* obj, object_t id )
{
	obj->id = id;
	atomic_store32( &obj->ref, 1 );
}

object_t _object_ref( object_base_t* obj )
{
	int32_t ref;
	if( obj ) do
	{
		ref = atomic_load32( &obj->ref );
		if( ( ref > 0 ) && atomic_cas32( &obj->ref, ref + 1, ref ) )
			return obj->id;
	} while( ref > 0 );
	return 0;
}

object_t _object_unref( object_base_t* obj )
{
	int32_t ref;
	if( obj ) do
	{
		ref = atomic_load32( &obj->ref );
		if( ( ref > 0 ) && atomic_cas32( &obj->ref, ref - 1, ref ) )
			return ( ref == 1 ) ? 0 : obj->id;
	} while( ref > 0 );
	return 0;
}

objectmap_t* objectmap_allocate( unsigned int size )
{
	objectmap_t* map;

	FOUNDATION_ASSERT_MSG( size > 2, "Invalid objectmap size" );
	if( size <= 2 )
		size = 2;

	map = memory_allocate( 0, sizeof( objectmap_t ) + ( sizeof( void* ) * size ), 16, MEMORY_PERSISTENT );

	objectmap_initialize( map, size );

	return map;
}

void objectmap_initialize( objectmap_t* map, unsigned int size )
{
	uint64_t bits;
	unsigned int ip;
	uintptr_t next_indexshift;
	void** slot;

	FOUNDATION_ASSERT_MSG( size > 2, "Invalid objectmap size" );
	bits = math_round( math_log2( (real)size ) ); //Number of bits needed
	FOUNDATION_ASSERT_MSGFORMAT( bits < 50, "Invalid objectmap size %d", size );

	memset( map, 0, sizeof( objectmap_t ) + ( sizeof( void* ) * size ) );

	//Top two bits unused for Lua compatibility
	map->size_bits   = bits;
	map->id_max      = ((1ULL<<(62ULL-bits))-1);
	map->size        = size;
	map->mask_index  = ((1ULL<<bits)-1ULL);
	map->mask_id     = ( 0x3FFFFFFFFFFFFFFFULL & ~map->mask_index );
	atomic_store64( &map->free, 0 );
	atomic_store64( &map->id, 1 );

	slot = map->map;
	for( ip = 0, next_indexshift = 3; ip < ( size - 1 ); ++ip, next_indexshift += 2, ++slot )
		*slot = (void*)next_indexshift;
	*slot = (void*)((uintptr_t)-1);
}

void objectmap_deallocate( objectmap_t* map )
{
	objectmap_finalize( map );
	memory_deallocate( map );
}

void objectmap_finalize( objectmap_t* map )
{
	uint64_t i;

	if( !map )
		return;

	for( i = 0; i < map->size; ++i )
	{
		bool is_object = !( (uintptr_t)map->map[i] & 1 );
		if( is_object )
		{
			log_error( 0, ERROR_MEMORY_LEAK, "Object still stored in objectmap when map deallocated" );
			break;
		}
	}
}

unsigned int objectmap_size( const objectmap_t* map )
{
	FOUNDATION_ASSERT( map );
	return (unsigned int)map->size;
}

void* objectmap_raw_lookup( const objectmap_t* map, unsigned int idx )
{
	uintptr_t ptr;

	/*lint --e{613} Performance path (no ptr checks)*/
	FOUNDATION_ASSERT( map );
	FOUNDATION_ASSERT( idx < map->size );
	ptr = (uintptr_t)map->map[idx];
	return ( ptr & 1 ) ? 0 : (void*)ptr;
}

object_t objectmap_reserve( objectmap_t* map )
{
	uint64_t idx, next, id;

	FOUNDATION_ASSERT( map ); /*lint -esym(613,pool) */

	//Reserve spot in array
	//TODO: Look into double-ended implementation with allocation from tail and free push to head
	do
	{
		idx = atomic_load64( &map->free );
		if( idx >= map->size )
		{
			log_error( 0, ERROR_OUT_OF_MEMORY, "Pool full, unable to reserve id" );
			return 0;
		}
		next = ((uintptr_t)map->map[idx]) >> 1;
	} while( !atomic_cas64( &map->free, next, idx ) );

	//Sanity check that slot isn't taken
	FOUNDATION_ASSERT_MSG( (intptr_t)(map->map[idx]) & 1, "Map failed sanity check, slot taken after reserve" );
	map->map[idx] = 0;

	//Allocate ID
	id = 0;
	do
	{
		id = atomic_incr64( &map->id ) & map->id_max; //Wrap-around handled by masking
	} while( !id );

	//Make sure id stays within correct bits (if fails, check objectmap allocation and the mask setup there)
	FOUNDATION_ASSERT( ( ( id << map->size_bits ) & map->mask_id ) == ( id << map->size_bits ) );

	return ( id << map->size_bits ) | idx; /*lint +esym(613,pool) */
}

void objectmap_free( objectmap_t* map, object_t id )
{
	uint64_t idx, last;

	FOUNDATION_ASSERT( map ); /*lint -esym(613,pool) */

	idx = (intptr_t)( id & map->mask_index );
	if( (uintptr_t)map->map[idx] & 1 )
		return; //Already free

	do
	{
		last = atomic_load64( &map->free );
		map->map[idx] = (void*)((uintptr_t)(last<<1)|1);
	} while( !atomic_cas64( &map->free, idx, last ) ); /*lint +esym(613,pool) */
}

void objectmap_set( objectmap_t* map, object_t id, void* object )
{
	uint64_t idx;

	FOUNDATION_ASSERT( map ); /*lint -esym(613,pool) */

	idx = (int)( id & map->mask_index );
	//Sanity check, can't set free slot, and non-free slot should be initialized to 0 in reserve function
	FOUNDATION_ASSERT( !(((uintptr_t)map->map[idx]) & 1 ) );
	FOUNDATION_ASSERT( !((uintptr_t)map->map[idx]) );
	if( !map->map[idx] )
		map->map[idx] = object;
	/*lint +esym(613,pool) */
}

void* objectmap_lookup_ref( const objectmap_t* map, object_t id )
{
	void* object;
	do
	{
		object = map->map[ id & map->mask_index ];
		if( object && !( (uintptr_t)object & 1 ) &&
		   ( ( *( (uint64_t*)object + 1 ) & map->mask_id ) == ( id & map->mask_id ) ) ) //ID in object is offset by 8 bytes
		{
			object_base_t* base_obj = object;
			int32_t ref = atomic_load32( &base_obj->ref );
			if( ref && atomic_cas32( &base_obj->ref, ref + 1, ref ) )
				return object;
		}
	} while( object );
	return 0;
}

bool objectmap_lookup_unref( const objectmap_t* map, object_t id, object_deallocate_fn deallocate )
{
	void* object;
	do
	{
		object = map->map[ id & map->mask_index ];
		if( object && !( (uintptr_t)object & 1 ) &&
		   ( ( *( (uint64_t*)object + 1 ) & map->mask_id ) == ( id & map->mask_id ) ) ) //ID in object is offset by 8 bytes
		{
			object_base_t* base_obj = object;
			int32_t ref = atomic_load32( &base_obj->ref );
			if( ref && atomic_cas32( &base_obj->ref, ref - 1, ref ) )
			{
				if( ref == 1 )
				{
					deallocate( id, object );
					return false;
				}
				return true;
			}
		}
	} while( object );
	return false;
}


text:
module Queri
  class Stats
    class CallDistributionByDayOfWeek
      class InclusiveServiceLevelAgreementPerDayOfWeek < Queri::Stats
        include CompositeReportHelpers

        class << self
          def xml_code
            CallDistributionByDayOfWeek.xml_code + ".InclSlaPerDOW"
          end

          def key_translations
            ActiveSupport::OrderedHash[
              :day_of_week, "DayOfWeek",
              :number_of_answered_calls, "Ans.",
              :number_of_unanswered_calls, "Unans.",
              :number_of_processed_calls, "Num",
              :percentage_of_calls_answered_under_10_sec, "< 10",
              :percentage_of_calls_answered_under_20_sec, "< 20",
              :percentage_of_calls_answered_under_30_sec, "< 30",
              :percentage_of_calls_answered_under_40_sec, "< 40",
              :percentage_of_calls_answered_under_50_sec, "< 50",
              :percentage_of_calls_answered_under_60_sec, "< 60",
              :percentage_of_calls_answered_under_70_sec, "< 70",
              :percentage_of_calls_answered_under_80_sec, "< 80",
              :percentage_of_calls_answered_under_90_sec, "< 90",
              :percentage_of_calls_answered_under_100_sec, "< 100",
              :percentage_of_calls_answered_under_110_sec, "< 110",
              :percentage_of_calls_answered_under_120_sec, "< 120"
            ]
          end
        end
      end
    end
  end
end


text:
The Tokenizer Tool

    The Tokenizer tool allows you to peek at and/or download your current
    Document-Term Matrix (DTM) according to your current tokenize, normalize,
    and culling options.

    Tokenizing is the backbone for many functions in Lexos.
    Tokenization is the process of dividing a string of text into countable units
    called "tokens". Tokens are typically individual characters or words, but
    they can also be "n-grams", units composed of one or more sequences of
    characters or words. By default, Lexos divides the text into tokens using s
    paces as token delimiters. However, it can create n-grams by tokens (e.g.
    1-gram: "the", 2-gram or bi-grams "the dog", etc.) or n-grams by character
    (e.g. 5-grams: "the d" and "he do", etc.).

Usage

What is the DTM?

        Once the text is divided into tokens, Lexos assembles a Document-Term Matrix (DTM).
        This is a table of "terms" — unique token forms — that occur in the
        active documents. Lexos calculates the number of times each document
        contains each term to produce the DTM. It displays the DTM as a table
        where you can explore the table of term counts representing your texts.
        Note: Text corpora containing a large number of documents or types
        can take a while to process, so please be patient.

Using the DTM

        By default, Lexos displays 10 table rows per page, but you can change this
        using the "Rows" radio buttons. You can also filter the rows by entering
        keywords in the "Search" form. Make sure to press "Generate" after
        changing these options to refresh the table.

        To sort the table, click on a column header, and either "Ascending" or
        "Descending" at the top next to "Order". Make sure to press "Generate" after
        changing these options to refresh the table.

Orientation

        By default, Lexos displays the DTM with documents listed in columns and
        terms listed in rows. When downloading the DTM you may choose to transpose
        the table by selecting the Documents as Rows, Terms as Columns option. It
        is most likely the case that you will have relatively few documents and a
        relatively large number of terms. Note: Transposing the matrix
        will produce a table with potentially hundreds or thousands of columns,
        requiring you to scroll horizontally to view them.

Options

    If you change the settings on any of the following options, make sure
    to click "Generate" to see your changes reflected in the DTM.

Tokenize

        By default Lexos tokenizes by tokens, meaning it splits strings of text
        into tokens every time it encounters a space character. For Western languages,
        this means that each token generally corresponds to a word. To tokenize
        by multiple words, you can increase the n-gram size.

        For example given the text: "the dog ran" tokenizing by 1-gram tokens
        would produce tokens "the", "dog", "ran". Tokenizing by 2-grams would
        count the instances of bi-grams or pairs of words, thus producing tokens
        "the dog", "dog ran", and so on.

        If you wish to tokenize by characters, Lexos will treat every character
        (letters, whitespace, punctuation, etc.) as a separate token. Tokenizing
        by 2-gram characters would produce tokens "th","he","e ", and so on.
        Tokenizing by characters is best used for non-western languages that don't
        have whitespace between tokens such as classical Chinese.

Normalize

        The default "Normalize" setting is "Proportional" which displays the
        frequency of the occurrence of terms in your documents as a proportion
        of the entire text.

        "Raw Counts" will display in the table the actual number of occurrences
        of each term in each document.

        "TF-IDF" or Term Frequency-Inverse Document Frequency attempts to
        take into account difference in the lengths of your documents by
        calculating their TF-IDF. Lexos uses basee (natural log) as the
        default.

Cull

        "Culling" is a generic term we use for methods of decreasing the number
        of terms used to generate the DTM based on statistical criteria (as
        opposed to something like applying a stop-word list in Scrubber). Culling
        is optional to use in Lexos. Lexos offers two different methods:

        "Use the top ___ words": This method takes a slice of the DTM
        containing only the top N most frequently occurring terms in the
        set of active documents. The default setting is 100, meaning
        Tokenizer will generate the DTM using only the top 100 most
        frequent terms.

        "Must be in ___ documents": This method build the DTM using only
        terms that occur in at least N documents. The default setting is
        1. If you have 10 active documents and you want to generate the
        DTM using only terms that appear in all your active documents,
        set the value to 10. Note: You can quickly determine
        the number of active documents in your workspace as indicated by
        the counter in the bottom right corner.

Download

        To download the DTM click the "Download" button and you will get a
        results .csv file. "CSV" is short for Comma-Separated Values.
        In your downloaded file, a comma will serve as the column delimiter and
        these files can be opened by other programs later, e.g., Excel.


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"/>
<title>Boost.Locale: boost::locale::boundary::boundary_point_index< BaseIterator > Class Template Reference</title>

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

Boost.Locale

Main Page

Modules

Namespaces

Classes

Files

Examples

Class List

Class Hierarchy

Class Members

Public Types |
Public Member Functions |
Friends

boost::locale::boundary::boundary_point_index< BaseIterator > Class Template Reference
Boundary Analysis

This class holds an index of boundary points and allows iterating over them.
 More...

#include <boost/locale/boundary/index.hpp>

List of all members.

Public Types

typedef BaseIterator 	base_iterator

typedef unspecified_iterator_type 	iterator

typedef unspecified_iterator_type 	const_iterator

typedef boundary_point

< base_iterator > 	value_type

Public Member Functions

 	boundary_point_index ()

 	boundary_point_index (boundary_type type, base_iterator begin, base_iterator end, rule_type mask, std::locale const &loc=std::locale())

 	boundary_point_index (boundary_type type, base_iterator begin, base_iterator end, std::locale const &loc=std::locale())

 	boundary_point_index (segment_index< base_iterator > const &other)

boundary_point_index const & 	operator= (segment_index< base_iterator > const &other)

void 	map (boundary_type type, base_iterator begin, base_iterator end, std::locale const &loc=std::locale())

iterator 	begin () const

iterator 	end () const

iterator 	find (base_iterator p) const

rule_type 	rule () const

void 	rule (rule_type v)

Friends

class 	segment_index< base_iterator >

Detailed Description

template<typename BaseIterator>

class boost::locale::boundary::boundary_point_index< BaseIterator >

This class holds an index of boundary points and allows iterating over them.

This class is provides begin() and end() member functions that return bidirectional iterators to the boundary_point objects.

It provides an option that affects selecting boundary points according to different rules: using rule(rule_type mask) member function. It allows to set a mask that select only specific types of boundary points like sentence_term.

For example for a sentence boundary analysis of a text "Hello! How\nare you?" when the default rule is used the boundary points would be:

"|Hello! How\nare you?"

"Hello! |How\nare you?"

"Hello! How\n|are you?"

"Hello! How\nare you?|"

However if rule() is set to sentence_term then the selected boundary points would be:

"|Hello! How\nare you?"

"Hello! |How\nare you?"

"Hello! How\nare you?|"

Such that a boundary point defined by a line feed character would be ignored.

This class allows to find a boundary_point according to the given iterator in range using find() member function.

Note:

Even an empty text range [x,x) considered to have a one boundary point x.

a and b points of the range [a,b) are always considered boundary points regardless the rules used.

Changing any of the option rule() or course re-indexing the text invalidates existing iterators and they can't be used any more.

boundary_point_index can be created from segment_index or other boundary_point_index that was created with same boundary_type. This is very fast operation as they shared same index and it does not require its regeneration.

See also:

segment_index

boundary_point

segment

The documentation for this class was generated from the following file:

boost/locale/boundary/index.hpp

boost

locale

boundary

boundary_point_index

© Copyright 2009-2012 Artyom Beilis,  Distributed under the Boost Software License, Version 1.0.


text:
require "mercury_rails_regions/version"

module MercuryRailsRegions
  # Your code goes here...
end


text:
<?php

  class API {

    // $db_host = "localhost";
    // $db_username = "root"; //TODO: DO NOT USE ROOT IN PRODUCTION
    // $db_password = ""; //TODO: USE A PASSWORD IN PRODUCTION
    // $db_table = "discordbans";

    function __construct() {}

    function get_mysql() { // In an actual production setting, better security would be implemented.
        $mysql = new mysqli("localhost", "root", "", "discordbans");

        if ($mysql->connect_error) {
            die($mysql->connect_error);
        }

        return $mysql;
    }

    function get_bans() {
      return $this->get_mysql()->query("select * from bans");
    }

    function get_icons() {
      return  $this->get_mysql()->query("select favicon from icons");
    }

    function get_guild_bans($id) {
      return  $this->get_mysql()->query("select * from `user_$id`");
    }

    function get_ban_table_by_ID($id) {
      return $this->get_mysql()->query("select * from bans where discordID = '$id'");
    }
  }
?>


text:
package br.uff.labtempo.tmon.tmonmanager.model;

/**
 *
 * @author Felipe Santos <live.proto at hotmail.com>
 */
public class Mote {
    private int id;
    private boolean status;
    private String moteModel;
    private String moteLocalization;
    private String localizationDescription;

    public Mote(int id, boolean status, String moteModel, String moteLocalization, String localizationDescription) {
        this.id = id;
        this.status = status;
        this.moteModel = moteModel;
        this.moteLocalization = moteLocalization;
        this.localizationDescription = localizationDescription;
    }

    public int getId() {
        return id;
    }

    public boolean getStatus() {
        return status;
    }

    public String getMoteModel() {
        return moteModel;
    }

    public String getMoteLocalization() {
        return moteLocalization;
    }

    public String getLocalizationDescription() {
        return localizationDescription;
    }
}


text:
/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2011
 */

package com.opendata.rs.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.validator.constraints.Length;

import com.opendata.common.base.BaseEntity;

/**
 * 资源扩展属性
 *
 * @author 王海龙
 * @version 1.0
 * @since 1.0
 */
@Entity
@Table(name = "rs_expand_property")
public class RsExpandProperty extends BaseEntity implements java.io.Serializable{
	private static final long serialVersionUID = 5454155825314635342L;

	//alias
	public static final String TABLE_ALIAS = "资源扩展属性";
	public static final String ALIAS_ID = "id";
	public static final String ALIAS_ATTR_CODE = "属性编码";
	public static final String ALIAS_ATTR_NAME = "属性名称";
	public static final String ALIAS_ATTR_VALUE = "属性值";
	public static final String ALIAS_INPUT_TYPE = "属性类型";
	public static final String ALIAS_OPTIONAL_VALUE = "属性扩展值";
	public static final String ALIAS_ATTR_SOURCE = "属性来源";
	public static final String ALIAS_RESOURCES_ID = "关联资源";
	public static final String ALIAS_TS = "时间";

	//date formats

	//可以直接使用: @Length(max=50,message="用户名长度不能大于50")显示错误消息
	//columns START
    /**
     * id       db_column: id
     */
	@Length(max=32)
	private java.lang.String id;
    /**
     * attrCode       db_column: attr_code
     */
	@Length(max=10)
	private java.lang.String attrCode;
    /**
     * attrName       db_column: attr_name
     */
	@Length(max=100)
	private java.lang.String attrName;
    /**
     * attrValue       db_column: attr_value
     */
	@Length(max=5000)
	private java.lang.String attrValue;
    /**
     * inputType       db_column: input_type
     */
	@Length(max=4)
	private java.lang.String inputType;//文本框:1,  文本域:2,  单选组:3,  下拉菜单:4,  多选组:5
	/**
     * optionalValue       db_column: optional_value
     */
	@Length(max=2000)
	private java.lang.String optionalValue;
    /**
     * attrSource       db_column: attr_source
     */
	@Length(max=200)
	private java.lang.String attrSource;
    /**
     * resourcesId       db_column: resources_id
     */
	@Length(max=32)
	private java.lang.String resourcesId;
    /**
     * ts       db_column: ts
     */
	@Length(max=19)
	private java.lang.String ts;
	//columns END

	public RsExpandProperty(){
	}

	public RsExpandProperty(String id, String attrCode, String attrName,
			String attrValue, String inputType, String optionalValue,
			String attrSource, String resourcesId, String ts,
			RsResources rsResources) {
		super();
		this.id = id;
		this.attrCode = attrCode;
		this.attrName = attrName;
		this.attrValue = attrValue;
		this.inputType = inputType;
		this.optionalValue = optionalValue;
		this.attrSource = attrSource;
		this.resourcesId = resourcesId;
		this.ts = ts;
		this.rsResources = rsResources;
	}

	public RsExpandProperty(java.lang.String id){
		this.id = id;
	}

	public void setId(java.lang.String value) {
		this.id = value;
	}

	@Id @GeneratedValue(generator="custom-id")
	@GenericGenerator(name="custom-id", strategy = "uuid.hex")
	@Column(name = "id",  nullable = false, insertable = true, updatable = true, length = 32)
	public java.lang.String getId() {
		return this.id;
	}

	@Column(name = "attr_code", unique = false, nullable = true, insertable = true, updatable = true, length = 10)
	public java.lang.String getAttrCode() {
		return this.attrCode;
	}

	public void setAttrCode(java.lang.String value) {
		this.attrCode = value;
	}

	@Column(name = "attr_name", unique = false, nullable = true, insertable = true, updatable = true, length = 100)
	public java.lang.String getAttrName() {
		return this.attrName;
	}

	public void setAttrName(java.lang.String value) {
		this.attrName = value;
	}

	@Column(name = "attr_value", unique = false, nullable = true, insertable = true, updatable = true, length = 5000)
	public java.lang.String getAttrValue() {
		return this.attrValue;
	}

	public void setAttrValue(java.lang.String value) {
		this.attrValue = value;
	}

	@Column(name = "input_type", unique = false, nullable = true, insertable = true, updatable = true, length = 4)
	public java.lang.String getInputType() {
		return this.inputType;
	}

	public void setInputType(java.lang.String value) {
		this.inputType = value;
	}

	@Column(name = "optional_value", unique = false, nullable = true, insertable = true, updatable = true, length = 2000)
	public java.lang.String getOptionalValue() {
		return this.optionalValue;
	}

	public void setOptionalValue(java.lang.String value) {
		this.optionalValue = value;
	}

	@Column(name = "attr_source", unique = false, nullable = true, insertable = true, updatable = true, length = 200)
	public java.lang.String getAttrSource() {
		return this.attrSource;
	}

	public void setAttrSource(java.lang.String value) {
		this.attrSource = value;
	}

	@Column(name = "resources_id", unique = false, nullable = true, insertable = false, updatable = false, length = 32)
	public java.lang.String getResourcesId() {
		return this.resourcesId;
	}

	public void setResourcesId(java.lang.String value) {
		this.resourcesId = value;
	}

	@Column(name = "ts", unique = false, nullable = true, insertable = true, updatable = true, length = 19)
	public java.lang.String getTs() {
		return this.ts;
	}

	public void setTs(java.lang.String value) {
		this.ts = value;
	}

	private RsResources rsResources;
	public void setRsResources(RsResources rsResources){
		this.rsResources = rsResources;
	}

	@ManyToOne(cascade = {}, fetch = FetchType.LAZY)
	@JoinColumns({
		@JoinColumn(name = "resources_id",nullable = true, insertable = true, updatable = true)
	})
	public RsResources getRsResources() {
		return rsResources;
	}

	public String toString() {
		return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
			.append("Id",getId())
			.append("AttrCode",getAttrCode())
			.append("AttrName",getAttrName())
			.append("AttrValue",getAttrValue())
			.append("InputType",getInputType())
			.append("AttrSource",getAttrSource())
			.append("ResourcesId",getResourcesId())
			.append("Ts",getTs())
			.toString();
	}

	public int hashCode() {
		return new HashCodeBuilder()
			.append(getId())
			.toHashCode();
	}

	public boolean equals(Object obj) {
		if(obj instanceof RsExpandProperty == false) return false;
		if(this == obj) return true;
		RsExpandProperty other = (RsExpandProperty)obj;
		return new EqualsBuilder()
			.append(getAttrCode(),other.getAttrCode())
			.append(getId(),other.getId())
			.isEquals();
	}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syst. mycol. (Lundae) 1: 191 (1821)

#### Original name
Agaricus acerosus Fr., 1821

### Remarks
null


text:
<?php
/**
 * Created by PhpStorm.
 * User: Pimpackiukas
 * Date: 4/11/14
 * Time: 2:28 PM
 */

namespace Nfq\NomNomBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class AddRecipeToEventType extends AbstractType
{
    /**
     * Returns the name of this type.
     *
     * @return string The name of this type
     */
    public function getName()
    {
        return 'addrecipetoevent';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('recipe', 'genemu_jqueryselect2_entity', array(
            'class' => 'NfqNomNomBundle:MyRecipe',
            'property' => 'recipeName',
        ))
            ->add('submit', 'submit');;
    }
}


text:
#ifndef _PACKETIZER_H
#define _PACKETIZER_H 1

#include <vlc_block.h>

enum
{
    STATE_NOSYNC,
    STATE_SYNC,
    STATE_HEADER,
    STATE_NEXT_SYNC,
    STATE_GET_DATA,
    STATE_SEND_DATA
};

typedef void (*packetizer_reset_t)( void *p_private, bool b_broken );
typedef block_t *(*packetizer_parse_t)( void *p_private, bool *pb_ts_used, block_t * );
typedef int (*packetizer_validate_t)( void *p_private, block_t * );

typedef struct
{
    int i_state;
    block_bytestream_t bytestream;
    size_t i_offset;
    bool   b_flushing;

    int i_startcode;
    const uint8_t *p_startcode;

    int i_au_prepend;
    const uint8_t *p_au_prepend;

    unsigned i_au_min_size;

    void *p_private;
    packetizer_reset_t    pf_reset;
    packetizer_parse_t    pf_parse;
    packetizer_validate_t pf_validate;

} packetizer_t;

static inline void packetizer_Init( packetizer_t *p_pack,
                                    const uint8_t *p_startcode, int i_startcode,
                                    const uint8_t *p_au_prepend, int i_au_prepend,
                                    unsigned i_au_min_size,
                                    packetizer_reset_t pf_reset,
                                    packetizer_parse_t pf_parse,
                                    packetizer_validate_t pf_validate,
                                    void *p_private )
{
    p_pack->i_state = STATE_NOSYNC;
    block_BytestreamInit( &p_pack->bytestream );
    p_pack->i_offset = 0;
    p_pack->b_flushing = false;

    p_pack->i_au_prepend = i_au_prepend;
    p_pack->p_au_prepend = p_au_prepend;
    p_pack->i_au_min_size = i_au_min_size;

    p_pack->i_startcode = i_startcode;
    p_pack->p_startcode = p_startcode;
    p_pack->pf_reset = pf_reset;
    p_pack->pf_parse = pf_parse;
    p_pack->pf_validate = pf_validate;
    p_pack->p_private = p_private;
}

static inline void packetizer_Clean( packetizer_t *p_pack )
{
    block_BytestreamRelease( &p_pack->bytestream );
}

static inline block_t *packetizer_Packetize( packetizer_t *p_pack, block_t **pp_block )
{
    if( !pp_block || !*pp_block )
        return NULL;

    if( (*pp_block)->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
    {
        const bool b_broken = ( (*pp_block)->i_flags&BLOCK_FLAG_CORRUPTED ) != 0;
        if( b_broken )
        {
            p_pack->i_state = STATE_NOSYNC;
            block_BytestreamEmpty( &p_pack->bytestream );
            p_pack->i_offset = 0;
        }
        p_pack->pf_reset( p_pack->p_private, b_broken );

        block_Release( *pp_block );
        return NULL;
    }

    block_BytestreamPush( &p_pack->bytestream, *pp_block );

    for( ;; )
    {
        bool b_used_ts;
        block_t *p_pic;

        switch( p_pack->i_state )
        {
        case STATE_NOSYNC:
            /* Find a startcode */
            if( !block_FindStartcodeFromOffset( &p_pack->bytestream, &p_pack->i_offset,
                                                p_pack->p_startcode, p_pack->i_startcode ) )
                p_pack->i_state = STATE_NEXT_SYNC;

            if( p_pack->i_offset )
            {
                block_SkipBytes( &p_pack->bytestream, p_pack->i_offset );
                p_pack->i_offset = 0;
                block_BytestreamFlush( &p_pack->bytestream );
            }

            if( p_pack->i_state != STATE_NEXT_SYNC )
                return NULL; /* Need more data */

            p_pack->i_offset = 1; /* To find next startcode */

        case STATE_NEXT_SYNC:
            /* Find the next startcode */
            if( block_FindStartcodeFromOffset( &p_pack->bytestream, &p_pack->i_offset,
                                               p_pack->p_startcode, p_pack->i_startcode ) )
            {
                if( !p_pack->b_flushing || !p_pack->bytestream.p_chain )
                    return NULL; /* Need more data */

                /* When flusing and we don't find a startcode, suppose that
                 * the data extend up to the end */
                block_ChainProperties( p_pack->bytestream.p_chain,
                                       NULL, &p_pack->i_offset, NULL );
                p_pack->i_offset -= p_pack->bytestream .i_offset;

                if( p_pack->i_offset <= (size_t)p_pack->i_startcode )
                    return NULL;
            }

            block_BytestreamFlush( &p_pack->bytestream );

            /* Get the new fragment and set the pts/dts */
            block_t *p_block_bytestream = p_pack->bytestream.p_block;

            p_pic = block_Alloc( p_pack->i_offset + p_pack->i_au_prepend );
            p_pic->i_pts = p_block_bytestream->i_pts;
            p_pic->i_dts = p_block_bytestream->i_dts;

            block_GetBytes( &p_pack->bytestream, &p_pic->p_buffer[p_pack->i_au_prepend],
                            p_pic->i_buffer - p_pack->i_au_prepend );
            if( p_pack->i_au_prepend > 0 )
                memcpy( p_pic->p_buffer, p_pack->p_au_prepend, p_pack->i_au_prepend );

            p_pack->i_offset = 0;

            /* Parse the NAL */
            if( p_pic->i_buffer < p_pack->i_au_min_size )
            {
                block_Release( p_pic );
                p_pic = NULL;
            }
            else
            {
                p_pic = p_pack->pf_parse( p_pack->p_private, &b_used_ts, p_pic );
                if( b_used_ts )
                {
                    p_block_bytestream->i_dts = VLC_TS_INVALID;
                    p_block_bytestream->i_pts = VLC_TS_INVALID;
                }
            }

            if( !p_pic )
            {
                p_pack->i_state = STATE_NOSYNC;
                break;
            }
            if( p_pack->pf_validate( p_pack->p_private, p_pic ) )
            {
                p_pack->i_state = STATE_NOSYNC;
                block_Release( p_pic );
                break;
            }

            /* So p_block doesn't get re-added several times */
            *pp_block = block_BytestreamPop( &p_pack->bytestream );

            p_pack->i_state = STATE_NOSYNC;

            return p_pic;
        }
    }
}

static inline void packetizer_Header( packetizer_t *p_pack,
                                      const uint8_t *p_header, int i_header )
{
    block_t *p_init = block_Alloc( i_header );
    if( !p_init )
        return;

    memcpy( p_init->p_buffer, p_header, i_header );

    p_pack->b_flushing = true;

    block_t *p_pic;
    while( ( p_pic = packetizer_Packetize( p_pack, &p_init ) ) )
        block_Release( p_pic ); /* Should not happen (only sequence header) */

    p_pack->i_state = STATE_NOSYNC;
    block_BytestreamEmpty( &p_pack->bytestream );
    p_pack->i_offset = 0;
    p_pack->b_flushing = false;
}

#endif


text:
using System;

namespace BenchmarkDotNet.Mathematics.StatisticalTesting
{
    public class StudentTest
    {
        public static readonly StudentTest Instance = new StudentTest();

        /// <summary>
        /// Determines whether the sample mean is different from a known mean
        /// </summary>
        /// <remarks>Should be consistent with t.test(x, mu = mu, alternative = "greater") from R </remarks>
        public OneSidedTestResult IsGreater(double[] sample, double value, Threshold threshold = null)
            => IsGreater(new Statistics(sample), value, threshold);

        /// <summary>
        /// Determines whether the sample mean is different from a known mean
        /// </summary>
        /// <remarks>Should be consistent with t.test(x, mu = mu, alternative = "greater") from R </remarks>
        public OneSidedTestResult IsGreater(Statistics sample, double value, Threshold threshold = null)
        {
            double mean = sample.Mean;
            double stdDev = sample.StandardDeviation;
            double n = sample.N;
            double df = n - 1;

            threshold = threshold ?? RelativeThreshold.Default;

            double t = (mean - value) /
                       (stdDev / Math.Sqrt(n));
            double pValue = 1 - MathHelper.StudentOneTail(t, df);

            return new OneSidedTestResult(pValue, threshold);
        }
    }
}


text:
from django.conf.urls import patterns, url

from depot import views

urlpatterns = patterns('',

        # Store View
        #url(r'^store/$', views.StoreView, name='store'),
        url(r'^store/dashboard/$', views.StoreDashboardView, name='store-dashboard'),
        url(r'^store/dashboard/products/(?P<id>\d+)/update/$', views.ProductUpdateView, name='product-update'),
        url(r'^store/dashboard/products/(?P<id>\d+)/delete/$', views.ProductDeleteView, name='product-delete'),

        # Front End
        url(r'^$', views.ProductView, name='index'),

        # Account
        url(r'^account/signup$', views.SignupView, name='signup'),
        url(r'^account/signin$', views.SigninView, name='signin'),
        url(r'^account/signout$', views.SignoutView, name='signout'),

        # User
        url(r'^user/dashboard/user=(?P<id>\d+)/$', views.UserDashboardView, name='user-dashboard'),
        url(r'^user/dashboard/cart/add/product=(?P<id>\d+)$', views.CartAddView, name='cart-add'),
        #url(r'^user/dashboard/cart/remove/product=(?P<id>\d+)$', views.CartRemoveView, name='cart-remove'),
        url(r'^user/dashboard/cart/clean$', views.CartCleanView, name='cart-clean'),
        url(r'^user/dashboard/order/create$', views.OrderCreateView, name='order-create'),
)


text:
//
//  S2MDelegateDispatcher.h
//  DelegateDispatch
//
//  Created by Nils Grabenhorst on 22/05/15.
//  Copyright (c) 2015 SinnerSchrader-Mobile. All rights reserved.
//

#import <Foundation/Foundation.h>
@protocol S2MDelegateDispatcher
@property (nonatomic, readonly) NSUInteger delegateCount;

/**
 Adds a delegate to an internal list of delegates.
 @param delegate The delegate @b must conform to the protocol that was provided when initializing an instance of this RFMessageTrampoline.
 */
- (void)addDelegate:(id)delegate;

/**
 Removes a delegate from the internal list of delegates.
 */
- (void)removeDelegate:(id)delegate;

- (BOOL)isRegisteredAsDelegate:(id)delegate;
@end

/**
 Forwards messages to multiple delegates.
 The messages must belong to a given protocol.
 Works for instance methods only, not for class methods.

 @note Each delegate can only be added once. Pointer equality is checked to determine whether a delegate can be added to the list. Two separate objects with the same hash and returning \c YES for \c isEqual can therefore be added to the list of delegates.

 @warning The return value of a message is undefined. Only the return value of the last delegate is returned to the sender of a message. Since the order of delegates called is undefined, it is best to only specify methods that do not return anything in the given protocol.
 */
@interface S2MDelegateDispatcher : NSProxy <S2MDelegateDispatcher>
- (instancetype)initWithDelegateProtocol:(Protocol *)protocol;
@end


text:
package com.baidubce.services.bmr.model;

import java.util.List;

import com.baidubce.model.AbstractBceResponse;

/**
 * Represent the response of GetClusterRequest.
 * <p>
 * The response contains the properties of the target cluster, such as:
 * id, imageType, imageVersion, logUri, name, autoTerminate, status, applications.
 */
public class GetClusterResponse extends AbstractBceResponse {
    private String id;
    private String imageType;
    private String imageVersion;
    private String logUri;
    private String name;
    private boolean autoTerminate;
    private ClusterStatus status;
    private List<Application> applications;
    private boolean serviceHaEnabled;
    private boolean safeModeEnabled;
    private String templateType;

    public String getTemplateType() {
        return templateType;
    }

    public void setTemplateType(String templateType) {
        this.templateType = templateType;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getImageType() {
        return imageType;
    }

    public void setImageType(String imageType) {
        this.imageType = imageType;
    }

    public String getImageVersion() {
        return imageVersion;
    }

    public void setImageVersion(String imageVersion) {
        this.imageVersion = imageVersion;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLogUri() {
        return logUri;
    }

    public void setLogUri(String logUri) {
        this.logUri = logUri;
    }

    public boolean getAutoTerminate() {
        return autoTerminate;
    }

    public void setAutoTerminate(boolean autoTerminate) {
        this.autoTerminate = autoTerminate;
    }

    public ClusterStatus getStatus() {
        return status;
    }

    public void setStatus(ClusterStatus status) {
        this.status = status;
    }

    public List<Application> getApplications() {
        return applications;
    }

    public void setApplications(List<Application> applications) {
        this.applications = applications;
    }

    public boolean getServiceHaEnabled() {
        return serviceHaEnabled;
    }

    public void setServiceHaEnabled(boolean serviceHaEnabled) {
        this.serviceHaEnabled = serviceHaEnabled;
    }

    public boolean getSafeModeEnabled() {
        return safeModeEnabled;
    }

    public void setSafeModeEnabled(boolean safeModeEnabled) {
        this.safeModeEnabled = safeModeEnabled;
    }
}


text:
A library to create the UI for chatting apps for Android.

![Message](/assets/MessageSample.png)

## Supported Android versions
3.0.x and higher

## Adding to your project

Add the dependency to your build.gradle:

	dependencies {
		compile 'com.github.samsao:messageui:1.0.0'
	}

## Usage
### Adding the chat window
1) Open your layout xml file and add the application namespace to the root element in the XML

~~~xml
xmlns:app="http://schemas.android.com/apk/res-auto"
~~~

2) Add the chat window to your layout

~~~xml
<com.samsao.messageui.views.MessagesWindow
        android:id="@+id/customized_messages_window"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:balloonMargins="20dp"
        app:thatBalloonBackground="@drawable/other_balloon_shape"
        app:thatBalloonTextColor="@android:color/white"
        app:thisBalloonBackground="@drawable/my_balloon_shape"
        app:thisBalloonTextColor="@android:color/white"/>
~~~
Everything with 'this' refers to the side where your messages are shown. 'that' refers to the side of the other person's messages.

These are the attributes you can add to your MessagesWindow:

~~~xml
thisBalloonBackground
thatBalloonBackground
thisBalloonTextColor
thatBalloonTextColor
balloonTextSize
balloonPadding
balloonMargins (the spacing between the ballonns)
progressBarColor (the color of the progress indicator to be shown when the user asks for more messages)
~~~

### Display the messages
Display the messages by calling `sendMessage()` or `receiveMessage()` and they will appear on the appropriate sides:

~~~java
MessagesWindow messagesWindow = (MessagesWindow) findViewById(R.id.messages_window);
messagesWindow.sendMessage("Hi!");
messagesWindow.receiveMessage("Hello!");
~~~

### Adding timestamps

You can display the timestamps inside or outside of the message balloon.

#### Outside

Just call `showTimestamp()` with the side where you want to display it. The current time will be displayed according to the device's time format.

~~~java
messagesWindow.showTimestamp(Message.THIS_SIDE);
~~~
![Timestamp outside](/assets/TSOut.png)

Or you can set it to be displayed after every message

~~~java
messagesWindow.setTimestampMode(MessagesWindow.ALWAYS_AFTER_BALLOON);
~~~
![Timestamp after](/assets/TSAfter.png)

#### Inside

Set the timestamp mode to display the timestamp inside the balloons. Then you can adjust its position using `setTimestampInsideBalloonGravity()`.

~~~java
messagesWindow.setTimestampMode(MessagesWindow.INSIDE_BALLOON_TOP);
messagesWindow.setTimestampInsideBalloonGravity(MessagesWindow.TIMESTAMP_INSIDE_BALLOON_GRAVITY_CORNER);
~~~
![Timestamp inside](/assets/TSInside.png)

#### Styling
There are some methods that allow you to style your timestamps.

~~~java
setTimestampMargins()
setTimestampTextSize()
setTimestampTextColor()
setTimestampBackground()
~~~
They will work for all timestamp modes.

### Loading old messages

You can display messages as soon as the user opens the chat by calling `loadMessages()`.

~~~java
List<Message> messages = new ArrayList<>();
Message message = new Message(":)", Message.THIS_SIDE);
message.setTime("7:20 pm");
messages.add(message);
messagesWindow.loadMessages(messages);
~~~

If you don't want to load all the messages at once, you can wait until the user scrolls to the top of the chat to load more. Set a callback to know when the user requests for more. A progress indicator will automatically be shown.

~~~java
mMessagesWindow.setOnAskToLoadMoreCallback(new OnAskToLoadMoreCallback() {
            @Override
            public void onAskToLoadMore() {
                List<Message> messages = getMessages();
                if (messages.isEmpty()) {
                    messagesWindow.removeOnAskToLoadMoreCallback();
                } else {
                    messagesWindow.loadOldMessages(messages);
                }
            }
        });
~~~

If all the messages were already loaded, you can simply call `removeOnAskToLoadMoreCallback` and the progress indicator won't show up anymore.

### Extra customization
The library comes with its own view for typing and sending text, but you can make your own. Just call `setWritingMessageView()` to replace it with your view. You don't have to add any inner views.

## Future improvements
* Support for group chats
* Typing indicator
* User pictures
* Animations
* Balloon grouping

## License
MessageUI is released under the MIT license. See the LICENSE file for details.


text:
function debugFirebugLiteInit() {
  this.hooks = [];
}

/* used on the client side only */
debugFirebugLite = new debugFirebugLiteInit();