text stringlengths 2 1.04M | meta dict |
|---|---|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v202211;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getReportJobStatusResponse element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getReportJobStatusResponse">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="rval" type="{https://www.google.com/apis/ads/publisher/v202211}ReportJobStatus" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"rval"
})
@XmlRootElement(name = "getReportJobStatusResponse")
public class ReportServiceInterfacegetReportJobStatusResponse {
@XmlSchemaType(name = "string")
protected ReportJobStatus rval;
/**
* Gets the value of the rval property.
*
* @return
* possible object is
* {@link ReportJobStatus }
*
*/
public ReportJobStatus getRval() {
return rval;
}
/**
* Sets the value of the rval property.
*
* @param value
* allowed object is
* {@link ReportJobStatus }
*
*/
public void setRval(ReportJobStatus value) {
this.rval = value;
}
}
| {
"content_hash": "091b6992cf4255a3352dba4b32c1a080",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 126,
"avg_line_length": 28.5875,
"alnum_prop": 0.6733712286838653,
"repo_name": "googleads/googleads-java-lib",
"id": "1d66bc8e06d5a01418ee942bc2da089ce74196f3",
"size": "2287",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202211/ReportServiceInterfacegetReportJobStatusResponse.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "81068791"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: gseidel
* Date: 12.08.18
* Time: 19:50
*/
namespace Enhavo\Bundle\TranslationBundle\AutoGenerator\Generator;
use Enhavo\Bundle\RoutingBundle\AutoGenerator\Generator\RouteNameGenerator;
use Enhavo\Bundle\RoutingBundle\Model\RouteInterface;
use Enhavo\Bundle\TranslationBundle\Translation\TranslationManager;
use Enhavo\Bundle\TranslationBundle\Translator\Route\RouteTranslator;
class TranslationRouteNameGenerator extends RouteNameGenerator
{
/** @var TranslationManager */
private $translationManager;
/** @var RouteTranslator */
private $routeTranslator;
/**
* TranslationRouteNameGenerator constructor.
* @param TranslationManager $translationManager
* @param RouteTranslator $routeTranslator
*/
public function __construct(TranslationManager $translationManager, RouteTranslator $routeTranslator)
{
$this->translationManager = $translationManager;
$this->routeTranslator = $routeTranslator;
}
public function generate($resource, $options = [])
{
parent::generate($resource, $options);
$this->generateTranslationRouteNames($resource, $options);
}
private function generateTranslationRouteNames($resource, $options = [])
{
$locales = $this->translationManager->getLocales();
foreach ($locales as $locale) {
if ($locale == $this->translationManager->getDefaultLocale()) {
continue;
}
$route = $this->routeTranslator->getTranslation($resource, $options['route_property'], $locale);
if ($route) {
/** @var RouteInterface $route */
if(!$options['overwrite'] && $route->getName()) {
return;
}
$route->setName($this->getRandomName());
}
}
}
public function getType()
{
return 'translation_route_name';
}
}
| {
"content_hash": "7133f8e7c56e8f995951eafe2fe5050a",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 108,
"avg_line_length": 29,
"alnum_prop": 0.6450304259634888,
"repo_name": "FabianLiebl/enhavo",
"id": "d472b8b1d59d511407010cd4bb922d0e8dcbb14d",
"size": "1972",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/Enhavo/Bundle/TranslationBundle/AutoGenerator/Generator/TranslationRouteNameGenerator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Gherkin",
"bytes": "13222"
},
{
"name": "Handlebars",
"bytes": "670"
},
{
"name": "JavaScript",
"bytes": "123744"
},
{
"name": "PHP",
"bytes": "3559334"
},
{
"name": "SCSS",
"bytes": "91683"
},
{
"name": "Shell",
"bytes": "1529"
},
{
"name": "Twig",
"bytes": "173459"
},
{
"name": "TypeScript",
"bytes": "386486"
},
{
"name": "Vue",
"bytes": "114061"
}
],
"symlink_target": ""
} |
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Faculty extends Model
{
protected $table = 'faculties';
protected $primaryKey = "id";
protected $fillable = [
'user_id',
'teacher_code',
'name',
'dob',
'present_address',
'permanent_address',
'is_active'
];
public $timestamps = TRUE;
public function user()
{
return $this->hasOne('App\Model\User','id','user_id');
}
}
| {
"content_hash": "a3c14e2ced0d8a0d084274a02755b7ba",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 62,
"avg_line_length": 18.76923076923077,
"alnum_prop": 0.5655737704918032,
"repo_name": "JUBanglaDepartment/stms",
"id": "3d6b18dd53d248baa4c4495f3f40fa7909226197",
"size": "488",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "app/Models/Faculty.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "646"
},
{
"name": "CSS",
"bytes": "690"
},
{
"name": "CoffeeScript",
"bytes": "83631"
},
{
"name": "HTML",
"bytes": "1250116"
},
{
"name": "JavaScript",
"bytes": "19202959"
},
{
"name": "PHP",
"bytes": "208751"
},
{
"name": "Shell",
"bytes": "444"
}
],
"symlink_target": ""
} |
package com.jetlag.jcreator.flickr;
import android.content.Context;
import android.util.Log;
import com.googlecode.flickrjandroid.Flickr;
import com.googlecode.flickrjandroid.FlickrException;
import com.googlecode.flickrjandroid.people.User;
import com.googlecode.flickrjandroid.photos.Photo;
import com.googlecode.flickrjandroid.photos.PhotoList;
import com.jetlag.jcreator.R;
import org.json.JSONException;
import java.io.IOException;
/**
* Created by vincent on 08/10/14.
*
* Uses the flickrj-android library to retrieve pictures for a specific user.
* This must be called from an asynchronous task, this cannot be called on the UI thread.
*/
public class FlickrJPicturesProvider implements FlickrProvider {
private Context context;
public FlickrJPicturesProvider(Context context) {
this.context = context;
}
@Override
public PhotoList getUserPhotos(String username, int count) {
PhotoList photos = new PhotoList();
Flickr f = new Flickr(context.getResources().getString(R.string.flickr_api_key));
try {
User user = f.getPeopleInterface().findByUsername(username);
photos = f.getPeopleInterface().getPublicPhotos(user.getId(), count, 1);
} catch (IOException | JSONException | FlickrException e) {
Log.d("flickr", e.getMessage());
}
return photos;
}
@Override
public Photo getPhotoForId(String photoId) {
Photo photo = null;
Flickr f = new Flickr(context.getResources().getString(R.string.flickr_api_key));
try {
photo = f.getPhotosInterface().getInfo(photoId, "");
} catch (IOException | JSONException | FlickrException e) {
Log.d("flickr", e.getMessage());
}
return photo;
}
}
| {
"content_hash": "71ee4bb4819f30fb6a2c0026c57fb705",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 89,
"avg_line_length": 30.303571428571427,
"alnum_prop": 0.7307012374779022,
"repo_name": "vpmalley/j-create",
"id": "57787278ef9485eaf2e0c09d49d927d244ec3a34",
"size": "1697",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/jetlag/jcreator/flickr/FlickrJPicturesProvider.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "65111"
}
],
"symlink_target": ""
} |
<?php if (false !== $label): ?>
<?php if ($required) { $label_attr['class'] = trim(($label_attr['class'] ?? '').' required'); } ?>
<?php if (!$compound) { $label_attr['for'] = $id; } ?>
<?php if (!$label) { $label = isset($label_format)
? strtr($label_format, ['%name%' => $name, '%id%' => $id])
: $view['form']->humanize($name); } ?>
<label<?php if ($label_attr) { echo ' '.$view['form']->block($form, 'attributes', ['attr' => $label_attr]); } ?>><?php echo $view->escape(false !== $translation_domain ? $view['translator']->trans($label, $label_translation_parameters, $translation_domain) : $label) ?></label>
<?php endif ?>
| {
"content_hash": "19d800036cd0070fc1e98acd4e6fd999",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 277,
"avg_line_length": 79.5,
"alnum_prop": 0.5676100628930818,
"repo_name": "Taluu/symfony",
"id": "a17a5ca2ab26f6bf9126f0d73746dffbd49e2976",
"size": "636",
"binary": false,
"copies": "3",
"ref": "refs/heads/4.4",
"path": "src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_label.html.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18634"
},
{
"name": "HTML",
"bytes": "348510"
},
{
"name": "Hack",
"bytes": "26"
},
{
"name": "JavaScript",
"bytes": "26198"
},
{
"name": "PHP",
"bytes": "17463009"
},
{
"name": "Shell",
"bytes": "3136"
}
],
"symlink_target": ""
} |
koa middleware for webpack
| {
"content_hash": "16dd01c3783d880c64324913b13f39a8",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 26,
"avg_line_length": 27,
"alnum_prop": 0.8518518518518519,
"repo_name": "frankwallis/koa-webpack",
"id": "b3e135f0f0088b908ef0a50b62cc4c05418ed2ad",
"size": "41",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2649"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<doc>
<assembly>
<name>ICSSoft.STORMNET.Drawing</name>
</assembly>
<members>
<member name="T:ICSSoft.STORMNET.Drawing.IconNotFoundException">
<summary>
картинка не найдена
</summary>
</member>
<member name="T:ICSSoft.STORMNET.Drawing.IconProvider">
<summary>
класс предоставлялщик иконок
</summary>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.GetIconFromAssembly(System.Type,System.String)">
<summary>
получить иконку из сборки (embeded)
</summary>
<param name="type">тип по которму брать сборку</param>
<param name="iconFileName">имя иконки</param>
<returns></returns>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.GetIconFromAssembly(System.Reflection.Assembly,System.String)">
<summary>
получить иконку из сборки (embeded)
</summary>
<param name="asm">сборка</param>
<param name="iconFileName">имя иконки</param>
<returns></returns>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.GetIconFromAssemblyByFullName(System.Reflection.Assembly,System.String)">
<summary>
получить иконку из сборки (embeded) по полному пути
</summary>
<param name="asm">сборка</param>
<param name="iconFileName">имя иконки</param>
<returns></returns>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.#cctor">
<summary>
</summary>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.GetIcon(System.Object,System.Boolean)">
<summary>
получить иконку по ключу
</summary>
<param name="key">ключ</param>
<param name="IsLarge">размер</param>
<returns></returns>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.AddIcon(System.Object,System.Drawing.Icon,System.Drawing.Icon)">
<summary>
добавить иконки
</summary>
<param name="key"></param>
<param name="LargeIcon"></param>
<param name="SmallIcon"></param>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.AddIcon(System.Object,System.String,System.Int32)">
<summary>
добавить иконку
</summary>
<param name="key"></param>
<param name="fileName"></param>
<param name="IconIndex"></param>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.RemoveIcon(System.Object)">
<summary>
удалить иконку
</summary>
<param name="key"></param>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.GetIcon(System.String,System.Int32,System.Boolean)">
<summary>
получить иконку из файла
</summary>
<param name="fileName"></param>
<param name="IconIndex"></param>
<param name="bIsLargeIcon"></param>
<returns></returns>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.GetTransparantedBitMap(System.Drawing.Icon)">
<summary>
преобразовать иконку к прозрачному битмапу
</summary>
<param name="icon"></param>
<returns></returns>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.GetTransparantedBitMap(System.Drawing.Icon,System.Drawing.Point)">
<summary>
преобразовать иконку к прозрачному битмапу
</summary>
<param name="icon"></param>
<param name="transparentPoint"></param>
<returns></returns>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.IconProvider.GetIconForFile(System.String)">
<summary>
получить иконку для файла
</summary>
<param name="FileName"></param>
<returns></returns>
</member>
<member name="P:ICSSoft.STORMNET.Drawing.IconProvider.ClosedFolder">
<summary>
стандартная иконка закрытый папок
</summary>
</member>
<member name="P:ICSSoft.STORMNET.Drawing.IconProvider.OpenedFolder">
<summary>
стандартная иконка открытый папок
</summary>
</member>
<member name="P:ICSSoft.STORMNET.Drawing.IconProvider.List">
<summary>
список
</summary>
</member>
<member name="P:ICSSoft.STORMNET.Drawing.IconProvider.LargeIconSize">
<summary>
Размер больших иконок
</summary>
</member>
<member name="P:ICSSoft.STORMNET.Drawing.IconProvider.SmallIconSize">
<summary>
Размер маленьких иконок
</summary>
</member>
<member name="T:ICSSoft.STORMNET.Drawing.GraphUtils">
<summary>
</summary>
</member>
<member name="M:ICSSoft.STORMNET.Drawing.GraphUtils.DrawImage(System.Drawing.Graphics,System.Drawing.Image,System.Int32,System.Int32,System.Boolean)">
<summary>
нарисовать картинку
</summary>
<param name="g">на чем</param>
<param name="image">что </param>
<param name="positionX">где.икс</param>
<param name="positionY">где.игрек</param>
<param name="NotGrayed">посерять-непосерять</param>
</member>
</members>
</doc>
| {
"content_hash": "9671c6dc329d03ae7785508185fef0d6",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 158,
"avg_line_length": 40.50675675675676,
"alnum_prop": 0.5519599666388657,
"repo_name": "Flexberry/FlexberryStudy2015",
"id": "4e3cd764580ffb7bf7ca9190b576cda7a7cdb7f2",
"size": "6534",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "Pepelyaeva Kseniya/Individual work/Ippodrom/packages/NewPlatform.Flexberry.ORM.2.0.0/lib/net35/ICSSoft.STORMNET.Drawing.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "810036"
},
{
"name": "C#",
"bytes": "3742621"
},
{
"name": "CSS",
"bytes": "12925570"
},
{
"name": "HTML",
"bytes": "5991"
},
{
"name": "JavaScript",
"bytes": "4635366"
},
{
"name": "PowerShell",
"bytes": "65632"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("MapMap")]
[assembly: AssemblyDescription("A tool to capture large pictures from maps in the browser.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("www.mastersign.de")]
[assembly: AssemblyProduct("MapMap")]
[assembly: AssemblyCopyright("Copyright © 2013 Tobias Kiertscher")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("ab8dae14-a292-4cad-880f-af30449be302")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]
| {
"content_hash": "6c3c034cae493cae7c388836ba1bf1f3",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 106,
"avg_line_length": 43.23684210526316,
"alnum_prop": 0.7662811929397444,
"repo_name": "mastersign/MapMap",
"id": "4119c5da7e13d063689d40c1277cfb52fd255f0f",
"size": "1661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "51127"
}
],
"symlink_target": ""
} |
using System;
using System.Globalization;
using Ploeh.AutoFixture.Kernel;
namespace Ploeh.AutoFixture
{
/// <summary>
/// Creates a strictly increasing sequence of ranged numbers, starting at range minimum.
/// Sequence restarts at range minimum when range maximum is exceeded.
/// </summary>
public class RangedNumberGenerator : ISpecimenBuilder
{
private readonly object syncRoot;
private object rangedValue;
/// <summary>
/// Initializes a new instance of the <see cref="RangedNumberGenerator"/> class.
/// </summary>
public RangedNumberGenerator()
{
this.syncRoot = new object();
this.rangedValue = null;
}
/// <summary>
/// Creates a new number based on a RangedNumberRequest.
/// </summary>
/// <param name="request">The request that describes what to create.</param>
/// <param name="context">A context that can be used to create other specimens.</param>
/// <returns>
/// The requested number if possible; otherwise a <see cref="NoSpecimen"/> instance.
/// </returns>
public object Create(object request, ISpecimenContext context)
{
if (request == null)
{
return new NoSpecimen();
}
if (context == null)
{
throw new ArgumentNullException("context");
}
var range = request as RangedNumberRequest;
if (range == null)
{
return new NoSpecimen(request);
}
var value = context.Resolve(range.OperandType) as IComparable;
if (value == null)
{
return new NoSpecimen(request);
}
try
{
this.CreateAnonymous(range, value);
}
catch (InvalidOperationException)
{
return new NoSpecimen(request);
}
return this.rangedValue;
}
private void CreateAnonymous(RangedNumberRequest range, IComparable value)
{
lock (this.syncRoot)
{
var minimum = (IComparable)range.Minimum;
var maximum = (IComparable)range.Maximum;
if (this.rangedValue != null)
{
object target;
if (range.OperandType == typeof(byte) &&
Convert.ToInt32(
this.rangedValue,
CultureInfo.CurrentCulture) > byte.MaxValue ||
range.OperandType == typeof(short) &&
Convert.ToInt32(
this.rangedValue,
CultureInfo.CurrentCulture) > short.MaxValue)
target = minimum;
else
target = this.rangedValue;
this.rangedValue = Convert.ChangeType(target, range.OperandType, CultureInfo.CurrentCulture);
}
if (this.rangedValue != null && (minimum.CompareTo(this.rangedValue) <= 0 && maximum.CompareTo(this.rangedValue) > 0))
{
this.rangedValue =
Convert.ChangeType(
RangedNumberGenerator.Add(
this.rangedValue,
Convert.ChangeType(
1,
range.OperandType,
CultureInfo.CurrentCulture)),
range.OperandType,
CultureInfo.CurrentCulture);
if (maximum.CompareTo(this.rangedValue) < 0)
{
this.rangedValue = Convert.ChangeType(
maximum,
range.OperandType,
CultureInfo.CurrentCulture);
}
}
else if (minimum.CompareTo(value) == 0)
{
this.rangedValue = minimum;
}
else if (maximum.CompareTo(value) == 0)
{
this.rangedValue = maximum;
}
else if (minimum.CompareTo(value) <= 0 && maximum.CompareTo(value) <= 0)
{
this.rangedValue = minimum;
}
else if (minimum.CompareTo(this.rangedValue) <= 0 && maximum.CompareTo(this.rangedValue) <= 0)
{
this.rangedValue = minimum;
}
else if (minimum.CompareTo(value) < 0)
{
this.rangedValue = value;
}
else
{
this.rangedValue = RangedNumberGenerator.Add(minimum, value);
if (minimum.CompareTo(this.rangedValue) > 0 ||
maximum.CompareTo(this.rangedValue) < 0)
{
this.rangedValue = minimum;
}
}
this.rangedValue = Convert.ChangeType(this.rangedValue, range.OperandType, CultureInfo.CurrentCulture);
}
}
private static object Add(object a, object b)
{
switch (Type.GetTypeCode(a.GetType()))
{
case TypeCode.Int16:
return (short)((short)a + (short)b);
case TypeCode.UInt16:
return (ushort)((ushort)a + (ushort)b);
case TypeCode.Int32:
return (int)a + (int)b;
case TypeCode.UInt32:
return (uint)a + (uint)b;
case TypeCode.Int64:
return (long)a + (long)b;
case TypeCode.UInt64:
return (ulong)a + (ulong)b;
case TypeCode.Decimal:
return (decimal)a + (decimal)b;
case TypeCode.Double:
return (double)a + (double)b;
case TypeCode.Byte:
return (byte)a + (byte)b;
case TypeCode.SByte:
return (sbyte)((sbyte)a + (sbyte)b);
case TypeCode.Single:
return (float)a + (float)b;
default:
throw new InvalidOperationException("The underlying type code of the specified types is not supported.");
}
}
}
}
| {
"content_hash": "02f76a74f0128c7c560f0a5af6a678ae",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 134,
"avg_line_length": 35.963541666666664,
"alnum_prop": 0.44808110065170165,
"repo_name": "mrinaldi/AutoFixture",
"id": "cb10d5d391de2766ce5a8ae840e7a68dc7442397",
"size": "6907",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Src/AutoFixture/RangedNumberGenerator.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3612884"
},
{
"name": "F#",
"bytes": "43535"
},
{
"name": "PowerShell",
"bytes": "861"
},
{
"name": "Puppet",
"bytes": "170"
},
{
"name": "Shell",
"bytes": "230"
},
{
"name": "Smalltalk",
"bytes": "2018"
},
{
"name": "XSLT",
"bytes": "17270"
}
],
"symlink_target": ""
} |
class Array
# TODO: probably do not need this anymore
def common_superclass
class_counter = {}
class_counter.default = 0
index = 0
each do |cls|
while (cls != BasicObject) do
class_counter[cls] += 1
cls = cls.superclass
end
index += 1
end
smallest = Object
class_counter.each do |cls, counter|
if counter == size
if cls < smallest
smallest = cls
end
end
end
smallest
end
def all_types
type_counter.keys
end
alias :old_push :push
def push(*elements)
old_push(*elements)
for element in elements
type_counter[element.class] += 1
end
self
end
alias :old_set :[]=
def []=(index, element)
type_counter[self[index].class] -= 1
if type_counter[self[index].class] == 0
type_counter.delete(self[index].class)
end
old_set(index, element)
type_counter[element.class] += 1
end
private
def type_counter
if @type_counter == nil
@type_counter = {}
@type_counter.default = 0
each do |element|
@type_counter[element.class] += 1
end
end
@type_counter
end
end
| {
"content_hash": "2fd743928118b7bc3e4df128c60b3ad9",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 50,
"avg_line_length": 21.12676056338028,
"alnum_prop": 0.458,
"repo_name": "prg-titech/ikra-ruby",
"id": "eb8780012e955abe05b4e3d9bb25b62d11858fd4",
"size": "1500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/type_aware_array.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "16530"
},
{
"name": "Cuda",
"bytes": "3389909"
},
{
"name": "Ruby",
"bytes": "535151"
}
],
"symlink_target": ""
} |
#include "UnresolvedNhopsProber.h"
#include "fboss/agent/NexthopToRouteCount.h"
#include "fboss/agent/state/SwitchState.h"
#include "fboss/agent/state/Interface.h"
#include "fboss/agent/state/Vlan.h"
#include "fboss/agent/state/VlanMap.h"
#include "fboss/agent/state/ArpTable.h"
#include "fboss/agent/state/NdpTable.h"
#include "fboss/agent/ArpHandler.h"
#include "fboss/agent/IPv6Handler.h"
namespace facebook { namespace fboss {
void UnresolvedNhopsProber::timeoutExpired() noexcept {
std::lock_guard<std::mutex> g(lock_);
auto state = sw_->getState();
for (const auto& ridAndNhopsRefCounts : nhops2RouteCount_) {
for (const auto& nhopAndRefCount : ridAndNhopsRefCounts.second) {
const auto& nhop = nhopAndRefCount.first;
auto intf = state->getInterfaces()->getInterfaceIf(nhop.intf());
if (!intf) {
continue; // interface got unconfigured
}
// Probe all nexthops for which either don't have a L2 entry
// or the entry is not resolved (port == 0). Note that we do
// not exclude pending entries here since in case of recursive
// routes we might get packets with destination set to prefix
// that needs to be resolved recursively. In ARP and NDP code
// we do not do route lookup when deciding to send ARP/NDP requests.
// So we would only try to ARP/NDP for the destination if it
// is in one of the interface subnets (which it won't be else
// we won't have needed recursive resolution). So ARP/NDP for
// all unresolved next hops. We could also consider doing route
// lookups in ARP/NDP code, but by probing all unresolved next
// hops we effectively do the same thing, since the next hops
// probed come from after the route was (recursively) resolved.
auto vlan = state->getVlans()->getVlanIf(intf->getVlanID());
CHECK(vlan); // must have vlan for configrued inteface
if (nhop.addr().isV4()) {
auto nhop4 = nhop.addr().asV4();
auto arpEntry = vlan->getArpTable()->getEntryIf(nhop4);
if (!arpEntry || arpEntry->getPort() == PortID(0)) {
VLOG(3) <<" Sending probe for unresolved next hop: " << nhop4;
ArpHandler::sendArpRequest(sw_, vlan, nhop4);
}
} else {
auto nhop6 = nhop.addr().asV6();
auto ndpEntry = vlan->getNdpTable()->getEntryIf(nhop6);
if (!ndpEntry || ndpEntry->getPort() == PortID(0)) {
VLOG(3) <<" Sending probe for unresolved next hop: " << nhop6;
IPv6Handler::sendNeighborSolicitation(sw_, nhop6, vlan);
}
}
}
}
scheduleTimeout(interval_);
}
}} // facebook::fboss
| {
"content_hash": "556aefb6936296476814819ae9046d8c",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 74,
"avg_line_length": 44.2,
"alnum_prop": 0.6628959276018099,
"repo_name": "peterlei/fboss",
"id": "3624501b8f09800ec90fa5a98a8a959cc5f80f09",
"size": "2967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fboss/agent/UnresolvedNhopsProber.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "685"
},
{
"name": "C++",
"bytes": "2430478"
},
{
"name": "CMake",
"bytes": "27397"
},
{
"name": "CSS",
"bytes": "228"
},
{
"name": "Python",
"bytes": "960516"
},
{
"name": "Shell",
"bytes": "3978"
},
{
"name": "Thrift",
"bytes": "50019"
}
],
"symlink_target": ""
} |
require 'spec_helper'
require 'vagrant-libvirt'
require 'vagrant-libvirt/plugin'
describe VagrantPlugins::ProviderLibvirt::Plugin do
subject { described_class.new }
include_context 'unit'
describe '#action_hook remove_libvirt_image' do
before do
# set up some dummy boxes
box_path = File.join(env[:env].boxes.directory, 'vagrant-libvirt-VAGRANTSLASH-test', '0.0.1')
['libvirt', 'virtualbox'].each do |provider|
provider_path = File.join(box_path, provider)
FileUtils.mkdir_p(provider_path)
metadata = {'provider': provider}
File.open(File.join(provider_path, 'metadata.json'), "w") { |f| f.write metadata.to_json }
end
end
it 'should call the action hook after box remove' do
expect(VagrantPlugins::ProviderLibvirt::Action).to receive(:remove_libvirt_image).and_return(Vagrant::Action::Builder.new)
expect {
env[:env].action_runner.run(
Vagrant::Action.action_box_remove, {
box_name: 'vagrant-libvirt/test',
box_provider: 'libvirt',
box_version: '0.0.1',
force_confirm_box_remove: true,
box_remove_all_versions: false,
ui: ui,
}
)
}.to_not raise_error
end
end
end
| {
"content_hash": "e10a2e9b69f21c5ab1b2369a51985fbc",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 128,
"avg_line_length": 31.9,
"alnum_prop": 0.6269592476489029,
"repo_name": "electrofelix/vagrant-libvirt",
"id": "463ec4132395775ce56162dc862fb67accf69d38",
"size": "1307",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "spec/unit/plugin_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "2415"
},
{
"name": "HTML",
"bytes": "15376"
},
{
"name": "Ruby",
"bytes": "515533"
},
{
"name": "Shell",
"bytes": "13885"
}
],
"symlink_target": ""
} |
@class NSArray, NSString;
@interface IDEMediaType : NSObject <NSCopying>
{
}
+ (id)sharedInstance;
@property(readonly) NSString *displayName;
@property(readonly) Class mediaResourceClass;
@property(readonly) NSArray *pasteboardTypes;
@property(readonly) NSString *pasteboardType;
- (BOOL)isKindOfMediaType:(id)arg1;
- (BOOL)isEqual:(id)arg1;
- (BOOL)isEqualToMediaType:(id)arg1;
- (unsigned long long)hash;
- (id)copyWithZone:(struct _NSZone *)arg1;
@end
| {
"content_hash": "d0e64146fb2b201d16e6a0f511563abc",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 46,
"avg_line_length": 24.157894736842106,
"alnum_prop": 0.7603485838779956,
"repo_name": "kolinkrewinkel/Multiplex",
"id": "fbd0c6f0a97da22398d7c4acda74ba9b5806ab5c",
"size": "625",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Multiplex/IDEHeaders/IDEHeaders/IDEKit/IDEMediaType.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "4691836"
},
{
"name": "Python",
"bytes": "2267"
},
{
"name": "Ruby",
"bytes": "109"
},
{
"name": "Shell",
"bytes": "293"
}
],
"symlink_target": ""
} |
class DmOfficer
include DataMapper::Resource
property :id, Serial
property :name, String
property :position_id, Integer
storage_names[:default] = 'officers'
belongs_to :position, :model => 'DmPosition', :child_key => [:position_id], :required => false
has n, :groups, :model => 'DmGroup', :through => Resource
@scaffold_name = 'officer'
@scaffold_human_name = 'Officer'
@scaffold_select_order = 'name'
@scaffold_use_auto_complete = true
@scaffold_browse_records_per_page = nil
def self.scaffold_association_use_auto_complete(association)
true
end
end
| {
"content_hash": "d2a080ed4dacb8420511cb4c215e96e4",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 96,
"avg_line_length": 26.727272727272727,
"alnum_prop": 0.6989795918367347,
"repo_name": "markus/scaffolding_extensions",
"id": "ce467c0c2395822564138e2231f154943568ab88",
"size": "588",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test_site/app/models/dm_officer.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1251"
},
{
"name": "CSS",
"bytes": "3193"
},
{
"name": "HTML",
"bytes": "27772"
},
{
"name": "JavaScript",
"bytes": "2857"
},
{
"name": "Ruby",
"bytes": "233668"
},
{
"name": "Shell",
"bytes": "789"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_connect_socket_system_73b.cpp
Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml
Template File: sources-sink-73b.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: connect_socket Read data using a connect socket (client side)
* GoodSource: Fixed string
* Sinks: system
* BadSink : Execute command in data using system()
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
#include <wchar.h>
#ifdef _WIN32
#define FULL_COMMAND "%WINDIR%\\system32\\cmd.exe /c dir "
#else
#include <unistd.h>
#define FULL_COMMAND "/bin/sh ls -la "
#endif
#ifdef _WIN32
#define SYSTEM system
#else /* NOT _WIN32 */
#define SYSTEM system
#endif
using namespace std;
namespace CWE78_OS_Command_Injection__char_connect_socket_system_73
{
#ifndef OMITBAD
void badSink(list<char *> dataList)
{
/* copy data out of dataList */
char * data = dataList.back();
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
if (SYSTEM(data) <= 0)
{
printLine("command execution failed!");
exit(1);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<char *> dataList)
{
char * data = dataList.back();
/* POTENTIAL FLAW: Execute command in data possibly leading to command injection */
if (SYSTEM(data) <= 0)
{
printLine("command execution failed!");
exit(1);
}
}
#endif /* OMITGOOD */
} /* close namespace */
| {
"content_hash": "8186ae44dd1b86114ea15ec7ab271093",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 107,
"avg_line_length": 24.48611111111111,
"alnum_prop": 0.6585365853658537,
"repo_name": "maurer/tiamat",
"id": "97a1a2ca8e6f6452b5d21a5b63be49318bffe571",
"size": "1763",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE78_OS_Command_Injection/s01/CWE78_OS_Command_Injection__char_connect_socket_system_73b.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import logging
from typing import Dict
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from django.core import exceptions
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from polyaxon.utils.bool_utils import to_bool
_logger = logging.getLogger("polyaxon.commands")
class Command(BaseCommand):
"""Management utility to create users/superusers.
This is command is different than the django one, because:
1. does not prompt the user to enter a password, i.e. can be used inline.
2. validates and requires an email.
"""
help = "Used to create a user/superuser."
requires_migrations_checks = True
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.UserModel = get_user_model()
# pylint:disable= protected-access
self.username_field = self.UserModel._meta.get_field(
self.UserModel.USERNAME_FIELD
)
# pylint:disable= protected-access
self.email_field = self.UserModel._meta.get_field("email")
def add_arguments(self, parser) -> None:
parser.add_argument(
"--%s" % self.UserModel.USERNAME_FIELD,
required=True,
dest=self.UserModel.USERNAME_FIELD,
help="Specifies the login for the user/superuser.",
)
parser.add_argument(
"--password",
required=True,
dest="password",
help="Specifies the password for the user/superuser.",
)
parser.add_argument(
"--email",
required=True,
dest="email",
help="Specifies the email for the user/superuser.",
)
parser.add_argument(
"--superuser",
dest="is_superuser",
action="store_true",
default=False,
help="Specifies a user or superuser.",
)
parser.add_argument(
"--force",
dest="force",
action="store_true",
default=False,
help="To force create the user even if the user is not valid.",
)
def validate_password(self, password: str, user_data: Dict, force: bool) -> None:
try:
validate_password(password, self.UserModel(**user_data))
except ValidationError as e:
_logger.warning("The password provided is not valid %s", e)
if force:
_logger.warning(
"The user will be created although the password does not meet the validation."
)
else:
raise e
def handle(self, *args, **options): # pylint:disable=too-many-branches
username = options[self.UserModel.USERNAME_FIELD].strip()
password = options["password"].strip()
email = options["email"].strip()
force = to_bool(options["force"])
is_superuser = to_bool(options["is_superuser"])
try:
username = self.username_field.clean(username, None)
except exceptions.ValidationError as e:
raise CommandError("; ".join(e.messages))
try:
self.email_field.clean(email, None)
except exceptions.ValidationError as e:
raise CommandError("; ".join(e.messages))
try:
self.UserModel.objects.get_by_natural_key(username)
except self.UserModel.DoesNotExist:
pass
else:
_logger.info(
"Info: Username %s is already taken. Will not recreate user.", username
)
return
try:
self.UserModel.objects.get(email=email)
except self.UserModel.DoesNotExist:
pass
except exceptions.MultipleObjectsReturned:
raise CommandError("Error: That %s is already taken." % email)
else:
raise CommandError("Error: That %s is already taken." % email)
if not username:
raise CommandError("Error: Blank username aren't allowed.")
if not password:
raise CommandError("Error: Blank passwords aren't allowed.")
if not email:
raise CommandError("Error: Blank email aren't allowed.")
user_data = {self.UserModel.USERNAME_FIELD: username, "email": email}
self.validate_password(password=password, user_data=user_data, force=force)
user_data["password"] = password
if is_superuser:
self.UserModel.objects.create_superuser(**user_data)
else:
self.UserModel.objects.create_user(**user_data)
if options["verbosity"] >= 1:
self.stdout.write(
"{} created successfully.".format(
"Superuser" if is_superuser else "User"
)
)
| {
"content_hash": "6aca9748b8e4b5acdf47a62435a1633c",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 98,
"avg_line_length": 34.48951048951049,
"alnum_prop": 0.58779399837794,
"repo_name": "polyaxon/polyaxon",
"id": "aa44cea184e0cf00b47c24ca6daf08d97909ca69",
"size": "5537",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "platform/polycommon/polycommon/commands/management/commands/createuser.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1989"
},
{
"name": "Python",
"bytes": "5201898"
},
{
"name": "Shell",
"bytes": "1565"
}
],
"symlink_target": ""
} |
/*** COMMENTS. ***/
#include <stdint.h>
#include "platform.h"
#include "internals.h"
#include "specialize.h"
#include "softfloat.h"
/*----------------------------------------------------------------------------
| Floating-point rounding mode, extended double-precision rounding precision,
| and exception flags.
*----------------------------------------------------------------------------*/
int_fast8_t softfloat_roundingMode = softfloat_round_nearest_even;
int_fast8_t softfloat_detectTininess = init_detectTininess;
int_fast8_t softfloat_exceptionFlags = 0;
int_fast8_t floatx80_roundingPrecision = 80;
| {
"content_hash": "745dd92877a33d06555c74fec131258c",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 79,
"avg_line_length": 32.1578947368421,
"alnum_prop": 0.5662847790507365,
"repo_name": "dededong/goblin-core",
"id": "cd9b04d4b015a9b75518bc7a0b47d428d0e6590c",
"size": "611",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "riscv/riscv-sim/softfloat/softfloat_state.c",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "1429"
},
{
"name": "Assembly",
"bytes": "37219664"
},
{
"name": "Awk",
"bytes": "1296"
},
{
"name": "Batchfile",
"bytes": "31924"
},
{
"name": "C",
"bytes": "121615973"
},
{
"name": "C#",
"bytes": "12418"
},
{
"name": "C++",
"bytes": "125512310"
},
{
"name": "CMake",
"bytes": "710738"
},
{
"name": "CSS",
"bytes": "43924"
},
{
"name": "Common Lisp",
"bytes": "65656"
},
{
"name": "Cuda",
"bytes": "12393"
},
{
"name": "D",
"bytes": "21699665"
},
{
"name": "DIGITAL Command Language",
"bytes": "53633"
},
{
"name": "DTrace",
"bytes": "8508630"
},
{
"name": "E",
"bytes": "3290"
},
{
"name": "Eiffel",
"bytes": "2314"
},
{
"name": "Elixir",
"bytes": "314"
},
{
"name": "Emacs Lisp",
"bytes": "41146"
},
{
"name": "FORTRAN",
"bytes": "377751"
},
{
"name": "Forth",
"bytes": "4188"
},
{
"name": "GAP",
"bytes": "21991"
},
{
"name": "GDScript",
"bytes": "54941"
},
{
"name": "Gnuplot",
"bytes": "446"
},
{
"name": "Groff",
"bytes": "1974816"
},
{
"name": "HTML",
"bytes": "1118040"
},
{
"name": "JavaScript",
"bytes": "24233"
},
{
"name": "LLVM",
"bytes": "48362057"
},
{
"name": "Lex",
"bytes": "598400"
},
{
"name": "Limbo",
"bytes": "755"
},
{
"name": "M",
"bytes": "2548"
},
{
"name": "Makefile",
"bytes": "6901261"
},
{
"name": "Mathematica",
"bytes": "5497"
},
{
"name": "Matlab",
"bytes": "54444"
},
{
"name": "Mercury",
"bytes": "1222"
},
{
"name": "OCaml",
"bytes": "748821"
},
{
"name": "Objective-C",
"bytes": "4995681"
},
{
"name": "Objective-C++",
"bytes": "1419213"
},
{
"name": "Perl",
"bytes": "881547"
},
{
"name": "Perl6",
"bytes": "80156"
},
{
"name": "PicoLisp",
"bytes": "31994"
},
{
"name": "Pure Data",
"bytes": "22171"
},
{
"name": "Python",
"bytes": "1375992"
},
{
"name": "R",
"bytes": "627855"
},
{
"name": "Rebol",
"bytes": "51929"
},
{
"name": "Scheme",
"bytes": "4296232"
},
{
"name": "Shell",
"bytes": "1994645"
},
{
"name": "Standard ML",
"bytes": "5682"
},
{
"name": "SuperCollider",
"bytes": "734239"
},
{
"name": "Tcl",
"bytes": "2234"
},
{
"name": "TeX",
"bytes": "601780"
},
{
"name": "VimL",
"bytes": "26411"
},
{
"name": "Yacc",
"bytes": "769886"
}
],
"symlink_target": ""
} |
package com.microsoft.azure.management.cosmosdb.v2019_08_01;
import java.util.Map;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
/**
* Parameters for patching Azure Cosmos DB database account properties.
*/
@JsonFlatten
public class DatabaseAccountUpdateParameters {
/**
* The tags property.
*/
@JsonProperty(value = "tags")
private Map<String, String> tags;
/**
* The location of the resource group to which the resource belongs.
*/
@JsonProperty(value = "location")
private String location;
/**
* The consistency policy for the Cosmos DB account.
*/
@JsonProperty(value = "properties.consistencyPolicy")
private ConsistencyPolicy consistencyPolicy;
/**
* An array that contains the georeplication locations enabled for the
* Cosmos DB account.
*/
@JsonProperty(value = "properties.locations")
private List<Location> locations;
/**
* Cosmos DB Firewall Support: This value specifies the set of IP addresses
* or IP address ranges in CIDR form to be included as the allowed list of
* client IPs for a given database account. IP addresses/ranges must be
* comma separated and must not contain any spaces.
*/
@JsonProperty(value = "properties.ipRangeFilter")
private String ipRangeFilter;
/**
* Flag to indicate whether to enable/disable Virtual Network ACL rules.
*/
@JsonProperty(value = "properties.isVirtualNetworkFilterEnabled")
private Boolean isVirtualNetworkFilterEnabled;
/**
* Enables automatic failover of the write region in the rare event that
* the region is unavailable due to an outage. Automatic failover will
* result in a new write region for the account and is chosen based on the
* failover priorities configured for the account.
*/
@JsonProperty(value = "properties.enableAutomaticFailover")
private Boolean enableAutomaticFailover;
/**
* List of Cosmos DB capabilities for the account.
*/
@JsonProperty(value = "properties.capabilities")
private List<Capability> capabilities;
/**
* List of Virtual Network ACL rules configured for the Cosmos DB account.
*/
@JsonProperty(value = "properties.virtualNetworkRules")
private List<VirtualNetworkRule> virtualNetworkRules;
/**
* Enables the account to write in multiple locations.
*/
@JsonProperty(value = "properties.enableMultipleWriteLocations")
private Boolean enableMultipleWriteLocations;
/**
* Enables the cassandra connector on the Cosmos DB C* account.
*/
@JsonProperty(value = "properties.enableCassandraConnector")
private Boolean enableCassandraConnector;
/**
* The cassandra connector offer type for the Cosmos DB database C*
* account. Possible values include: 'Small'.
*/
@JsonProperty(value = "properties.connectorOffer")
private ConnectorOffer connectorOffer;
/**
* Disable write operations on metadata resources (databases, containers,
* throughput) via account keys.
*/
@JsonProperty(value = "properties.disableKeyBasedMetadataWriteAccess")
private Boolean disableKeyBasedMetadataWriteAccess;
/**
* Get the tags value.
*
* @return the tags value
*/
public Map<String, String> tags() {
return this.tags;
}
/**
* Set the tags value.
*
* @param tags the tags value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
/**
* Get the location of the resource group to which the resource belongs.
*
* @return the location value
*/
public String location() {
return this.location;
}
/**
* Set the location of the resource group to which the resource belongs.
*
* @param location the location value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withLocation(String location) {
this.location = location;
return this;
}
/**
* Get the consistency policy for the Cosmos DB account.
*
* @return the consistencyPolicy value
*/
public ConsistencyPolicy consistencyPolicy() {
return this.consistencyPolicy;
}
/**
* Set the consistency policy for the Cosmos DB account.
*
* @param consistencyPolicy the consistencyPolicy value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withConsistencyPolicy(ConsistencyPolicy consistencyPolicy) {
this.consistencyPolicy = consistencyPolicy;
return this;
}
/**
* Get an array that contains the georeplication locations enabled for the Cosmos DB account.
*
* @return the locations value
*/
public List<Location> locations() {
return this.locations;
}
/**
* Set an array that contains the georeplication locations enabled for the Cosmos DB account.
*
* @param locations the locations value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withLocations(List<Location> locations) {
this.locations = locations;
return this;
}
/**
* Get cosmos DB Firewall Support: This value specifies the set of IP addresses or IP address ranges in CIDR form to be included as the allowed list of client IPs for a given database account. IP addresses/ranges must be comma separated and must not contain any spaces.
*
* @return the ipRangeFilter value
*/
public String ipRangeFilter() {
return this.ipRangeFilter;
}
/**
* Set cosmos DB Firewall Support: This value specifies the set of IP addresses or IP address ranges in CIDR form to be included as the allowed list of client IPs for a given database account. IP addresses/ranges must be comma separated and must not contain any spaces.
*
* @param ipRangeFilter the ipRangeFilter value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withIpRangeFilter(String ipRangeFilter) {
this.ipRangeFilter = ipRangeFilter;
return this;
}
/**
* Get flag to indicate whether to enable/disable Virtual Network ACL rules.
*
* @return the isVirtualNetworkFilterEnabled value
*/
public Boolean isVirtualNetworkFilterEnabled() {
return this.isVirtualNetworkFilterEnabled;
}
/**
* Set flag to indicate whether to enable/disable Virtual Network ACL rules.
*
* @param isVirtualNetworkFilterEnabled the isVirtualNetworkFilterEnabled value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withIsVirtualNetworkFilterEnabled(Boolean isVirtualNetworkFilterEnabled) {
this.isVirtualNetworkFilterEnabled = isVirtualNetworkFilterEnabled;
return this;
}
/**
* Get enables automatic failover of the write region in the rare event that the region is unavailable due to an outage. Automatic failover will result in a new write region for the account and is chosen based on the failover priorities configured for the account.
*
* @return the enableAutomaticFailover value
*/
public Boolean enableAutomaticFailover() {
return this.enableAutomaticFailover;
}
/**
* Set enables automatic failover of the write region in the rare event that the region is unavailable due to an outage. Automatic failover will result in a new write region for the account and is chosen based on the failover priorities configured for the account.
*
* @param enableAutomaticFailover the enableAutomaticFailover value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withEnableAutomaticFailover(Boolean enableAutomaticFailover) {
this.enableAutomaticFailover = enableAutomaticFailover;
return this;
}
/**
* Get list of Cosmos DB capabilities for the account.
*
* @return the capabilities value
*/
public List<Capability> capabilities() {
return this.capabilities;
}
/**
* Set list of Cosmos DB capabilities for the account.
*
* @param capabilities the capabilities value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withCapabilities(List<Capability> capabilities) {
this.capabilities = capabilities;
return this;
}
/**
* Get list of Virtual Network ACL rules configured for the Cosmos DB account.
*
* @return the virtualNetworkRules value
*/
public List<VirtualNetworkRule> virtualNetworkRules() {
return this.virtualNetworkRules;
}
/**
* Set list of Virtual Network ACL rules configured for the Cosmos DB account.
*
* @param virtualNetworkRules the virtualNetworkRules value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withVirtualNetworkRules(List<VirtualNetworkRule> virtualNetworkRules) {
this.virtualNetworkRules = virtualNetworkRules;
return this;
}
/**
* Get enables the account to write in multiple locations.
*
* @return the enableMultipleWriteLocations value
*/
public Boolean enableMultipleWriteLocations() {
return this.enableMultipleWriteLocations;
}
/**
* Set enables the account to write in multiple locations.
*
* @param enableMultipleWriteLocations the enableMultipleWriteLocations value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withEnableMultipleWriteLocations(Boolean enableMultipleWriteLocations) {
this.enableMultipleWriteLocations = enableMultipleWriteLocations;
return this;
}
/**
* Get enables the cassandra connector on the Cosmos DB C* account.
*
* @return the enableCassandraConnector value
*/
public Boolean enableCassandraConnector() {
return this.enableCassandraConnector;
}
/**
* Set enables the cassandra connector on the Cosmos DB C* account.
*
* @param enableCassandraConnector the enableCassandraConnector value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withEnableCassandraConnector(Boolean enableCassandraConnector) {
this.enableCassandraConnector = enableCassandraConnector;
return this;
}
/**
* Get the cassandra connector offer type for the Cosmos DB database C* account. Possible values include: 'Small'.
*
* @return the connectorOffer value
*/
public ConnectorOffer connectorOffer() {
return this.connectorOffer;
}
/**
* Set the cassandra connector offer type for the Cosmos DB database C* account. Possible values include: 'Small'.
*
* @param connectorOffer the connectorOffer value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withConnectorOffer(ConnectorOffer connectorOffer) {
this.connectorOffer = connectorOffer;
return this;
}
/**
* Get disable write operations on metadata resources (databases, containers, throughput) via account keys.
*
* @return the disableKeyBasedMetadataWriteAccess value
*/
public Boolean disableKeyBasedMetadataWriteAccess() {
return this.disableKeyBasedMetadataWriteAccess;
}
/**
* Set disable write operations on metadata resources (databases, containers, throughput) via account keys.
*
* @param disableKeyBasedMetadataWriteAccess the disableKeyBasedMetadataWriteAccess value to set
* @return the DatabaseAccountUpdateParameters object itself.
*/
public DatabaseAccountUpdateParameters withDisableKeyBasedMetadataWriteAccess(Boolean disableKeyBasedMetadataWriteAccess) {
this.disableKeyBasedMetadataWriteAccess = disableKeyBasedMetadataWriteAccess;
return this;
}
}
| {
"content_hash": "1ea99d7c15b793665f913b89e60aed01",
"timestamp": "",
"source": "github",
"line_count": 362,
"max_line_length": 273,
"avg_line_length": 34.853591160220994,
"alnum_prop": 0.7031782515653483,
"repo_name": "navalev/azure-sdk-for-java",
"id": "c05d2b5eb98675a29e8cb4dc3bdd34e86b96edae",
"size": "12847",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sdk/cosmosdb/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/cosmosdb/v2019_08_01/DatabaseAccountUpdateParameters.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "7230"
},
{
"name": "CSS",
"bytes": "5411"
},
{
"name": "Groovy",
"bytes": "1570436"
},
{
"name": "HTML",
"bytes": "29221"
},
{
"name": "Java",
"bytes": "250218562"
},
{
"name": "JavaScript",
"bytes": "15605"
},
{
"name": "PowerShell",
"bytes": "30924"
},
{
"name": "Python",
"bytes": "42119"
},
{
"name": "Shell",
"bytes": "1408"
}
],
"symlink_target": ""
} |
namespace AngleSharp
{
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Simple wrapper for static methods of Task, which are missing in older
/// versions of the .NET-Framework.
/// </summary>
static class TaskEx
{
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(params Task[] tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(IEnumerable<Task> tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.FromResult, but also works with .NET 4 and SL due
/// to same naming as TaskEx in BCL.Async.
/// </summary>
public static Task<TResult> FromResult<TResult>(TResult result)
{
return Task.FromResult(result);
}
}
}
| {
"content_hash": "479185cca9543ada22dace400d7f6c63",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 78,
"avg_line_length": 30.333333333333332,
"alnum_prop": 0.5680473372781065,
"repo_name": "Livven/AngleSharp",
"id": "d6a4e3ba619d943da9d658fdfbd191bde5797a6a",
"size": "1185",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "AngleSharp/Foundation/TaskEx.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "9473875"
},
{
"name": "HTML",
"bytes": "469943"
},
{
"name": "JavaScript",
"bytes": "75888"
},
{
"name": "PowerShell",
"bytes": "1003"
}
],
"symlink_target": ""
} |
package org.apache.flink.runtime.rest.handler.cluster;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.rest.handler.AbstractRestHandler;
import org.apache.flink.runtime.rest.handler.HandlerRequest;
import org.apache.flink.runtime.rest.messages.DashboardConfiguration;
import org.apache.flink.runtime.rest.messages.EmptyMessageParameters;
import org.apache.flink.runtime.rest.messages.EmptyRequestBody;
import org.apache.flink.runtime.rest.messages.MessageHeaders;
import org.apache.flink.runtime.webmonitor.RestfulGateway;
import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever;
import javax.annotation.Nonnull;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
/**
* Handler which returns the dashboard configuration.
*/
public class DashboardConfigHandler extends AbstractRestHandler<RestfulGateway, EmptyRequestBody, DashboardConfiguration, EmptyMessageParameters> {
private final DashboardConfiguration dashboardConfiguration;
public DashboardConfigHandler(
GatewayRetriever<? extends RestfulGateway> leaderRetriever,
Time timeout,
Map<String, String> responseHeaders,
MessageHeaders<EmptyRequestBody, DashboardConfiguration, EmptyMessageParameters> messageHeaders,
long refreshInterval,
boolean webSubmitEnabled) {
super(leaderRetriever, timeout, responseHeaders, messageHeaders);
dashboardConfiguration = DashboardConfiguration.from(refreshInterval, ZonedDateTime.now(), webSubmitEnabled);
}
@Override
public CompletableFuture<DashboardConfiguration> handleRequest(@Nonnull HandlerRequest<EmptyRequestBody, EmptyMessageParameters> request, @Nonnull RestfulGateway gateway) {
return CompletableFuture.completedFuture(dashboardConfiguration);
}
}
| {
"content_hash": "04165e2481ed12f5c928d3aa593a508a",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 173,
"avg_line_length": 40.65909090909091,
"alnum_prop": 0.840134153158189,
"repo_name": "sunjincheng121/flink",
"id": "312dc03e8c4923ed8f3b56c4f2282de8560017cf",
"size": "2594",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/cluster/DashboardConfigHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4588"
},
{
"name": "CSS",
"bytes": "57936"
},
{
"name": "Clojure",
"bytes": "93205"
},
{
"name": "Dockerfile",
"bytes": "10793"
},
{
"name": "FreeMarker",
"bytes": "17422"
},
{
"name": "HTML",
"bytes": "224462"
},
{
"name": "Java",
"bytes": "48828103"
},
{
"name": "JavaScript",
"bytes": "1829"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "809916"
},
{
"name": "Scala",
"bytes": "13394897"
},
{
"name": "Shell",
"bytes": "483872"
},
{
"name": "TypeScript",
"bytes": "243702"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel='shortcut icon' href='/img/favicon.ico' type='image/x-icon'>
<link rel='apple-touch-icon' href='/img/favicon-apple-57x57.png'>
<link rel='apple-touch-icon' sizes='72x72' href='/img/favicon-apple-72x72.png'>
<link rel='apple-touch-icon' sizes='114x114' href='/img/favicon-apple-114x114.png'>
<link href='http://fonts.googleapis.com/css?family=Titillium+Web:300,300italic,600,600italic|Alegreya:400italic,700italic,400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>
<link rel='stylesheet' href='/stylesheets/style.css'>
<title>Separando los hacks webcollage y bsod de XScreenSaver — GHOSTBAR</title>
</head>
<body>
<header id="header" class='container'>
<div class='row'>
<div id='logo' class='twocol'>
<a href=''><img src='/img/logo-128x128.png'></a>
</div> <!-- end of #logo -->
<div id='title' class='sixcol'>
<a href=''><h1 class='leaguegothic'>ghostbar</h1></a>
<p id='tagline'>Random thoughts on technology written by <a href='http://joseluisrivas.net/'>Jose Luis Rivas</a></p>
</div> <!-- end of #title -->
</div> <!-- end of .row -->
</header> <!-- end of #header.container -->
<div id='post' class='container'>
<div class='row container'>
<article class='twelvecol post'>
<header>
<h1>Separando los hacks webcollage y bsod de XScreenSaver</h1>
<div class='date'>
December 03, 2009
</div>
</header>
<div class='content'>
<p>Desde hace mucho tiempo se me había pedido que el hack o salvapantalla <code>webcollage</code> de <a href="http://jwz.org/xscreensaver/"><code>XScreenSaver</code></a> estuviese en un paquete separado en <a href="http://www.debian.org">Debian</a>. Las razones son muy simples: el salvapantalla lo que hace es descargar imágenes aleatorias desde Internet y la Internet siendo como es tiene pornografía por lo que, estando en un paquete estándar, siendo seleccionado por omisión y por ende pudiendo ser usado aleatoriamente en sitios de trabajo o donde hayan niños no era muy bonito el resultado.</p>
<p>Hace como un mes se empezaron a quejar igualmente del hack <code>bsod</code> que es una broma de pantallazos de error de varios sistemas operativos, desde Windows, Unix, Linux hasta HP/UX y Apple[] lo cuál toma a algunos usuarios por desprevenidos y sin saber lo que es podría llevarles a perder datos por reacciones normales de usuarios nóveles como reiniciar la máquina.</p>
<p>Esto me llevó a crear paquetes separados paquetes separados los cuáles serán <code>xscreensaver-screensaver-webcollage</code> y <code>xscreensaver-screensaver-bsod</code> una vez que hayan pasado a través de NEW la versión 5.10-4 que es la que tiene estos cambios.</p>
</div>
<footer>
<small>
<em>You should follow me on twitter <a href='http://twitter.com/ghostbar'>here</a></em>.
</small>
</footer>
</article>
</div> <!-- end .row -->
</div> <!-- end .container -->
<div class='clearfix'></div>
<footer id='footer' class='container'>
<div class='row'>
<div class='twelvecol last'>
<small>© 2012-2013, Jose Luis Rivas. Built with <a href='http://jekyllrb.com'>Jekyll</a> by <a href='http://joseluisrivas.net'>Jose Luis Rivas</a> from <a href='http://eserre.com'>Eserre</a>.</small>
<small class='pull-right'><a href='/feed.xml'>RSS</a></small>
</div> <!-- end of .twelvecol -->
</div> <!-- end of .row -->
</footer>
<div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1022716-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</div>
</body>
</html>
| {
"content_hash": "28cf838041fac9ad2684179f83aaeff7",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 608,
"avg_line_length": 39.027272727272724,
"alnum_prop": 0.6540880503144654,
"repo_name": "ghostbar/ghostbar.co",
"id": "9505b7861cbd9bdcdfc243c0068c4eadc6647550",
"size": "4309",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_site/2009/12/03/separando-los-hacks-webcollage-y-bsod-de-xscreensaver/index.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "29273"
},
{
"name": "CSS",
"bytes": "27530"
},
{
"name": "HTML",
"bytes": "894286"
},
{
"name": "JavaScript",
"bytes": "9751"
},
{
"name": "Makefile",
"bytes": "48"
},
{
"name": "Ruby",
"bytes": "1278"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#if UNITY_WP8 && !UNITY_EDITOR
using SoomlaWpCore.util;
using SoomlaWpCore.events;
#endif
namespace Soomla {
/// <summary>
/// This class provides functions for event handling.
/// </summary>
public class CoreEvents : MonoBehaviour {
#if UNITY_IOS && !UNITY_EDITOR
[DllImport ("__Internal")]
private static extern void soomlaCore_Init(string secret, [MarshalAs(UnmanagedType.Bool)] bool debug);
#endif
private const string TAG = "SOOMLA CoreEvents";
private static CoreEvents instance = null;
/// <summary>
/// Initializes game state before the game starts.
/// </summary>
void Awake(){
if(instance == null){ // making sure we only initialize one instance.
instance = this;
gameObject.name = "CoreEvents";
GameObject.DontDestroyOnLoad(this.gameObject);
Initialize();
} else { // Destroying unused instances.
GameObject.Destroy(this.gameObject);
}
}
public static void Initialize() {
SoomlaUtils.LogDebug(TAG, "Initializing CoreEvents and Soomla Core ...");
#if UNITY_ANDROID && !UNITY_EDITOR
AndroidJNI.PushLocalFrame(100);
using(AndroidJavaClass jniStoreConfigClass = new AndroidJavaClass("com.soomla.SoomlaConfig")) {
jniStoreConfigClass.SetStatic("logDebug", CoreSettings.DebugMessages);
}
// Initializing SoomlaEventHandler
using(AndroidJavaClass jniEventHandler = new AndroidJavaClass("com.soomla.core.unity.SoomlaEventHandler")) {
jniEventHandler.CallStatic("initialize");
}
// Initializing Soomla Secret
using(AndroidJavaClass jniSoomlaClass = new AndroidJavaClass("com.soomla.Soomla")) {
jniSoomlaClass.CallStatic("initialize", CoreSettings.SoomlaSecret);
}
AndroidJNI.PopLocalFrame(IntPtr.Zero);
#elif UNITY_IOS && !UNITY_EDITOR
soomlaCore_Init(CoreSettings.SoomlaSecret, CoreSettings.DebugMessages);
#elif UNITY_WP8 && !UNITY_EDITOR
SoomlaWpCore.SoomlaConfig.logDebug = CoreSettings.DebugMessages;
SoomlaWpCore.Soomla.initialize(CoreSettings.SoomlaSecret);
BusProvider.Instance.Register(CoreEvents.instance);
#endif
}
#if UNITY_WP8 && !UNITY_EDITOR
[Subscribe]
public void onRewardGiven(RewardGivenEvent _Event)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onRewardGiven:" + _Event.RewardId);
string rewardId = _Event.RewardId;
CoreEvents.OnRewardGiven(Reward.GetReward(rewardId));
}
[Subscribe]
public void onRewardTaken(RewardTakenEvent _Event) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onRewardTaken:" + _Event.RewardId);
string rewardId = _Event.RewardId;
CoreEvents.OnRewardTaken(Reward.GetReward(rewardId));
}
#endif
/// <summary>
/// Will be called when a reward was given to the user.
/// </summary>
/// <param name="message">Will contain a JSON representation of a <c>Reward</c> and a flag saying if it's a Badge or not.</param>
public void onRewardGiven(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onRewardGiven:" + message);
JSONObject eventJSON = new JSONObject(message);
string rewardId = eventJSON["rewardId"].str;
CoreEvents.OnRewardGiven(Reward.GetReward(rewardId));
}
/// <summary>
/// Will be called when a reward was given to the user.
/// </summary>
/// <param name="message">Will contain a JSON representation of a <c>Reward</c> and a flag saying if it's a Badge or not.</param>
public void onRewardTaken(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onRewardTaken:" + message);
JSONObject eventJSON = new JSONObject(message);
string rewardId = eventJSON["rewardId"].str;
CoreEvents.OnRewardTaken(Reward.GetReward(rewardId));
}
/// <summary>
/// Will be called on custom events. Used for internal operations.
/// </summary>
public void onCustomEvent(string message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onCustomEvent:" + message);
JSONObject eventJSON = new JSONObject(message);
string name = eventJSON["name"].str;
Dictionary<string, string> extra = eventJSON["extra"].ToDictionary();
CoreEvents.OnCustomEvent(name, extra);
}
public delegate void Action();
public static Action<Reward> OnRewardGiven = delegate {};
public static Action<Reward> OnRewardTaken = delegate {};
public static Action<string, Dictionary<string, string>> OnCustomEvent = delegate {};
}
}
| {
"content_hash": "cb0853eb0de759a97acca3c9e000ac8c",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 131,
"avg_line_length": 34.234848484848484,
"alnum_prop": 0.7145386147377738,
"repo_name": "Chanisco/SoomlaHandler",
"id": "8b40b307fe181152f53ebbc4867e57bf7fb7e560",
"size": "5131",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Assets/Plugins/Soomla/Core/CoreEvents.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "449368"
},
{
"name": "Python",
"bytes": "52194"
}
],
"symlink_target": ""
} |
const program = require('commander')
program
.version('0.1.0')
.command('init [name]', 'initialize')
.command('dev [name]', 'dev')
.command('build [name]', 'build')
.parse(process.argv)
| {
"content_hash": "bc6fa91875b46b959da8e0524451190c",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 37,
"avg_line_length": 20.88888888888889,
"alnum_prop": 0.6595744680851063,
"repo_name": "Terry-Su/MVVC",
"id": "7fabbf6ae647ee541a389628ace5e2947fabf9c2",
"size": "209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bin/mvvc.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2166"
},
{
"name": "JavaScript",
"bytes": "3897400"
}
],
"symlink_target": ""
} |
function CouetteFlow( varargin )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
close all; % closes all figures
addpath('../Functions');
h=4; % height of the channel
U=10; % velocity of the moving surface
dPdx=0; % pressure gradient in x direction
mu=0.001; % dynamic viscosity
% function for the analytical solution
u_analFunc=@(y) y./h.*(U-h.^2./(2*mu).*dPdx.*(1-y/h));
% create mesh
m=createMesh2D(8,8,2*h,h);
%% Boundary Conditions
U_BC = createBC(m); % all Neumann boundary condition structure
% Assign boundary conditions
U_BC.left.a(:) = 1; U_BC.left.b(:)=0; U_BC.left.c(:)=0; % Dirichlet for the left boundary
U_BC.right.a(:) = 1; U_BC.right.b(:)=0; U_BC.right.c(:)=0; % Dirichlet for the left boundary
U_BC.top.a(:) = 0; U_BC.top.b(:)=1; U_BC.top.c(:)=U; % Dirichlet for the left boundary
U_BC.bottom.a(:) = 0; U_BC.bottom.b(:)=1; U_BC.bottom.c(:)=0; % Dirichlet for the left boundary
V_BC = createBC(m); % all Neumann boundary condition structure
% Assign boundary conditions
V_BC.top.a(:) = 0; V_BC.top.b(:)=1; V_BC.top.c(:)=0; % Dirichlet for the left boundary
V_BC.bottom.a(:) = 0; V_BC.bottom.b(:)=1; V_BC.bottom.c(:)=0; % Dirichlet for the left boundary
V_BC.left.a(:) = 0; V_BC.left.b(:)=1; V_BC.left.c(:)=0; % Dirichlet for the left boundary
V_BC.right.a(:) = 0; V_BC.right.b(:)=1; V_BC.right.c(:)=0; % Dirichlet for the left boundary
BC_pressureCorrection = createBC(m);
BC_pressureCorrection.left.a(:) = 1; BC_pressureCorrection.left.b(:)=0; BC_pressureCorrection.left.c(:)=0;
BC_pressureCorrection.right.a(:) = 1; BC_pressureCorrection.right.b(:)=0; BC_pressureCorrection.right.c(:)=0;
BC_pressureCorrection.bottom.a(:) = 1; BC_pressureCorrection.bottom.b(:)=0; BC_pressureCorrection.bottom.c(:)=0;
BC_pressureCorrection.bottom.a(end/2) = 0; BC_pressureCorrection.bottom.b(end/2)=1; BC_pressureCorrection.bottom.c(end/2)=1;
BC_pressureCorrection.top.a(:) = 1; BC_pressureCorrection.top.b(:)=0; BC_pressureCorrection.top.c(:)=0;
% constant pressure - so there is no gradient
p_cellVar=createCellVariable(m,1,BC_pressureCorrection);
mu_faceVar=createFaceVariable(m,0.001);
rho=1000;
pGradMat = gradientCellTerm(p_cellVar);
faceVelocity=createFaceVariable(m,[0 0]);
U_cellVar=createCellVariable(m,0,U_BC);
V_cellVar=createCellVariable(m,0,V_BC);
% solve momentum equation Momentum equation
[U_cellVar,~,~,~]=MomentumEq(1,m,pGradMat,mu_faceVar,faceVelocity,U_cellVar,V_cellVar,U_BC,V_BC,rho,'SIMPLE');
y_anal=linspace(0,h,100);
u_anal=u_analFunc(y_anal);
figure;
plot(u_anal,y_anal); % plot analytical solution
hold on;
plot(U_cellVar.value(3,2:end-1),U_cellVar.domain.cellcenters.y,'o');
hold off;
figure;
visualizeCells(U_cellVar);
end
| {
"content_hash": "3944964844b94bc073327c4ec2a38fd7",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 124,
"avg_line_length": 38.785714285714285,
"alnum_prop": 0.7027624309392265,
"repo_name": "KaiSchu/FVTool",
"id": "cedc765b176b7779cd80e84949243631b86c7656",
"size": "2715",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Examples/External/SteadyLidDrivenCavityProblem/Testcases/CouetteFlow.m",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Matlab",
"bytes": "861200"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _09_Longer_Line
{
class Program
{
static void Main(string[] args)
{
//40 out of 100, logic is correct though!
decimal xOne = decimal.Parse(Console.ReadLine());
decimal yOne = decimal.Parse(Console.ReadLine());
decimal xTwo = decimal.Parse(Console.ReadLine());
decimal yTwo = decimal.Parse(Console.ReadLine());
decimal xThree = decimal.Parse(Console.ReadLine());
decimal yThree = decimal.Parse(Console.ReadLine());
decimal xFour = decimal.Parse(Console.ReadLine());
decimal yFour = decimal.Parse(Console.ReadLine());
decimal topSum, botSum, thirdSum, fourthSum;
BiggerMethod(xOne, yOne, xTwo, yTwo, out topSum, out botSum);
BiggerMethod(xThree, yThree, xFour, yFour, out thirdSum, out fourthSum);
if (topSum + botSum >= thirdSum + fourthSum)
{
if (topSum > botSum)
{
PrintOutput(xOne, yOne, xTwo, yTwo);
}
else if (botSum > topSum)
{
PrintOutput(xTwo, yTwo, xOne, yOne);
}
}
else if (thirdSum + fourthSum > topSum + botSum)
{
if (thirdSum < fourthSum)
{
PrintOutput(xFour, yFour, xThree, yThree);
}
else if (fourthSum < thirdSum)
{
PrintOutput(xThree, yThree, xFour, yFour);
}
}
}
private static void PrintOutput(decimal xOne, decimal yOne, decimal xTwo, decimal yTwo)
{
Console.WriteLine($"({xTwo}, {yTwo})({xOne}, {yOne})");
}
private static void BiggerMethod(decimal xOne, decimal yOne, decimal xTwo, decimal yTwo, out decimal topSum, out decimal botSum)
{
topSum = Math.Abs(xOne) + Math.Abs(yOne);
botSum = Math.Abs(xTwo) + Math.Abs(yTwo);
}
}
} | {
"content_hash": "327e431bd3560f48c7b3072e3b635389",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 136,
"avg_line_length": 34.390625,
"alnum_prop": 0.5252158109950023,
"repo_name": "Bullsized/Assignments-Fundamentals-Normal",
"id": "e77a6eb4f7bd590942b1422379e2a5b791852ec4",
"size": "2203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "13 - 14 Methods and Debug/2017-06-06/09 Longer Line/09 Longer Line.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "780228"
}
],
"symlink_target": ""
} |
package com.hazelcast.test.starter;
import com.hazelcast.test.starter.HazelcastProxyFactory.ProxyPolicy;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Annotation for constructor classes for {@link HazelcastProxyFactory}.
* <p>
* The annotated classes have to be in the package
* {@code com.hazelcast.test.starter.constructor} to be registered.
*/
@Retention(value = RUNTIME)
@Target(TYPE)
public @interface HazelcastStarterConstructor {
/**
* The class names which this constructor class constructs.
*
* @return the supported class names
*/
String[] classNames() default "";
/**
* The {@link ProxyPolicy} the supported classes should use.
* <p>
* Note: Classes which use {@link ProxyPolicy#NO_PROXY} have to implement
* {@link com.hazelcast.util.ConstructorFunction}. Classes which use
* {@link ProxyPolicy#SUBCLASS_PROXY} can be an empty class.
*
* @return the {@link ProxyPolicy} of the supported classes
*/
ProxyPolicy proxyPolicy() default ProxyPolicy.NO_PROXY;
}
| {
"content_hash": "fc7e9b700208e7f73b47957cbb108abd",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 77,
"avg_line_length": 30.125,
"alnum_prop": 0.7203319502074689,
"repo_name": "dsukhoroslov/hazelcast",
"id": "1e2926ce5210bb11766549a1dbce0eac97983a53",
"size": "1830",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "hazelcast/src/test/java/com/hazelcast/test/starter/HazelcastStarterConstructor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "948"
},
{
"name": "Java",
"bytes": "29443040"
},
{
"name": "Shell",
"bytes": "12217"
}
],
"symlink_target": ""
} |
package org.apache.lucene.xmlparser;
import java.io.*;
import junit.framework.TestCase;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
public class TestParser extends TestCase {
CoreParser builder;
static Directory dir;
Analyzer analyzer=new StandardAnalyzer();
IndexReader reader;
private IndexSearcher searcher;
//CHANGE THIS TO SEE OUTPUT
boolean printResults=false;
/*
* @see TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
//initialize the parser
builder=new CorePlusExtensionsParser("contents",analyzer);
//initialize the index (done once, then cached in static data for use with ALL tests)
if(dir==null)
{
BufferedReader d = new BufferedReader(new InputStreamReader(TestParser.class.getResourceAsStream("reuters21578.txt")));
dir=new RAMDirectory();
IndexWriter writer=new IndexWriter(dir,analyzer,true);
String line = d.readLine();
while(line!=null)
{
int endOfDate=line.indexOf('\t');
String date=line.substring(0,endOfDate).trim();
String content=line.substring(endOfDate).trim();
org.apache.lucene.document.Document doc =new org.apache.lucene.document.Document();
doc.add(new Field("date",date,Field.Store.YES,Field.Index.ANALYZED));
doc.add(new Field("contents",content,Field.Store.YES,Field.Index.ANALYZED));
writer.addDocument(doc);
line=d.readLine();
}
d.close();
writer.close();
}
reader=IndexReader.open(dir);
searcher=new IndexSearcher(reader);
}
protected void tearDown() throws Exception {
reader.close();
searcher.close();
// dir.close();
}
public void testSimpleXML() throws ParserException, IOException
{
Query q=parse("TermQuery.xml");
dumpResults("TermQuery", q, 5);
}
public void testSimpleTermsQueryXML() throws ParserException, IOException
{
Query q=parse("TermsQuery.xml");
dumpResults("TermsQuery", q, 5);
}
public void testBooleanQueryXML() throws ParserException, IOException
{
Query q=parse("BooleanQuery.xml");
dumpResults("BooleanQuery", q, 5);
}
public void testRangeFilterQueryXML() throws ParserException, IOException
{
Query q=parse("RangeFilterQuery.xml");
dumpResults("RangeFilter", q, 5);
}
public void testUserQueryXML() throws ParserException, IOException
{
Query q=parse("UserInputQuery.xml");
dumpResults("UserInput with Filter", q, 5);
}
public void testCustomFieldUserQueryXML() throws ParserException, IOException
{
Query q=parse("UserInputQueryCustomField.xml");
Hits h = searcher.search(q);
assertEquals("UserInputQueryCustomField should produce 0 result ", 0,h.length());
}
public void testLikeThisQueryXML() throws Exception
{
Query q=parse("LikeThisQuery.xml");
dumpResults("like this", q, 5);
}
public void testBoostingQueryXML() throws Exception
{
Query q=parse("BoostingQuery.xml");
dumpResults("boosting ",q, 5);
}
public void testFuzzyLikeThisQueryXML() throws Exception
{
Query q=parse("FuzzyLikeThisQuery.xml");
//show rewritten fuzzyLikeThisQuery - see what is being matched on
if(printResults)
{
System.out.println(q.rewrite(reader));
}
dumpResults("FuzzyLikeThis", q, 5);
}
public void testTermsFilterXML() throws Exception
{
Query q=parse("TermsFilterQuery.xml");
dumpResults("Terms Filter",q, 5);
}
public void testBoostingTermQueryXML() throws Exception
{
Query q=parse("BoostingTermQuery.xml");
dumpResults("BoostingTermQuery",q, 5);
}
public void testSpanTermXML() throws Exception
{
Query q=parse("SpanQuery.xml");
dumpResults("Span Query",q, 5);
}
public void testConstantScoreQueryXML() throws Exception
{
Query q=parse("ConstantScoreQuery.xml");
dumpResults("ConstantScoreQuery",q, 5);
}
public void testMatchAllDocsPlusFilterXML() throws ParserException, IOException
{
Query q=parse("MatchAllDocsQuery.xml");
dumpResults("MatchAllDocsQuery with range filter", q, 5);
}
public void testBooleanFilterXML() throws ParserException, IOException
{
Query q=parse("BooleanFilter.xml");
dumpResults("Boolean filter", q, 5);
}
public void testNestedBooleanQuery() throws ParserException, IOException
{
Query q=parse("NestedBooleanQuery.xml");
dumpResults("Nested Boolean query", q, 5);
}
public void testCachedFilterXML() throws ParserException, IOException
{
Query q=parse("CachedFilter.xml");
dumpResults("Cached filter", q, 5);
}
public void testDuplicateFilterQueryXML() throws ParserException, IOException
{
Query q=parse("DuplicateFilterQuery.xml");
Hits h = searcher.search(q);
assertEquals("DuplicateFilterQuery should produce 1 result ", 1,h.length());
}
//================= Helper methods ===================================
private Query parse(String xmlFileName) throws ParserException, IOException
{
InputStream xmlStream=TestParser.class.getResourceAsStream(xmlFileName);
Query result=builder.parse(xmlStream);
xmlStream.close();
return result;
}
private void dumpResults(String qType,Query q, int numDocs) throws IOException
{
Hits h = searcher.search(q);
assertTrue(qType +" should produce results ", h.length()>0);
if(printResults)
{
System.out.println("========="+qType+"============");
for(int i=0;i<Math.min(numDocs,h.length());i++)
{
org.apache.lucene.document.Document ldoc=h.doc(i);
System.out.println("["+ldoc.get("date")+"]"+ldoc.get("contents"));
}
System.out.println();
}
}
}
| {
"content_hash": "321184c65fef1ed0986f5ec2ba35b3f0",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 123,
"avg_line_length": 29.10891089108911,
"alnum_prop": 0.7183673469387755,
"repo_name": "Photobucket/Solbase-Lucene",
"id": "88dc76217a8ea4264ae5acece8c82f12f6052e32",
"size": "6682",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "contrib/xml-query-parser/src/test/org/apache/lucene/xmlparser/TestParser.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9882222"
},
{
"name": "JavaScript",
"bytes": "43988"
},
{
"name": "Perl",
"bytes": "32431"
},
{
"name": "Shell",
"bytes": "1183"
}
],
"symlink_target": ""
} |
/*
* DBListRenderer.java
*
* Created on 26 May 2007, 02:07
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package generator.gui.db;
import generator.misc.Constants;
import generator.misc.DBDriverInfo;
import generator.misc.Utils;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
class DBListDriverInfoRenderer extends JLabel implements ListCellRenderer
{
/**
*
*/
private static final long serialVersionUID = 1570989729341695670L;
ImageIcon iconOK;
ImageIcon iconError;
Utils utils;
public DBListDriverInfoRenderer()
{
utils = new Utils();
iconOK = utils.createImageIcon("generator/images/no-error.png");
iconError = utils.createImageIcon("generator/images/error.png");
}
// This is the only method defined by ListCellRenderer.
// We just reconfigure the JLabel each time we're called.
public Component getListCellRendererComponent(
JList list,
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // the list and the cell have the focus
{
DBDriverInfo dbInfo = (DBDriverInfo) value;
setText(dbInfo.toString());
if(dbInfo.getStatus()==Constants.DRIVER_OK)
setIcon(iconOK);
else if(dbInfo.getStatus()==Constants.DRIVER_NOT_OK)
setIcon(iconError);
if (isSelected)
{
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else
{
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
return this;
}
}
| {
"content_hash": "9f63338eeacee82c8709355507ae61b2",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 76,
"avg_line_length": 28.205479452054796,
"alnum_prop": 0.6304031083050025,
"repo_name": "tchico/dgMaster-trunk",
"id": "6caf925d10d8aa51b91bf2027068b4f6befcfa93",
"size": "2059",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/generator/gui/db/DBListDriverInfoRenderer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "672"
},
{
"name": "Java",
"bytes": "1416753"
}
],
"symlink_target": ""
} |
<?php
namespace test\WArslett\TweetSync\Remote;
use Mockery as m;
use WArslett\TweetSync\Remote\TweetSync;
class TweetSyncTest extends \PHPUnit_Framework_TestCase
{
public function testSyncAllForUser_CallsFindByTwitterUserOnce()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$remote = $this->remoteWithResponseForUser($userObj);
$sync = new TweetSync(
$remote,
$this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
),
m::mock('\WArslett\TweetSync\Model\TweetFactory'),
$this->userFactory($twitterUser)
);
$sync->syncAllForUser($userObj->screen_name);
$remote->shouldHaveReceived('findByTwitterUser')->once()->with($userObj->screen_name);
}
public function testSyncAllForUser_CallsRemoteFindTwitterUserOnce()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$remote = $this->remoteWithResponseForUser($userObj);
$sync = new TweetSync(
$remote,
$this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
),
m::mock('\WArslett\TweetSync\Model\TweetFactory'),
$this->userFactory($twitterUser)
);
$sync->syncAllForUser($userObj->screen_name);
$remote->shouldHaveReceived('findTwitterUser')->once()->with($userObj->screen_name);
}
public function testSyncAllForUser_CallsTwitterUserRepositoryFindOnce()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$sync = new TweetSync(
$remote,
$this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
),
m::mock('\WArslett\TweetSync\Model\TweetFactory'),
$this->userFactory($twitterUser)
);
$sync->syncAllForUser($userObj->screen_name);
$twitterUserRepository->shouldHaveReceived('find')->once()->with($userObj->id_str);
}
public function testSyncAllForUser_DoesNotCreateNewTwitterUser_TwitterUserExists()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns($twitterUser);
$userFactory = $this->userFactory();
$persistence = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
);
$sync = new TweetSync(
$remote,
$persistence,
m::mock('\WArslett\TweetSync\Model\TweetFactory'),
$userFactory
);
$sync->syncAllForUser($userObj->screen_name);
$userFactory->shouldNotHaveReceived('buildFromStdObj');
$persistence->shouldNotHaveReceived('persistTwitterUser');
}
public function testSyncAllForUser_PatchesExistingTwitterUser_TwitterUserExists()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns($twitterUser);
$userFactory = $this->userFactory();
$persistence = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
);
$sync = new TweetSync(
$remote,
$persistence,
m::mock('\WArslett\TweetSync\Model\TweetFactory'),
$userFactory
);
$sync->syncAllForUser($userObj->screen_name);
$userFactory->shouldHaveReceived('patchFromStdObj')->once()->with($twitterUser, $userObj);
}
public function testSyncAllForUser_ensuresTwitterUserUpdated_TwitterUserExists()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns($twitterUser);
$userFactory = $this->userFactory();
$persistence = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
);
$sync = new TweetSync(
$remote,
$persistence,
m::mock('\WArslett\TweetSync\Model\TweetFactory'),
$userFactory
);
$sync->syncAllForUser($userObj->screen_name);
$persistence->shouldHaveReceived('ensureTwitterUserUpdated')->once()->with($twitterUser);
}
public function testSyncAllForUser_DoesNotPatch_NewTwitterUser()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$userFactory = $this->userFactory($twitterUser);
$sync = new TweetSync(
$remote,
$this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
),
m::mock('\WArslett\TweetSync\Model\TweetFactory'),
$userFactory
);
$sync->syncAllForUser($userObj->screen_name);
$userFactory->shouldNotHaveReceived('patchFromStdObj');
}
public function testSyncAllForUser_CallsUserFactoryBuildFromStdObj_NewTwitterUser()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$userFactory = $this->userFactory($twitterUser);
$sync = new TweetSync(
$remote,
$this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
),
m::mock('\WArslett\TweetSync\Model\TweetFactory'),
$userFactory
);
$sync->syncAllForUser($userObj->screen_name);
$userFactory->shouldHaveReceived('buildFromStdObj')->once()->with($userObj);
}
public function testSyncAllForUser_PersistsNewTwitterUser_NewTwitterUser()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$userFactory = $this->userFactory($twitterUser);
$persistence = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
);
$sync = new TweetSync(
$remote,
$persistence,
m::mock('\WArslett\TweetSync\Model\TweetFactory'),
$userFactory
);
$sync->syncAllForUser($userObj->screen_name);
$persistence->shouldHaveReceived('persistTwitterUser')->once()->with($twitterUser);
}
public function testSyncAllForUser_DoesNotCallBuildFromStdObj_ForUserWithNoTweets()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$factory = m::mock('\WArslett\TweetSync\Model\TweetFactory');
$sync = new TweetSync(
$remote,
$this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
),
$factory,
$this->userFactory($twitterUser)
);
$sync->syncAllForUser($userObj->screen_name);
$factory->shouldNotHaveReceived('buildFromStdObj');
}
public function testSyncAllForUser_CallsTweetRepositoryFindOnce_ForUserWithOneNewTweet()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$tweetId = '657921145627394048';
$remote = $this->remoteWithResponseForUser($userObj, [$this->tweetObj($tweetId)]);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$factory = m::mock('\WArslett\TweetSync\Model\TweetFactory');
$factory->shouldReceive('buildFromStdObj')->andReturn(m::mock('\WArslett\TweetSync\Model\Tweet'));
$tweetRepository = $this->tweetRepositoryReturns([$tweetId => null]);
$persistenceService = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$tweetRepository
);
$persistenceService->shouldReceive('persistTweet');
$sync = new TweetSync(
$remote,
$persistenceService,
$factory,
$this->userFactory($twitterUser)
);
$sync->syncAllForUser($userObj->screen_name);
$tweetRepository->shouldHaveReceived('find')->with($tweetId)->once();
}
public function testSyncAllForUser_CallsTweetRepositoryFindTwice_ForUserWithTwoNewTweets()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj, $this->arrayOfXNoOfObjects(2));
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$factory = m::mock('\WArslett\TweetSync\Model\TweetFactory');
$factory->shouldReceive('buildFromStdObj')->andReturn(m::mock('\WArslett\TweetSync\Model\Tweet'));
$tweetRepository = $this->tweetRepositoryReturns();
$persistenceService = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$tweetRepository
);
$persistenceService->shouldReceive('persistTweet');
$sync = new TweetSync(
$remote,
$persistenceService,
$factory,
$this->userFactory($twitterUser)
);
$sync->syncAllForUser($userObj->screen_name);
$tweetRepository->shouldHaveReceived('find')->twice();
}
public function testSyncAllForUser_DoesNotBuildNewTweet_ForUserWithOneExistingTweet()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$tweetId = '657921145627394048';
$remote = $this->remoteWithResponseForUser($userObj, [$this->tweetObj($tweetId)]);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns($twitterUser);
$factory = m::mock('\WArslett\TweetSync\Model\TweetFactory');
$factory->shouldReceive('patchFromStdObj');
$tweetRepository = $this->tweetRepositoryReturns(
[$tweetId => m::mock('\WArslett\TweetSync\Model\Tweet')]
);
$persistenceService = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$tweetRepository
);
$sync = new TweetSync(
$remote,
$persistenceService,
$factory,
$this->userFactory()
);
$sync->syncAllForUser($userObj->screen_name);
$factory->shouldNotHaveReceived('buildFromStdObj');
$persistenceService->shouldNotHaveReceived('persistTweet');
}
public function testSyncAllForUser_PatchesExistingTweet_ForUserWithOneExistingTweet()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$tweetId = '657921145627394048';
$tweetObj = $this->tweetObj($tweetId);
$tweet = m::mock('\WArslett\TweetSync\Model\Tweet');
$remote = $this->remoteWithResponseForUser($userObj, [$tweetObj]);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns($twitterUser);
$factory = m::mock('\WArslett\TweetSync\Model\TweetFactory');
$factory->shouldReceive('patchFromStdObj');
$tweetRepository = $this->tweetRepositoryReturns(
[$tweetId => $tweet]
);
$persistenceService = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$tweetRepository
);
$sync = new TweetSync(
$remote,
$persistenceService,
$factory,
$this->userFactory()
);
$sync->syncAllForUser($userObj->screen_name);
$factory->shouldHaveReceived('patchFromStdObj')->with($tweet, $tweetObj);
}
public function testSyncAllForUser_ensuresTweetUpdated_ForUserWithOneExistingTweet()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$tweetId = '657921145627394048';
$tweetObj = $this->tweetObj($tweetId);
$tweet = m::mock('\WArslett\TweetSync\Model\Tweet');
$remote = $this->remoteWithResponseForUser($userObj, [$tweetObj]);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns($twitterUser);
$factory = m::mock('\WArslett\TweetSync\Model\TweetFactory');
$factory->shouldReceive('patchFromStdObj');
$tweetRepository = $this->tweetRepositoryReturns(
[$tweetId => $tweet]
);
$persistenceService = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$tweetRepository
);
$sync = new TweetSync(
$remote,
$persistenceService,
$factory,
$this->userFactory()
);
$sync->syncAllForUser($userObj->screen_name);
$persistenceService->shouldHaveReceived('ensureTweetUpdated')->with($tweet);
}
public function testSyncAllForUser_CallsBuildFromStdObjOnce_ForUserWithOneNewTweets()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj, $this->arrayOfXNoOfObjects(1));
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$factory = m::mock('\WArslett\TweetSync\Model\TweetFactory');
$factory->shouldReceive('buildFromStdObj')->andReturn(m::mock('\WArslett\TweetSync\Model\Tweet'));
$persistenceService = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
);
$persistenceService->shouldReceive('persistTweet');
$sync = new TweetSync(
$remote,
$persistenceService,
$factory,
$this->userFactory($twitterUser)
);
$sync->syncAllForUser($userObj->screen_name);
$factory->shouldHaveReceived('buildFromStdObj')->once();
}
public function testSyncAllForUser_PersistsOneTweet_ForUserWithOneNewTweets()
{
$userObj = new \stdClass();
$userObj->screen_name = 'foo';
$userObj->id_str = '5402612';
$remote = $this->remoteWithResponseForUser($userObj, $this->arrayOfXNoOfObjects(1));
$tweet = m::mock('\WArslett\TweetSync\Model\Tweet');
$factory = m::mock('\WArslett\TweetSync\Model\TweetFactory');
$factory->shouldReceive('buildFromStdObj')->andReturn($tweet);
$twitterUserRepository = $this->twitterUserRepositoryReturns(null);
$twitterUser = m::mock('\WArslett\TweetSync\Model\TwitterUser');
$persistenceService = $this->persistenceService(
$twitterUser,
$twitterUserRepository,
$this->tweetRepositoryReturns()
);
$persistenceService->shouldReceive('persistTweet')->with($tweet);
$sync = new TweetSync(
$remote,
$persistenceService,
$factory,
$this->userFactory($twitterUser)
);
$sync->syncAllForUser($userObj->screen_name);
$persistenceService->shouldHaveReceived('persistTweet')->once()->with($tweet);
}
private function arrayOfXNoOfObjects($x)
{
$objects = array();
while (count($objects)<$x) {
$objects[] = $this->tweetObj();
}
return $objects;
}
private function remoteWithResponseForUser($userObj, $response = [])
{
$mock = m::mock('\WArslett\TweetSync\Remote\RemoteService');
$mock->shouldReceive('findByTwitterUser')->with($userObj->screen_name)->andReturn($response);
$mock->shouldReceive('findTwitterUser')->with($userObj->screen_name)->andReturn($userObj);
return $mock;
}
private function userFactory($return = null)
{
$mock = m::mock('\WArslett\TweetSync\Model\TwitterUserFactory');
if (!is_null($return)) {
$mock->shouldReceive('buildFromStdObj')->andReturn($return);
} else {
$mock->shouldReceive('patchFromStdObj')->withAnyArgs();
}
return $mock;
}
private function persistenceService($expect, $twitterUserRepository, $tweetRepository)
{
$mock = m::mock('\WArslett\TweetSync\Model\TweetPersistenceService');
$mock->shouldReceive('persistTwitterUser')->with($expect);
$mock->shouldReceive('getTwitterUserRepository')->andReturn($twitterUserRepository);
$mock->shouldReceive('getTweetRepository')->andReturn($tweetRepository);
$mock->shouldReceive('ensureTwitterUserUpdated')->with($expect);
$mock->shouldReceive('ensureTweetUpdated');
return $mock;
}
private function twitterUserRepositoryReturns($user)
{
$mock = m::mock('\WArslett\TweetSync\Model\TwitterUserRepository');
$mock->shouldReceive('find')->andReturn($user);
return $mock;
}
private function tweetRepositoryReturns($tweets = [])
{
$mock = m::mock('\WArslett\TweetSync\Model\TweetRepository');
$mock->shouldReceive('find')->with(null)->andReturnNull();
foreach ($tweets as $id => $tweet) {
$mock->shouldReceive('find')->with($id)->andReturn($tweet);
}
return $mock;
}
private function tweetObj($id = null)
{
$obj = new \stdClass();
$obj->id_str = $id;
return $obj;
}
}
| {
"content_hash": "8f4d77c599c9c25eef8853d841ee0c1c",
"timestamp": "",
"source": "github",
"line_count": 540,
"max_line_length": 106,
"avg_line_length": 37.80740740740741,
"alnum_prop": 0.6101097178683386,
"repo_name": "warslett/TweetSync",
"id": "879681d9c60f99215f2c1e154a349d45bc75cd10",
"size": "20416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/Remote/TweetSyncTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "39824"
}
],
"symlink_target": ""
} |
/*
** This file contains compatibilty wrapper header for things that used
** to be generated from mach/sync.defs. Now that code is split into two
** different interface generator files, so include the two resulting
** headers here.
*/
#include <mach/semaphore.h>
#include <mach/lock_set.h>
| {
"content_hash": "20f1491374cf5516551c842b0c99a793",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 72,
"avg_line_length": 32.44444444444444,
"alnum_prop": 0.75,
"repo_name": "jmpews/HookZz",
"id": "b3057205a092aae2c08d83e14859054895065b09",
"size": "1621",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "builtin-plugin/SupervisorCallMonitor/XnuInternal/mach/sync.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "3566"
},
{
"name": "C",
"bytes": "81640"
},
{
"name": "C++",
"bytes": "883443"
},
{
"name": "CMake",
"bytes": "44952"
},
{
"name": "Objective-C",
"bytes": "853"
},
{
"name": "Shell",
"bytes": "1059"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>metacoq-template: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">dev / metacoq-template - 1.0~beta2+8.13</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
metacoq-template
<small>
1.0~beta2+8.13
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-29 02:01:24 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-29 02:01:24 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq dev Formal proof management system
dune 3.0.3 Fast, portable, and opinionated build system
ocaml 4.11.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.11.2 Official release 4.11.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "matthieu.sozeau@inria.fr"
homepage: "https://metacoq.github.io/metacoq"
dev-repo: "git+https://github.com/MetaCoq/metacoq.git#coq-8.13"
bug-reports: "https://github.com/MetaCoq/metacoq/issues"
authors: ["Abhishek Anand <aa755@cs.cornell.edu>"
"Simon Boulier <simon.boulier@inria.fr>"
"Cyril Cohen <cyril.cohen@inria.fr>"
"Yannick Forster <forster@ps.uni-saarland.de>"
"Fabian Kunze <fkunze@fakusb.de>"
"Gregory Malecha <gmalecha@gmail.com>"
"Matthieu Sozeau <matthieu.sozeau@inria.fr>"
"Nicolas Tabareau <nicolas.tabareau@inria.fr>"
"Théo Winterhalter <theo.winterhalter@inria.fr>"
]
license: "MIT"
build: [
["sh" "./configure.sh"]
[make "-j" "%{jobs}%" "template-coq"]
]
install: [
[make "-C" "template-coq" "install"]
]
depends: [
"ocaml" {>= "4.07.1"}
"coq" {>= "8.13" & < "8.14~"}
"coq-equations" { >= "1.2.3" }
]
synopsis: "A quoting and unquoting library for Coq in Coq"
description: """
MetaCoq is a meta-programming framework for Coq.
Template Coq is a quoting library for Coq. It takes Coq terms and
constructs a representation of their syntax tree as a Coq inductive data
type. The representation is based on the kernel's term representation.
In addition to a complete reification and denotation of CIC terms,
Template Coq includes:
- Reification of the environment structures, for constant and inductive declarations.
- Denotation of terms and global declarations
- A monad for manipulating global declarations, calling the type
checker, and inserting them in the global environment, in the style of
MetaCoq/MTac.
"""
url {
src: "https://github.com/MetaCoq/metacoq/archive/v1.0-beta2-8.13.tar.gz"
checksum: "sha256=15e1cfde70e6c4dbf33bff1a77266ac5c0c3e280586ef059e0cdec07bee814f2"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-metacoq-template.1.0~beta2+8.13 coq.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is dev).
The following dependencies couldn't be met:
- coq-metacoq-template -> coq < 8.14~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq-template.1.0~beta2+8.13</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "bd829e03865fb12c9932cfc5c446bddf",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 159,
"avg_line_length": 43.22872340425532,
"alnum_prop": 0.568598498831057,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "d01d65b9fec6dce481eba026ba048e34ccc276cd",
"size": "8153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.11.2-2.0.7/extra-dev/dev/metacoq-template/1.0~beta2+8.13.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Rickshaw.namespace('Rickshaw.Series.FixedDuration');
Rickshaw.Series.FixedDuration = Rickshaw.Class.create(Rickshaw.Series, {
initialize: function (data, palette, options) {
options = options || {};
if (typeof(options.timeInterval) === 'undefined') {
throw new Error('FixedDuration series requires timeInterval');
}
if (typeof(options.maxDataPoints) === 'undefined') {
throw new Error('FixedDuration series requires maxDataPoints');
}
this.palette = new Rickshaw.Color.Palette(palette);
this.timeBase = typeof(options.timeBase) === 'undefined' ? Math.floor(new Date().getTime() / 1000) : options.timeBase;
this.setTimeInterval(options.timeInterval);
if (this[0] && this[0].data && this[0].data.length) {
this.currentSize = this[0].data.length;
this.currentIndex = this[0].data.length;
} else {
this.currentSize = 0;
this.currentIndex = 0;
}
this.maxDataPoints = options.maxDataPoints;
if (data && (typeof(data) == "object") && Array.isArray(data)) {
data.forEach( function (item) { this.addItem(item) }, this );
this.currentSize += 1;
this.currentIndex += 1;
}
// reset timeBase for zero-filled values if needed
this.timeBase -= (this.maxDataPoints - this.currentSize) * this.timeInterval;
// zero-fill up to maxDataPoints size if we don't have that much data yet
if ((typeof(this.maxDataPoints) !== 'undefined') && (this.currentSize < this.maxDataPoints)) {
for (var i = this.maxDataPoints - this.currentSize - 1; i > 1; i--) {
this.currentSize += 1;
this.currentIndex += 1;
this.forEach( function (item) {
item.data.unshift({ x: ((i-1) * this.timeInterval || 1) + this.timeBase, y: 0, i: i });
}, this );
}
}
},
addData: function($super, data, x) {
$super(data, x);
this.currentSize += 1;
this.currentIndex += 1;
if (this.maxDataPoints !== undefined) {
while (this.currentSize > this.maxDataPoints) {
this.dropData();
}
}
},
dropData: function() {
this.forEach(function(item) {
item.data.splice(0, 1);
} );
this.currentSize -= 1;
},
getIndex: function () {
return this.currentIndex;
},
setTime: function(){
return
}
} );
| {
"content_hash": "741ec218bf275a83d059211e60235abc",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 120,
"avg_line_length": 26.13095238095238,
"alnum_prop": 0.6492027334851936,
"repo_name": "benhuang21828/System-perfomance-graph",
"id": "01fd9ed38e147807d875a202968153bf009c0a78",
"size": "2195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/live_cpu_graph/live_cpu_graph/static/rickshaw/src/js/Rickshaw.Series.FixedDuration.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "102285"
},
{
"name": "HTML",
"bytes": "134946"
},
{
"name": "JavaScript",
"bytes": "3740834"
},
{
"name": "Makefile",
"bytes": "2479"
},
{
"name": "Mako",
"bytes": "4158"
},
{
"name": "Perl",
"bytes": "1637"
},
{
"name": "Python",
"bytes": "194715"
},
{
"name": "Shell",
"bytes": "773"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>appfuse</display-name>
<distributable/>
<!-- precompiled jsp mappings -->
<!-- Define the basename for a resource bundle for I18N -->
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>ApplicationResources</param-value>
</context-param>
<!-- Fallback locale if no bundles found for browser's preferred locale -->
<!-- Force a single locale using param-name 'javax.servlet.jsp.jstl.fmt.locale' -->
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.fallbackLocale</param-name>
<param-value>en</param-value>
</context-param>
<!-- Context Configuration locations for Spring XML files -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/applicationContext-resources.xml
classpath:/applicationContext-dao.xml
classpath:/applicationContext-service.xml
classpath*:/applicationContext.xml
/WEB-INF/applicationContext*.xml
/WEB-INF/cxf-servlet.xml
/WEB-INF/security.xml
</param-value>
</context-param>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter>
<filter-name>exportFilter</filter-name>
<filter-class>org.displaytag.filter.ResponseOverrideFilter</filter-class>
</filter>
<!-- GZipFilter has issues with XFire's service-listing servlet. -->
<!-- http://issues.appfuse.org/browse/APF-863 -->
<!-- And showing blank pages. http://issues.appfuse.org/browse/APF-1037 -->
<!-- We recommend you configure gzipping in your servlet container.
web server, or load balancer. -->
<!--filter>
<filter-name>gzipFilter</filter-name>
<filter-class>net.sf.ehcache.constructs.web.filter.GzipFilter</filter-class>
</filter-->
<!--<filter>
<filter-name>lazyLoadingFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>-->
<!-- Use "org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter" if you're using JPA -->
<filter>
<filter-name>localeFilter</filter-name>
<filter-class>com.vnpt.spdv.webapp.filter.LocaleFilter</filter-class>
</filter>
<filter>
<filter-name>rewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<!-- sets up log level (will be logged to context log)
can be: TRACE, DEBUG, INFO (default), WARN, ERROR, FATAL, log4j, commons, sysout:{level} (ie, sysout:DEBUG)
if you are having trouble using normal levels use sysout:DEBUG -->
<init-param>
<param-name>logLevel</param-name>
<param-value>commons</param-value>
</init-param>
<!-- set the amount of seconds the conf file will be checked for reload
can be a valid integer (0 denotes check every time,
-1 denotes no reload check, default -1) -->
<init-param>
<param-name>confReloadCheckInterval</param-name>
<param-value>-1</param-value>
</init-param>
</filter>
<filter>
<filter-name>securityFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>springSecurityFilterChain</param-value>
</init-param>
</filter>
<filter>
<filter-name>sitemesh</filter-name>
<filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
</filter>
<filter>
<filter-name>wroFilter</filter-name>
<filter-class>ro.isdc.wro.http.WroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--<filter-mapping>
<filter-name>lazyLoadingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>-->
<filter-mapping>
<filter-name>localeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--filter-mapping>
<filter-name>gzipFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping-->
<filter-mapping>
<filter-name>rewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>wroFilter</filter-name>
<url-pattern>/assets/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>securityFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>exportFilter</filter-name>
<url-pattern>/app/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>com.vnpt.spdv.webapp.listener.StartupListener</listener-class>
</listener>
<listener>
<listener-class>com.vnpt.spdv.webapp.listener.UserCounterListener</listener-class>
</listener>
<listener>
<listener-class>com.vnpt.spdv.webapp.jsp.EscapeXmlELResolverListener</listener-class>
</listener>
<listener>
<listener-class>net.sf.navigator.menu.MenuContextListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
<error-page>
<error-code>400</error-code>
<location>/index.jsp</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/403.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<trim-directive-whitespaces>true</trim-directive-whitespaces>
</jsp-property-group>
</jsp-config>
<session-config>
<session-timeout>15</session-timeout>
<cookie-config>
<http-only>true</http-only>
<!--<secure>true</secure>-->
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
</web-app>
| {
"content_hash": "91b7f9acfa9008636203b80f6db4e556",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 119,
"avg_line_length": 37.04526748971193,
"alnum_prop": 0.6325261053099311,
"repo_name": "hungcuongbsm/spdv",
"id": "7ea4759aa44e92d466b6c867cda067ae3db077d3",
"size": "9002",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/src/main/webapp/WEB-INF/web.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4835"
},
{
"name": "Java",
"bytes": "289347"
},
{
"name": "JavaScript",
"bytes": "3350"
}
],
"symlink_target": ""
} |
package com.facebook.buck.util.network;
public class HttpResponse {
private final String responseBody;
public HttpResponse(String response) {
this.responseBody = response;
}
public String getResponseBody() {
return responseBody;
}
}
| {
"content_hash": "021f00ced2deccf3090258f558cafc10",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 40,
"avg_line_length": 16.0625,
"alnum_prop": 0.7276264591439688,
"repo_name": "kageiit/buck",
"id": "6684607929ed13619f69cd67fe2883096e4941c3",
"size": "873",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/com/facebook/buck/util/network/HttpResponse.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1692"
},
{
"name": "C",
"bytes": "250514"
},
{
"name": "CSS",
"bytes": "56119"
},
{
"name": "Dockerfile",
"bytes": "2094"
},
{
"name": "HTML",
"bytes": "11770"
},
{
"name": "Java",
"bytes": "33114896"
},
{
"name": "JavaScript",
"bytes": "931240"
},
{
"name": "Kotlin",
"bytes": "310039"
},
{
"name": "Lex",
"bytes": "14469"
},
{
"name": "Makefile",
"bytes": "1704"
},
{
"name": "PowerShell",
"bytes": "2154"
},
{
"name": "Python",
"bytes": "2152087"
},
{
"name": "Shell",
"bytes": "43626"
},
{
"name": "Smalltalk",
"bytes": "194"
},
{
"name": "Thrift",
"bytes": "18638"
}
],
"symlink_target": ""
} |
import unittest
from telemetry.user_story import user_story_filter
from telemetry.page import page
from telemetry.page import page_set
class MockUrlFilterOptions(object):
def __init__(self, page_filter_include, page_filter_exclude):
self.page_filter = page_filter_include
self.page_filter_exclude = page_filter_exclude
self.page_label_filter = None
self.page_label_filter_exclude = None
class MockLabelFilterOptions(object):
def __init__(self, page_label_filter, page_label_filter_exclude):
self.page_filter = None
self.page_filter_exclude = None
self.page_label_filter = page_label_filter
self.page_label_filter_exclude = page_label_filter_exclude
class UserStoryFilterTest(unittest.TestCase):
def setUp(self):
ps = page_set.PageSet()
self.p1 = page.Page(
'file://conformance/textures/tex-sub-image-2d.html', page_set=ps,
name='WebglConformance.conformance_textures_tex_sub_image_2d',
labels=['label1', 'label2'])
self.p2 = page.Page(
'file://othersuite/textures/tex-sub-image-3d.html', page_set=ps,
name='OtherSuite.textures_tex_sub_image_3d',
labels=['label1'])
self.p3 = page.Page(
'file://othersuite/textures/tex-sub-image-3d.html', page_set=ps,
labels=['label2'])
def testURLPattern(self):
options = MockUrlFilterOptions('conformance_textures', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p1))
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p2))
options = MockUrlFilterOptions('textures', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p1))
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p2))
options = MockUrlFilterOptions('somethingelse', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p1))
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p2))
def testName(self):
options = MockUrlFilterOptions('somethingelse', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p1))
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p2))
options = MockUrlFilterOptions('textures_tex_sub_image', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p1))
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p2))
options = MockUrlFilterOptions('WebglConformance', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p1))
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p2))
options = MockUrlFilterOptions('OtherSuite', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p1))
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p2))
def testNameNone(self):
options = MockUrlFilterOptions('othersuite/textures', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p3))
options = MockUrlFilterOptions('conformance/textures', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p3))
def testLabelFilters(self):
# Include both labels
options = MockLabelFilterOptions('label1,label2', '')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p1))
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p2))
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p3))
# Exclude takes priority
options = MockLabelFilterOptions('label1', 'label2')
user_story_filter.UserStoryFilter.ProcessCommandLineArgs(None, options)
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p1))
self.assertTrue(user_story_filter.UserStoryFilter.IsSelected(self.p2))
self.assertFalse(user_story_filter.UserStoryFilter.IsSelected(self.p3))
| {
"content_hash": "6e3f6d98be5a97652431b5f4071481aa",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 75,
"avg_line_length": 50.362637362637365,
"alnum_prop": 0.7636919048658084,
"repo_name": "dushu1203/chromium.src",
"id": "8445e70dcc5a06cad7731f477a8f0e0e3fc44290",
"size": "4746",
"binary": false,
"copies": "12",
"ref": "refs/heads/nw12",
"path": "tools/telemetry/telemetry/user_story/user_story_filter_unittest.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "34522"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9249764"
},
{
"name": "C++",
"bytes": "222763973"
},
{
"name": "CSS",
"bytes": "875874"
},
{
"name": "Dart",
"bytes": "74976"
},
{
"name": "Go",
"bytes": "18155"
},
{
"name": "HTML",
"bytes": "27190037"
},
{
"name": "Java",
"bytes": "7645280"
},
{
"name": "JavaScript",
"bytes": "18828195"
},
{
"name": "Makefile",
"bytes": "96270"
},
{
"name": "Objective-C",
"bytes": "1397246"
},
{
"name": "Objective-C++",
"bytes": "7575073"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "248854"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "418340"
},
{
"name": "Python",
"bytes": "8032766"
},
{
"name": "Shell",
"bytes": "464218"
},
{
"name": "Standard ML",
"bytes": "4965"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18335"
}
],
"symlink_target": ""
} |
SocialStream.setup do |config|
# List the models that are social entities. These will have ties between them.
# Remember you must add an "actor_id" foreign key column to your migration!
#
# config.subjects = [:user, :group ]
# Include devise modules in User. See devise documentation for details.
# Others available are:
# :confirmable, :lockable, :timeoutable, :validatable
# config.devise_modules = :database_authenticatable, :registerable,
# :recoverable, :rememberable, :trackable,
# :omniauthable, :token_authenticatable
# Type of activities managed by actors
# Remember you must add an "activity_object_id" foreign key column to your migration!
#
# config.objects = [ :post, :comment ]
# Form modules to be loaded
# config.activity_forms = [ :document, :other_module, :foo, :bar ]
end
| {
"content_hash": "e3a647c6989704b69a12e0d468e181ec",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 87,
"avg_line_length": 41.857142857142854,
"alnum_prop": 0.6746302616609784,
"repo_name": "Marisayem/social_stream-base",
"id": "8975eeac97a78e2afab28071576400b2b2f0c96e",
"size": "879",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/generators/social_stream/base/templates/initializer.rb",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
.. _gs_clustermesh_services:
**********************************
Load-balancing & Service Discovery
**********************************
This tutorial will guide you to perform load-balancing and service
discovery across multiple Kubernetes clusters when using Cilium.
Prerequisites
#############
You need to have a functioning Cluster Mesh setup, please follow the guide
:ref:`gs_clustermesh` to set it up.
Load-balancing with Global Services
###################################
Establishing load-balancing between clusters is achieved by defining a
Kubernetes service with identical name and namespace in each cluster and adding
the annotation ``io.cilium/global-service: "true"`` to declare it global.
Cilium will automatically perform load-balancing to pods in both clusters.
.. literalinclude:: ../../../examples/kubernetes/clustermesh/global-service-example/rebel-base-global-shared.yaml
:language: YAML
Load-balancing Only to a Remote Cluster
#######################################
By default, a Global Service will load-balance across backends in multiple clusters.
This implicitly configures ``io.cilium/shared-service: "true"``. To prevent service
backends from being shared to other clusters, and to ensure that the service
will only load-balance to backends in remote clusters, this option should be
disabled.
Below example will expose remote endpoint without sharing local endpoints.
.. code-block:: yaml
apiVersion: v1
kind: Service
metadata:
name: rebel-base
annotations:
io.cilium/global-service: "true"
io.cilium/shared-service: "false"
spec:
type: ClusterIP
ports:
- port: 80
selector:
name: rebel-base
Deploying a Simple Example Service
==================================
1. In cluster 1, deploy:
.. parsed-literal::
kubectl apply -f \ |SCM_WEB|\/examples/kubernetes/clustermesh/global-service-example/rebel-base-global-shared.yaml
kubectl apply -f \ |SCM_WEB|\/examples/kubernetes/clustermesh/global-service-example/cluster1.yaml
2. In cluster 2, deploy:
.. parsed-literal::
kubectl apply -f \ |SCM_WEB|\/examples/kubernetes/clustermesh/global-service-example/rebel-base-global-shared.yaml
kubectl apply -f \ |SCM_WEB|\/examples/kubernetes/clustermesh/global-service-example/cluster2.yaml
3. From either cluster, access the global service:
.. code-block:: shell-session
kubectl exec -ti xwing-xxx -- curl rebel-base
You will see replies from pods in both clusters.
| {
"content_hash": "15a72ee0ab05bc5b0b43285eec4f51c9",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 121,
"avg_line_length": 32.282051282051285,
"alnum_prop": 0.6922160444797458,
"repo_name": "tklauser/cilium",
"id": "3b43906f46a3c3b619ae3cd7a867d10412d38c74",
"size": "2518",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Documentation/gettingstarted/clustermesh/services.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "939774"
},
{
"name": "Dockerfile",
"bytes": "27555"
},
{
"name": "Go",
"bytes": "9502023"
},
{
"name": "HCL",
"bytes": "1394"
},
{
"name": "Makefile",
"bytes": "76523"
},
{
"name": "Mustache",
"bytes": "1457"
},
{
"name": "Python",
"bytes": "11097"
},
{
"name": "Ruby",
"bytes": "394"
},
{
"name": "Shell",
"bytes": "349188"
},
{
"name": "SmPL",
"bytes": "6540"
},
{
"name": "Smarty",
"bytes": "10430"
},
{
"name": "TeX",
"bytes": "416"
},
{
"name": "sed",
"bytes": "2642"
}
],
"symlink_target": ""
} |
clean:
find content -name *~ -delete
rm -rf ../sidesaddle-pages/*
build: clean
python run.py build content/
serve: build
python run.py serve content/
| {
"content_hash": "c0b32320a433796254045ab23cb24686",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 30,
"avg_line_length": 17.333333333333332,
"alnum_prop": 0.7115384615384616,
"repo_name": "mirisuzanne/sidesaddle",
"id": "9097d14044453ce962624cf171e1f5c8eaa27c76",
"size": "156",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "29795"
},
{
"name": "HTML",
"bytes": "7160"
},
{
"name": "JavaScript",
"bytes": "3034"
},
{
"name": "Makefile",
"bytes": "156"
},
{
"name": "Python",
"bytes": "18473"
},
{
"name": "Ruby",
"bytes": "265"
}
],
"symlink_target": ""
} |
import global from 'global';
import hasDependency from '../hasDependency';
import configure from '../configure';
import { Loader } from '../Loader';
import { StoryshotsOptions } from '../../api/StoryshotsOptions';
function mockVueToIncludeCompiler() {
jest.mock('vue', () => jest.requireActual('vue/dist/vue.common.js'));
}
function test(options: StoryshotsOptions): boolean {
return options.framework === 'vue' || (!options.framework && hasDependency('@storybook/vue'));
}
function load(options: StoryshotsOptions) {
global.STORYBOOK_ENV = 'vue';
mockVueToIncludeCompiler();
const storybook = jest.requireActual('@storybook/vue');
configure({ ...options, storybook });
return {
framework: 'vue' as const,
renderTree: jest.requireActual('./renderTree').default,
renderShallowTree: () => {
throw new Error('Shallow renderer is not supported for vue');
},
storybook,
};
}
const vueLoader: Loader = {
load,
test,
};
export default vueLoader;
| {
"content_hash": "ff396a0a9c96b6d44191c1543ecfbc42",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 96,
"avg_line_length": 26.13157894736842,
"alnum_prop": 0.6888217522658611,
"repo_name": "kadirahq/react-storybook",
"id": "4ab5fad6fa365de75a10047e415ee6f3c42f27a8",
"size": "993",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "addons/storyshots/storyshots-core/src/frameworks/vue/loader.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "55306"
},
{
"name": "Shell",
"bytes": "307"
}
],
"symlink_target": ""
} |
namespace SharpZendeskApi
{
using SharpZendeskApi.Models;
public interface IZendeskSerializer
{
#region Public Properties
#endregion
#region Public Methods and Operators
string Serialize(TrackableZendeskThingBase zendeskThing);
#endregion
}
} | {
"content_hash": "307b4ed0b49dfe7cde525618240745cb",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 65,
"avg_line_length": 17.88235294117647,
"alnum_prop": 0.6776315789473685,
"repo_name": "ghostsquad/SharpZendeskApi",
"id": "b08dd684aa7cd7e7bd867902bd31080f04acef6b",
"size": "306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SharpZendeskApi/IZendeskSerializer.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "288869"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Sep 05 03:08:39 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ManagementOperationsServiceSupplier (BOM: * : All 2.2.0.Final API)</title>
<meta name="date" content="2018-09-05">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ManagementOperationsServiceSupplier (BOM: * : All 2.2.0.Final API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ManagementOperationsServiceSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.2.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/config/management/ManagementOperationsServiceConsumer.html" title="interface in org.wildfly.swarm.config.management"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/wildfly/swarm/config/management/NativeInterfaceManagementInterface.html" title="class in org.wildfly.swarm.config.management"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/management/ManagementOperationsServiceSupplier.html" target="_top">Frames</a></li>
<li><a href="ManagementOperationsServiceSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.config.management</div>
<h2 title="Interface ManagementOperationsServiceSupplier" class="title">Interface ManagementOperationsServiceSupplier<T extends <a href="../../../../../org/wildfly/swarm/config/management/ManagementOperationsService.html" title="class in org.wildfly.swarm.config.management">ManagementOperationsService</a>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a>
public interface <span class="typeNameLabel">ManagementOperationsServiceSupplier<T extends <a href="../../../../../org/wildfly/swarm/config/management/ManagementOperationsService.html" title="class in org.wildfly.swarm.config.management">ManagementOperationsService</a>></span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/config/management/ManagementOperationsService.html" title="class in org.wildfly.swarm.config.management">ManagementOperationsService</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/management/ManagementOperationsServiceSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of ManagementOperationsService resource</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="get--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>get</h4>
<pre><a href="../../../../../org/wildfly/swarm/config/management/ManagementOperationsService.html" title="class in org.wildfly.swarm.config.management">ManagementOperationsService</a> get()</pre>
<div class="block">Constructed instance of ManagementOperationsService resource</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The instance</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/ManagementOperationsServiceSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.2.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/config/management/ManagementOperationsServiceConsumer.html" title="interface in org.wildfly.swarm.config.management"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/wildfly/swarm/config/management/NativeInterfaceManagementInterface.html" title="class in org.wildfly.swarm.config.management"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/management/ManagementOperationsServiceSupplier.html" target="_top">Frames</a></li>
<li><a href="ManagementOperationsServiceSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "95b6d7060a275bc16476771348e3c89e",
"timestamp": "",
"source": "github",
"line_count": 237,
"max_line_length": 391,
"avg_line_length": 40.9451476793249,
"alnum_prop": 0.6586974443528442,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "88bfa46350bd3d77db9e968f611488d57daa7d11",
"size": "9704",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.2.0.Final/apidocs/org/wildfly/swarm/config/management/ManagementOperationsServiceSupplier.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="overlord-rtgov-activity-orm" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>org.overlord.rtgov.activity.model.ActivityUnit</class>
<class>org.overlord.rtgov.activity.model.ActivityType</class>
<class>org.overlord.rtgov.activity.model.ActivityTypeId</class>
<class>org.overlord.rtgov.activity.model.Context</class>
<class>org.overlord.rtgov.activity.model.app.CustomActivity</class>
<class>org.overlord.rtgov.activity.model.app.LogMessage</class>
<class>org.overlord.rtgov.activity.model.bpm.BPMActivityType</class>
<class>org.overlord.rtgov.activity.model.bpm.ProcessCompleted</class>
<class>org.overlord.rtgov.activity.model.bpm.ProcessStarted</class>
<class>org.overlord.rtgov.activity.model.bpm.ProcessVariableSet</class>
<class>org.overlord.rtgov.activity.model.common.MessageExchange</class>
<class>org.overlord.rtgov.activity.model.mom.MOMActivityType</class>
<class>org.overlord.rtgov.activity.model.mom.MessageReceived</class>
<class>org.overlord.rtgov.activity.model.mom.MessageSent</class>
<class>org.overlord.rtgov.activity.model.soa.RPCActivityType</class>
<class>org.overlord.rtgov.activity.model.soa.RequestSent</class>
<class>org.overlord.rtgov.activity.model.soa.RequestReceived</class>
<class>org.overlord.rtgov.activity.model.soa.ResponseSent</class>
<class>org.overlord.rtgov.activity.model.soa.ResponseReceived</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.driver_class" value="org.h2.Driver"/>
<property name="hibernate.connection.url" value="jdbc:h2:target/db/h2"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
| {
"content_hash": "e7cf99e793b606e16bf95a89cffdfb23",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 130,
"avg_line_length": 62.729729729729726,
"alnum_prop": 0.7630331753554502,
"repo_name": "jboss-switchyard/learning",
"id": "0a0641789344fd7c6afe204bf3f33379c87fb01e",
"size": "2321",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "summit2014/lab3/sla/report/src/test/resources/META-INF/persistence.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "144244"
}
],
"symlink_target": ""
} |
package org.apache.flink.table.planner.delegation.hive.copy;
import org.apache.flink.table.planner.delegation.hive.HiveParserIN;
import org.apache.flink.table.planner.delegation.hive.parse.HiveASTParser;
import org.apache.calcite.rel.type.RelDataType;
import org.apache.calcite.sql.SqlAggFunction;
import org.apache.calcite.sql.SqlFunction;
import org.apache.calcite.sql.SqlFunctionCategory;
import org.apache.calcite.sql.SqlIdentifier;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.fun.SqlMonotonicBinaryOperator;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.sql.type.InferTypes;
import org.apache.calcite.sql.type.OperandTypes;
import org.apache.calcite.sql.type.ReturnTypes;
import org.apache.calcite.sql.type.SqlOperandTypeChecker;
import org.apache.calcite.sql.type.SqlOperandTypeInference;
import org.apache.calcite.sql.type.SqlReturnTypeInference;
import org.apache.calcite.sql.type.SqlTypeFamily;
import org.apache.calcite.util.Util;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.FunctionInfo;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBridge;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPNegative;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPPositive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Counterpart of hive's
* org.apache.hadoop.hive.ql.optimizer.calcite.translator.SqlFunctionConverter.
*/
public class HiveParserSqlFunctionConverter {
private static final Logger LOG = LoggerFactory.getLogger(HiveParserSqlFunctionConverter.class);
static final Map<String, SqlOperator> HIVE_TO_CALCITE;
static final Map<SqlOperator, HiveToken> CALCITE_TO_HIVE_TOKEN;
static final Map<SqlOperator, String> REVERSE_OPERATOR_MAP;
static {
StaticBlockBuilder builder = new StaticBlockBuilder();
HIVE_TO_CALCITE = Collections.unmodifiableMap(builder.hiveToCalcite);
CALCITE_TO_HIVE_TOKEN = Collections.unmodifiableMap(builder.calciteToHiveToken);
REVERSE_OPERATOR_MAP = Collections.unmodifiableMap(builder.reverseOperatorMap);
}
public static SqlOperator getCalciteOperator(
String funcTextName,
GenericUDF hiveUDF,
List<RelDataType> calciteArgTypes,
RelDataType retType)
throws SemanticException {
// handle overloaded methods first
if (hiveUDF instanceof GenericUDFOPNegative) {
return SqlStdOperatorTable.UNARY_MINUS;
} else if (hiveUDF instanceof GenericUDFOPPositive) {
return SqlStdOperatorTable.UNARY_PLUS;
} // do generic lookup
String name = null;
if (StringUtils.isEmpty(funcTextName)) {
name = getName(hiveUDF); // this should probably never happen, see getName comment
LOG.warn("The function text was empty, name from annotation is " + name);
} else {
// We could just do toLowerCase here and let SA qualify it, but
// let's be proper...
name = FunctionRegistry.getNormalizedFunctionName(funcTextName);
}
return getCalciteFn(
name, calciteArgTypes, retType, FunctionRegistry.isDeterministic(hiveUDF));
}
// TODO: this is not valid. Function names for built-in UDFs are specified in
// FunctionRegistry, and only happen to match annotations. For user UDFs, the
// name is what user specifies at creation time (annotation can be absent,
// different, or duplicate some other function).
private static String getName(GenericUDF hiveUDF) {
String udfName = null;
if (hiveUDF instanceof GenericUDFBridge) {
udfName = hiveUDF.getUdfName();
} else {
Class<? extends GenericUDF> udfClass = hiveUDF.getClass();
Description udfAnnotation = udfClass.getAnnotation(Description.class);
if (udfAnnotation != null) {
udfName = udfAnnotation.name();
if (udfName != null) {
String[] aliases = udfName.split(",");
if (aliases.length > 0) {
udfName = aliases[0];
}
}
}
if (udfName == null || udfName.isEmpty()) {
udfName = hiveUDF.getClass().getName();
int indx = udfName.lastIndexOf(".");
if (indx >= 0) {
indx += 1;
udfName = udfName.substring(indx);
}
}
}
return udfName;
}
/** This class is used to build immutable hashmaps in the static block above. */
private static class StaticBlockBuilder {
final Map<String, SqlOperator> hiveToCalcite = new HashMap<>();
final Map<SqlOperator, HiveToken> calciteToHiveToken = new HashMap<>();
final Map<SqlOperator, String> reverseOperatorMap = new HashMap<>();
StaticBlockBuilder() {
registerFunction("+", SqlStdOperatorTable.PLUS, hToken(HiveASTParser.PLUS, "+"));
registerFunction("-", SqlStdOperatorTable.MINUS, hToken(HiveASTParser.MINUS, "-"));
registerFunction("*", SqlStdOperatorTable.MULTIPLY, hToken(HiveASTParser.STAR, "*"));
registerFunction("/", SqlStdOperatorTable.DIVIDE, hToken(HiveASTParser.DIVIDE, "/"));
registerFunction("%", SqlStdOperatorTable.MOD, hToken(HiveASTParser.Identifier, "%"));
registerFunction("and", SqlStdOperatorTable.AND, hToken(HiveASTParser.KW_AND, "and"));
registerFunction("or", SqlStdOperatorTable.OR, hToken(HiveASTParser.KW_OR, "or"));
registerFunction("=", SqlStdOperatorTable.EQUALS, hToken(HiveASTParser.EQUAL, "="));
registerDuplicateFunction(
"==", SqlStdOperatorTable.EQUALS, hToken(HiveASTParser.EQUAL, "="));
registerFunction(
"<", SqlStdOperatorTable.LESS_THAN, hToken(HiveASTParser.LESSTHAN, "<"));
registerFunction(
"<=",
SqlStdOperatorTable.LESS_THAN_OR_EQUAL,
hToken(HiveASTParser.LESSTHANOREQUALTO, "<="));
registerFunction(
">", SqlStdOperatorTable.GREATER_THAN, hToken(HiveASTParser.GREATERTHAN, ">"));
registerFunction(
">=",
SqlStdOperatorTable.GREATER_THAN_OR_EQUAL,
hToken(HiveASTParser.GREATERTHANOREQUALTO, ">="));
registerFunction("not", SqlStdOperatorTable.NOT, hToken(HiveASTParser.KW_NOT, "not"));
registerDuplicateFunction(
"!", SqlStdOperatorTable.NOT, hToken(HiveASTParser.KW_NOT, "not"));
registerFunction(
"<>", SqlStdOperatorTable.NOT_EQUALS, hToken(HiveASTParser.NOTEQUAL, "<>"));
registerDuplicateFunction(
"!=", SqlStdOperatorTable.NOT_EQUALS, hToken(HiveASTParser.NOTEQUAL, "<>"));
registerFunction("in", HiveParserIN.INSTANCE, hToken(HiveASTParser.Identifier, "in"));
registerFunction(
"between",
HiveParserBetween.INSTANCE,
hToken(HiveASTParser.Identifier, "between"));
registerFunction(
"struct", SqlStdOperatorTable.ROW, hToken(HiveASTParser.Identifier, "struct"));
registerFunction(
"isnotnull",
SqlStdOperatorTable.IS_NOT_NULL,
hToken(HiveASTParser.TOK_ISNOTNULL, "TOK_ISNOTNULL"));
registerFunction(
"isnull",
SqlStdOperatorTable.IS_NULL,
hToken(HiveASTParser.TOK_ISNULL, "TOK_ISNULL"));
// let's try removing 'when' for better compatibility
// registerFunction("when", SqlStdOperatorTable.CASE, hToken(HiveASTParser.Identifier,
// "when"));
// let's try removing 'case' for better compatibility
// registerDuplicateFunction("case", SqlStdOperatorTable.CASE,
// hToken(HiveASTParser.Identifier, "when"));
// timebased
registerFunction(
"year", HiveParserExtractDate.YEAR, hToken(HiveASTParser.Identifier, "year"));
registerFunction(
"quarter",
HiveParserExtractDate.QUARTER,
hToken(HiveASTParser.Identifier, "quarter"));
registerFunction(
"month",
HiveParserExtractDate.MONTH,
hToken(HiveASTParser.Identifier, "month"));
registerFunction(
"weekofyear",
HiveParserExtractDate.WEEK,
hToken(HiveASTParser.Identifier, "weekofyear"));
registerFunction(
"day", HiveParserExtractDate.DAY, hToken(HiveASTParser.Identifier, "day"));
registerFunction(
"hour", HiveParserExtractDate.HOUR, hToken(HiveASTParser.Identifier, "hour"));
registerFunction(
"minute",
HiveParserExtractDate.MINUTE,
hToken(HiveASTParser.Identifier, "minute"));
registerFunction(
"second",
HiveParserExtractDate.SECOND,
hToken(HiveASTParser.Identifier, "second"));
registerFunction(
"floor_year",
HiveParserFloorDate.YEAR,
hToken(HiveASTParser.Identifier, "floor_year"));
registerFunction(
"floor_quarter",
HiveParserFloorDate.QUARTER,
hToken(HiveASTParser.Identifier, "floor_quarter"));
registerFunction(
"floor_month",
HiveParserFloorDate.MONTH,
hToken(HiveASTParser.Identifier, "floor_month"));
registerFunction(
"floor_week",
HiveParserFloorDate.WEEK,
hToken(HiveASTParser.Identifier, "floor_week"));
registerFunction(
"floor_day",
HiveParserFloorDate.DAY,
hToken(HiveASTParser.Identifier, "floor_day"));
registerFunction(
"floor_hour",
HiveParserFloorDate.HOUR,
hToken(HiveASTParser.Identifier, "floor_hour"));
registerFunction(
"floor_minute",
HiveParserFloorDate.MINUTE,
hToken(HiveASTParser.Identifier, "floor_minute"));
registerFunction(
"floor_second",
HiveParserFloorDate.SECOND,
hToken(HiveASTParser.Identifier, "floor_second"));
// support <=>
registerFunction(
"<=>",
SqlStdOperatorTable.IS_NOT_DISTINCT_FROM,
hToken(HiveASTParser.EQUAL_NS, "<=>"));
}
private void registerFunction(String name, SqlOperator calciteFn, HiveToken hiveToken) {
reverseOperatorMap.put(calciteFn, name);
FunctionInfo hFn;
try {
hFn = FunctionRegistry.getFunctionInfo(name);
} catch (SemanticException e) {
LOG.warn("Failed to load udf " + name, e);
hFn = null;
}
if (hFn != null) {
String hFnName = getName(hFn.getGenericUDF());
hiveToCalcite.put(hFnName, calciteFn);
if (hiveToken != null) {
calciteToHiveToken.put(calciteFn, hiveToken);
}
}
}
private void registerDuplicateFunction(
String name, SqlOperator calciteFn, HiveToken hiveToken) {
hiveToCalcite.put(name, calciteFn);
if (hiveToken != null) {
calciteToHiveToken.put(calciteFn, hiveToken);
}
}
}
private static HiveToken hToken(int type, String text) {
return new HiveToken(type, text);
}
/** UDAF is assumed to be deterministic. */
private static class CalciteUDAF extends SqlAggFunction implements CanAggregateDistinct {
private final boolean isDistinct;
public CalciteUDAF(
boolean isDistinct,
String opName,
SqlIdentifier identifier,
SqlReturnTypeInference returnTypeInference,
SqlOperandTypeInference operandTypeInference,
SqlOperandTypeChecker operandTypeChecker) {
super(
opName,
identifier,
SqlKind.OTHER_FUNCTION,
returnTypeInference,
operandTypeInference,
operandTypeChecker,
SqlFunctionCategory.USER_DEFINED_FUNCTION);
this.isDistinct = isDistinct;
}
@Override
public boolean isDistinct() {
return isDistinct;
}
}
/** CalciteSqlFn. */
public static class CalciteSqlFn extends SqlFunction {
private final boolean deterministic;
public CalciteSqlFn(
String name,
SqlIdentifier identifier,
SqlKind kind,
SqlReturnTypeInference returnTypeInference,
SqlOperandTypeInference operandTypeInference,
SqlOperandTypeChecker operandTypeChecker,
SqlFunctionCategory category,
boolean deterministic) {
super(
name,
identifier,
kind,
returnTypeInference,
operandTypeInference,
operandTypeChecker,
category);
this.deterministic = deterministic;
}
@Override
public boolean isDeterministic() {
return deterministic;
}
}
private static class CalciteUDFInfo {
private String udfName;
// need an identifier if we have a composite name
private SqlIdentifier identifier;
private SqlReturnTypeInference returnTypeInference;
private SqlOperandTypeInference operandTypeInference;
private SqlOperandTypeChecker operandTypeChecker;
}
private static CalciteUDFInfo getUDFInfo(
String hiveUdfName, List<RelDataType> calciteArgTypes, RelDataType calciteRetType) {
CalciteUDFInfo udfInfo = new CalciteUDFInfo();
udfInfo.udfName = hiveUdfName;
String[] nameParts = hiveUdfName.split("\\.");
if (nameParts.length > 1) {
udfInfo.identifier =
new SqlIdentifier(
Arrays.stream(nameParts).collect(Collectors.toList()),
new SqlParserPos(0, 0));
}
udfInfo.returnTypeInference = ReturnTypes.explicit(calciteRetType);
udfInfo.operandTypeInference = InferTypes.explicit(calciteArgTypes);
List<SqlTypeFamily> typeFamily = new ArrayList<>();
for (RelDataType argType : calciteArgTypes) {
typeFamily.add(Util.first(argType.getSqlTypeName().getFamily(), SqlTypeFamily.ANY));
}
udfInfo.operandTypeChecker = OperandTypes.family(Collections.unmodifiableList(typeFamily));
return udfInfo;
}
public static SqlOperator getCalciteFn(
String hiveUdfName,
List<RelDataType> calciteArgTypes,
RelDataType calciteRetType,
boolean deterministic) {
SqlOperator calciteOp;
CalciteUDFInfo uInf = getUDFInfo(hiveUdfName, calciteArgTypes, calciteRetType);
switch (hiveUdfName) {
// Follow hive's rules for type inference as oppose to Calcite's
// for return type.
// TODO: Perhaps we should do this for all functions, not just +,-
case "-":
calciteOp =
new SqlMonotonicBinaryOperator(
"-",
SqlKind.MINUS,
40,
true,
uInf.returnTypeInference,
uInf.operandTypeInference,
OperandTypes.MINUS_OPERATOR);
break;
case "+":
calciteOp =
new SqlMonotonicBinaryOperator(
"+",
SqlKind.PLUS,
40,
true,
uInf.returnTypeInference,
uInf.operandTypeInference,
OperandTypes.PLUS_OPERATOR);
break;
default:
calciteOp = HIVE_TO_CALCITE.get(hiveUdfName);
if (null == calciteOp) {
calciteOp =
new CalciteSqlFn(
uInf.udfName,
uInf.identifier,
SqlKind.OTHER_FUNCTION,
uInf.returnTypeInference,
uInf.operandTypeInference,
uInf.operandTypeChecker,
SqlFunctionCategory.USER_DEFINED_FUNCTION,
deterministic);
}
break;
}
return calciteOp;
}
public static SqlAggFunction getCalciteAggFn(
String hiveUdfName,
boolean isDistinct,
List<RelDataType> calciteArgTypes,
RelDataType calciteRetType) {
SqlAggFunction calciteAggFn = (SqlAggFunction) HIVE_TO_CALCITE.get(hiveUdfName);
if (calciteAggFn == null) {
CalciteUDFInfo udfInfo = getUDFInfo(hiveUdfName, calciteArgTypes, calciteRetType);
switch (hiveUdfName.toLowerCase()) {
case "sum":
calciteAggFn =
new HiveParserSqlSumAggFunction(
isDistinct,
udfInfo.returnTypeInference,
udfInfo.operandTypeInference,
udfInfo.operandTypeChecker);
break;
case "count":
calciteAggFn =
new HiveParserSqlCountAggFunction(
isDistinct,
udfInfo.returnTypeInference,
udfInfo.operandTypeInference,
udfInfo.operandTypeChecker);
break;
case "min":
calciteAggFn =
new HiveParserSqlMinMaxAggFunction(
udfInfo.returnTypeInference,
udfInfo.operandTypeInference,
udfInfo.operandTypeChecker,
true);
break;
case "max":
calciteAggFn =
new HiveParserSqlMinMaxAggFunction(
udfInfo.returnTypeInference,
udfInfo.operandTypeInference,
udfInfo.operandTypeChecker,
false);
break;
default:
calciteAggFn =
new CalciteUDAF(
isDistinct,
udfInfo.udfName,
udfInfo.identifier,
udfInfo.returnTypeInference,
udfInfo.operandTypeInference,
udfInfo.operandTypeChecker);
break;
}
}
return calciteAggFn;
}
static class HiveToken {
int type;
String text;
String[] args;
HiveToken(int type, String text, String... args) {
this.type = type;
this.text = text;
this.args = args;
}
}
/** CanAggregateDistinct. */
public interface CanAggregateDistinct {
boolean isDistinct();
}
}
| {
"content_hash": "bc0906fe185831286490a6931a2c66c6",
"timestamp": "",
"source": "github",
"line_count": 494,
"max_line_length": 100,
"avg_line_length": 43.19028340080972,
"alnum_prop": 0.5553055868016498,
"repo_name": "tillrohrmann/flink",
"id": "621729b307d0039b7031a0dd4f975f008797e51a",
"size": "22141",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/table/planner/delegation/hive/copy/HiveParserSqlFunctionConverter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "20448"
},
{
"name": "Batchfile",
"bytes": "1863"
},
{
"name": "C",
"bytes": "847"
},
{
"name": "Clojure",
"bytes": "84400"
},
{
"name": "Dockerfile",
"bytes": "5563"
},
{
"name": "FreeMarker",
"bytes": "86639"
},
{
"name": "GAP",
"bytes": "139514"
},
{
"name": "HTML",
"bytes": "135625"
},
{
"name": "HiveQL",
"bytes": "78611"
},
{
"name": "Java",
"bytes": "83158201"
},
{
"name": "JavaScript",
"bytes": "1829"
},
{
"name": "Less",
"bytes": "65918"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "2433935"
},
{
"name": "Scala",
"bytes": "10501870"
},
{
"name": "Shell",
"bytes": "525933"
},
{
"name": "TypeScript",
"bytes": "288472"
},
{
"name": "q",
"bytes": "7406"
}
],
"symlink_target": ""
} |
// Copyright 2010-2014 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "linear_solver/linear_solver.h"
#if !defined(_MSC_VER)
#include <unistd.h>
#endif
#include <cmath>
#include <cstddef>
#include <utility>
#include "base/commandlineflags.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/timer.h"
#ifndef ANDROID_JNI
#include "base/file.h"
#endif
#ifdef ANDROID_JNI
#include "base/numbers.h"
#endif /// ANDROID_JNI
#include "base/map_util.h"
#include "base/stl_util.h"
#include "base/hash.h"
#include "base/accurate_sum.h"
#include "linear_solver/linear_solver.pb.h"
#include "linear_solver/model_exporter.h"
#include "linear_solver/model_validator.h"
#include "util/fp_utils.h"
#ifndef ANDROID_JNI
#include "util/proto_tools.h"
#endif
// TODO(user): Clean up includes. E.g., parameters.pb.h seems not used.
DEFINE_bool(verify_solution, false,
"Systematically verify the solution when calling Solve()"
", and change the return value of Solve() to ABNORMAL if"
" an error was detected.");
DEFINE_bool(log_verification_errors, true,
"If --verify_solution is set: LOG(ERROR) all errors detected"
" during the verification of the solution.");
DEFINE_bool(linear_solver_enable_verbose_output, false,
"If set, enables verbose output for the solver. Setting this flag"
" is the same as calling MPSolver::EnableOutput().");
DEFINE_bool(mpsolver_bypass_model_validation, false,
"If set, the user-provided Model won't be verified before Solve()."
" Invalid models will typically trigger various error responses"
" from the underlying solvers; sometimes crashes.");
// To compile the open-source code, the anonymous namespace should be
// inside the operations_research namespace (This is due to the
// open-sourced version of StringPrintf which is defined inside the
// operations_research namespace in open_source/base).
namespace operations_research {
#if defined(ANDROID_JNI) && (defined(__ANDROID__) || defined(__APPLE__))
// Enum -> std::string conversions are not present in MessageLite that is being used
// on Android.
std::string MPSolverResponseStatus_Name(int status) {
return SimpleItoa(status);
}
std::string MPModelRequest_SolverType_Name(int type) {
return SimpleItoa(type);
}
#endif // defined(ANDROID_JNI) && (defined(__ANDROID__) || defined(__APPLE__))
double MPConstraint::GetCoefficient(const MPVariable* const var) const {
DLOG_IF(DFATAL, !interface_->solver_->OwnsVariable(var)) << var;
if (var == NULL) return 0.0;
return FindWithDefault(coefficients_, var, 0.0);
}
void MPConstraint::SetCoefficient(const MPVariable* const var, double coeff) {
DLOG_IF(DFATAL, !interface_->solver_->OwnsVariable(var)) << var;
if (var == NULL) return;
if (coeff == 0.0) {
CoeffMap::iterator it = coefficients_.find(var);
// If setting a coefficient to 0 when this coefficient did not
// exist or was already 0, do nothing: skip
// interface_->SetCoefficient() and do not store a coefficient in
// the map. Note that if the coefficient being set to 0 did exist
// and was not 0, we do have to keep a 0 in the coefficients_ map,
// because the extraction of the constraint might rely on it,
// depending on the underlying solver.
if (it != coefficients_.end() && it->second != 0.0) {
const double old_value = it->second;
it->second = 0.0;
interface_->SetCoefficient(this, var, 0.0, old_value);
}
return;
}
std::pair<CoeffMap::iterator, bool> insertion_result =
coefficients_.insert(std::make_pair(var, coeff));
const double old_value =
insertion_result.second ? 0.0 : insertion_result.first->second;
insertion_result.first->second = coeff;
interface_->SetCoefficient(this, var, coeff, old_value);
}
void MPConstraint::Clear() {
interface_->ClearConstraint(this);
coefficients_.clear();
}
void MPConstraint::SetBounds(double lb, double ub) {
const bool change = lb != lb_ || ub != ub_;
lb_ = lb;
ub_ = ub;
if (change && interface_->constraint_is_extracted(index_)) {
interface_->SetConstraintBounds(index_, lb_, ub_);
}
}
double MPConstraint::dual_value() const {
if (!interface_->IsContinuous()) {
LOG(DFATAL) << "Dual value only available for continuous problems";
return 0.0;
}
if (!interface_->CheckSolutionIsSynchronizedAndExists()) return 0.0;
return dual_value_;
}
MPSolver::BasisStatus MPConstraint::basis_status() const {
if (!interface_->IsContinuous()) {
LOG(DFATAL) << "Basis status only available for continuous problems";
return MPSolver::FREE;
}
if (!interface_->CheckSolutionIsSynchronizedAndExists()) {
return MPSolver::FREE;
}
// This is done lazily as this method is expected to be rarely used.
return interface_->row_status(index_);
}
bool MPConstraint::ContainsNewVariables() {
const int last_variable_index = interface_->last_variable_index();
for (CoeffEntry entry : coefficients_) {
const int variable_index = entry.first->index();
if (variable_index >= last_variable_index ||
!interface_->variable_is_extracted(variable_index)) {
return true;
}
}
return false;
}
// ----- MPObjective -----
double MPObjective::GetCoefficient(const MPVariable* const var) const {
DLOG_IF(DFATAL, !interface_->solver_->OwnsVariable(var)) << var;
if (var == NULL) return 0.0;
return FindWithDefault(coefficients_, var, 0.0);
}
void MPObjective::SetCoefficient(const MPVariable* const var, double coeff) {
DLOG_IF(DFATAL, !interface_->solver_->OwnsVariable(var)) << var;
if (var == NULL) return;
if (coeff == 0.0) {
CoeffMap::iterator it = coefficients_.find(var);
// See the discussion on MPConstraint::SetCoefficient() for 0 coefficients,
// the same reasoning applies here.
if (it == coefficients_.end() || it->second == 0.0) return;
it->second = 0.0;
} else {
coefficients_[var] = coeff;
}
interface_->SetObjectiveCoefficient(var, coeff);
}
void MPObjective::SetOffset(double value) {
offset_ = value;
interface_->SetObjectiveOffset(offset_);
}
void MPObjective::Clear() {
interface_->ClearObjective();
coefficients_.clear();
offset_ = 0.0;
SetMinimization();
}
void MPObjective::SetOptimizationDirection(bool maximize) {
// Note(user): The maximize_ bool would more naturally belong to the
// MPObjective, but it actually has to be a member of MPSolverInterface,
// because some implementations (such as GLPK) need that bool for the
// MPSolverInterface constructor, i.e at a time when the MPObjective is not
// constructed yet (MPSolverInterface is always built before MPObjective
// when a new MPSolver is constructed).
interface_->maximize_ = maximize;
interface_->SetOptimizationDirection(maximize);
}
bool MPObjective::maximization() const { return interface_->maximize_; }
bool MPObjective::minimization() const { return !interface_->maximize_; }
double MPObjective::Value() const {
// Note(user): implementation-wise, the objective value belongs more
// naturally to the MPSolverInterface, since all of its implementations write
// to it directly.
return interface_->objective_value();
}
double MPObjective::BestBound() const {
// Note(user): the best objective bound belongs to the interface for the
// same reasons as the objective value does.
return interface_->best_objective_bound();
}
// ----- MPVariable -----
double MPVariable::solution_value() const {
if (!interface_->CheckSolutionIsSynchronizedAndExists()) return 0.0;
return integer_ ? round(solution_value_) : solution_value_;
}
double MPVariable::unrounded_solution_value() const {
if (!interface_->CheckSolutionIsSynchronizedAndExists()) return 0.0;
return solution_value_;
}
double MPVariable::reduced_cost() const {
if (!interface_->IsContinuous()) {
LOG(DFATAL) << "Reduced cost only available for continuous problems";
return 0.0;
}
if (!interface_->CheckSolutionIsSynchronizedAndExists()) return 0.0;
return reduced_cost_;
}
MPSolver::BasisStatus MPVariable::basis_status() const {
if (!interface_->IsContinuous()) {
LOG(DFATAL) << "Basis status only available for continuous problems";
return MPSolver::FREE;
}
if (!interface_->CheckSolutionIsSynchronizedAndExists()) {
return MPSolver::FREE;
}
// This is done lazily as this method is expected to be rarely used.
return interface_->column_status(index_);
}
void MPVariable::SetBounds(double lb, double ub) {
const bool change = lb != lb_ || ub != ub_;
lb_ = lb;
ub_ = ub;
if (change && interface_->variable_is_extracted(index_)) {
interface_->SetVariableBounds(index_, lb_, ub_);
}
}
void MPVariable::SetInteger(bool integer) {
if (integer_ != integer) {
integer_ = integer;
if (interface_->variable_is_extracted(index_)) {
interface_->SetVariableInteger(index_, integer);
}
}
}
// ----- Version -----
std::string MPSolver::SolverVersion() const { return interface_->SolverVersion(); }
// ---- Underlying solver ----
void* MPSolver::underlying_solver() { return interface_->underlying_solver(); }
// ---- Solver-specific parameters ----
bool MPSolver::SetSolverSpecificParametersAsString(const std::string& parameters) {
solver_specific_parameter_string_ = parameters;
return interface_->SetSolverSpecificParametersAsString(parameters);
}
// ----- Solver -----
#if defined(USE_CLP) || defined(USE_CBC)
extern MPSolverInterface* BuildCLPInterface(MPSolver* const solver);
#endif
#if defined(USE_CBC)
extern MPSolverInterface* BuildCBCInterface(MPSolver* const solver);
#endif
#if defined(USE_GLPK)
extern MPSolverInterface* BuildGLPKInterface(bool mip, MPSolver* const solver);
#endif
#if defined(USE_BOP)
extern MPSolverInterface* BuildBopInterface(MPSolver* const solver);
#endif
#if defined(USE_GLOP)
extern MPSolverInterface* BuildGLOPInterface(MPSolver* const solver);
#endif
#if defined(USE_SCIP)
extern MPSolverInterface* BuildSCIPInterface(MPSolver* const solver);
#endif
#if defined(USE_SLM)
extern MPSolverInterface* BuildSLMInterface(MPSolver* const solver, bool mip);
#endif
#if defined(USE_GUROBI)
extern MPSolverInterface* BuildGurobiInterface(bool mip,
MPSolver* const solver);
#endif
#if defined(USE_CPLEX)
extern MPSolverInterface* BuildCplexInterface(bool mip, MPSolver* const solver);
#endif
#ifdef ANDROID_JNI
extern MPSolverInterface* BuildGLOPInterface(MPSolver* const solver);
#endif
namespace {
MPSolverInterface* BuildSolverInterface(MPSolver* const solver) {
DCHECK(solver != NULL);
switch (solver->ProblemType()) {
#if defined(USE_BOP)
case MPSolver::BOP_INTEGER_PROGRAMMING:
return BuildBopInterface(solver);
#endif
#if defined(USE_GLOP)
case MPSolver::GLOP_LINEAR_PROGRAMMING:
return BuildGLOPInterface(solver);
#endif
#if defined(USE_GLPK)
case MPSolver::GLPK_LINEAR_PROGRAMMING:
return BuildGLPKInterface(false, solver);
case MPSolver::GLPK_MIXED_INTEGER_PROGRAMMING:
return BuildGLPKInterface(true, solver);
#endif
#if defined(USE_CLP) || defined(USE_CBC)
case MPSolver::CLP_LINEAR_PROGRAMMING:
return BuildCLPInterface(solver);
#endif
#if defined(USE_CBC)
case MPSolver::CBC_MIXED_INTEGER_PROGRAMMING:
return BuildCBCInterface(solver);
#endif
#if defined(USE_SCIP)
case MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING:
return BuildSCIPInterface(solver);
#endif
#if defined(USE_SLM)
case MPSolver::SULUM_LINEAR_PROGRAMMING:
return BuildSLMInterface(solver, false);
case MPSolver::SULUM_MIXED_INTEGER_PROGRAMMING:
return BuildSLMInterface(solver, true);
#endif
#if defined(USE_GUROBI)
case MPSolver::GUROBI_LINEAR_PROGRAMMING:
return BuildGurobiInterface(false, solver);
case MPSolver::GUROBI_MIXED_INTEGER_PROGRAMMING:
return BuildGurobiInterface(true, solver);
#endif
#if defined(USE_CPLEX)
case MPSolver::CPLEX_LINEAR_PROGRAMMING:
return BuildCplexInterface(false, solver);
case MPSolver::CPLEX_MIXED_INTEGER_PROGRAMMING:
return BuildCplexInterface(true, solver);
#endif
default:
// TODO(user): Revert to the best *available* interface.
LOG(FATAL) << "Linear solver not recognized.";
}
return NULL;
}
} // namespace
namespace {
int NumDigits(int n) {
// Number of digits needed to write a non-negative integer in base 10.
// Note(user): std::max(1, log(0) + 1) == std::max(1, -inf) == 1.
#if defined(_MSC_VER)
return static_cast<int>(std::max(1.0L, log(1.0L * n) / log(10.0L) + 1.0));
#else
return static_cast<int>(std::max(1.0, log10(static_cast<double>(n)) + 1.0));
#endif
}
} // namespace
MPSolver::MPSolver(const std::string& name, OptimizationProblemType problem_type)
: name_(name),
problem_type_(problem_type),
#if !defined(_MSC_VER)
variable_name_to_index_(1),
constraint_name_to_index_(1),
#endif
time_limit_(0.0) {
timer_.Restart();
interface_.reset(BuildSolverInterface(this));
if (FLAGS_linear_solver_enable_verbose_output) {
EnableOutput();
}
objective_.reset(new MPObjective(interface_.get()));
}
MPSolver::~MPSolver() { Clear(); }
// static
bool MPSolver::SupportsProblemType(OptimizationProblemType problem_type) {
#ifdef USE_CLP
if (problem_type == CLP_LINEAR_PROGRAMMING) return true;
#endif
#ifdef USE_GLPK
if (problem_type == GLPK_LINEAR_PROGRAMMING) return true;
if (problem_type == GLPK_MIXED_INTEGER_PROGRAMMING) return true;
#endif
#ifdef USE_BOP
if (problem_type == BOP_INTEGER_PROGRAMMING) return true;
#endif
#ifdef USE_GLOP
if (problem_type == GLOP_LINEAR_PROGRAMMING) return true;
#endif
#if defined(USE_SLM)
if (problem_type == SULUM_LINEAR_PROGRAMMING) return true;
if (problem_type == SULUM_MIXED_INTEGER_PROGRAMMING) return true;
#endif
#ifdef USE_GUROBI
if (problem_type == GUROBI_LINEAR_PROGRAMMING) return true;
if (problem_type == GUROBI_MIXED_INTEGER_PROGRAMMING) return true;
#endif
#ifdef USE_SCIP
if (problem_type == SCIP_MIXED_INTEGER_PROGRAMMING) return true;
#endif
#ifdef USE_CBC
if (problem_type == CBC_MIXED_INTEGER_PROGRAMMING) return true;
#endif
return false;
}
MPVariable* MPSolver::LookupVariableOrNull(const std::string& var_name) const {
hash_map<std::string, int>::const_iterator it =
variable_name_to_index_.find(var_name);
if (it == variable_name_to_index_.end()) return NULL;
return variables_[it->second];
}
MPConstraint* MPSolver::LookupConstraintOrNull(const std::string& constraint_name)
const {
hash_map<std::string, int>::const_iterator it =
constraint_name_to_index_.find(constraint_name);
if (it == constraint_name_to_index_.end()) return NULL;
return constraints_[it->second];
}
// ----- Methods using protocol buffers -----
MPSolverResponseStatus MPSolver::LoadModelFromProto(
const MPModelProto& input_model, std::string* error_message) {
// The variable and constraint names are dropped, because we allow
// duplicate names in the proto (they're not considered as 'ids'),
// unlike the MPSolver C++ API which crashes if there are duplicate names.
// Clearing the names makes the MPSolver generate unique names.
//
// TODO(user): This limits the number of variables and constraints to 10^9:
// we should fix that.
return LoadModelFromProtoInternal(input_model, /*clear_names=*/true,
error_message);
}
MPSolverResponseStatus MPSolver::LoadModelFromProtoWithUniqueNamesOrDie(
const MPModelProto& input_model, std::string* error_message) {
return LoadModelFromProtoInternal(input_model, /*clear_names=*/false,
error_message);
}
MPSolverResponseStatus MPSolver::LoadModelFromProtoInternal(
const MPModelProto& input_model, bool clear_names, std::string* error_message) {
CHECK(error_message != nullptr);
const std::string error = FindErrorInMPModelProto(input_model);
if (!error.empty()) {
*error_message = error;
LOG_IF(INFO, OutputIsEnabled())
<< "Invalid model given to LoadModelFromProto(): " << error;
if (FLAGS_mpsolver_bypass_model_validation) {
LOG_IF(INFO, OutputIsEnabled())
<< "Ignoring the model error(s) because of"
<< " --mpsolver_bypass_model_validation.";
} else {
return error.find("Infeasible") == std::string::npos ? MPSOLVER_MODEL_INVALID
: MPSOLVER_INFEASIBLE;
}
}
MPObjective* const objective = MutableObjective();
// Passing empty names makes the MPSolver generate unique names.
const std::string empty;
for (int i = 0; i < input_model.variable_size(); ++i) {
const MPVariableProto& var_proto = input_model.variable(i);
MPVariable* variable =
MakeNumVar(var_proto.lower_bound(), var_proto.upper_bound(),
clear_names ? empty : var_proto.name());
variable->SetInteger(var_proto.is_integer());
objective->SetCoefficient(variable, var_proto.objective_coefficient());
}
for (int i = 0; i < input_model.constraint_size(); ++i) {
const MPConstraintProto& ct_proto = input_model.constraint(i);
MPConstraint* const ct =
MakeRowConstraint(ct_proto.lower_bound(), ct_proto.upper_bound(),
clear_names ? empty : ct_proto.name());
ct->set_is_lazy(ct_proto.is_lazy());
for (int j = 0; j < ct_proto.var_index_size(); ++j) {
ct->SetCoefficient(variables_[ct_proto.var_index(j)],
ct_proto.coefficient(j));
}
}
objective->SetOptimizationDirection(input_model.maximize());
if (input_model.has_objective_offset()) {
objective->SetOffset(input_model.objective_offset());
}
// Stores any hints about where to start the solve.
solution_hint_.clear();
for (int i = 0; i < input_model.solution_hint().var_index_size(); ++i) {
solution_hint_.push_back(
std::make_pair(variables_[input_model.solution_hint().var_index(i)],
input_model.solution_hint().var_value(i)));
}
return MPSOLVER_MODEL_IS_VALID;
}
namespace {
MPSolverResponseStatus ResultStatusToMPSolverResponseStatus(
MPSolver::ResultStatus status) {
switch (status) {
case MPSolver::OPTIMAL:
return MPSOLVER_OPTIMAL;
case MPSolver::FEASIBLE:
return MPSOLVER_FEASIBLE;
case MPSolver::INFEASIBLE:
return MPSOLVER_INFEASIBLE;
case MPSolver::UNBOUNDED:
return MPSOLVER_UNBOUNDED;
case MPSolver::ABNORMAL:
return MPSOLVER_ABNORMAL;
case MPSolver::MODEL_INVALID:
return MPSOLVER_MODEL_INVALID;
case MPSolver::NOT_SOLVED:
return MPSOLVER_NOT_SOLVED;
}
return MPSOLVER_UNKNOWN_STATUS;
}
} // namespace
void MPSolver::FillSolutionResponseProto(MPSolutionResponse* response) const {
CHECK_NOTNULL(response);
response->Clear();
response->set_status(
ResultStatusToMPSolverResponseStatus(interface_->result_status_));
if (interface_->result_status_ == MPSolver::OPTIMAL ||
interface_->result_status_ == MPSolver::FEASIBLE) {
response->set_objective_value(Objective().Value());
for (int i = 0; i < variables_.size(); ++i) {
response->add_variable_value(variables_[i]->solution_value());
}
if (interface_->IsMIP()) {
response->set_best_objective_bound(interface_->best_objective_bound());
}
}
}
// static
void MPSolver::SolveWithProto(const MPModelRequest& model_request,
MPSolutionResponse* response) {
CHECK_NOTNULL(response);
const MPModelProto& model = model_request.model();
MPSolver solver(model.name(), static_cast<MPSolver::OptimizationProblemType>(
model_request.solver_type()));
if (model_request.enable_internal_solver_output()) {
solver.EnableOutput();
}
std::string error_message;
response->set_status(solver.LoadModelFromProto(model, &error_message));
if (response->status() != MPSOLVER_MODEL_IS_VALID) {
LOG_EVERY_N_SEC(WARNING, 1.0)
<< "Loading model from protocol buffer failed, load status = "
<< MPSolverResponseStatus_Name(response->status()) << " ("
<< response->status() << "); Error: " << error_message;
return;
}
if (model_request.has_solver_time_limit_seconds()) {
// static_cast<int64> avoids a warning with -Wreal-conversion. This
// helps catching bugs with unwanted conversions from double to ints.
solver.set_time_limit(
static_cast<int64>(model_request.solver_time_limit_seconds() * 1000));
}
solver.SetSolverSpecificParametersAsString(
model_request.solver_specific_parameters());
solver.Solve();
solver.FillSolutionResponseProto(response);
}
void MPSolver::ExportModelToProto(MPModelProto* output_model) const {
DCHECK(output_model != NULL);
output_model->Clear();
// Name
output_model->set_name(Name());
// Variables
for (int j = 0; j < variables_.size(); ++j) {
const MPVariable* const var = variables_[j];
MPVariableProto* const variable_proto = output_model->add_variable();
// TODO(user): Add option to avoid filling the var name to avoid overly
// large protocol buffers.
variable_proto->set_name(var->name());
variable_proto->set_lower_bound(var->lb());
variable_proto->set_upper_bound(var->ub());
variable_proto->set_is_integer(var->integer());
if (objective_->GetCoefficient(var) != 0.0) {
variable_proto->set_objective_coefficient(
objective_->GetCoefficient(var));
}
}
// Map the variables to their indices. This is needed to output the
// variables in the order they were created, which in turn is needed to have
// repeatable results with ExportModelAsLpString and ExportModelAsMpsString.
// This step is needed as long as the variable indices are given by the
// underlying solver at the time of model extraction.
// TODO(user): remove this step.
hash_map<const MPVariable*, int> var_to_index;
for (int j = 0; j < variables_.size(); ++j) {
var_to_index[variables_[j]] = j;
}
// Constraints
for (int i = 0; i < constraints_.size(); ++i) {
MPConstraint* const constraint = constraints_[i];
MPConstraintProto* const constraint_proto = output_model->add_constraint();
constraint_proto->set_name(constraint->name());
constraint_proto->set_lower_bound(constraint->lb());
constraint_proto->set_upper_bound(constraint->ub());
constraint_proto->set_is_lazy(constraint->is_lazy());
// Vector linear_term will contain pairs (variable index, coeff), that will
// be sorted by variable index.
std::vector<std::pair<int, double> > linear_term;
for (CoeffEntry entry : constraint->coefficients_) {
const MPVariable* const var = entry.first;
const int var_index = FindWithDefault(var_to_index, var, -1);
DCHECK_NE(-1, var_index);
const double coeff = entry.second;
linear_term.push_back(std::pair<int, double>(var_index, coeff));
}
// The cost of sort is expected to be low as constraints usually have very
// few terms.
std::sort(linear_term.begin(), linear_term.end());
// Now use linear term.
for (const std::pair<int, double> var_and_coeff : linear_term) {
constraint_proto->add_var_index(var_and_coeff.first);
constraint_proto->add_coefficient(var_and_coeff.second);
}
}
output_model->set_maximize(Objective().maximization());
output_model->set_objective_offset(Objective().offset());
}
bool MPSolver::LoadSolutionFromProto(const MPSolutionResponse& response) {
interface_->result_status_ = static_cast<ResultStatus>(response.status());
if (response.status() != MPSOLVER_OPTIMAL &&
response.status() != MPSOLVER_FEASIBLE) {
LOG(ERROR)
<< "Cannot load a solution unless its status is OPTIMAL or FEASIBLE.";
return false;
}
// Before touching the variables, verify that the solution looks legit:
// each variable of the MPSolver must have its value listed exactly once, and
// each listed solution should correspond to a known variable.
if (response.variable_value_size() != variables_.size()) {
LOG(ERROR) << "Trying to load a solution whose number of variables does not"
<< " correspond to the Solver.";
return false;
}
double largest_error = 0;
interface_->ExtractModel();
int num_vars_out_of_bounds = 0;
const double tolerance = MPSolverParameters::kDefaultPrimalTolerance;
for (int i = 0; i < response.variable_value_size(); ++i) {
// Look further: verify the bounds. Since linear solvers yield (small)
// numerical errors, though, we just log a warning if the variables look
// like they are out of their bounds. The user should inspect the values.
const double var_value = response.variable_value(i);
MPVariable* var = variables_[i];
// TODO(user): Use parameter when they become available in this class.
const double lb_error = var->lb() - var_value;
const double ub_error = var_value - var->ub();
if (lb_error > tolerance || ub_error > tolerance) {
++num_vars_out_of_bounds;
largest_error = std::max(largest_error, std::max(lb_error, ub_error));
}
var->set_solution_value(var_value);
}
if (num_vars_out_of_bounds > 0) {
LOG(WARNING)
<< "Loaded a solution whose variables matched the solver's, but "
<< num_vars_out_of_bounds << " out of " << variables_.size()
<< " exceed one of their bounds by more than the primal tolerance: "
<< tolerance;
}
// Set the objective value, if is known.
if (response.has_objective_value()) {
interface_->objective_value_ = response.objective_value();
}
// Mark the status as SOLUTION_SYNCHRONIZED, so that users may inspect the
// solution normally.
interface_->sync_status_ = MPSolverInterface::SOLUTION_SYNCHRONIZED;
return true;
}
void MPSolver::Clear() {
MutableObjective()->Clear();
STLDeleteElements(&variables_);
STLDeleteElements(&constraints_);
variables_.clear();
variable_name_to_index_.clear();
variable_is_extracted_.clear();
constraints_.clear();
constraint_name_to_index_.clear();
constraint_is_extracted_.clear();
interface_->Reset();
solution_hint_.clear();
}
void MPSolver::Reset() { interface_->Reset(); }
bool MPSolver::InterruptSolve() { return interface_->InterruptSolve(); }
MPVariable* MPSolver::MakeVar(double lb, double ub, bool integer,
const std::string& name) {
const int var_index = NumVariables();
const std::string fixed_name =
name.empty() ? StringPrintf("auto_v_%09d", var_index) : name;
InsertOrDie(&variable_name_to_index_, fixed_name, var_index);
MPVariable* v =
new MPVariable(var_index, lb, ub, integer, fixed_name, interface_.get());
variables_.push_back(v);
variable_is_extracted_.push_back(false);
interface_->AddVariable(v);
return v;
}
MPVariable* MPSolver::MakeNumVar(double lb, double ub, const std::string& name) {
return MakeVar(lb, ub, false, name);
}
MPVariable* MPSolver::MakeIntVar(double lb, double ub, const std::string& name) {
return MakeVar(lb, ub, true, name);
}
MPVariable* MPSolver::MakeBoolVar(const std::string& name) {
return MakeVar(0.0, 1.0, true, name);
}
void MPSolver::MakeVarArray(int nb, double lb, double ub, bool integer,
const std::string& name, std::vector<MPVariable*>* vars) {
DCHECK_GE(nb, 0);
if (nb <= 0) return;
const int num_digits = NumDigits(nb);
for (int i = 0; i < nb; ++i) {
if (name.empty()) {
vars->push_back(MakeVar(lb, ub, integer, name));
} else {
std::string vname = StringPrintf("%s%0*d", name.c_str(), num_digits, i);
vars->push_back(MakeVar(lb, ub, integer, vname));
}
}
}
void MPSolver::MakeNumVarArray(int nb, double lb, double ub, const std::string& name,
std::vector<MPVariable*>* vars) {
MakeVarArray(nb, lb, ub, false, name, vars);
}
void MPSolver::MakeIntVarArray(int nb, double lb, double ub, const std::string& name,
std::vector<MPVariable*>* vars) {
MakeVarArray(nb, lb, ub, true, name, vars);
}
void MPSolver::MakeBoolVarArray(int nb, const std::string& name,
std::vector<MPVariable*>* vars) {
MakeVarArray(nb, 0.0, 1.0, true, name, vars);
}
MPConstraint* MPSolver::MakeRowConstraint(double lb, double ub) {
return MakeRowConstraint(lb, ub, "");
}
MPConstraint* MPSolver::MakeRowConstraint() {
return MakeRowConstraint(-infinity(), infinity(), "");
}
MPConstraint* MPSolver::MakeRowConstraint(double lb, double ub,
const std::string& name) {
const int constraint_index = NumConstraints();
const std::string fixed_name =
name.empty() ? StringPrintf("auto_c_%09d", constraint_index) : name;
InsertOrDie(&constraint_name_to_index_, fixed_name, constraint_index);
MPConstraint* const constraint =
new MPConstraint(constraint_index, lb, ub, fixed_name, interface_.get());
constraints_.push_back(constraint);
constraint_is_extracted_.push_back(false);
interface_->AddRowConstraint(constraint);
return constraint;
}
MPConstraint* MPSolver::MakeRowConstraint(const std::string& name) {
return MakeRowConstraint(-infinity(), infinity(), name);
}
int MPSolver::ComputeMaxConstraintSize(int min_constraint_index,
int max_constraint_index) const {
int max_constraint_size = 0;
DCHECK_GE(min_constraint_index, 0);
DCHECK_LE(max_constraint_index, constraints_.size());
for (int i = min_constraint_index; i < max_constraint_index; ++i) {
MPConstraint* const ct = constraints_[i];
if (ct->coefficients_.size() > max_constraint_size) {
max_constraint_size = ct->coefficients_.size();
}
}
return max_constraint_size;
}
bool MPSolver::HasInfeasibleConstraints() const {
bool hasInfeasibleConstraints = false;
for (int i = 0; i < constraints_.size(); ++i) {
if (constraints_[i]->lb() > constraints_[i]->ub()) {
LOG(WARNING) << "Constraint " << constraints_[i]->name() << " (" << i
<< ") has contradictory bounds:"
<< " lower bound = " << constraints_[i]->lb()
<< " upper bound = " << constraints_[i]->ub();
hasInfeasibleConstraints = true;
}
}
return hasInfeasibleConstraints;
}
MPSolver::ResultStatus MPSolver::Solve() {
MPSolverParameters default_param;
return Solve(default_param);
}
MPSolver::ResultStatus MPSolver::Solve(const MPSolverParameters& param) {
// Special case for infeasible constraints so that all solvers have
// the same behavior.
// TODO(user): replace this by model extraction to proto + proto validation
// (the proto has very low overhead compared to the wrapper, both in
// performance and memory, so it's ok).
if (HasInfeasibleConstraints()) {
interface_->result_status_ = MPSolver::INFEASIBLE;
return interface_->result_status_;
}
MPSolver::ResultStatus status = interface_->Solve(param);
if (FLAGS_verify_solution) {
if (status != MPSolver::OPTIMAL) {
VLOG(1) << "--verify_solution enabled, but the solver did not find an"
<< " optimal solution: skipping the verification.";
} else if (!VerifySolution(
param.GetDoubleParam(MPSolverParameters::PRIMAL_TOLERANCE),
FLAGS_log_verification_errors)) {
status = MPSolver::ABNORMAL;
interface_->result_status_ = status;
}
}
DCHECK_EQ(interface_->result_status_, status);
return status;
}
void MPSolver::Write(const std::string& file_name) { interface_->Write(file_name); }
namespace {
std::string PrettyPrintVar(const MPVariable& var) {
const std::string prefix = "Variable '" + var.name() + "': domain = ";
if (var.lb() >= MPSolver::infinity() || var.ub() <= -MPSolver::infinity() ||
var.lb() > var.ub()) {
return prefix + "∅"; // Empty set.
}
// Special case: integer variable with at most two possible values
// (and potentially none).
if (var.integer() && var.ub() - var.lb() <= 1) {
const int64 lb = static_cast<int64>(ceil(var.lb()));
const int64 ub = static_cast<int64>(floor(var.ub()));
if (lb > ub) {
return prefix + "∅";
} else if (lb == ub) {
return StringPrintf("%s{ %lld }", prefix.c_str(), lb);
} else {
return StringPrintf("%s{ %lld, %lld }", prefix.c_str(), lb, ub);
}
}
// Special case: single (non-infinite) real value.
if (var.lb() == var.ub()) {
return StringPrintf("%s{ %f }", prefix.c_str(), var.lb());
}
return prefix + (var.integer() ? "Integer" : "Real") + " in " +
(var.lb() <= -MPSolver::infinity() ? std::string("]-∞")
: StringPrintf("[%f", var.lb())) +
", " +
(var.ub() >= MPSolver::infinity() ? std::string("+∞[")
: StringPrintf("%f]", var.ub()));
}
std::string PrettyPrintConstraint(const MPConstraint& constraint) {
std::string prefix = "Constraint '" + constraint.name() + "': ";
if (constraint.lb() >= MPSolver::infinity() ||
constraint.ub() <= -MPSolver::infinity() ||
constraint.lb() > constraint.ub()) {
return prefix + "ALWAYS FALSE";
}
if (constraint.lb() <= -MPSolver::infinity() &&
constraint.ub() >= MPSolver::infinity()) {
return prefix + "ALWAYS TRUE";
}
prefix += "<linear expr>";
// Equality.
if (constraint.lb() == constraint.ub()) {
return StringPrintf("%s = %f", prefix.c_str(), constraint.lb());
}
// Inequalities.
if (constraint.lb() <= -MPSolver::infinity()) {
return StringPrintf("%s ≤ %f", prefix.c_str(), constraint.ub());
}
if (constraint.ub() >= MPSolver::infinity()) {
return StringPrintf("%s ≥ %f", prefix.c_str(), constraint.lb());
}
return StringPrintf("%s ∈ [%f, %f]", prefix.c_str(), constraint.lb(),
constraint.ub());
}
} // namespace
std::vector<double> MPSolver::ComputeConstraintActivities() const {
// TODO(user): test this failure case.
if (!interface_->CheckSolutionIsSynchronizedAndExists()) return {};
std::vector<double> activities(constraints_.size(), 0.0);
for (int i = 0; i < constraints_.size(); ++i) {
const MPConstraint& constraint = *constraints_[i];
AccurateSum<double> sum;
for (CoeffEntry entry : constraint.coefficients_) {
sum.Add(entry.first->solution_value() * entry.second);
}
activities[i] = sum.Value();
}
return activities;
}
// TODO(user): split.
bool MPSolver::VerifySolution(double tolerance, bool log_errors) const {
double max_observed_error = 0;
if (tolerance < 0) tolerance = infinity();
int num_errors = 0;
// Verify variables.
for (int i = 0; i < variables_.size(); ++i) {
const MPVariable& var = *variables_[i];
const double value = var.solution_value();
// Check for NaN.
if (isnan(value)) {
++num_errors;
max_observed_error = infinity();
LOG_IF(ERROR, log_errors) << "NaN value for " << PrettyPrintVar(var);
continue;
}
// Check lower bound.
if (var.lb() != -infinity()) {
if (value < var.lb() - tolerance) {
++num_errors;
max_observed_error = std::max(max_observed_error, var.lb() - value);
LOG_IF(ERROR, log_errors) << "Value " << value << " too low for "
<< PrettyPrintVar(var);
}
}
// Check upper bound.
if (var.ub() != infinity()) {
if (value > var.ub() + tolerance) {
++num_errors;
max_observed_error = std::max(max_observed_error, value - var.ub());
LOG_IF(ERROR, log_errors) << "Value " << value << " too high for "
<< PrettyPrintVar(var);
}
}
// Check integrality.
if (var.integer()) {
if (fabs(value - round(value)) > tolerance) {
++num_errors;
max_observed_error =
std::max(max_observed_error, fabs(value - round(value)));
LOG_IF(ERROR, log_errors) << "Non-integer value " << value << " for "
<< PrettyPrintVar(var);
}
}
}
// Verify constraints.
const std::vector<double> activities = ComputeConstraintActivities();
for (int i = 0; i < constraints_.size(); ++i) {
const MPConstraint& constraint = *constraints_[i];
const double activity = activities[i];
// Re-compute the activity with a inaccurate summing algorithm.
double inaccurate_activity = 0.0;
for (CoeffEntry entry : constraint.coefficients_) {
inaccurate_activity += entry.first->solution_value() * entry.second;
}
// Catch NaNs.
if (isnan(activity) || isnan(inaccurate_activity)) {
++num_errors;
max_observed_error = infinity();
LOG_IF(ERROR, log_errors) << "NaN value for "
<< PrettyPrintConstraint(constraint);
continue;
}
// Check bounds.
if (constraint.lb() != -infinity()) {
if (activity < constraint.lb() - tolerance) {
++num_errors;
max_observed_error =
std::max(max_observed_error, constraint.lb() - activity);
LOG_IF(ERROR, log_errors) << "Activity " << activity << " too low for "
<< PrettyPrintConstraint(constraint);
} else if (inaccurate_activity < constraint.lb() - tolerance) {
LOG_IF(WARNING, log_errors)
<< "Activity " << activity << ", computed with the (inaccurate)"
<< " standard sum of its terms, is too low for "
<< PrettyPrintConstraint(constraint);
}
}
if (constraint.ub() != infinity()) {
if (activity > constraint.ub() + tolerance) {
++num_errors;
max_observed_error =
std::max(max_observed_error, activity - constraint.ub());
LOG_IF(ERROR, log_errors) << "Activity " << activity << " too high for "
<< PrettyPrintConstraint(constraint);
} else if (inaccurate_activity > constraint.ub() + tolerance) {
LOG_IF(WARNING, log_errors)
<< "Activity " << activity << ", computed with the (inaccurate)"
<< " standard sum of its terms, is too high for "
<< PrettyPrintConstraint(constraint);
}
}
}
// Verify that the objective value wasn't reported incorrectly.
const MPObjective& objective = Objective();
AccurateSum<double> objective_sum;
objective_sum.Add(objective.offset());
double inaccurate_objective_value = objective.offset();
for (CoeffEntry entry : objective.coefficients_) {
const double term = entry.first->solution_value() * entry.second;
objective_sum.Add(term);
inaccurate_objective_value += term;
}
const double actual_objective_value = objective_sum.Value();
if (!AreWithinAbsoluteOrRelativeTolerances(
objective.Value(), actual_objective_value, tolerance, tolerance)) {
++num_errors;
max_observed_error = std::max(
max_observed_error, fabs(actual_objective_value - objective.Value()));
LOG_IF(ERROR, log_errors) << "Objective value " << objective.Value()
<< " isn't accurate"
<< ", it should be " << actual_objective_value
<< " (delta=" << actual_objective_value -
objective.Value() << ").";
} else if (!AreWithinAbsoluteOrRelativeTolerances(objective.Value(),
inaccurate_objective_value,
tolerance, tolerance)) {
LOG_IF(WARNING, log_errors)
<< "Objective value " << objective.Value() << " doesn't correspond"
<< " to the value computed with the standard (and therefore inaccurate)"
<< " sum of its terms.";
}
if (num_errors > 0) {
LOG_IF(ERROR, log_errors) << "There were " << num_errors
<< " errors above the tolerance (" << tolerance
<< "), the largest was " << max_observed_error;
return false;
}
return true;
}
bool MPSolver::OutputIsEnabled() const { return !interface_->quiet(); }
void MPSolver::EnableOutput() { interface_->set_quiet(false); }
void MPSolver::SuppressOutput() { interface_->set_quiet(true); }
int64 MPSolver::iterations() const { return interface_->iterations(); }
int64 MPSolver::nodes() const { return interface_->nodes(); }
double MPSolver::ComputeExactConditionNumber() const {
return interface_->ComputeExactConditionNumber();
}
bool MPSolver::OwnsVariable(const MPVariable* var) const {
if (var == NULL) return false;
// First, verify that a variable with the same name exists, and look up
// its index (names are unique, so there can be only one).
const int var_index =
FindWithDefault(variable_name_to_index_, var->name(), -1);
if (var_index == -1) return false;
// Then, verify that the variable with this index has the same address.
return variables_[var_index] == var;
}
#ifndef ANDROID_JNI
bool MPSolver::ExportModelAsLpFormat(bool obfuscate, std::string* output) {
MPModelProto proto;
ExportModelToProto(&proto);
MPModelProtoExporter exporter(proto);
return exporter.ExportModelAsLpFormat(obfuscate, output);
}
bool MPSolver::ExportModelAsMpsFormat(bool fixed_format, bool obfuscate,
std::string* output) {
MPModelProto proto;
ExportModelToProto(&proto);
MPModelProtoExporter exporter(proto);
return exporter.ExportModelAsMpsFormat(fixed_format, obfuscate, output);
}
#endif
// ---------- MPSolverInterface ----------
const int MPSolverInterface::kDummyVariableIndex = 0;
MPSolverInterface::MPSolverInterface(MPSolver* const solver)
: solver_(solver),
sync_status_(MODEL_SYNCHRONIZED),
result_status_(MPSolver::NOT_SOLVED),
maximize_(false),
last_constraint_index_(0),
last_variable_index_(0),
objective_value_(0.0),
quiet_(true) {}
MPSolverInterface::~MPSolverInterface() {}
void MPSolverInterface::Write(const std::string& filename) {
LOG(WARNING) << "Writing model not implemented in this solver interface.";
}
void MPSolverInterface::ExtractModel() {
switch (sync_status_) {
case MUST_RELOAD: {
ExtractNewVariables();
ExtractNewConstraints();
ExtractObjective();
last_constraint_index_ = solver_->constraints_.size();
last_variable_index_ = solver_->variables_.size();
sync_status_ = MODEL_SYNCHRONIZED;
break;
}
case MODEL_SYNCHRONIZED: {
// Everything has already been extracted.
DCHECK_EQ(last_constraint_index_, solver_->constraints_.size());
DCHECK_EQ(last_variable_index_, solver_->variables_.size());
break;
}
case SOLUTION_SYNCHRONIZED: {
// Nothing has changed since last solve.
DCHECK_EQ(last_constraint_index_, solver_->constraints_.size());
DCHECK_EQ(last_variable_index_, solver_->variables_.size());
break;
}
}
}
// TODO(user): remove this method.
void MPSolverInterface::ResetExtractionInformation() {
sync_status_ = MUST_RELOAD;
last_constraint_index_ = 0;
last_variable_index_ = 0;
solver_->variable_is_extracted_.assign(solver_->variables_.size(), false);
solver_->constraint_is_extracted_.assign(solver_->constraints_.size(), false);
}
bool MPSolverInterface::CheckSolutionIsSynchronized() const {
if (sync_status_ != SOLUTION_SYNCHRONIZED) {
LOG(DFATAL)
<< "The model has been changed since the solution was last computed."
<< " MPSolverInterface::status_ = " << sync_status_;
return false;
}
return true;
}
// Default version that can be overwritten by a solver-specific
// version to accomodate for the quirks of each solver.
bool MPSolverInterface::CheckSolutionExists() const {
if (result_status_ != MPSolver::OPTIMAL &&
result_status_ != MPSolver::FEASIBLE) {
LOG(DFATAL) << "No solution exists. MPSolverInterface::result_status_ = "
<< result_status_;
return false;
}
return true;
}
// Default version that can be overwritten by a solver-specific
// version to accomodate for the quirks of each solver.
bool MPSolverInterface::CheckBestObjectiveBoundExists() const {
if (result_status_ != MPSolver::OPTIMAL &&
result_status_ != MPSolver::FEASIBLE) {
LOG(DFATAL) << "No information is available for the best objective bound."
<< " MPSolverInterface::result_status_ = " << result_status_;
return false;
}
return true;
}
double MPSolverInterface::trivial_worst_objective_bound() const {
return maximize_ ? -std::numeric_limits<double>::infinity()
: std::numeric_limits<double>::infinity();
}
double MPSolverInterface::objective_value() const {
if (!CheckSolutionIsSynchronizedAndExists()) return 0;
return objective_value_;
}
void MPSolverInterface::InvalidateSolutionSynchronization() {
if (sync_status_ == SOLUTION_SYNCHRONIZED) {
sync_status_ = MODEL_SYNCHRONIZED;
}
}
double MPSolverInterface::ComputeExactConditionNumber() const {
// Override this method in interfaces that actually support it.
LOG(DFATAL) << "ComputeExactConditionNumber not implemented for "
<< MPModelRequest_SolverType_Name(
static_cast<MPModelRequest::SolverType>(
solver_->ProblemType()));
return 0.0;
}
void MPSolverInterface::SetCommonParameters(const MPSolverParameters& param) {
// TODO(user): Overhaul the code that sets parameters to enable changing
// GLOP parameters without issuing warnings.
// By default, we let GLOP keep its own default tolerance, much more accurate
// than for the rest of the solvers.
//
#if defined(USE_GLOP)
if (solver_->ProblemType() != MPSolver::GLOP_LINEAR_PROGRAMMING) {
#endif
SetPrimalTolerance(
param.GetDoubleParam(MPSolverParameters::PRIMAL_TOLERANCE));
SetDualTolerance(param.GetDoubleParam(MPSolverParameters::DUAL_TOLERANCE));
#if defined(USE_GLOP)
}
#endif
SetPresolveMode(param.GetIntegerParam(MPSolverParameters::PRESOLVE));
// TODO(user): In the future, we could distinguish between the
// algorithm to solve the root LP and the algorithm to solve node
// LPs. Not sure if underlying solvers support it.
int value = param.GetIntegerParam(MPSolverParameters::LP_ALGORITHM);
if (value != MPSolverParameters::kDefaultIntegerParamValue) {
SetLpAlgorithm(value);
}
}
void MPSolverInterface::SetMIPParameters(const MPSolverParameters& param) {
#if defined(USE_GLOP)
if (solver_->ProblemType() != MPSolver::GLOP_LINEAR_PROGRAMMING) {
#endif
SetRelativeMipGap(param.GetDoubleParam(
MPSolverParameters::RELATIVE_MIP_GAP));
#if defined(USE_GLOP)
}
#endif
}
void MPSolverInterface::SetUnsupportedDoubleParam(
MPSolverParameters::DoubleParam param) const {
LOG(WARNING) << "Trying to set an unsupported parameter: " << param << ".";
}
void MPSolverInterface::SetUnsupportedIntegerParam(
MPSolverParameters::IntegerParam param) const {
LOG(WARNING) << "Trying to set an unsupported parameter: " << param << ".";
}
void MPSolverInterface::SetDoubleParamToUnsupportedValue(
MPSolverParameters::DoubleParam param, double value) const {
LOG(WARNING) << "Trying to set a supported parameter: " << param
<< " to an unsupported value: " << value;
}
void MPSolverInterface::SetIntegerParamToUnsupportedValue(
MPSolverParameters::IntegerParam param, int value) const {
LOG(WARNING) << "Trying to set a supported parameter: " << param
<< " to an unsupported value: " << value;
}
bool MPSolverInterface::SetSolverSpecificParametersAsString(
const std::string& parameters) {
#ifdef ANDROID_JNI
// This is not implemented on Android because there is no default /tmp and a
// pointer to the Java environment is require to query for the application
// folder or the location of external storage (if any).
return false;
#else
if (parameters.empty()) return true;
// Note(user): this method needs to return a success/failure boolean
// immediately, so we also perform the actual parameter parsing right away.
// Some implementations will keep them forever and won't need to re-parse
// them; some (eg. SCIP, Gurobi) need to re-parse the parameters every time
// they do Solve(). We just store the parameters std::string anyway.
std::string extension = ValidFileExtensionForParameterFile();
#if defined(__linux)
int32 tid = static_cast<int32>(pthread_self());
#else // defined(__linux__)
int32 tid = 123;
#endif // defined(__linux__)
#if !defined(_MSC_VER)
int32 pid = static_cast<int32>(getpid());
#else // _MSC_VER
int32 pid = 456;
#endif // _MSC_VER
int64 now = base::GetCurrentTimeNanos();
std::string filename = StringPrintf("/tmp/parameters-tempfile-%x-%d-%llx%s",
tid, pid, now, extension.c_str());
bool no_error_so_far = true;
if (no_error_so_far) {
no_error_so_far =
file::SetContents(filename, parameters, file::Defaults()).ok();
}
if (no_error_so_far) {
no_error_so_far = ReadParameterFile(filename);
// We need to clean up the file even if ReadParameterFile() returned
// false. In production we can continue even if the deletion failed.
if (!file::Delete(filename, file::Defaults()).ok()) {
LOG(DFATAL) << "Couldn't delete temporary parameters file: " << filename;
}
}
if (!no_error_so_far) {
LOG(WARNING) << "Error in SetSolverSpecificParametersAsString() "
<< "for solver type: "
<< MPModelRequest::SolverType_Name(
static_cast<MPModelRequest::SolverType>(
solver_->ProblemType()));
}
return no_error_so_far;
#endif
}
bool MPSolverInterface::ReadParameterFile(const std::string& filename) {
LOG(WARNING) << "ReadParameterFile() not supported by this solver.";
return false;
}
std::string MPSolverInterface::ValidFileExtensionForParameterFile() const {
return ".tmp";
}
// ---------- MPSolverParameters ----------
const double MPSolverParameters::kDefaultRelativeMipGap = 1e-4;
// For the primal and dual tolerances, choose the same default as CLP and GLPK.
const double MPSolverParameters::kDefaultPrimalTolerance = 1e-7;
const double MPSolverParameters::kDefaultDualTolerance = 1e-7;
const MPSolverParameters::PresolveValues MPSolverParameters::kDefaultPresolve =
MPSolverParameters::PRESOLVE_ON;
const MPSolverParameters::IncrementalityValues
MPSolverParameters::kDefaultIncrementality =
MPSolverParameters::INCREMENTALITY_ON;
const double MPSolverParameters::kDefaultDoubleParamValue = -1.0;
const int MPSolverParameters::kDefaultIntegerParamValue = -1;
const double MPSolverParameters::kUnknownDoubleParamValue = -2.0;
const int MPSolverParameters::kUnknownIntegerParamValue = -2;
// The constructor sets all parameters to their default value.
MPSolverParameters::MPSolverParameters()
: relative_mip_gap_value_(kDefaultRelativeMipGap),
primal_tolerance_value_(kDefaultPrimalTolerance),
dual_tolerance_value_(kDefaultDualTolerance),
presolve_value_(kDefaultPresolve),
scaling_value_(kDefaultIntegerParamValue),
lp_algorithm_value_(kDefaultIntegerParamValue),
incrementality_value_(kDefaultIncrementality),
lp_algorithm_is_default_(true) {}
void MPSolverParameters::SetDoubleParam(MPSolverParameters::DoubleParam param,
double value) {
switch (param) {
case RELATIVE_MIP_GAP: {
relative_mip_gap_value_ = value;
break;
}
case PRIMAL_TOLERANCE: {
primal_tolerance_value_ = value;
break;
}
case DUAL_TOLERANCE: {
dual_tolerance_value_ = value;
break;
}
default: {
LOG(ERROR) << "Trying to set an unknown parameter: " << param << ".";
}
}
}
void MPSolverParameters::SetIntegerParam(MPSolverParameters::IntegerParam param,
int value) {
switch (param) {
case PRESOLVE: {
if (value != PRESOLVE_OFF && value != PRESOLVE_ON) {
LOG(ERROR) << "Trying to set a supported parameter: " << param
<< " to an unknown value: " << value;
}
presolve_value_ = value;
break;
}
case SCALING: {
if (value != SCALING_OFF && value != SCALING_ON) {
LOG(ERROR) << "Trying to set a supported parameter: " << param
<< " to an unknown value: " << value;
}
scaling_value_ = value;
break;
}
case LP_ALGORITHM: {
if (value != DUAL && value != PRIMAL && value != BARRIER) {
LOG(ERROR) << "Trying to set a supported parameter: " << param
<< " to an unknown value: " << value;
}
lp_algorithm_value_ = value;
lp_algorithm_is_default_ = false;
break;
}
case INCREMENTALITY: {
if (value != INCREMENTALITY_OFF && value != INCREMENTALITY_ON) {
LOG(ERROR) << "Trying to set a supported parameter: " << param
<< " to an unknown value: " << value;
}
incrementality_value_ = value;
break;
}
default: {
LOG(ERROR) << "Trying to set an unknown parameter: " << param << ".";
}
}
}
void MPSolverParameters::ResetDoubleParam(
MPSolverParameters::DoubleParam param) {
switch (param) {
case RELATIVE_MIP_GAP: {
relative_mip_gap_value_ = kDefaultRelativeMipGap;
break;
}
case PRIMAL_TOLERANCE: {
primal_tolerance_value_ = kDefaultPrimalTolerance;
break;
}
case DUAL_TOLERANCE: {
dual_tolerance_value_ = kDefaultDualTolerance;
break;
}
default: {
LOG(ERROR) << "Trying to reset an unknown parameter: " << param << ".";
}
}
}
void MPSolverParameters::ResetIntegerParam(
MPSolverParameters::IntegerParam param) {
switch (param) {
case PRESOLVE: {
presolve_value_ = kDefaultPresolve;
break;
}
case SCALING: {
scaling_value_ = kDefaultIntegerParamValue;
break;
}
case LP_ALGORITHM: {
lp_algorithm_is_default_ = true;
break;
}
case INCREMENTALITY: {
incrementality_value_ = kDefaultIncrementality;
break;
}
default: {
LOG(ERROR) << "Trying to reset an unknown parameter: " << param << ".";
}
}
}
void MPSolverParameters::Reset() {
ResetDoubleParam(RELATIVE_MIP_GAP);
ResetDoubleParam(PRIMAL_TOLERANCE);
ResetDoubleParam(DUAL_TOLERANCE);
ResetIntegerParam(PRESOLVE);
ResetIntegerParam(SCALING);
ResetIntegerParam(LP_ALGORITHM);
ResetIntegerParam(INCREMENTALITY);
}
double MPSolverParameters::GetDoubleParam(MPSolverParameters::DoubleParam param)
const {
switch (param) {
case RELATIVE_MIP_GAP: { return relative_mip_gap_value_; }
case PRIMAL_TOLERANCE: { return primal_tolerance_value_; }
case DUAL_TOLERANCE: { return dual_tolerance_value_; }
default: {
LOG(ERROR) << "Trying to get an unknown parameter: " << param << ".";
return kUnknownDoubleParamValue;
}
}
}
int MPSolverParameters::GetIntegerParam(MPSolverParameters::IntegerParam param)
const {
switch (param) {
case PRESOLVE: { return presolve_value_; }
case LP_ALGORITHM: {
if (lp_algorithm_is_default_) return kDefaultIntegerParamValue;
return lp_algorithm_value_;
}
case INCREMENTALITY: { return incrementality_value_; }
case SCALING: { return scaling_value_; }
default: {
LOG(ERROR) << "Trying to get an unknown parameter: " << param << ".";
return kUnknownIntegerParamValue;
}
}
}
} // namespace operations_research
| {
"content_hash": "7349da41c7307f613f45091207007f85",
"timestamp": "",
"source": "github",
"line_count": 1557,
"max_line_length": 86,
"avg_line_length": 36.238921001926784,
"alnum_prop": 0.6607826456826882,
"repo_name": "WendellDuncan/or-tools",
"id": "c235f4502602741c8f3fc5c2ae451bfc8e47de88",
"size": "56438",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/linear_solver/linear_solver.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "3535"
},
{
"name": "C#",
"bytes": "82084"
},
{
"name": "C++",
"bytes": "7135517"
},
{
"name": "Java",
"bytes": "1439"
},
{
"name": "Lex",
"bytes": "2195"
},
{
"name": "Makefile",
"bytes": "231754"
},
{
"name": "Protocol Buffer",
"bytes": "103614"
},
{
"name": "Python",
"bytes": "10772"
},
{
"name": "Shell",
"bytes": "3811"
},
{
"name": "Yacc",
"bytes": "22646"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: Gumacs
* Date: 2016-11-09
* Time: 08:32 PM
*/
namespace Tests\Unit\Rules\Validators;
use Processor\DataProcessor;
use Processor\Exceptions\FailedProcessingException;
use Processor\Rules\Abstraction\Errors;
use Processor\Rules\Abstraction\RuleSettings;
class AlnumRuleTest extends \PHPUnit_Framework_TestCase
{
public function testAlnumTrueExtraCharacters(){
$return = DataProcessor::init()->alnum("-")->process("123-a");
$this->assertEquals(true, $return->isSuccess());
}
public function testAlnumTrue(){
$return = DataProcessor::init()->alnum()->process("123");
$this->assertEquals(true, $return->isSuccess());
}
public function testAlnumFalse(){
$return = DataProcessor::init()->alnum()->process("12-a");
$this->assertEquals(false, $return->isSuccess());
}
public function testAlnumTrueWithError(){
$return = DataProcessor::init()->alnum()->process("123", Errors::ALL);
$this->assertEquals(true, $return->isSuccess());
}
public function testAlnumFalseWithError(){
try{
$return = DataProcessor::init()->alnum()->process("123-a", Errors::ALL);
} catch(FailedProcessingException $e) {
$return = false;
$this->assertEquals(1, sizeof($e->getErrors()));
$this->assertEquals(RuleSettings::getErrorSetting("alnum"), $e->getErrors()['alnum']);
}finally{
$this->assertEquals(false, $return->isSuccess());
}
}
}
| {
"content_hash": "6f9908722a7667f8de19a584ee20d9e9",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 98,
"avg_line_length": 29.327272727272728,
"alnum_prop": 0.6106633601983881,
"repo_name": "gumacs92/dataprocessor",
"id": "7d9cbcb241deb17a6a08583a111152460c25c5f2",
"size": "1613",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/unit/rules/validators/AlnumValidatorRuleTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "125299"
}
],
"symlink_target": ""
} |
package com.by_syk.lib.nanoiconpack;
import android.app.SearchManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import com.by_syk.lib.nanoiconpack.bean.IconBean;
import com.by_syk.lib.nanoiconpack.dialog.IconDialog;
import com.by_syk.lib.nanoiconpack.util.AllIconsGetter;
import com.by_syk.lib.nanoiconpack.util.adapter.IconAdapter;
import com.wang.avi.AVLoadingIndicatorView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by By_syk on 2017-07-15.
*/
public class SearchActivity extends AppCompatActivity {
private SearchView searchView;
private IconAdapter adapter;
private List<IconBean> dataList = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
init();
(new LoadDataTask()).execute();
}
private void init() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
int[] gridNumAndWidth = calculateGridNumAndWidth();
recyclerView.setLayoutManager(new GridLayoutManager(this, gridNumAndWidth[0]));
adapter = new IconAdapter(this, gridNumAndWidth[1]);
adapter.setMode(IconAdapter.MODE_ICON_LABEL);
adapter.setOnItemClickListener(new IconAdapter.OnItemClickListener() {
@Override
public void onClick(int pos, IconBean bean) {
searchView.clearFocus();
IconDialog.newInstance(bean, false).show(getSupportFragmentManager(), "iconDialog");
}
});
recyclerView.setAdapter(adapter);
}
private int[] calculateGridNumAndWidth() {
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int totalWidth = displayMetrics.widthPixels;
int minGridSize = getResources().getDimensionPixelSize(R.dimen.grid_size);
int num = totalWidth / minGridSize;
return new int[]{num, totalWidth / num};
}
private void initSearchView() {
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconified(false);
searchView.setQueryHint(getString(R.string.search_hint));
searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
searchView.clearFocus();
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
(new SearchTask()).execute(newText);
return false;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
finish();
return true;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
initSearchView();
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private class LoadDataTask extends AsyncTask<String, Integer, List<IconBean>> {
@Override
protected List<IconBean> doInBackground(String... strings) {
try {
return (new AllIconsGetter()).getIcons(SearchActivity.this);
} catch (Exception e) {
e.printStackTrace();
}
return new ArrayList<>();
}
@Override
protected void onPostExecute(List<IconBean> list) {
super.onPostExecute(list);
dataList = list;
((AVLoadingIndicatorView) findViewById(R.id.view_loading)).hide();
}
}
private class SearchTask extends AsyncTask<String, Integer, List<IconBean>> {
@Override
protected List<IconBean> doInBackground(String... strings) {
String keyword = strings[0];
if (TextUtils.isEmpty(keyword)) {
return new ArrayList<>();
}
List<IconBean> result = new ArrayList<>();
for (IconBean bean : dataList) {
boolean findComponent = false;
for (IconBean.Component component : bean.getComponents()) {
if (component.getPkg().equals(keyword) || (component.getLabel() != null
&& component.getLabel().contains(keyword))) {
findComponent = true;
result.add(bean);
break;
}
}
if (findComponent) {
continue;
}
if (bean.getLabel() != null && bean.getLabel().contains(keyword)) {
result.add(bean);
} else if (bean.getName().contains(keyword)) {
result.add(bean);
}
}
Collections.sort(result);
return result;
}
@Override
protected void onPostExecute(List<IconBean> list) {
super.onPostExecute(list);
adapter.refresh(list);
}
}
}
| {
"content_hash": "fddb884076ce06a94232735c48ea534c",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 100,
"avg_line_length": 32.53061224489796,
"alnum_prop": 0.6137076537013801,
"repo_name": "by-syk/NanoIconPack",
"id": "38e2b52d3e0625a364fa65628775ad5221586edc",
"size": "6965",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "nanoiconpack/src/main/java/com/by_syk/lib/nanoiconpack/SearchActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "711"
},
{
"name": "Java",
"bytes": "293197"
},
{
"name": "Python",
"bytes": "2147"
}
],
"symlink_target": ""
} |
using ::enquery::Buffer;
int main(int argc, char* argv[]) {
// Test empty buffer has size of zero.
Buffer b1;
ASSERT_EQUALS(b1.Size(), 0);
// Test construction from string. Size should include NULL.
const std::string kTestStr1 = "test1";
Buffer b2(kTestStr1);
ASSERT_EQUALS(b2.Size(), kTestStr1.size() + 1);
// Test copy construction
Buffer b2_copy(b2);
// Test equality operator
ASSERT_TRUE(b2 == b2_copy);
// Ensure equality operator fails appropriately.
const std::string kTestStr2 = "test2";
Buffer b3(kTestStr2);
ASSERT_FALSE(b2 == b3);
// Test Data accessor
ASSERT_EQUALS(b3.Data()[0], 't');
return EXIT_SUCCESS;
}
| {
"content_hash": "15f7f346f22c9a61453387c3223485fb",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 61,
"avg_line_length": 23.714285714285715,
"alnum_prop": 0.6686746987951807,
"repo_name": "enquery/enquery",
"id": "3296cf2ec0aaf3e9532a48256e2b4319f9a286a4",
"size": "1388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "base/buffer_test.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "6062"
},
{
"name": "C++",
"bytes": "103099"
},
{
"name": "Makefile",
"bytes": "4558"
},
{
"name": "Shell",
"bytes": "4832"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>DbEnv::err()</title>
<link rel="stylesheet" href="apiReference.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Berkeley DB C++ API Reference" />
<link rel="up" href="env.html" title="Chapter 5. The DbEnv Handle" />
<link rel="prev" href="envdbrename.html" title="DbEnv::dbrename()" />
<link rel="next" href="envfailchk.html" title="DbEnv::failchk()" />
</head>
<body>
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">DbEnv::err()</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="envdbrename.html">Prev</a> </td>
<th width="60%" align="center">Chapter 5.
The DbEnv Handle
</th>
<td width="20%" align="right"> <a accesskey="n" href="envfailchk.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="enverr"></a>DbEnv::err()</h2>
</div>
</div>
</div>
<pre class="programlisting">#include <db_cxx.h>
DbEnv::err(int error, const char *fmt, ...);
DbEnv::errx(const char *fmt, ...); </pre>
<p>
The <code class="methodname">DbEnv::err()</code>, <code class="methodname">DbEnv::errx,()</code>,
<a class="xref" href="dberr.html" title="Db::err()">Db::err()</a> and
<code class="methodname">Db::errx()</code> methods provide
error-messaging functionality for applications written using the
Berkeley DB library.
</p>
<p>
The <a class="xref" href="dberr.html" title="Db::err()">Db::err()</a> and
<a class="xref" href="enverr.html" title="DbEnv::err()">DbEnv::err()</a>
methods constructs an error message consisting of the
following elements:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
<span class="bold"><strong>An optional prefix string</strong></span>
</p>
<p>
If no error callback function has been set using the
<a class="xref" href="envset_errcall.html" title="DbEnv::set_errcall()">DbEnv::set_errcall()</a>
method, any prefix string specified using the
<a class="xref" href="envset_errpfx.html" title="DbEnv::set_errpfx()">DbEnv::set_errpfx()</a>
method, followed by two separating characters: a colon and a
<space> character.
</p>
</li>
<li>
<p>
<span class="bold"><strong>An optional printf-style message</strong></span>
</p>
<p>
The supplied message <span class="bold"><strong>fmt</strong></span>, if
non-NULL, in which the ANSI C X3.159-1989 (ANSI C) printf function
specifies how subsequent parameters are converted for output.
</p>
</li>
<li>
<p>
<span class="bold"><strong>A separator</strong></span>
</p>
<p>
Two separating characters: a colon and a <space> character.
</p>
</li>
<li>
<p>
<span class="bold"><strong>A standard error string</strong></span>
</p>
<p>
The standard system or Berkeley DB library error string associated
with the <span class="bold"><strong>error</strong></span> value, as returned by
the <a class="xref" href="envstrerror.html" title="DbEnv::strerror()">DbEnv::strerror()</a>
method.
</p>
</li>
</ul>
</div>
<p>
This constructed error message is then handled as follows:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>
If an error callback function has been set (see
<a class="xref" href="dbset_errcall.html" title="Db::set_errcall()">Db::set_errcall()</a> and
<a class="xref" href="envset_errcall.html" title="DbEnv::set_errcall()">DbEnv::set_errcall()</a>),
that function is called with two parameters: any prefix string
specified (see <a class="xref" href="dbset_errpfx.html" title="Db::set_errpfx()">Db::set_errpfx()</a>
and <a class="xref" href="envset_errpfx.html" title="DbEnv::set_errpfx()">DbEnv::set_errpfx()</a>) and
the error message.
</p>
</li>
<li>
<p>
If a C library FILE * has been set (see
<a class="xref" href="dbset_errfile.html" title="Db::set_errfile()">Db::set_errfile()</a> and
<a class="xref" href="envset_errfile.html" title="DbEnv::set_errfile()">DbEnv::set_errfile()</a>),
the error message is written to that output stream.
</p>
</li>
<li>
<p>
If a C++ ostream has been set (see
<a class="xref" href="envset_error_stream.html" title="DbEnv::set_error_stream()">DbEnv::set_error_stream()</a>
and
<a class="xref" href="dbset_error_stream.html" title="Db::set_error_stream()">Db::set_error_stream()</a>),
the error message is written to that stream.
</p>
</li>
<li>
<p>
If none of these output options have been configured, the error message
is written to stderr, the standard error output stream.
</p>
</li>
</ul>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="id3806755"></a>Parameters</h3>
</div>
</div>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id3806744"></a>error</h4>
</div>
</div>
</div>
<p>
The <span class="bold"><strong>error</strong></span> parameter is the error
value for which the <code class="methodname">DbEnv::err()</code> and
<a class="xref" href="dberr.html" title="Db::err()">Db::err()</a> methods will display a
explanatory string.
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id3806381"></a>fmt</h4>
</div>
</div>
</div>
<p>
The <span class="bold"><strong>fmt</strong></span> parameter is an optional
printf-style message to display.
</p>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="id3806311"></a>Class</h3>
</div>
</div>
</div>
<p>
<a class="link" href="env.html" title="Chapter 5. The DbEnv Handle">DbEnv</a>
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="id3806575"></a>See Also</h3>
</div>
</div>
</div>
<p>
<a class="xref" href="env.html#envlist" title="Database Environments and Related Methods">Database Environments and Related Methods</a>
</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="envdbrename.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="env.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="envfailchk.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">DbEnv::dbrename() </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> DbEnv::failchk()</td>
</tr>
</table>
</div>
</body>
</html>
| {
"content_hash": "d4858fc815ef25692b053b51de64bd4d",
"timestamp": "",
"source": "github",
"line_count": 225,
"max_line_length": 157,
"avg_line_length": 42.45333333333333,
"alnum_prop": 0.4798994974874372,
"repo_name": "racker/omnibus",
"id": "0d36429862d430429717abd523e110c3567dee1e",
"size": "9564",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "source/db-5.0.26.NC/docs/api_reference/CXX/enverr.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "21896"
},
{
"name": "ActionScript",
"bytes": "7811"
},
{
"name": "Ada",
"bytes": "913692"
},
{
"name": "Assembly",
"bytes": "546596"
},
{
"name": "Awk",
"bytes": "147229"
},
{
"name": "C",
"bytes": "118056858"
},
{
"name": "C#",
"bytes": "1871806"
},
{
"name": "C++",
"bytes": "28581121"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CSS",
"bytes": "162089"
},
{
"name": "Clojure",
"bytes": "79070"
},
{
"name": "D",
"bytes": "4925"
},
{
"name": "DOT",
"bytes": "1898"
},
{
"name": "Emacs Lisp",
"bytes": "625560"
},
{
"name": "Erlang",
"bytes": "79712366"
},
{
"name": "FORTRAN",
"bytes": "3755"
},
{
"name": "Java",
"bytes": "5632652"
},
{
"name": "JavaScript",
"bytes": "1240931"
},
{
"name": "Logos",
"bytes": "119270"
},
{
"name": "Objective-C",
"bytes": "1088478"
},
{
"name": "PHP",
"bytes": "39064"
},
{
"name": "Pascal",
"bytes": "66389"
},
{
"name": "Perl",
"bytes": "4971637"
},
{
"name": "PowerShell",
"bytes": "1885"
},
{
"name": "Prolog",
"bytes": "5214"
},
{
"name": "Python",
"bytes": "912999"
},
{
"name": "R",
"bytes": "4009"
},
{
"name": "Racket",
"bytes": "2713"
},
{
"name": "Ragel in Ruby Host",
"bytes": "24585"
},
{
"name": "Rebol",
"bytes": "106436"
},
{
"name": "Ruby",
"bytes": "27360215"
},
{
"name": "Scala",
"bytes": "5487"
},
{
"name": "Scheme",
"bytes": "5036"
},
{
"name": "Scilab",
"bytes": "771"
},
{
"name": "Shell",
"bytes": "8793006"
},
{
"name": "Tcl",
"bytes": "3330919"
},
{
"name": "Visual Basic",
"bytes": "10926"
},
{
"name": "XQuery",
"bytes": "4276"
},
{
"name": "XSLT",
"bytes": "2003063"
},
{
"name": "eC",
"bytes": "4568"
}
],
"symlink_target": ""
} |
namespace {
const int kBufferSize = 1024;
}
namespace content {
MockURLRequestDelegate::MockURLRequestDelegate()
: io_buffer_(new net::IOBuffer(kBufferSize)) {
}
MockURLRequestDelegate::~MockURLRequestDelegate() {
}
void MockURLRequestDelegate::OnResponseStarted(net::URLRequest* request) {
if (request->status().is_success()) {
EXPECT_TRUE(request->response_headers());
ReadSome(request);
} else {
RequestComplete();
}
}
void MockURLRequestDelegate::OnReadCompleted(net::URLRequest* request,
int bytes_read) {
if (bytes_read > 0)
ReceiveData(request, bytes_read);
else
RequestComplete();
}
void MockURLRequestDelegate::ReadSome(net::URLRequest* request) {
if (!request->is_pending()) {
RequestComplete();
return;
}
int bytes_read = 0;
if (!request->Read(io_buffer_.get(), kBufferSize, &bytes_read)) {
if (!request->status().is_io_pending())
RequestComplete();
return;
}
ReceiveData(request, bytes_read);
}
void MockURLRequestDelegate::ReceiveData(net::URLRequest* request,
int bytes_read) {
if (bytes_read) {
response_data_.append(io_buffer_->data(),
static_cast<size_t>(bytes_read));
ReadSome(request);
} else {
RequestComplete();
}
}
void MockURLRequestDelegate::RequestComplete() {
base::MessageLoop::current()->QuitWhenIdle();
}
} // namespace
| {
"content_hash": "f57b22ad5a788919307525faa0828625",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 74,
"avg_line_length": 23.56451612903226,
"alnum_prop": 0.6358658453114305,
"repo_name": "highweb-project/highweb-webcl-html5spec",
"id": "79333b740e51e7e30c2b3dd9e5ebda155344559d",
"size": "1819",
"binary": false,
"copies": "10",
"ref": "refs/heads/highweb-20160310",
"path": "content/browser/fileapi/mock_url_request_delegate.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package org.apache.calcite.avatica;
import java.io.InputStream;
import java.io.Reader;
import java.sql.NClob;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.util.Properties;
import java.util.TimeZone;
/**
* Implementation of {@link AvaticaFactory} for JDBC 4.1 (corresponds to JDK
* 1.7).
*/
@SuppressWarnings("UnusedDeclaration")
class AvaticaJdbc41Factory implements AvaticaFactory {
private final int major;
private final int minor;
/** Creates a JDBC factory. */
public AvaticaJdbc41Factory() {
this(4, 1);
}
/** Creates a JDBC factory with given major/minor version number. */
protected AvaticaJdbc41Factory(int major, int minor) {
this.major = major;
this.minor = minor;
}
public int getJdbcMajorVersion() {
return major;
}
public int getJdbcMinorVersion() {
return minor;
}
public AvaticaConnection newConnection(
UnregisteredDriver driver,
AvaticaFactory factory,
String url,
Properties info) {
return new AvaticaJdbc41Connection(driver, factory, url, info);
}
public AvaticaSpecificDatabaseMetaData newDatabaseMetaData(
AvaticaConnection connection) {
return new AvaticaJdbc41DatabaseMetaData(connection);
}
public AvaticaStatement newStatement(AvaticaConnection connection,
Meta.StatementHandle h, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) {
return new AvaticaJdbc41Statement(connection, h, resultSetType,
resultSetConcurrency, resultSetHoldability);
}
public AvaticaPreparedStatement newPreparedStatement(
AvaticaConnection connection, Meta.StatementHandle h,
Meta.Signature signature, int resultSetType, int resultSetConcurrency,
int resultSetHoldability)
throws SQLException {
return new AvaticaJdbc41PreparedStatement(connection, h, signature,
resultSetType, resultSetConcurrency, resultSetHoldability);
}
public AvaticaResultSet newResultSet(AvaticaStatement statement,
QueryState state, Meta.Signature signature, TimeZone timeZone, Meta.Frame firstFrame) {
final ResultSetMetaData metaData =
newResultSetMetaData(statement, signature);
return new AvaticaResultSet(statement, state, signature, metaData, timeZone,
firstFrame);
}
public AvaticaResultSetMetaData newResultSetMetaData(
AvaticaStatement statement, Meta.Signature signature) {
return new AvaticaResultSetMetaData(statement, null, signature);
}
/** Implementation of Connection for JDBC 4.1. */
private static class AvaticaJdbc41Connection extends AvaticaConnection {
AvaticaJdbc41Connection(UnregisteredDriver driver,
AvaticaFactory factory,
String url,
Properties info) {
super(driver, factory, url, info);
}
}
/** Implementation of Statement for JDBC 4.1. */
private static class AvaticaJdbc41Statement extends AvaticaStatement {
public AvaticaJdbc41Statement(AvaticaConnection connection,
Meta.StatementHandle h, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) {
super(connection, h, resultSetType, resultSetConcurrency,
resultSetHoldability);
}
}
/** Implementation of PreparedStatement for JDBC 4.1. */
private static class AvaticaJdbc41PreparedStatement
extends AvaticaPreparedStatement {
AvaticaJdbc41PreparedStatement(AvaticaConnection connection,
Meta.StatementHandle h, Meta.Signature signature, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
super(connection, h, signature, resultSetType, resultSetConcurrency,
resultSetHoldability);
}
public void setRowId(
int parameterIndex,
RowId x) throws SQLException {
getSite(parameterIndex).setRowId(x);
}
public void setNString(
int parameterIndex, String value) throws SQLException {
getSite(parameterIndex).setNString(value);
}
public void setNCharacterStream(
int parameterIndex,
Reader value,
long length) throws SQLException {
getSite(parameterIndex)
.setNCharacterStream(value, length);
}
public void setNClob(
int parameterIndex,
NClob value) throws SQLException {
getSite(parameterIndex).setNClob(value);
}
public void setClob(
int parameterIndex,
Reader reader,
long length) throws SQLException {
getSite(parameterIndex)
.setClob(reader, length);
}
public void setBlob(
int parameterIndex,
InputStream inputStream,
long length) throws SQLException {
getSite(parameterIndex)
.setBlob(inputStream, length);
}
public void setNClob(
int parameterIndex,
Reader reader,
long length) throws SQLException {
getSite(parameterIndex)
.setNClob(reader, length);
}
public void setSQLXML(
int parameterIndex, SQLXML xmlObject) throws SQLException {
getSite(parameterIndex).setSQLXML(xmlObject);
}
public void setAsciiStream(
int parameterIndex,
InputStream x,
long length) throws SQLException {
getSite(parameterIndex)
.setAsciiStream(x, length);
}
public void setBinaryStream(
int parameterIndex,
InputStream x,
long length) throws SQLException {
getSite(parameterIndex)
.setBinaryStream(x, length);
}
public void setCharacterStream(
int parameterIndex,
Reader reader,
long length) throws SQLException {
getSite(parameterIndex)
.setCharacterStream(reader, length);
}
public void setAsciiStream(
int parameterIndex, InputStream x) throws SQLException {
getSite(parameterIndex).setAsciiStream(x);
}
public void setBinaryStream(
int parameterIndex, InputStream x) throws SQLException {
getSite(parameterIndex).setBinaryStream(x);
}
public void setCharacterStream(
int parameterIndex, Reader reader) throws SQLException {
getSite(parameterIndex)
.setCharacterStream(reader);
}
public void setNCharacterStream(
int parameterIndex, Reader value) throws SQLException {
getSite(parameterIndex)
.setNCharacterStream(value);
}
public void setClob(
int parameterIndex,
Reader reader) throws SQLException {
getSite(parameterIndex).setClob(reader);
}
public void setBlob(
int parameterIndex, InputStream inputStream) throws SQLException {
getSite(parameterIndex).setBlob(inputStream);
}
public void setNClob(
int parameterIndex, Reader reader) throws SQLException {
getSite(parameterIndex).setNClob(reader);
}
}
/** Implementation of DatabaseMetaData for JDBC 4.1. */
private static class AvaticaJdbc41DatabaseMetaData
extends AvaticaDatabaseMetaData {
AvaticaJdbc41DatabaseMetaData(AvaticaConnection connection) {
super(connection);
}
}
}
// End AvaticaJdbc41Factory.java
| {
"content_hash": "cae18367f808994bd4ec3671f18c03fe",
"timestamp": "",
"source": "github",
"line_count": 241,
"max_line_length": 93,
"avg_line_length": 29.896265560165975,
"alnum_prop": 0.7049271339347675,
"repo_name": "sreev/incubator-calcite",
"id": "2edf515f0a500acabc27179587678215d37118ee",
"size": "8002",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "avatica/core/src/main/java/org/apache/calcite/avatica/AvaticaJdbc41Factory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2810"
},
{
"name": "CSS",
"bytes": "36560"
},
{
"name": "FreeMarker",
"bytes": "2154"
},
{
"name": "HTML",
"bytes": "18711"
},
{
"name": "Java",
"bytes": "12943399"
},
{
"name": "Protocol Buffer",
"bytes": "14111"
},
{
"name": "Ruby",
"bytes": "1769"
},
{
"name": "Shell",
"bytes": "7923"
}
],
"symlink_target": ""
} |
package org.xcolab.util.enums.promotion;
public enum ContestPhasePromoteType {
DEFAULT(-1, "DEFAULT", "Default autopromote used"),
NULL(0, "", "No autopromote specified"),
PROMOTE(1, "PROMOTE", "Proposals in this phase will automatically promoted to the next contest phase"),
PROMOTE_JUDGED(2, "PROMOTE_JUDGED", "Proposals in this phase will only be promoted to the next phase if judges decide so"),
PROMOTE_DONE(3, "PROMOTE_DONE", "All proposals in that phase have been promoted to the next phase"),
PROMOTE_RIBBONIZE(4, "PROMOTE_RIBBONIZE", "All proposals from previous phases will be copied to the next phase" +
" and (semi) finalist ribbons will be distributed.");
private final int index;
private final String value;
private final String description;
ContestPhasePromoteType(int index, String value, String description) {
this.index = index;
this.value = value;
this.description = description;
}
public int getIndex() {
return index;
}
public String getDescription() {
return description;
}
public String getValue() {
return value;
}
public static ContestPhasePromoteType getPromoteType(String theType) {
for (ContestPhasePromoteType aType : ContestPhasePromoteType.values()) {
if (aType.value.equals(theType)) {
return aType;
}
}
return null;
}
public static ContestPhasePromoteType getPromoteType(int index) {
for (ContestPhasePromoteType aType : ContestPhasePromoteType.values()) {
if (aType.index == index) {
return aType;
}
}
return null;
}
}
| {
"content_hash": "d08f7eb4f5165860f3c7c1919df6e721",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 127,
"avg_line_length": 33.98039215686274,
"alnum_prop": 0.6468551644547028,
"repo_name": "CCI-MIT/XCoLab",
"id": "9a0539b2989f07e8cb9bf96e7d5566a9a1182d69",
"size": "1733",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "util/xcolab-utils/src/main/java/org/xcolab/util/enums/promotion/ContestPhasePromoteType.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22697"
},
{
"name": "HTML",
"bytes": "69904"
},
{
"name": "Java",
"bytes": "4089581"
},
{
"name": "JavaScript",
"bytes": "1172118"
},
{
"name": "SCSS",
"bytes": "201019"
},
{
"name": "Shell",
"bytes": "13707"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using WebsitePanel.WebDavPortal.Models.Common;
namespace WebsitePanel.WebDavPortal.Models.FileSystem
{
public class DeleteFilesModel : AjaxModel
{
public DeleteFilesModel()
{
DeletedFiles = new List<string>();
}
public List<string> DeletedFiles { get; set; }
}
} | {
"content_hash": "66f14407d5d63c9aad3017d78a3a4b6d",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 54,
"avg_line_length": 24.6,
"alnum_prop": 0.6395663956639567,
"repo_name": "titan68/Websitepanel",
"id": "8908f86f3da1bf5ff01456ebdffe64a49c0b7025",
"size": "371",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "WebsitePanel/Sources/WebsitePanel.WebDavPortal/Models/FileSystem/DeleteFilesModel.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "3085258"
},
{
"name": "Batchfile",
"bytes": "17935"
},
{
"name": "C#",
"bytes": "47779562"
},
{
"name": "CSS",
"bytes": "150532"
},
{
"name": "HTML",
"bytes": "12188"
},
{
"name": "JavaScript",
"bytes": "1142405"
},
{
"name": "PHP",
"bytes": "75235"
},
{
"name": "PLpgSQL",
"bytes": "3887"
},
{
"name": "PowerShell",
"bytes": "14705"
},
{
"name": "Smarty",
"bytes": "288"
},
{
"name": "Visual Basic",
"bytes": "656959"
}
],
"symlink_target": ""
} |
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"os"
"strings"
"time"
"github.com/docker/docker/pkg/integration/checker"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/docker/runconfig"
"github.com/docker/engine-api/types"
"github.com/docker/engine-api/types/versions/v1p20"
"github.com/docker/libnetwork/driverapi"
remoteapi "github.com/docker/libnetwork/drivers/remote/api"
"github.com/docker/libnetwork/ipamapi"
remoteipam "github.com/docker/libnetwork/ipams/remote/api"
"github.com/docker/libnetwork/netlabel"
"github.com/go-check/check"
"github.com/vishvananda/netlink"
)
const dummyNetworkDriver = "dummy-network-driver"
const dummyIpamDriver = "dummy-ipam-driver"
var remoteDriverNetworkRequest remoteapi.CreateNetworkRequest
func init() {
check.Suite(&DockerNetworkSuite{
ds: &DockerSuite{},
})
}
type DockerNetworkSuite struct {
server *httptest.Server
ds *DockerSuite
d *Daemon
}
func (s *DockerNetworkSuite) SetUpTest(c *check.C) {
s.d = NewDaemon(c)
}
func (s *DockerNetworkSuite) TearDownTest(c *check.C) {
s.d.Stop()
s.ds.TearDownTest(c)
}
func (s *DockerNetworkSuite) SetUpSuite(c *check.C) {
mux := http.NewServeMux()
s.server = httptest.NewServer(mux)
c.Assert(s.server, check.NotNil, check.Commentf("Failed to start a HTTP Server"))
setupRemoteNetworkDrivers(c, mux, s.server.URL, dummyNetworkDriver, dummyIpamDriver)
}
func setupRemoteNetworkDrivers(c *check.C, mux *http.ServeMux, url, netDrv, ipamDrv string) {
mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"Implements": ["%s", "%s"]}`, driverapi.NetworkPluginEndpointType, ipamapi.PluginEndpointType)
})
// Network driver implementation
mux.HandleFunc(fmt.Sprintf("/%s.GetCapabilities", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"Scope":"local"}`)
})
mux.HandleFunc(fmt.Sprintf("/%s.CreateNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&remoteDriverNetworkRequest)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.DeleteNetwork", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.CreateEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"Interface":{"MacAddress":"a0:b1:c2:d3:e4:f5"}}`)
})
mux.HandleFunc(fmt.Sprintf("/%s.Join", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
veth := &netlink.Veth{
LinkAttrs: netlink.LinkAttrs{Name: "randomIfName", TxQLen: 0}, PeerName: "cnt0"}
if err := netlink.LinkAdd(veth); err != nil {
fmt.Fprintf(w, `{"Error":"failed to add veth pair: `+err.Error()+`"}`)
} else {
fmt.Fprintf(w, `{"InterfaceName":{ "SrcName":"cnt0", "DstPrefix":"veth"}}`)
}
})
mux.HandleFunc(fmt.Sprintf("/%s.Leave", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, "null")
})
mux.HandleFunc(fmt.Sprintf("/%s.DeleteEndpoint", driverapi.NetworkPluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
if link, err := netlink.LinkByName("cnt0"); err == nil {
netlink.LinkDel(link)
}
fmt.Fprintf(w, "null")
})
// Ipam Driver implementation
var (
poolRequest remoteipam.RequestPoolRequest
poolReleaseReq remoteipam.ReleasePoolRequest
addressRequest remoteipam.RequestAddressRequest
addressReleaseReq remoteipam.ReleaseAddressRequest
lAS = "localAS"
gAS = "globalAS"
pool = "172.28.0.0/16"
poolID = lAS + "/" + pool
gw = "172.28.255.254/16"
)
mux.HandleFunc(fmt.Sprintf("/%s.GetDefaultAddressSpaces", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
fmt.Fprintf(w, `{"LocalDefaultAddressSpace":"`+lAS+`", "GlobalDefaultAddressSpace": "`+gAS+`"}`)
})
mux.HandleFunc(fmt.Sprintf("/%s.RequestPool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&poolRequest)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
if poolRequest.AddressSpace != lAS && poolRequest.AddressSpace != gAS {
fmt.Fprintf(w, `{"Error":"Unknown address space in pool request: `+poolRequest.AddressSpace+`"}`)
} else if poolRequest.Pool != "" && poolRequest.Pool != pool {
fmt.Fprintf(w, `{"Error":"Cannot handle explicit pool requests yet"}`)
} else {
fmt.Fprintf(w, `{"PoolID":"`+poolID+`", "Pool":"`+pool+`"}`)
}
})
mux.HandleFunc(fmt.Sprintf("/%s.RequestAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&addressRequest)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
// make sure libnetwork is now querying on the expected pool id
if addressRequest.PoolID != poolID {
fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
} else if addressRequest.Address != "" {
fmt.Fprintf(w, `{"Error":"Cannot handle explicit address requests yet"}`)
} else {
fmt.Fprintf(w, `{"Address":"`+gw+`"}`)
}
})
mux.HandleFunc(fmt.Sprintf("/%s.ReleaseAddress", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&addressReleaseReq)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
// make sure libnetwork is now asking to release the expected address from the expected poolid
if addressRequest.PoolID != poolID {
fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
} else if addressReleaseReq.Address != gw {
fmt.Fprintf(w, `{"Error":"unknown address"}`)
} else {
fmt.Fprintf(w, "null")
}
})
mux.HandleFunc(fmt.Sprintf("/%s.ReleasePool", ipamapi.PluginEndpointType), func(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&poolReleaseReq)
if err != nil {
http.Error(w, "Unable to decode JSON payload: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json")
// make sure libnetwork is now asking to release the expected poolid
if addressRequest.PoolID != poolID {
fmt.Fprintf(w, `{"Error":"unknown pool id"}`)
} else {
fmt.Fprintf(w, "null")
}
})
err := os.MkdirAll("/etc/docker/plugins", 0755)
c.Assert(err, checker.IsNil)
fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv)
err = ioutil.WriteFile(fileName, []byte(url), 0644)
c.Assert(err, checker.IsNil)
ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv)
err = ioutil.WriteFile(ipamFileName, []byte(url), 0644)
c.Assert(err, checker.IsNil)
}
func (s *DockerNetworkSuite) TearDownSuite(c *check.C) {
if s.server == nil {
return
}
s.server.Close()
err := os.RemoveAll("/etc/docker/plugins")
c.Assert(err, checker.IsNil)
}
func assertNwIsAvailable(c *check.C, name string) {
if !isNwPresent(c, name) {
c.Fatalf("Network %s not found in network ls o/p", name)
}
}
func assertNwNotAvailable(c *check.C, name string) {
if isNwPresent(c, name) {
c.Fatalf("Found network %s in network ls o/p", name)
}
}
func isNwPresent(c *check.C, name string) bool {
out, _ := dockerCmd(c, "network", "ls")
lines := strings.Split(out, "\n")
for i := 1; i < len(lines)-1; i++ {
netFields := strings.Fields(lines[i])
if netFields[1] == name {
return true
}
}
return false
}
// assertNwList checks network list retrieved with ls command
// equals to expected network list
// note: out should be `network ls [option]` result
func assertNwList(c *check.C, out string, expectNws []string) {
lines := strings.Split(out, "\n")
var nwList []string
for _, line := range lines[1 : len(lines)-1] {
netFields := strings.Fields(line)
// wrap all network name in nwList
nwList = append(nwList, netFields[1])
}
// network ls should contains all expected networks
c.Assert(nwList, checker.DeepEquals, expectNws)
}
func getNwResource(c *check.C, name string) *types.NetworkResource {
out, _ := dockerCmd(c, "network", "inspect", name)
nr := []types.NetworkResource{}
err := json.Unmarshal([]byte(out), &nr)
c.Assert(err, check.IsNil)
return &nr[0]
}
func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *check.C) {
defaults := []string{"bridge", "host", "none"}
for _, nn := range defaults {
assertNwIsAvailable(c, nn)
}
}
func (s *DockerNetworkSuite) TestDockerNetworkCreatePredefined(c *check.C) {
predefined := []string{"bridge", "host", "none", "default"}
for _, net := range predefined {
// predefined networks can't be created again
out, _, err := dockerCmdWithError("network", "create", net)
c.Assert(err, checker.NotNil, check.Commentf("%v", out))
}
}
func (s *DockerNetworkSuite) TestDockerNetworkCreateHostBind(c *check.C) {
dockerCmd(c, "network", "create", "--subnet=192.168.10.0/24", "--gateway=192.168.10.1", "-o", "com.docker.network.bridge.host_binding_ipv4=192.168.10.1", "testbind")
assertNwIsAvailable(c, "testbind")
out, _ := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000")
id := strings.TrimSpace(out)
c.Assert(waitRun(id), checker.IsNil)
out, _ = dockerCmd(c, "ps")
c.Assert(out, checker.Contains, "192.168.10.1:5000->5000/tcp")
}
func (s *DockerNetworkSuite) TestDockerNetworkRmPredefined(c *check.C) {
predefined := []string{"bridge", "host", "none", "default"}
for _, net := range predefined {
// predefined networks can't be removed
out, _, err := dockerCmdWithError("network", "rm", net)
c.Assert(err, checker.NotNil, check.Commentf("%v", out))
}
}
func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *check.C) {
testNet := "testnet1"
testLabel := "foo"
testValue := "bar"
out, _ := dockerCmd(c, "network", "create", "dev")
defer func() {
dockerCmd(c, "network", "rm", "dev")
dockerCmd(c, "network", "rm", testNet)
}()
networkID := strings.TrimSpace(out)
// filter with partial ID
// only show 'dev' network
out, _ = dockerCmd(c, "network", "ls", "-f", "id="+networkID[0:5])
assertNwList(c, out, []string{"dev"})
out, _ = dockerCmd(c, "network", "ls", "-f", "name=dge")
assertNwList(c, out, []string{"bridge"})
// only show built-in network (bridge, none, host)
out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin")
assertNwList(c, out, []string{"bridge", "host", "none"})
// only show custom networks (dev)
out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom")
assertNwList(c, out, []string{"dev"})
// show all networks with filter
// it should be equivalent of ls without option
out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin")
assertNwList(c, out, []string{"bridge", "dev", "host", "none"})
out, _ = dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
assertNwIsAvailable(c, testNet)
out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel)
assertNwList(c, out, []string{testNet})
out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel+"="+testValue)
assertNwList(c, out, []string{testNet})
out, _ = dockerCmd(c, "network", "ls", "-f", "label=nonexistent")
outArr := strings.Split(strings.TrimSpace(out), "\n")
c.Assert(len(outArr), check.Equals, 1, check.Commentf("%s\n", out))
out, _ = dockerCmd(c, "network", "ls", "-f", "driver=null")
assertNwList(c, out, []string{"none"})
out, _ = dockerCmd(c, "network", "ls", "-f", "driver=host")
assertNwList(c, out, []string{"host"})
out, _ = dockerCmd(c, "network", "ls", "-f", "driver=bridge")
assertNwList(c, out, []string{"bridge", "dev", testNet})
}
func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *check.C) {
dockerCmd(c, "network", "create", "test")
assertNwIsAvailable(c, "test")
dockerCmd(c, "network", "rm", "test")
assertNwNotAvailable(c, "test")
}
func (s *DockerNetworkSuite) TestDockerNetworkCreateLabel(c *check.C) {
testNet := "testnetcreatelabel"
testLabel := "foo"
testValue := "bar"
dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet)
assertNwIsAvailable(c, testNet)
out, _, err := dockerCmdWithError("network", "inspect", "--format='{{ .Labels."+testLabel+" }}'", testNet)
c.Assert(err, check.IsNil)
c.Assert(strings.TrimSpace(out), check.Equals, testValue)
dockerCmd(c, "network", "rm", testNet)
assertNwNotAvailable(c, testNet)
}
func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) {
out, _, err := dockerCmdWithError("network", "rm", "test")
c.Assert(err, checker.NotNil, check.Commentf("%v", out))
}
func (s *DockerSuite) TestDockerNetworkDeleteMultiple(c *check.C) {
dockerCmd(c, "network", "create", "testDelMulti0")
assertNwIsAvailable(c, "testDelMulti0")
dockerCmd(c, "network", "create", "testDelMulti1")
assertNwIsAvailable(c, "testDelMulti1")
dockerCmd(c, "network", "create", "testDelMulti2")
assertNwIsAvailable(c, "testDelMulti2")
out, _ := dockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top")
containerID := strings.TrimSpace(out)
waitRun(containerID)
// delete three networks at the same time, since testDelMulti2
// contains active container, its deletion should fail.
out, _, err := dockerCmdWithError("network", "rm", "testDelMulti0", "testDelMulti1", "testDelMulti2")
// err should not be nil due to deleting testDelMulti2 failed.
c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
// testDelMulti2 should fail due to network has active endpoints
c.Assert(out, checker.Contains, "has active endpoints")
assertNwNotAvailable(c, "testDelMulti0")
assertNwNotAvailable(c, "testDelMulti1")
// testDelMulti2 can't be deleted, so it should exist
assertNwIsAvailable(c, "testDelMulti2")
}
func (s *DockerSuite) TestDockerNetworkInspect(c *check.C) {
out, _ := dockerCmd(c, "network", "inspect", "host")
networkResources := []types.NetworkResource{}
err := json.Unmarshal([]byte(out), &networkResources)
c.Assert(err, check.IsNil)
c.Assert(networkResources, checker.HasLen, 1)
out, _ = dockerCmd(c, "network", "inspect", "--format='{{ .Name }}'", "host")
c.Assert(strings.TrimSpace(out), check.Equals, "host")
}
func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) {
out, _ := dockerCmd(c, "network", "inspect", "host", "none")
networkResources := []types.NetworkResource{}
err := json.Unmarshal([]byte(out), &networkResources)
c.Assert(err, check.IsNil)
c.Assert(networkResources, checker.HasLen, 2)
// Should print an error, return an exitCode 1 *but* should print the host network
out, exitCode, err := dockerCmdWithError("network", "inspect", "host", "nonexistent")
c.Assert(err, checker.NotNil)
c.Assert(exitCode, checker.Equals, 1)
c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
networkResources = []types.NetworkResource{}
inspectOut := strings.SplitN(out, "\nError: No such network: nonexistent\n", 2)[0]
err = json.Unmarshal([]byte(inspectOut), &networkResources)
c.Assert(networkResources, checker.HasLen, 1)
// Should print an error and return an exitCode, nothing else
out, exitCode, err = dockerCmdWithError("network", "inspect", "nonexistent")
c.Assert(err, checker.NotNil)
c.Assert(exitCode, checker.Equals, 1)
c.Assert(out, checker.Contains, "Error: No such network: nonexistent")
}
func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) {
dockerCmd(c, "network", "create", "brNetForInspect")
assertNwIsAvailable(c, "brNetForInspect")
defer func() {
dockerCmd(c, "network", "rm", "brNetForInspect")
assertNwNotAvailable(c, "brNetForInspect")
}()
out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top")
c.Assert(waitRun("testNetInspect1"), check.IsNil)
containerID := strings.TrimSpace(out)
defer func() {
// we don't stop container by name, because we'll rename it later
dockerCmd(c, "stop", containerID)
}()
out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
networkResources := []types.NetworkResource{}
err := json.Unmarshal([]byte(out), &networkResources)
c.Assert(err, check.IsNil)
c.Assert(networkResources, checker.HasLen, 1)
container, ok := networkResources[0].Containers[containerID]
c.Assert(ok, checker.True)
c.Assert(container.Name, checker.Equals, "testNetInspect1")
// rename container and check docker inspect output update
newName := "HappyNewName"
dockerCmd(c, "rename", "testNetInspect1", newName)
// check whether network inspect works properly
out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect")
newNetRes := []types.NetworkResource{}
err = json.Unmarshal([]byte(out), &newNetRes)
c.Assert(err, check.IsNil)
c.Assert(newNetRes, checker.HasLen, 1)
container1, ok := newNetRes[0].Containers[containerID]
c.Assert(ok, checker.True)
c.Assert(container1.Name, checker.Equals, newName)
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) {
dockerCmd(c, "network", "create", "test")
assertNwIsAvailable(c, "test")
nr := getNwResource(c, "test")
c.Assert(nr.Name, checker.Equals, "test")
c.Assert(len(nr.Containers), checker.Equals, 0)
// run a container
out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
c.Assert(waitRun("test"), check.IsNil)
containerID := strings.TrimSpace(out)
// connect the container to the test network
dockerCmd(c, "network", "connect", "test", containerID)
// inspect the network to make sure container is connected
nr = getNetworkResource(c, nr.ID)
c.Assert(len(nr.Containers), checker.Equals, 1)
c.Assert(nr.Containers[containerID], check.NotNil)
// check if container IP matches network inspect
ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address)
c.Assert(err, check.IsNil)
containerIP := findContainerIP(c, "test", "test")
c.Assert(ip.String(), checker.Equals, containerIP)
// disconnect container from the network
dockerCmd(c, "network", "disconnect", "test", containerID)
nr = getNwResource(c, "test")
c.Assert(nr.Name, checker.Equals, "test")
c.Assert(len(nr.Containers), checker.Equals, 0)
// run another container
out, _ = dockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top")
c.Assert(waitRun("test2"), check.IsNil)
containerID = strings.TrimSpace(out)
nr = getNwResource(c, "test")
c.Assert(nr.Name, checker.Equals, "test")
c.Assert(len(nr.Containers), checker.Equals, 1)
// force disconnect the container to the test network
dockerCmd(c, "network", "disconnect", "-f", "test", containerID)
nr = getNwResource(c, "test")
c.Assert(nr.Name, checker.Equals, "test")
c.Assert(len(nr.Containers), checker.Equals, 0)
dockerCmd(c, "network", "rm", "test")
assertNwNotAvailable(c, "test")
}
func (s *DockerNetworkSuite) TestDockerNetworkIpamMultipleNetworks(c *check.C) {
// test0 bridge network
dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1")
assertNwIsAvailable(c, "test1")
// test2 bridge network does not overlap
dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2")
assertNwIsAvailable(c, "test2")
// for networks w/o ipam specified, docker will choose proper non-overlapping subnets
dockerCmd(c, "network", "create", "test3")
assertNwIsAvailable(c, "test3")
dockerCmd(c, "network", "create", "test4")
assertNwIsAvailable(c, "test4")
dockerCmd(c, "network", "create", "test5")
assertNwIsAvailable(c, "test5")
// test network with multiple subnets
// bridge network doesn't support multiple subnets. hence, use a dummy driver that supports
dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16", "test6")
assertNwIsAvailable(c, "test6")
// test network with multiple subnets with valid ipam combinations
// also check same subnet across networks when the driver supports it.
dockerCmd(c, "network", "create", "-d", dummyNetworkDriver,
"--subnet=192.168.0.0/16", "--subnet=192.170.0.0/16",
"--gateway=192.168.0.100", "--gateway=192.170.0.100",
"--ip-range=192.168.1.0/24",
"--aux-address", "a=192.168.1.5", "--aux-address", "b=192.168.1.6",
"--aux-address", "a=192.170.1.5", "--aux-address", "b=192.170.1.6",
"test7")
assertNwIsAvailable(c, "test7")
// cleanup
for i := 1; i < 8; i++ {
dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i))
}
}
func (s *DockerNetworkSuite) TestDockerNetworkCustomIpam(c *check.C) {
// Create a bridge network using custom ipam driver
dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "br0")
assertNwIsAvailable(c, "br0")
// Verify expected network ipam fields are there
nr := getNetworkResource(c, "br0")
c.Assert(nr.Driver, checker.Equals, "bridge")
c.Assert(nr.IPAM.Driver, checker.Equals, dummyIpamDriver)
// remove network and exercise remote ipam driver
dockerCmd(c, "network", "rm", "br0")
assertNwNotAvailable(c, "br0")
}
func (s *DockerNetworkSuite) TestDockerNetworkIpamOptions(c *check.C) {
// Create a bridge network using custom ipam driver and options
dockerCmd(c, "network", "create", "--ipam-driver", dummyIpamDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0")
assertNwIsAvailable(c, "br0")
// Verify expected network ipam options
nr := getNetworkResource(c, "br0")
opts := nr.IPAM.Options
c.Assert(opts["opt1"], checker.Equals, "drv1")
c.Assert(opts["opt2"], checker.Equals, "drv2")
}
func (s *DockerNetworkSuite) TestDockerNetworkInspectDefault(c *check.C) {
nr := getNetworkResource(c, "none")
c.Assert(nr.Driver, checker.Equals, "null")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, false)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
nr = getNetworkResource(c, "host")
c.Assert(nr.Driver, checker.Equals, "host")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, false)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 0)
nr = getNetworkResource(c, "bridge")
c.Assert(nr.Driver, checker.Equals, "bridge")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, false)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
}
func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomUnspecified(c *check.C) {
// if unspecified, network subnet will be selected from inside preferred pool
dockerCmd(c, "network", "create", "test01")
assertNwIsAvailable(c, "test01")
nr := getNetworkResource(c, "test01")
c.Assert(nr.Driver, checker.Equals, "bridge")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, false)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
c.Assert(nr.IPAM.Config[0].Subnet, checker.NotNil)
c.Assert(nr.IPAM.Config[0].Gateway, checker.NotNil)
dockerCmd(c, "network", "rm", "test01")
assertNwNotAvailable(c, "test01")
}
func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *check.C) {
dockerCmd(c, "network", "create", "--driver=bridge", "--ipv6", "--subnet=172.28.0.0/16", "--ip-range=172.28.5.0/24", "--gateway=172.28.5.254", "br0")
assertNwIsAvailable(c, "br0")
nr := getNetworkResource(c, "br0")
c.Assert(nr.Driver, checker.Equals, "bridge")
c.Assert(nr.Scope, checker.Equals, "local")
c.Assert(nr.Internal, checker.Equals, false)
c.Assert(nr.EnableIPv6, checker.Equals, true)
c.Assert(nr.IPAM.Driver, checker.Equals, "default")
c.Assert(len(nr.IPAM.Config), checker.Equals, 1)
c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16")
c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24")
c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254")
c.Assert(nr.Internal, checker.False)
dockerCmd(c, "network", "rm", "br0")
assertNwNotAvailable(c, "test01")
}
func (s *DockerNetworkSuite) TestDockerNetworkIpamInvalidCombinations(c *check.C) {
// network with ip-range out of subnet range
_, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test")
c.Assert(err, check.NotNil)
// network with multiple gateways for a single subnet
_, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test")
c.Assert(err, check.NotNil)
// Multiple overlapping subnets in the same network must fail
_, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test")
c.Assert(err, check.NotNil)
// overlapping subnets across networks must fail
// create a valid test0 network
dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0")
assertNwIsAvailable(c, "test0")
// create an overlapping test1 network
_, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1")
c.Assert(err, check.NotNil)
dockerCmd(c, "network", "rm", "test0")
assertNwNotAvailable(c, "test0")
}
func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) {
dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt")
assertNwIsAvailable(c, "testopt")
gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData]
c.Assert(gopts, checker.NotNil)
opts, ok := gopts.(map[string]interface{})
c.Assert(ok, checker.Equals, true)
c.Assert(opts["opt1"], checker.Equals, "drv1")
c.Assert(opts["opt2"], checker.Equals, "drv2")
dockerCmd(c, "network", "rm", "testopt")
assertNwNotAvailable(c, "testopt")
}
func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c *check.C) {
testRequires(c, ExecSupport)
// On default bridge network built-in service discovery should not happen
hostsFile := "/etc/hosts"
bridgeName := "external-bridge"
bridgeIP := "192.169.255.254/24"
out, err := createInterface(c, "bridge", bridgeName, bridgeIP)
c.Assert(err, check.IsNil, check.Commentf(out))
defer deleteInterface(c, bridgeName)
err = s.d.StartWithBusybox("--bridge", bridgeName)
c.Assert(err, check.IsNil)
defer s.d.Restart()
// run two containers and store first container's etc/hosts content
out, err = s.d.Cmd("run", "-d", "busybox", "top")
c.Assert(err, check.IsNil)
cid1 := strings.TrimSpace(out)
defer s.d.Cmd("stop", cid1)
hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top")
c.Assert(err, check.IsNil)
cid2 := strings.TrimSpace(out)
// verify first container's etc/hosts file has not changed after spawning the second named container
hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts), checker.Equals, string(hostsPost),
check.Commentf("Unexpected %s change on second container creation", hostsFile))
// stop container 2 and verify first container's etc/hosts has not changed
_, err = s.d.Cmd("stop", cid2)
c.Assert(err, check.IsNil)
hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts), checker.Equals, string(hostsPost),
check.Commentf("Unexpected %s change on second container creation", hostsFile))
// but discovery is on when connecting to non default bridge network
network := "anotherbridge"
out, err = s.d.Cmd("network", "create", network)
c.Assert(err, check.IsNil, check.Commentf(out))
defer s.d.Cmd("network", "rm", network)
out, err = s.d.Cmd("network", "connect", network, cid1)
c.Assert(err, check.IsNil, check.Commentf(out))
hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts), checker.Equals, string(hostsPost),
check.Commentf("Unexpected %s change on second network connection", hostsFile))
}
func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) {
testRequires(c, ExecSupport, NotArm)
hostsFile := "/etc/hosts"
cstmBridgeNw := "custom-bridge-nw"
cstmBridgeNw1 := "custom-bridge-nw1"
dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw)
assertNwIsAvailable(c, cstmBridgeNw)
// run two anonymous containers and store their etc/hosts content
out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
cid1 := strings.TrimSpace(out)
hosts1, err := readContainerFileWithExec(cid1, hostsFile)
c.Assert(err, checker.IsNil)
out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top")
cid2 := strings.TrimSpace(out)
hosts2, err := readContainerFileWithExec(cid2, hostsFile)
c.Assert(err, checker.IsNil)
// verify first container etc/hosts file has not changed
hosts1post, err := readContainerFileWithExec(cid1, hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts1), checker.Equals, string(hosts1post),
check.Commentf("Unexpected %s change on anonymous container creation", hostsFile))
// Connect the 2nd container to a new network and verify the
// first container /etc/hosts file still hasn't changed.
dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1)
assertNwIsAvailable(c, cstmBridgeNw1)
dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2)
hosts2, err = readContainerFileWithExec(cid2, hostsFile)
c.Assert(err, checker.IsNil)
hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts1), checker.Equals, string(hosts1post),
check.Commentf("Unexpected %s change on container connect", hostsFile))
// start a named container
cName := "AnyName"
out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top")
cid3 := strings.TrimSpace(out)
// verify that container 1 and 2 can ping the named container
dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName)
dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName)
// Stop named container and verify first two containers' etc/hosts file hasn't changed
dockerCmd(c, "stop", cid3)
hosts1post, err = readContainerFileWithExec(cid1, hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts1), checker.Equals, string(hosts1post),
check.Commentf("Unexpected %s change on name container creation", hostsFile))
hosts2post, err := readContainerFileWithExec(cid2, hostsFile)
c.Assert(err, checker.IsNil)
c.Assert(string(hosts2), checker.Equals, string(hosts2post),
check.Commentf("Unexpected %s change on name container creation", hostsFile))
// verify that container 1 and 2 can't ping the named container now
_, _, err = dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName)
c.Assert(err, check.NotNil)
_, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName)
c.Assert(err, check.NotNil)
}
func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *check.C) {
// Legacy Link feature must work only on default network, and not across networks
cnt1 := "container1"
cnt2 := "container2"
network := "anotherbridge"
// Run first container on default network
dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top")
// Create another network and run the second container on it
dockerCmd(c, "network", "create", network)
assertNwIsAvailable(c, network)
dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top")
// Try launching a container on default network, linking to the first container. Must succeed
dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top")
// Try launching a container on default network, linking to the second container. Must fail
_, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
c.Assert(err, checker.NotNil)
// Connect second container to default network. Now a container on default network can link to it
dockerCmd(c, "network", "connect", "bridge", cnt2)
dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top")
}
func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) {
// Verify exposed ports are present in ps output when running a container on
// a network managed by a driver which does not provide the default gateway
// for the container
nwn := "ov"
ctn := "bb"
port1 := 80
port2 := 443
expose1 := fmt.Sprintf("--expose=%d", port1)
expose2 := fmt.Sprintf("--expose=%d", port2)
dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
assertNwIsAvailable(c, nwn)
dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top")
// Check docker ps o/p for last created container reports the unpublished ports
unpPort1 := fmt.Sprintf("%d/tcp", port1)
unpPort2 := fmt.Sprintf("%d/tcp", port2)
out, _ := dockerCmd(c, "ps", "-n=1")
// Missing unpublished ports in docker ps output
c.Assert(out, checker.Contains, unpPort1)
// Missing unpublished ports in docker ps output
c.Assert(out, checker.Contains, unpPort2)
}
func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
dnd := "dnd"
did := "did"
mux := http.NewServeMux()
server := httptest.NewServer(mux)
setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
s.d.StartWithBusybox()
_, err := s.d.Cmd("network", "create", "-d", dnd, "--subnet", "1.1.1.0/24", "net1")
c.Assert(err, checker.IsNil)
_, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "foo", "--ip", "1.1.1.10", "busybox", "sh")
c.Assert(err, checker.IsNil)
// Kill daemon and restart
if err = s.d.cmd.Process.Kill(); err != nil {
c.Fatal(err)
}
server.Close()
startTime := time.Now().Unix()
if err = s.d.Restart(); err != nil {
c.Fatal(err)
}
lapse := time.Now().Unix() - startTime
if lapse > 60 {
// In normal scenarios, daemon restart takes ~1 second.
// Plugin retry mechanism can delay the daemon start. systemd may not like it.
// Avoid accessing plugins during daemon bootup
c.Logf("daemon restart took too long : %d seconds", lapse)
}
// Restart the custom dummy plugin
mux = http.NewServeMux()
server = httptest.NewServer(mux)
setupRemoteNetworkDrivers(c, mux, server.URL, dnd, did)
// trying to reuse the same ip must succeed
_, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "bar", "--ip", "1.1.1.10", "busybox", "sh")
c.Assert(err, checker.IsNil)
}
func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) {
// Verify endpoint MAC address is correctly populated in container's network settings
nwn := "ov"
ctn := "bb"
dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn)
assertNwIsAvailable(c, nwn)
dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top")
mac := inspectField(c, ctn, "NetworkSettings.Networks."+nwn+".MacAddress")
c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5")
}
func (s *DockerSuite) TestInspectApiMultipleNetworks(c *check.C) {
dockerCmd(c, "network", "create", "mybridge1")
dockerCmd(c, "network", "create", "mybridge2")
out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
id := strings.TrimSpace(out)
c.Assert(waitRun(id), check.IsNil)
dockerCmd(c, "network", "connect", "mybridge1", id)
dockerCmd(c, "network", "connect", "mybridge2", id)
body := getInspectBody(c, "v1.20", id)
var inspect120 v1p20.ContainerJSON
err := json.Unmarshal(body, &inspect120)
c.Assert(err, checker.IsNil)
versionedIP := inspect120.NetworkSettings.IPAddress
body = getInspectBody(c, "v1.21", id)
var inspect121 types.ContainerJSON
err = json.Unmarshal(body, &inspect121)
c.Assert(err, checker.IsNil)
c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3)
bridge := inspect121.NetworkSettings.Networks["bridge"]
c.Assert(bridge.IPAddress, checker.Equals, versionedIP)
c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress)
}
func connectContainerToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
// Run a container on the default network
out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top")
c.Assert(err, checker.IsNil, check.Commentf(out))
// Attach the container to other networks
for _, nw := range nws {
out, err = d.Cmd("network", "create", nw)
c.Assert(err, checker.IsNil, check.Commentf(out))
out, err = d.Cmd("network", "connect", nw, cName)
c.Assert(err, checker.IsNil, check.Commentf(out))
}
}
func verifyContainerIsConnectedToNetworks(c *check.C, d *Daemon, cName string, nws []string) {
// Verify container is connected to all the networks
for _, nw := range nws {
out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName)
c.Assert(err, checker.IsNil, check.Commentf(out))
c.Assert(out, checker.Not(checker.Equals), "<no value>\n")
}
}
func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) {
cName := "bb"
nwList := []string{"nw1", "nw2", "nw3"}
s.d.StartWithBusybox()
connectContainerToNetworks(c, s.d, cName, nwList)
verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
// Reload daemon
s.d.Restart()
_, err := s.d.Cmd("start", cName)
c.Assert(err, checker.IsNil)
verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
}
func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) {
cName := "cc"
nwList := []string{"nw1", "nw2", "nw3"}
s.d.StartWithBusybox()
connectContainerToNetworks(c, s.d, cName, nwList)
verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
// Kill daemon and restart
if err := s.d.cmd.Process.Kill(); err != nil {
c.Fatal(err)
}
s.d.Restart()
// Restart container
_, err := s.d.Cmd("start", cName)
c.Assert(err, checker.IsNil)
verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList)
}
func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) {
out, _ := dockerCmd(c, "network", "create", "one")
containerOut, _, err := dockerCmdWithError("run", "-d", "--net", strings.TrimSpace(out), "busybox", "top")
c.Assert(err, checker.IsNil, check.Commentf(containerOut))
}
func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *check.C) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
s.d.StartWithBusybox()
// Run a few containers on host network
for i := 0; i < 10; i++ {
cName := fmt.Sprintf("hostc-%d", i)
out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top")
c.Assert(err, checker.IsNil, check.Commentf(out))
// verfiy container has finished starting before killing daemon
err = s.d.waitRun(cName)
c.Assert(err, checker.IsNil)
}
// Kill daemon ungracefully and restart
if err := s.d.cmd.Process.Kill(); err != nil {
c.Fatal(err)
}
if err := s.d.Restart(); err != nil {
c.Fatal(err)
}
// make sure all the containers are up and running
for i := 0; i < 10; i++ {
err := s.d.waitRun(fmt.Sprintf("hostc-%d", i))
c.Assert(err, checker.IsNil)
}
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *check.C) {
dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top")
c.Assert(waitRun("container1"), check.IsNil)
dockerCmd(c, "network", "disconnect", "bridge", "container1")
out, _, err := dockerCmdWithError("network", "connect", "host", "container1")
c.Assert(err, checker.NotNil, check.Commentf(out))
c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
}
func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *check.C) {
dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top")
c.Assert(waitRun("container1"), check.IsNil)
out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1")
c.Assert(err, checker.NotNil, check.Commentf("Should err out disconnect from host"))
c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error())
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *check.C) {
testRequires(c, NotArm)
dockerCmd(c, "network", "create", "test1")
dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top")
c.Assert(waitRun("c1"), check.IsNil)
dockerCmd(c, "network", "connect", "test1", "c1")
}
func verifyPortMap(c *check.C, container, port, originalMapping string, mustBeEqual bool) {
chk := checker.Equals
if !mustBeEqual {
chk = checker.Not(checker.Equals)
}
currentMapping, _ := dockerCmd(c, "port", container, port)
c.Assert(currentMapping, chk, originalMapping)
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectWithPortMapping(c *check.C) {
// Connect and disconnect a container with explicit and non-explicit
// host port mapping to/from networks which do cause and do not cause
// the container default gateway to change, and verify docker port cmd
// returns congruent information
testRequires(c, NotArm)
cnt := "c1"
dockerCmd(c, "network", "create", "aaa")
dockerCmd(c, "network", "create", "ccc")
dockerCmd(c, "run", "-d", "--name", cnt, "-p", "9000:90", "-p", "70", "busybox", "top")
c.Assert(waitRun(cnt), check.IsNil)
curPortMap, _ := dockerCmd(c, "port", cnt, "70")
curExplPortMap, _ := dockerCmd(c, "port", cnt, "90")
// Connect to a network which causes the container's default gw switch
dockerCmd(c, "network", "connect", "aaa", cnt)
verifyPortMap(c, cnt, "70", curPortMap, false)
verifyPortMap(c, cnt, "90", curExplPortMap, true)
// Read current mapping
curPortMap, _ = dockerCmd(c, "port", cnt, "70")
// Disconnect from a network which causes the container's default gw switch
dockerCmd(c, "network", "disconnect", "aaa", cnt)
verifyPortMap(c, cnt, "70", curPortMap, false)
verifyPortMap(c, cnt, "90", curExplPortMap, true)
// Read current mapping
curPortMap, _ = dockerCmd(c, "port", cnt, "70")
// Connect to a network which does not cause the container's default gw switch
dockerCmd(c, "network", "connect", "ccc", cnt)
verifyPortMap(c, cnt, "70", curPortMap, true)
verifyPortMap(c, cnt, "90", curExplPortMap, true)
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *check.C) {
macAddress := "02:42:ac:11:00:02"
dockerCmd(c, "network", "create", "mynetwork")
dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top")
c.Assert(waitRun("test"), check.IsNil)
mac1 := inspectField(c, "test", "NetworkSettings.Networks.bridge.MacAddress")
c.Assert(strings.TrimSpace(mac1), checker.Equals, macAddress)
dockerCmd(c, "network", "connect", "mynetwork", "test")
mac2 := inspectField(c, "test", "NetworkSettings.Networks.mynetwork.MacAddress")
c.Assert(strings.TrimSpace(mac2), checker.Not(checker.Equals), strings.TrimSpace(mac1))
}
func (s *DockerNetworkSuite) TestDockerNetworkInspectCreatedContainer(c *check.C) {
dockerCmd(c, "create", "--name", "test", "busybox")
networks := inspectField(c, "test", "NetworkSettings.Networks")
c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should return 'bridge' network"))
}
func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMultipleNetworks(c *check.C) {
dockerCmd(c, "network", "create", "test")
dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top")
c.Assert(waitRun("foo"), checker.IsNil)
dockerCmd(c, "network", "connect", "test", "foo")
dockerCmd(c, "restart", "foo")
networks := inspectField(c, "foo", "NetworkSettings.Networks")
c.Assert(networks, checker.Contains, "bridge", check.Commentf("Should contain 'bridge' network"))
c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContainer(c *check.C) {
dockerCmd(c, "network", "create", "test")
dockerCmd(c, "create", "--name=foo", "busybox", "top")
dockerCmd(c, "network", "connect", "test", "foo")
networks := inspectField(c, "foo", "NetworkSettings.Networks")
c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
// Restart docker daemon to test the config has persisted to disk
s.d.Restart()
networks = inspectField(c, "foo", "NetworkSettings.Networks")
c.Assert(networks, checker.Contains, "test", check.Commentf("Should contain 'test' network"))
// start the container and test if we can ping it from another container in the same network
dockerCmd(c, "start", "foo")
c.Assert(waitRun("foo"), checker.IsNil)
ip := inspectField(c, "foo", "NetworkSettings.Networks.test.IPAddress")
ip = strings.TrimSpace(ip)
dockerCmd(c, "run", "--net=test", "busybox", "sh", "-c", fmt.Sprintf("ping -c 1 %s", ip))
dockerCmd(c, "stop", "foo")
// Test disconnect
dockerCmd(c, "network", "disconnect", "test", "foo")
networks = inspectField(c, "foo", "NetworkSettings.Networks")
c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
// Restart docker daemon to test the config has persisted to disk
s.d.Restart()
networks = inspectField(c, "foo", "NetworkSettings.Networks")
c.Assert(networks, checker.Not(checker.Contains), "test", check.Commentf("Should not contain 'test' network"))
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIP(c *check.C) {
// create two networks
dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "n0")
assertNwIsAvailable(c, "n0")
dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.30.0.0/16", "--ip-range=172.30.5.0/24", "--subnet=2001:db8:abcd::/64", "--ip-range=2001:db8:abcd::/80", "n1")
assertNwIsAvailable(c, "n1")
// run a container on first network specifying the ip addresses
dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
c.Assert(waitRun("c0"), check.IsNil)
verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
// connect the container to the second network specifying an ip addresses
dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0")
verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
// Stop and restart the container
dockerCmd(c, "stop", "c0")
dockerCmd(c, "start", "c0")
// verify requested addresses are applied and configs are still there
verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988")
verifyIPAddressConfig(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
verifyIPAddresses(c, "c0", "n1", "172.30.55.44", "2001:db8:abcd::5544")
// Still it should fail to connect to the default network with a specified IP (whatever ip)
out, _, err := dockerCmdWithError("network", "connect", "--ip", "172.21.55.44", "bridge", "c0")
c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIPStoppedContainer(c *check.C) {
// create a container
dockerCmd(c, "create", "--name", "c0", "busybox", "top")
// create a network
dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.30.0.0/16", "--subnet=2001:db8:abcd::/64", "n0")
assertNwIsAvailable(c, "n0")
// connect the container to the network specifying an ip addresses
dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n0", "c0")
verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
// start the container, verify config has not changed and ip addresses are assigned
dockerCmd(c, "start", "c0")
c.Assert(waitRun("c0"), check.IsNil)
verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
verifyIPAddresses(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
// stop the container and check ip config has not changed
dockerCmd(c, "stop", "c0")
verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544")
}
func (s *DockerNetworkSuite) TestDockerNetworkUnsupportedRequiredIP(c *check.C) {
// requested IP is not supported on predefined networks
for _, mode := range []string{"none", "host", "bridge", "default"} {
checkUnsupportedNetworkAndIP(c, mode)
}
// requested IP is not supported on networks with no user defined subnets
dockerCmd(c, "network", "create", "n0")
assertNwIsAvailable(c, "n0")
out, _, err := dockerCmdWithError("run", "-d", "--ip", "172.28.99.88", "--net", "n0", "busybox", "top")
c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
out, _, err = dockerCmdWithError("run", "-d", "--ip6", "2001:db8:1234::9988", "--net", "n0", "busybox", "top")
c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())
dockerCmd(c, "network", "rm", "n0")
assertNwNotAvailable(c, "n0")
}
func checkUnsupportedNetworkAndIP(c *check.C, nwMode string) {
out, _, err := dockerCmdWithError("run", "-d", "--net", nwMode, "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top")
c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndIP.Error())
}
func verifyIPAddressConfig(c *check.C, cName, nwname, ipv4, ipv6 string) {
if ipv4 != "" {
out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv4Address", nwname))
c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
}
if ipv6 != "" {
out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAMConfig.IPv6Address", nwname))
c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
}
}
func verifyIPAddresses(c *check.C, cName, nwname, ipv4, ipv6 string) {
out := inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.IPAddress", nwname))
c.Assert(strings.TrimSpace(out), check.Equals, ipv4)
out = inspectField(c, cName, fmt.Sprintf("NetworkSettings.Networks.%s.GlobalIPv6Address", nwname))
c.Assert(strings.TrimSpace(out), check.Equals, ipv6)
}
func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *check.C) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
dockerCmd(c, "network", "create", "-d", "bridge", "foo1")
dockerCmd(c, "network", "create", "-d", "bridge", "foo2")
dockerCmd(c, "run", "-d", "--net=foo1", "--name=first", "busybox", "top")
c.Assert(waitRun("first"), check.IsNil)
// run a container in a user-defined network with a link for an existing container
// and a link for a container that doesn't exist
dockerCmd(c, "run", "-d", "--net=foo1", "--name=second", "--link=first:FirstInFoo1",
"--link=third:bar", "busybox", "top")
c.Assert(waitRun("second"), check.IsNil)
// ping to first and its alias FirstInFoo1 must succeed
_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
c.Assert(err, check.IsNil)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
c.Assert(err, check.IsNil)
// connect first container to foo2 network
dockerCmd(c, "network", "connect", "foo2", "first")
// connect second container to foo2 network with a different alias for first container
dockerCmd(c, "network", "connect", "--link=first:FirstInFoo2", "foo2", "second")
// ping the new alias in network foo2
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
c.Assert(err, check.IsNil)
// disconnect first container from foo1 network
dockerCmd(c, "network", "disconnect", "foo1", "first")
// link in foo1 network must fail
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1")
c.Assert(err, check.NotNil)
// link in foo2 network must succeed
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2")
c.Assert(err, check.IsNil)
}
// #19100 This is a deprecated feature test, it should be removed in Docker 1.12
func (s *DockerNetworkSuite) TestDockerNetworkStartAPIWithHostconfig(c *check.C) {
netName := "test"
conName := "foo"
dockerCmd(c, "network", "create", netName)
dockerCmd(c, "create", "--name", conName, "busybox", "top")
config := map[string]interface{}{
"HostConfig": map[string]interface{}{
"NetworkMode": netName,
},
}
_, _, err := sockRequest("POST", "/containers/"+conName+"/start", config)
c.Assert(err, checker.IsNil)
c.Assert(waitRun(conName), checker.IsNil)
networks := inspectField(c, conName, "NetworkSettings.Networks")
c.Assert(networks, checker.Contains, netName, check.Commentf(fmt.Sprintf("Should contain '%s' network", netName)))
c.Assert(networks, checker.Not(checker.Contains), "bridge", check.Commentf("Should not contain 'bridge' network"))
}
func (s *DockerNetworkSuite) TestDockerNetworkDisconnectDefault(c *check.C) {
netWorkName1 := "test1"
netWorkName2 := "test2"
containerName := "foo"
dockerCmd(c, "network", "create", netWorkName1)
dockerCmd(c, "network", "create", netWorkName2)
dockerCmd(c, "create", "--name", containerName, "busybox", "top")
dockerCmd(c, "network", "connect", netWorkName1, containerName)
dockerCmd(c, "network", "connect", netWorkName2, containerName)
dockerCmd(c, "network", "disconnect", "bridge", containerName)
dockerCmd(c, "start", containerName)
c.Assert(waitRun(containerName), checker.IsNil)
networks := inspectField(c, containerName, "NetworkSettings.Networks")
c.Assert(networks, checker.Contains, netWorkName1, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName1)))
c.Assert(networks, checker.Contains, netWorkName2, check.Commentf(fmt.Sprintf("Should contain '%s' network", netWorkName2)))
c.Assert(networks, checker.Not(checker.Contains), "bridge", check.Commentf("Should not contain 'bridge' network"))
}
func (s *DockerNetworkSuite) TestDockerNetworkConnectWithAliasOnDefaultNetworks(c *check.C) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
defaults := []string{"bridge", "host", "none"}
out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
containerID := strings.TrimSpace(out)
for _, net := range defaults {
res, _, err := dockerCmdWithError("network", "connect", "--alias", "alias"+net, net, containerID)
c.Assert(err, checker.NotNil)
c.Assert(res, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
}
}
func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectAlias(c *check.C) {
testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
dockerCmd(c, "network", "create", "-d", "bridge", "net1")
dockerCmd(c, "network", "create", "-d", "bridge", "net2")
cid, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo", "busybox", "top")
c.Assert(waitRun("first"), check.IsNil)
dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox", "top")
c.Assert(waitRun("second"), check.IsNil)
// ping first container and its alias
_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
c.Assert(err, check.IsNil)
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
c.Assert(err, check.IsNil)
// ping first container's short-id alias
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid))
c.Assert(err, check.IsNil)
// connect first container to net2 network
dockerCmd(c, "network", "connect", "--alias=bar", "net2", "first")
// connect second container to foo2 network with a different alias for first container
dockerCmd(c, "network", "connect", "net2", "second")
// ping the new alias in network foo2
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
c.Assert(err, check.IsNil)
// disconnect first container from net1 network
dockerCmd(c, "network", "disconnect", "net1", "first")
// ping to net1 scoped alias "foo" must fail
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
c.Assert(err, check.NotNil)
// ping to net2 scoped alias "bar" must still succeed
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
c.Assert(err, check.IsNil)
// ping to net2 scoped alias short-id must still succeed
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid))
c.Assert(err, check.IsNil)
// verify the alias option is rejected when running on predefined network
out, _, err := dockerCmdWithError("run", "--rm", "--name=any", "--net-alias=any", "busybox", "top")
c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
// verify the alias option is rejected when connecting to predefined network
out, _, err = dockerCmdWithError("network", "connect", "--alias=any", "bridge", "first")
c.Assert(err, checker.NotNil, check.Commentf("out: %s", out))
c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
}
func (s *DockerSuite) TestUserDefinedNetworkConnectivity(c *check.C) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
dockerCmd(c, "network", "create", "-d", "bridge", "br.net1")
dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c1.net1", "busybox", "top")
c.Assert(waitRun("c1.net1"), check.IsNil)
dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c2.net1", "busybox", "top")
c.Assert(waitRun("c2.net1"), check.IsNil)
// ping first container by its unqualified name
_, _, err := dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1")
c.Assert(err, check.IsNil)
// ping first container by its qualified name
_, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1")
c.Assert(err, check.IsNil)
// ping with first qualified name masked by an additional domain. should fail
_, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1.google.com")
c.Assert(err, check.NotNil)
}
func (s *DockerSuite) TestEmbeddedDNSInvalidInput(c *check.C) {
testRequires(c, DaemonIsLinux, NotUserNamespace)
dockerCmd(c, "network", "create", "-d", "bridge", "nw1")
// Sending garbage to embedded DNS shouldn't crash the daemon
dockerCmd(c, "run", "-i", "--net=nw1", "--name=c1", "debian:jessie", "bash", "-c", "echo InvalidQuery > /dev/udp/127.0.0.11/53")
}
func (s *DockerSuite) TestDockerNetworkConnectFailsNoInspectChange(c *check.C) {
dockerCmd(c, "run", "-d", "--name=bb", "busybox", "top")
c.Assert(waitRun("bb"), check.IsNil)
ns0 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
// A failing redundant network connect should not alter current container's endpoint settings
_, _, err := dockerCmdWithError("network", "connect", "bridge", "bb")
c.Assert(err, check.NotNil)
ns1 := inspectField(c, "bb", "NetworkSettings.Networks.bridge")
c.Assert(ns1, check.Equals, ns0)
}
func (s *DockerSuite) TestDockerNetworkInternalMode(c *check.C) {
dockerCmd(c, "network", "create", "--driver=bridge", "--internal", "internal")
assertNwIsAvailable(c, "internal")
nr := getNetworkResource(c, "internal")
c.Assert(nr.Internal, checker.True)
dockerCmd(c, "run", "-d", "--net=internal", "--name=first", "busybox", "top")
c.Assert(waitRun("first"), check.IsNil)
dockerCmd(c, "run", "-d", "--net=internal", "--name=second", "busybox", "top")
c.Assert(waitRun("second"), check.IsNil)
out, _, err := dockerCmdWithError("exec", "first", "ping", "-W", "4", "-c", "1", "www.google.com")
c.Assert(err, check.NotNil)
c.Assert(out, checker.Contains, "ping: bad address")
_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
c.Assert(err, check.IsNil)
}
// Test for #21401
func (s *DockerNetworkSuite) TestDockerNetworkCreateDeleteSpecialCharacters(c *check.C) {
dockerCmd(c, "network", "create", "test@#$")
assertNwIsAvailable(c, "test@#$")
dockerCmd(c, "network", "rm", "test@#$")
assertNwNotAvailable(c, "test@#$")
dockerCmd(c, "network", "create", "kiwl$%^")
assertNwIsAvailable(c, "kiwl$%^")
dockerCmd(c, "network", "rm", "kiwl$%^")
assertNwNotAvailable(c, "kiwl$%^")
}
| {
"content_hash": "c86fc5bbe299c83430578240b351ba32",
"timestamp": "",
"source": "github",
"line_count": 1548,
"max_line_length": 168,
"avg_line_length": 40.01744186046512,
"alnum_prop": 0.6931893392738955,
"repo_name": "14rcole/docker",
"id": "9d76ff43c931bd4a34fb46d1b6205936cf5b3be9",
"size": "61967",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "integration-cli/docker_cli_network_unix_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "3817048"
},
{
"name": "Makefile",
"bytes": "4376"
},
{
"name": "Shell",
"bytes": "235938"
},
{
"name": "VimL",
"bytes": "1328"
}
],
"symlink_target": ""
} |
var path = require('path');
// Settings
var config = {
'port': process.env.PORT || 80,
'dev': process.env.DEV || false,
// GitHub deployment
'github': {
script: '/utils/update.sh',
path: path.join('/', process.env.G_PATH),
secret: process.env.G_SECRET
},
// Web paths (from root)
'web': {
'css': '/css',
'static': {
'/': '/static',
},
},
// Physical paths (from here)
'paths': {
'express': 'express/express.js',
'github': 'github.js',
'routes': 'routes/routes.js',
},
// Physical paths (from root)
'root': {
'docs': '/static/docs',
'sass': '/assets/sass',
'sass_dest': '/static/css',
'views': '/views',
}
};
// Prepend local paths with __dirname
for(var name in config.paths) {
config.paths[name] = path.join(__dirname, config.paths[name]);
}
// Prepend root paths with __dirname/..
for(var name in config.root) {
config.root[name] = path.join(__dirname, '..', config.root[name]);
}
// Prepend the GitHub script with __dirname/..
config.github.script = path.join(__dirname, '..', config.github.script);
module.exports = config;
| {
"content_hash": "42ca190689342d5dcf93d04f60cbed47",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 72,
"avg_line_length": 22.48076923076923,
"alnum_prop": 0.562874251497006,
"repo_name": "Alex4913/node-website",
"id": "a3f8a5d4a926bc341cde20f5c97b588cc53063fe",
"size": "1205",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "support/config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37591"
},
{
"name": "HTML",
"bytes": "2254"
},
{
"name": "JavaScript",
"bytes": "8711"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright © Microsoft Open Technologies, Inc.
All Rights Reserved
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A
PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
See the Apache License, Version 2.0 for the specific language
governing permissions and limitations under the License.
-->
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/StaticService/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>proxy</servlet-name>
<servlet-class>org.esigate.servlet.RewriteProxyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>proxy</servlet-name>
<url-pattern>/DefaultService.svc/*</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Auth</web-resource-name>
<url-pattern>/DefaultService.svc/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>odatajclient</role-name>
</auth-constraint>
<user-data-constraint>
<!-- transport-guarantee can be CONFIDENTIAL, INTEGRAL, or NONE -->
<transport-guarantee>NONE</transport-guarantee>
</user-data-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
<security-role>
<role-name>odatajclient</role-name>
</security-role>
</web-app>
| {
"content_hash": "80eb7e9363eb22d5ddeae52f0287e63b",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 74,
"avg_line_length": 31.605263157894736,
"alnum_prop": 0.6927560366361366,
"repo_name": "0359xiaodong/Office-365-SDK-for-Android",
"id": "a528a2a41639b6eb9902ec3530f399fae1869c55",
"size": "2403",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "sdk/office365-mail-calendar-contact-sdk/proxy/test-service/src/main/webapp/WEB-INF/web.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!-- HTML header for doxygen 1.8.13-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>MTB CAT1 Peripheral driver library: Data structures</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><a href="http://www.cypress.com/"><img alt="Logo" src="IFXCYP_one-line.png"/></a></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">MTB CAT1 Peripheral driver library</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('group__group__sar2__data__structures.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#nested-classes">Data Structures</a> </div>
<div class="headertitle">
<div class="title">Data structures<div class="ingroups"><a class="el" href="group__group__sar2.html">SAR2 (Analog to Digital Converter (ADC))</a></div></div> </div>
</div><!--header-->
<div class="contents">
<a name="details" id="details"></a><h2 class="groupheader">General Description</h2>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Data Structures</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structcy__stc__sar2__channel__config__t.html">cy_stc_sar2_channel_config_t</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">Configuration structure of the SAR2 ADC channel. <a href="structcy__stc__sar2__channel__config__t.html#details">More...</a><br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structcy__stc__sar2__config__t.html">cy_stc_sar2_config_t</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">Configuration structure of the SAR2 HW block. <a href="structcy__stc__sar2__config__t.html#details">More...</a><br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structcy__stc__sar2__digital__calibration__config__t.html">cy_stc_sar2_digital_calibration_config_t</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">Digital calibration values. <a href="structcy__stc__sar2__digital__calibration__config__t.html#details">More...</a><br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structcy__stc__sar2__analog__calibration__conifg__t.html">cy_stc_sar2_analog_calibration_conifg_t</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">Analog calibration values. <a href="structcy__stc__sar2__analog__calibration__conifg__t.html#details">More...</a><br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structcy__stc__sar2__diag__config__t.html">cy_stc_sar2_diag_config_t</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">Configuration structure of diagnosis function. <a href="structcy__stc__sar2__diag__config__t.html#details">More...</a><br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structcy__stc__sar2__debug__freeze__config__t.html">cy_stc_sar2_debug_freeze_config_t</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">Control freeze feature for debugging. <a href="structcy__stc__sar2__debug__freeze__config__t.html#details">More...</a><br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part
<div id="nav-path" class="navpath">
<ul>
<li class="footer">
Generated for <b>MTB CAT1 Peripheral driver library</b> by <b>Cypress Semiconductor Corporation</b>.
All rights reserved.
</li>
</ul>
</div>
-->
</body>
</html>
| {
"content_hash": "064eafc6234687db423873f1fb2c5d78",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 264,
"avg_line_length": 58.184,
"alnum_prop": 0.6749621889179156,
"repo_name": "Infineon/mtb-pdl-cat1",
"id": "9ec1b4cab4648a95763756f7a2dee5c29349f437",
"size": "7273",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/pdl_api_reference_manual/html/group__group__sar2__data__structures.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "16538"
},
{
"name": "C",
"bytes": "45610434"
},
{
"name": "Tcl",
"bytes": "58782"
}
],
"symlink_target": ""
} |
import sys
# Need different unic implementations for different Pythons because:
# 1) Importing unicodedata module on Jython takes a very long time, and doesn't
# seem to be necessary as Java probably already handles normalization.
# Furthermore, Jython on Java 1.5 doesn't even have unicodedata.normalize.
# 2) IronPython 2.6 doesn't have unicodedata and probably doesn't need it.
# 3) CPython doesn't automatically normalize Unicode strings.
if sys.platform.startswith('java'):
from java.lang import Object, Class
def unic(item, *args):
# http://bugs.jython.org/issue1564
if isinstance(item, Object) and not isinstance(item, Class):
try:
item = item.toString() # http://bugs.jython.org/issue1563
except:
return _unrepresentable_object(item)
return _unic(item, *args)
elif sys.platform == 'cli':
def unic(item, *args):
return _unic(item, *args)
else:
from unicodedata import normalize
def unic(item, *args):
return normalize('NFC', _unic(item, *args))
def _unic(item, *args):
# Based on a recipe from http://code.activestate.com/recipes/466341
try:
return unicode(item, *args)
except UnicodeError:
try:
ascii_text = str(item).encode('string_escape')
except:
return _unrepresentable_object(item)
else:
return unicode(ascii_text)
except:
return _unrepresentable_object(item)
def safe_repr(item):
try:
return unic(repr(item))
except UnicodeError:
return repr(unic(item))
except:
return _unrepresentable_object(item)
_unrepresentable_msg = u"<Unrepresentable object '%s'. Error: %s>"
def _unrepresentable_object(item):
from robot.utils.error import get_error_message
return _unrepresentable_msg % (item.__class__.__name__, get_error_message())
| {
"content_hash": "2599b26e501762cd39e1ec60a794ca33",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 80,
"avg_line_length": 31.75,
"alnum_prop": 0.6561679790026247,
"repo_name": "Senseg/robotframework",
"id": "dbf240a7f89cadc8452b360e7c1c2d1aaa21d2cb",
"size": "2511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/robot/utils/unic.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "716"
},
{
"name": "Java",
"bytes": "48873"
},
{
"name": "JavaScript",
"bytes": "149654"
},
{
"name": "Python",
"bytes": "1637427"
},
{
"name": "Shell",
"bytes": "1323"
}
],
"symlink_target": ""
} |
<?php
defined('C5_EXECUTE') or die(_("Access Denied."));
$textHelper = Loader::helper("text");
// now that we're in the specialized content file for this block type,
// we'll include this block type's class, and pass the block to it, and get
// the content
if (count($cArray) > 0) {
?>
<div class="news-block">
<?php
for ($i = 0; $i < count($cArray); $i++) {
$cobj = $cArray[$i];
$title = $cobj->getCollectionName();
$secondaryheadline = $cobj->getAttribute('secondary_headline');
$author = $cobj->getAttribute('author');
$photo_caption = $cobj->getAttribute('photo_caption');
$dateline = $cobj->getAttribute('dateline');
$newsDate = $cobj->getCollectionDatePublic('F jS Y');
$slideimage = $cobj->getAttribute('files');
$sliderimages = explode('^', $slideimage);
$pid = $cobj->cID;
?>
<div class="article guest">
<h2><?php echo $title; ?></h2>
<h4><?php echo $secondaryheadline; ?></h4>
<strong class="date">by <?php echo $author; ?></strong>
<?php if ($cobj->getAttribute('main_photo') != '' && $cobj->getAttribute('single_multiple_photo_status') == 1) { ?>
<div class="image-holder">
<?php
$CatImage = $cobj->getAttribute('main_photo');
if ($CatImage) {
$ih = Loader::helper('image');
$image_arr['realimg'] = $CatImage->getRelativePath();
$thumb = $ih->getThumbnail($CatImage, 400, 283);
$image = '';
$image = '<img alt="" src="' . $thumb->src . '">';
echo $image;
}
?>
<strong class="title"><?php echo $photo_caption ?></strong>
</div>
<?php } elseif ($slideimage != '' && $cobj->getAttribute('single_multiple_photo_status') == 2) { ?>
<div class="slideshow-holder">
<ul class="news-slideshow">
<?php foreach ($sliderimages as $simages) {
$sliders = explode('||', $simages)
?>
<li>
<?php
$f = File::getByID($sliders[0]);
$ih = Loader::helper('image');
$image_arr['realimg'] = $f->getRelativePath();
$thumb = $ih->getThumbnail($f, 400, 283);
$image = '';
$image = '<img alt="" src="' . $thumb->src . '">';
echo $image;
?>
<strong class="title"><?php echo $sliders[1] ?></strong>
</li>
<?php } ?>
</ul>
<nav>
<ul class="switcher">
<?php foreach ($sliderimages as $simages) { ?>
<li class=""><a href="#"></a></li>
<?php } ?>
</ul>
</nav>
</div>
<?php } ?>
<div id="article_content">
<p><span class="dateline"><?php echo $dateline ?>, MI — </span>
<?php
$block = $cobj->getBlocks('Main');
foreach ($block as $bi) {
if ($bi->getBlockTypeHandle() == 'content') {
$content = $bi->getInstance()->getContent();
}
}
echo $content;
?>
</div>
<strong class="date">Submitted on: <span id="pub_date"><?php echo $newsDate ?></span></strong>
</div>
<?php } ?>
</div>
<div class="article-fade"> </div>
<div class="more-guest">
<a class="more" href="<?php echo $nh->getLinkToCollection($cobj) ?>">Read Full Article »</a>
</div>
<?php } ?>
<script type="text/javascript">
var html = $('#article_content').html();
html = html.replace('♥', '');
$('#article_content').html(html);
</script>
| {
"content_hash": "a67b5b360ffa9bbeee0bfed2ce645a81",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 135,
"avg_line_length": 41.669642857142854,
"alnum_prop": 0.38461538461538464,
"repo_name": "kevinwwilson/schoolnews",
"id": "1a4834af054cace9602d66e4cde7ab9281ad6e1d",
"size": "4672",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blocks/pronews_list/templates/full_article/view.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "342502"
},
{
"name": "AngelScript",
"bytes": "3276"
},
{
"name": "CSS",
"bytes": "1105957"
},
{
"name": "CoffeeScript",
"bytes": "23848"
},
{
"name": "HTML",
"bytes": "52511"
},
{
"name": "JavaScript",
"bytes": "1400500"
},
{
"name": "PHP",
"bytes": "8193686"
}
],
"symlink_target": ""
} |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTypesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('types', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('provider_id')->unsigned();
$table->integer('group_id')->unsigned();
$table->timestamps();
$table->foreign('provider_id')
->references('id')
->on('providers')
->onDelete('cascade');
$table->foreign('group_id')
->references('id')
->on('groups')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('types');
}
}
| {
"content_hash": "5107853379d870a8c25533ed034ca5ca",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 61,
"avg_line_length": 22.837209302325583,
"alnum_prop": 0.48676171079429736,
"repo_name": "Meepnix/libreBudgetSnapShot",
"id": "3b61ad178f046c404baeada2af097673e45371f2",
"size": "982",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/migrations/2016_06_16_023408_create_types_table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "64454"
},
{
"name": "JavaScript",
"bytes": "623"
},
{
"name": "PHP",
"bytes": "96680"
}
],
"symlink_target": ""
} |
Reimplementation of [Google's Wide & Deep Network](https://arxiv.org/abs/1606.07792) in Keras
Based on a [TF Tutorial](https://www.tensorflow.org/tutorials/wide_and_deep/) and [Liu Sida's Blog Post](https://liusida.github.io/2016/10/31/translate-from-tf-2-keras/).
work in progress
| {
"content_hash": "c238f58874fea17e08d9124d28155d88",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 170,
"avg_line_length": 57.6,
"alnum_prop": 0.75,
"repo_name": "jorahn/keras-wide-n-deep",
"id": "fe0f40986f670c112dbf32b38b5e1f190c6f3cf9",
"size": "308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "2717"
}
],
"symlink_target": ""
} |
typedef struct ReadBuffer_t
{
bool isFull;
bool waitUntilNextMessage;
bool previousCharWasCR;
uint8_t startIdx;
uint8_t endIdx;
Message buffer[UART_READ_BUFFER_MAX_MESSAGES_LEN];
} ReadBuffer;
typedef struct WriteBuffer_t
{
bool isEmpty;
uint16_t startIdx;
uint16_t endIdx;
uint8_t buffer[UART_WRITE_BUFFER_MAX_CHARS_LEN];
} WriteBuffer;
typedef struct UartChannelData_t
{
uint32_t base;
uint32_t interruptId;
ReadBuffer readBuffer;
WriteBuffer writeBuffer;
} UartChannelData;
void uartReadIntHandler(UartChannelData* pChannelData);
void uartWriteIntHandler(UartChannelData* pChannelData);
extern UartChannelData uartChannelData[UART_NUMBER_OF_CHANNELS];
| {
"content_hash": "21fdcbfa0b8cf83b509e7920430ddcd4",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 64,
"avg_line_length": 23.833333333333332,
"alnum_prop": 0.7538461538461538,
"repo_name": "usaguerrilla/hab",
"id": "15b7ab784bbea3a13c9dff5a53836ad10611aaad",
"size": "1434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gps-radio-tiva-c/src/uart_impl.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "16904"
},
{
"name": "Batchfile",
"bytes": "1294"
},
{
"name": "C",
"bytes": "153468"
},
{
"name": "C#",
"bytes": "60915"
},
{
"name": "C++",
"bytes": "123719"
},
{
"name": "Eagle",
"bytes": "2536782"
},
{
"name": "PowerShell",
"bytes": "446"
},
{
"name": "Ruby",
"bytes": "1201"
}
],
"symlink_target": ""
} |
import { Component, OnInit, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { EmployeeListItem } from 'client';
import { SubAccountForm } from '../form/form.component';
@Component({
selector: 'sub-account-add',
template: require('./add.template.html'),
styles: [require('./add.style.scss')],
//directives: [ROUTER_DIRECTIVES]
})
export class SubAccountAdd {
// 控制员工列表层是否显示
showEmployeeLayer: boolean = false;
// 选中的技师
selectedEmployee: EmployeeListItem;
@ViewChild(SubAccountForm) saf: SubAccountForm;
constructor(private router: Router, private route: ActivatedRoute ) {
}
ngOnInit() {
console.log('account add init');
}
/**
* 显示 员工列表层
*/
onShowEmployeeListLayer(show) {
console.log('form employee', show);
console.log(this.selectedEmployee);
this.showEmployeeLayer = show ? true : false;
}
/**
* 从员工列表中选来的员工
*/
onChangeEmployee(data) {
this.selectedEmployee = Object.assign({}, data);
console.log('selectedEmployee', this.selectedEmployee);
this.saf.onSetEmployeeName(data);
this.showEmployeeLayer = false;
}
/**
* 从 Form 表单中更新 选中的技师
*/
onUpdateSelectEmployee(evt) {
this.selectedEmployee = evt;
}
}
| {
"content_hash": "354b84c81a4e613380f0434c52f7ee68",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 73,
"avg_line_length": 24.70909090909091,
"alnum_prop": 0.6291390728476821,
"repo_name": "thzhishu/angular2-webpack-starter-master-h5",
"id": "454db4afff41d64c7212b8eca372937f060181e2",
"size": "1449",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/+subAccount/add/add.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "89859"
},
{
"name": "HTML",
"bytes": "96204"
},
{
"name": "JavaScript",
"bytes": "42928"
},
{
"name": "Shell",
"bytes": "1664"
},
{
"name": "TypeScript",
"bytes": "521128"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe GroupMilestone do
let(:group) { create(:group) }
let(:project) { create(:project, group: group) }
let(:project_milestone) do
create(:milestone, title: "Milestone v1.2", project: project)
end
describe '.build' do
it 'returns milestone with group assigned' do
milestone = described_class.build(
group,
[project],
project_milestone.title
)
expect(milestone.group).to eq group
end
end
describe '.build_collection' do
let(:group) { create(:group) }
let(:project1) { create(:project, group: group) }
let(:project2) { create(:project, path: 'gitlab-ci', group: group) }
let(:project3) { create(:project, path: 'cookbook-gitlab', group: group) }
let!(:projects) do
[
project1,
project2,
project3
]
end
it 'returns array of milestones, each with group assigned' do
milestones = described_class.build_collection(group, [project], {})
expect(milestones).to all(have_attributes(group: group))
end
context 'when adding new milestones' do
it 'does not add more queries' do
control_count = ActiveRecord::QueryRecorder.new do
described_class.build_collection(group, projects, {})
end.count
create(:milestone, title: 'This title', project: project1)
expect do
described_class.build_collection(group, projects, {})
end.not_to exceed_all_query_limit(control_count)
end
end
end
end
| {
"content_hash": "eafb02c99a2ce5e2c379c1d0241271c4",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 78,
"avg_line_length": 27.963636363636365,
"alnum_prop": 0.6300390117035111,
"repo_name": "iiet/iiet-git",
"id": "01856870fe046a8de315e19399c794157e53fc7c",
"size": "1569",
"binary": false,
"copies": "2",
"ref": "refs/heads/release",
"path": "spec/models/group_milestone_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "694819"
},
{
"name": "Clojure",
"bytes": "79"
},
{
"name": "Dockerfile",
"bytes": "1907"
},
{
"name": "HTML",
"bytes": "1386003"
},
{
"name": "JavaScript",
"bytes": "4784137"
},
{
"name": "Ruby",
"bytes": "21288676"
},
{
"name": "Shell",
"bytes": "47962"
},
{
"name": "Vue",
"bytes": "1163492"
}
],
"symlink_target": ""
} |
<!-- Begin Direction Details-->
<section id="direction-details" class="direction-details">
<div class="content-wrapper">
<section class="image-section standart-height" title="By Alurín (Own work) [CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons" style="background-image: url('{{ site.baseurl }}/img/sections-background/{{ site.directionDetailsImage }}');">
<h3>{{ site.directionDetailsTitle }}</h3>
</section>
<div class="row">
<div class="col-lg-10 col-lg-offset-1 text-left">
{% assign animationDelay = 0 %}
{% for card in site.directionDetailsCards %}
{% assign colWidth = 12 | divided_by: forloop.length %}
<div class="col-md-{{ colWidth }} col-xs-12 same-height animated hiding" data-animation="fadeInDown" data-delay="{{ animationDelay }}">
<div class="card">
<h4>{{ card.title }}</h4>
<p>{{ card.information }}</p>
</div>
</div>
{% assign animationDelay = animationDelay | plus:500 %}
{% endfor %}
{% for wideCard in site.directionDetailsWideCards %}
<div class="col-md-12 col-xs-12 animated hiding" data-animation="fadeInDown" data-delay="0">
<div class="card questions">
<h4>{{ wideCard.title }}</h4>
{% for subCard in wideCard.subCards %}
{% assign wideCardColWidth = 12 | divided_by: forloop.length %}
<div class="col-md-{{ wideCardColWidth }} col-xs-12">
<h5>{{ subCard.title }}</h5>
<ul>
{% for linkElement in subCard.links %}
<li><a href="{% if linkElement.permalink != null %} {{ linkElement.permalink | prepend: site.baseurl }} {% else %} {{ linkElement.link }} {% endif %}" {% if linkElement.link != null %}target="_blank"{% endif %}>{{ linkElement.text }}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</section>
<!-- End Direction Details --> | {
"content_hash": "fed48e5cec11279902318e1d0d908da6",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 280,
"avg_line_length": 57.41860465116279,
"alnum_prop": 0.47671121911705144,
"repo_name": "GDGSalamanca/design-tech2014",
"id": "cfe4c0ce45dc3ad3b3d88dd4bb6b20c61a268d58",
"size": "2470",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_includes/direction-details.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3678"
},
{
"name": "CSS",
"bytes": "55488"
},
{
"name": "HTML",
"bytes": "82595"
},
{
"name": "JavaScript",
"bytes": "24663"
},
{
"name": "Ruby",
"bytes": "1236"
}
],
"symlink_target": ""
} |
goog.provide('ol.reproj.Tile');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.math');
goog.require('goog.object');
goog.require('ol.Tile');
goog.require('ol.TileState');
goog.require('ol.extent');
goog.require('ol.proj');
goog.require('ol.reproj');
goog.require('ol.reproj.Triangulation');
/**
* @classdesc
* Class encapsulating single reprojected tile.
* See {@link ol.source.TileImage}.
*
* @constructor
* @extends {ol.Tile}
* @param {ol.proj.Projection} sourceProj Source projection.
* @param {ol.tilegrid.TileGrid} sourceTileGrid Source tile grid.
* @param {ol.proj.Projection} targetProj Target projection.
* @param {ol.tilegrid.TileGrid} targetTileGrid Target tile grid.
* @param {number} z Zoom level.
* @param {number} x X.
* @param {number} y Y.
* @param {number} pixelRatio Pixel ratio.
* @param {function(number, number, number, number) : ol.Tile} getTileFunction
* Function returning source tiles (z, x, y, pixelRatio).
* @param {number=} opt_errorThreshold Acceptable reprojection error (in px).
* @param {boolean=} opt_renderEdges Render reprojection edges.
*/
ol.reproj.Tile = function(sourceProj, sourceTileGrid,
targetProj, targetTileGrid, z, x, y, pixelRatio, getTileFunction,
opt_errorThreshold,
opt_renderEdges) {
goog.base(this, [z, x, y], ol.TileState.IDLE);
/**
* @private
* @type {boolean}
*/
this.renderEdges_ = goog.isDef(opt_renderEdges) ? opt_renderEdges : false;
/**
* @private
* @type {number}
*/
this.pixelRatio_ = pixelRatio;
/**
* @private
* @type {HTMLCanvasElement}
*/
this.canvas_ = null;
/**
* @private
* @type {Object.<number, HTMLCanvasElement>}
*/
this.canvasByContext_ = {};
/**
* @private
* @type {ol.tilegrid.TileGrid}
*/
this.sourceTileGrid_ = sourceTileGrid;
/**
* @private
* @type {ol.tilegrid.TileGrid}
*/
this.targetTileGrid_ = targetTileGrid;
/**
* @private
* @type {!Array.<ol.Tile>}
*/
this.srcTiles_ = [];
/**
* @private
* @type {Array.<goog.events.Key>}
*/
this.sourcesListenerKeys_ = null;
/**
* @private
* @type {number}
*/
this.srcZ_ = 0;
var targetExtent = targetTileGrid.getTileCoordExtent(this.getTileCoord());
var maxTargetExtent = this.targetTileGrid_.getExtent();
var maxSourceExtent = this.sourceTileGrid_.getExtent();
var limitedTargetExtent = goog.isNull(maxTargetExtent) ?
targetExtent : ol.extent.getIntersection(targetExtent, maxTargetExtent);
if (ol.extent.getArea(limitedTargetExtent) === 0) {
// Tile is completely outside range -> EMPTY
// TODO: is it actually correct that the source even creates the tile ?
this.state = ol.TileState.EMPTY;
return;
}
var sourceProjExtent = sourceProj.getExtent();
if (!goog.isNull(sourceProjExtent)) {
if (goog.isNull(maxSourceExtent)) {
maxSourceExtent = sourceProjExtent;
} else {
maxSourceExtent = ol.extent.getIntersection(
maxSourceExtent, sourceProjExtent);
}
}
var targetResolution = targetTileGrid.getResolution(z);
var targetCenter = ol.extent.getCenter(limitedTargetExtent);
var sourceResolution = ol.reproj.calculateSourceResolution(
sourceProj, targetProj, targetCenter, targetResolution);
if (!goog.math.isFiniteNumber(sourceResolution) || sourceResolution <= 0) {
// invalid sourceResolution -> EMPTY
// probably edges of the projections when no extent is defined
this.state = ol.TileState.EMPTY;
return;
}
var errorThresholdInPixels = goog.isDef(opt_errorThreshold) ?
opt_errorThreshold : ol.DEFAULT_RASTER_REPROJ_ERROR_THRESHOLD;
/**
* @private
* @type {!ol.reproj.Triangulation}
*/
this.triangulation_ = new ol.reproj.Triangulation(
sourceProj, targetProj, limitedTargetExtent, maxSourceExtent,
sourceResolution * errorThresholdInPixels);
if (this.triangulation_.getTriangles().length === 0) {
// no valid triangles -> EMPTY
this.state = ol.TileState.EMPTY;
return;
}
this.srcZ_ = sourceTileGrid.getZForResolution(sourceResolution);
var srcExtent = this.triangulation_.calculateSourceExtent();
if (!goog.isNull(maxSourceExtent) &&
!this.triangulation_.getWrapsXInSource() &&
!ol.extent.intersects(maxSourceExtent, srcExtent)) {
this.state = ol.TileState.EMPTY;
} else {
var srcRange = sourceTileGrid.getTileRangeForExtentAndZ(
srcExtent, this.srcZ_);
var xRange;
var srcFullRange = sourceTileGrid.getFullTileRange(this.srcZ_);
if (!goog.isNull(srcFullRange)) {
srcRange.minY = Math.max(srcRange.minY, srcFullRange.minY);
srcRange.maxY = Math.min(srcRange.maxY, srcFullRange.maxY);
if (srcRange.minX > srcRange.maxX) {
xRange = goog.array.concat(
goog.array.range(srcRange.minX, srcFullRange.maxX + 1),
goog.array.range(srcFullRange.minX, srcRange.maxX + 1)
);
} else {
xRange = goog.array.range(
Math.max(srcRange.minX, srcFullRange.minX),
Math.min(srcRange.maxX, srcFullRange.maxX) + 1
);
}
} else {
xRange = goog.array.range(srcRange.minX, srcRange.maxX + 1);
}
var tilesRequired = xRange.length * srcRange.getHeight();
if (!goog.asserts.assert(tilesRequired < ol.RASTER_REPROJ_MAX_SOURCE_TILES,
'reasonable number of tiles is required')) {
this.state = ol.TileState.ERROR;
return;
}
goog.array.forEach(xRange, function(srcX, i, arr) {
for (var srcY = srcRange.minY; srcY <= srcRange.maxY; srcY++) {
var tile = getTileFunction(this.srcZ_, srcX, srcY, pixelRatio);
if (tile) {
this.srcTiles_.push(tile);
}
}
}, this);
if (this.srcTiles_.length === 0) {
this.state = ol.TileState.EMPTY;
}
}
};
goog.inherits(ol.reproj.Tile, ol.Tile);
/**
* @inheritDoc
*/
ol.reproj.Tile.prototype.disposeInternal = function() {
if (this.state == ol.TileState.LOADING) {
this.unlistenSources_();
}
goog.base(this, 'disposeInternal');
};
/**
* @inheritDoc
*/
ol.reproj.Tile.prototype.getImage = function(opt_context) {
if (goog.isDef(opt_context)) {
var image;
var key = goog.getUid(opt_context);
if (key in this.canvasByContext_) {
return this.canvasByContext_[key];
} else if (goog.object.isEmpty(this.canvasByContext_)) {
image = this.canvas_;
} else {
image = /** @type {HTMLCanvasElement} */ (this.canvas_.cloneNode(false));
}
this.canvasByContext_[key] = image;
return image;
} else {
return this.canvas_;
}
};
/**
* @private
*/
ol.reproj.Tile.prototype.reproject_ = function() {
var sources = [];
goog.array.forEach(this.srcTiles_, function(tile, i, arr) {
if (tile && tile.getState() == ol.TileState.LOADED) {
sources.push({
extent: this.sourceTileGrid_.getTileCoordExtent(tile.tileCoord),
image: tile.getImage()
});
}
}, this);
var tileCoord = this.getTileCoord();
var z = tileCoord[0];
var size = this.targetTileGrid_.getTileSize(z);
var width = goog.isNumber(size) ? size : size[0];
var height = goog.isNumber(size) ? size : size[1];
var targetResolution = this.targetTileGrid_.getResolution(z);
var sourceResolution = this.sourceTileGrid_.getResolution(this.srcZ_);
var targetExtent = this.targetTileGrid_.getTileCoordExtent(tileCoord);
this.canvas_ = ol.reproj.render(width, height, this.pixelRatio_,
sourceResolution, this.sourceTileGrid_.getExtent(),
targetResolution, targetExtent, this.triangulation_, sources,
this.renderEdges_);
this.state = ol.TileState.LOADED;
this.changed();
};
/**
* @inheritDoc
*/
ol.reproj.Tile.prototype.load = function() {
if (this.state == ol.TileState.IDLE) {
this.state = ol.TileState.LOADING;
this.changed();
var leftToLoad = 0;
goog.asserts.assert(goog.isNull(this.sourcesListenerKeys_),
'this.sourcesListenerKeys_ should be null');
this.sourcesListenerKeys_ = [];
goog.array.forEach(this.srcTiles_, function(tile, i, arr) {
var state = tile.getState();
if (state == ol.TileState.IDLE || state == ol.TileState.LOADING) {
leftToLoad++;
var sourceListenKey;
sourceListenKey = tile.listen(goog.events.EventType.CHANGE,
function(e) {
var state = tile.getState();
if (state == ol.TileState.LOADED ||
state == ol.TileState.ERROR ||
state == ol.TileState.EMPTY) {
goog.events.unlistenByKey(sourceListenKey);
leftToLoad--;
goog.asserts.assert(leftToLoad >= 0,
'leftToLoad should not be negative');
if (leftToLoad <= 0) {
this.unlistenSources_();
this.reproject_();
}
}
}, false, this);
this.sourcesListenerKeys_.push(sourceListenKey);
}
}, this);
goog.array.forEach(this.srcTiles_, function(tile, i, arr) {
var state = tile.getState();
if (state == ol.TileState.IDLE) {
tile.load();
}
});
if (leftToLoad === 0) {
this.reproject_();
}
}
};
/**
* @private
*/
ol.reproj.Tile.prototype.unlistenSources_ = function() {
goog.asserts.assert(!goog.isNull(this.sourcesListenerKeys_),
'this.sourcesListenerKeys_ should not be null');
goog.array.forEach(this.sourcesListenerKeys_, goog.events.unlistenByKey);
this.sourcesListenerKeys_ = null;
};
| {
"content_hash": "876b0447f109e491b4d1a56d849127b1",
"timestamp": "",
"source": "github",
"line_count": 335,
"max_line_length": 79,
"avg_line_length": 28.86268656716418,
"alnum_prop": 0.6444306546695625,
"repo_name": "klokantech/ol3raster",
"id": "fb1070b7eabb11f96c4891417864fc4cb0dc4903",
"size": "9669",
"binary": false,
"copies": "1",
"ref": "refs/heads/rasterreproj",
"path": "src/ol/reproj/tile.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "23794"
},
{
"name": "GLSL",
"bytes": "4241"
},
{
"name": "HTML",
"bytes": "11157"
},
{
"name": "JavaScript",
"bytes": "3256010"
},
{
"name": "Makefile",
"bytes": "11519"
},
{
"name": "Python",
"bytes": "14469"
},
{
"name": "Shell",
"bytes": "3517"
}
],
"symlink_target": ""
} |
package android.taobao.atlas.runtime;
import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.taobao.atlas.R;
import android.taobao.atlas.framework.Atlas;
import android.taobao.atlas.framework.FrameworkProperties;
import android.text.TextUtils;
import android.view.ViewGroup;
import java.io.Serializable;
import java.lang.reflect.Field;
public class RuntimeVariables implements Serializable{
public static Application androidApplication;
public static ClassLoader delegateClassLoader;
public static Resources delegateResources;
public static Resources originalResources;
public static String sRealApplicationName;
public static String sCurrentProcessName;
public static boolean safeMode = false;
public static int patchVersion = 1;
public static String sInstalledVersionName;
public static long sInstalledVersionCode;
public static long sAppLastUpdateTime;
public static String sApkPath;
public static Atlas.ExternalBundleInstallReminder sReminder;
public static Atlas.BundleVerifier sBundleVerifier;
public static boolean sCachePreVersionBundles = false;
/**
* apilevel >=23
*/
public static ClassLoader sRawClassLoader;
public static Object sDexLoadBooster;
private static String launchActivityName;
public static Class FrameworkPropertiesClazz;
public static Object getFrameworkProperty(String fieldName){
if(FrameworkPropertiesClazz==null){
FrameworkPropertiesClazz = FrameworkProperties.class;
}
try {
Field field = FrameworkPropertiesClazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(FrameworkPropertiesClazz);
}catch(Throwable e){
return null;
}
}
public static String getProcessName(Context context) {
return sCurrentProcessName;
}
public static boolean shouldSyncUpdateInThisProcess(){
String processName = RuntimeVariables.sCurrentProcessName;
if(processName!=null &&
(processName.equals(RuntimeVariables.androidApplication.getPackageName()) ||
processName.toLowerCase().contains(":safemode")
)){
return true;
}else{
return false;
}
}
public static ClassLoader getRawClassLoader(){
if(sRawClassLoader!=null){
return sRawClassLoader;
}else{
return RuntimeVariables.class.getClassLoader();
}
}
public static String getLauncherClassName() {
if (!TextUtils.isEmpty(launchActivityName)){
return launchActivityName;
}
if (androidApplication == null){
return null;
}
Intent launchIntentForPackage = RuntimeVariables.androidApplication.getPackageManager().getLaunchIntentForPackage(RuntimeVariables.androidApplication.getPackageName());
if (launchIntentForPackage != null) {
ComponentName componentName = launchIntentForPackage.resolveActivity(RuntimeVariables.androidApplication.getPackageManager());
launchActivityName = componentName.getClassName();
}
return launchActivityName;
}
}
| {
"content_hash": "4de7fde66546f220ce93d060b2c63fdb",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 176,
"avg_line_length": 31.278260869565216,
"alnum_prop": 0.6783430636641646,
"repo_name": "alibaba/atlas",
"id": "a2addb96202c1b923705eed4d2346b2a80f4b7b0",
"size": "15191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "atlas-core/src/main/java/android/taobao/atlas/runtime/RuntimeVariables.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "64906"
},
{
"name": "C",
"bytes": "1975639"
},
{
"name": "C++",
"bytes": "5114248"
},
{
"name": "CMake",
"bytes": "3090"
},
{
"name": "CSS",
"bytes": "87762"
},
{
"name": "HTML",
"bytes": "628309"
},
{
"name": "Java",
"bytes": "11894753"
},
{
"name": "JavaScript",
"bytes": "37802"
},
{
"name": "Kotlin",
"bytes": "2217"
},
{
"name": "Makefile",
"bytes": "47196"
},
{
"name": "Python",
"bytes": "1262"
},
{
"name": "Shell",
"bytes": "11347"
}
],
"symlink_target": ""
} |
//
// The MIT License(MIT)
//
// Copyright(c) 2015 Hans Wolff
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using FidoU2f.Serializers;
using Newtonsoft.Json;
namespace FidoU2f.Models
{
/// <summary>
/// FIDO AppId (see section 3 in FIDO specification for valid FacetIds)
/// </summary>
[JsonConverter(typeof(FidoAppIdConverter))]
public class FidoAppId : IEquatable<FidoAppId>, IEquatable<FidoFacetId>
{
private readonly Uri _appUri;
public FidoAppId(Uri appId)
{
if (!appId.IsAbsoluteUri)
ThrowFormatException();
_appUri = appId;
ValidateUri(appId);
}
public FidoAppId(string facetId)
{
if (!Uri.TryCreate(facetId, UriKind.Absolute, out _appUri))
ThrowFormatException();
ValidateUri(_appUri);
}
private void ValidateUri(Uri uri)
{
var scheme = uri.Scheme.ToLowerInvariant();
if (scheme != "http" && scheme != "https")
ThrowFormatException();
}
public bool Equals(FidoFacetId other)
{
if (other == null) return false;
return ToString().StartsWith(other.ToString());
}
public bool Equals(FidoAppId other)
{
if (other == null) return false;
var localAuthority = Helpers.GetAuthority(_appUri);
var otherAuthority = Helpers.GetAuthority(other._appUri);
return localAuthority == otherAuthority;
}
private static void ThrowFormatException()
{
throw new FormatException("FIDO App ID must be a URL prefix (e.g. 'https://website.com')");
}
public override string ToString()
{
return Helpers.GetAuthority(_appUri);
}
}
}
| {
"content_hash": "18e0468f8da79739a4007bf12e49553a",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 94,
"avg_line_length": 29.930232558139537,
"alnum_prop": 0.7233877233877234,
"repo_name": "hanswolff/fido-u2f-net",
"id": "de46902598d5e8b3ffdb58bd022cae1eeafa87f4",
"size": "2576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FidoU2f/Models/FidoAppId.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "C#",
"bytes": "177696"
},
{
"name": "CSS",
"bytes": "315"
},
{
"name": "JavaScript",
"bytes": "484"
}
],
"symlink_target": ""
} |
<style>
nav-bar {
position: absolute;
height: 160px;
width: 100%;
bottom: 0;
background-color: rgba(0, 0, 0, 0.3);
color: white;
transition: 1s;
align-items: flex-start;
justify-content: space-around;
display: flex;
flex-direction: column;
}
/* Big screens have room for the entire navbar */
@media screen and (min-width: 768px) {
nav-bar {
align-items: center;
flex-direction: row;
justify-content: space-between;
height: 80px;
}
}
div.flex-container {
display: flex;
width: 100%;
}
div.thumbnail {
position: relative;
overflow: hidden;
display: block;
width: 40px;
height: 40px;
background-size: cover;
background-position: center;
border-radius: 20px;
margin: 0 10px;
}
div.title-container {
flex-direction: column;
display: flex;
justify-content: space-between;
}
span.model-title {
font-size: 125%;
}
span.model-subtitle {
font-size: 90%;
}
div.button-container {
align-items: center;
justify-content: flex-end;
}
div.button {
cursor: pointer;
height: 30px;
margin: 0 10px;
}
div.button img {
height: 100%;
}
</style>
{{#if disableOnFullscreen}}
<style>
viewer:fullscreen nav-bar {
display: none;
}
viewer:-moz-full-screen nav-bar {
display: none;
}
viewer:-webkit-full-screen nav-bar {
display: none;
}
</style>
{{/if}}
<div class="flex-container" id="model-metadata">
<!-- holding the description -->
<div class="thumbnail">
<!-- holding the thumbnail
<img src="{{thumbnail}}" alt="{{title}}">-->
</div>
<div class="title-container">
<span class="model-title">{{#if title}}{{title}}{{/if}}</span>
<span class="model-subtitle"> {{#if subtitle}}{{subtitle}} {{/if}}</span>
</div>
</div>
<div class="button-container flex-container">
<!-- holding the buttons -->
{{#eachInMap buttons}}
<div id="{{id}}" class="button">
{{#if text}}
<span>{{text}}</span>> {{/if}} {{#if image}}
<img src="{{image}}" alt="{{altText}}"> {{/if}}
</div>
{{/eachInMap}}
</div> | {
"content_hash": "49d0fff0c5779fffc2c475f329d9b075",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 81,
"avg_line_length": 22.6875,
"alnum_prop": 0.49586776859504134,
"repo_name": "Hersir88/Babylon.js",
"id": "2a53ca3d8c3161a41f382cdda80c219f6b368564",
"size": "2541",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Viewer/assets/templates/default/navbar.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2834"
},
{
"name": "CSS",
"bytes": "41988"
},
{
"name": "HLSL",
"bytes": "320538"
},
{
"name": "HTML",
"bytes": "178508"
},
{
"name": "JavaScript",
"bytes": "459157"
},
{
"name": "TypeScript",
"bytes": "5641586"
}
],
"symlink_target": ""
} |
package net.lingala.zip4j.crypto.PBKDF2;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/*
* Source referred from Matthias Gartner's PKCS#5 implementation -
* see http://rtner.de/software/PBKDF2.html
*/
public class MacBasedPRF implements PRF
{
protected Mac mac;
protected int hLen;
protected String macAlgorithm;
public MacBasedPRF(String macAlgorithm)
{
this.macAlgorithm = macAlgorithm;
try
{
mac = Mac.getInstance(macAlgorithm);
hLen = mac.getMacLength();
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
}
public MacBasedPRF(String macAlgorithm, String provider)
{
this.macAlgorithm = macAlgorithm;
try
{
mac = Mac.getInstance(macAlgorithm, provider);
hLen = mac.getMacLength();
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
catch (NoSuchProviderException e)
{
throw new RuntimeException(e);
}
}
public byte[] doFinal(byte[] M)
{
byte[] r = mac.doFinal(M);
return r;
}
public byte[] doFinal() {
byte[] r = mac.doFinal();
return r;
}
public int getHLen()
{
return hLen;
}
public void init(byte[] P)
{
try
{
mac.init(new SecretKeySpec(P, macAlgorithm));
}
catch (InvalidKeyException e)
{
throw new RuntimeException(e);
}
}
public void update(byte[] U) {
try {
mac.update(U);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
}
}
public void update (byte[] U, int start, int len) {
try {
mac.update(U, start, len);
} catch (IllegalStateException e) {
throw new RuntimeException(e);
}
}
}
| {
"content_hash": "c46c56831b252ae734ff4c176901010b",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 67,
"avg_line_length": 21.676470588235293,
"alnum_prop": 0.5481682496607869,
"repo_name": "blinkboxbooks/android-ePub-Library",
"id": "8b67715ff0f766b0f1e1766b8b3b18085deb7b1a",
"size": "2826",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/net/lingala/zip4j/crypto/PBKDF2/MacBasedPRF.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "448884"
},
{
"name": "Shell",
"bytes": "583"
}
],
"symlink_target": ""
} |
* Use PostCSS 5.0 API.
* Add `unknown` option.
## 0.3
* Allow to use variables in variables values.
* Accept function in `variables` option.
* Support PostCSS 4.1 API.
* Fix falling on non-string values in AST (by Anton Telesh).
## 0.2.4
* Fix simple syntax variables in at-rule parameters.
## 0.2.3
* Fix extra space on variables ignoring.
## 0.2.2
* Fix undefined variable error message.
## 0.2.1
* Fix look-behind regexp in simple syntax.
## 0.2
* Allow to use simple syntax with minus like `-$width`.
* Add support for multiple variables in one value.
* Do not remove space before `$var`.
## 0.1
* Initial release.
| {
"content_hash": "2f090377e724c121a16a0472d2522152",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 60,
"avg_line_length": 22.357142857142858,
"alnum_prop": 0.6996805111821086,
"repo_name": "bendtherules/postcss-simple-vars",
"id": "d4f7c61fda554587f3bca2f81ae291f91c5cfd0c",
"size": "633",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "7410"
}
],
"symlink_target": ""
} |
#include <chrono>
#include <fstream>
#include <thread>
#include "Window/Window.hpp"
#include "Math/Math.hpp"
#include "Graphics/BufferManager.hpp"
#include "Graphics/Program.hpp"
#include "Graphics/Shader.hpp"
#include "Graphics/Uniform.hpp"
#define INVERT_MOUSE_Y
using namespace dbr::eng;
int main(int argc, char** argv)
{
std::uint32_t windowWidth = 1280;
std::uint32_t windowHeight = 720;
float aspectRatio = static_cast<float>(windowWidth) / windowHeight;
float verticalFOV = glm::quarter_pi<float>();
auto calcProjMat = [&]() { return glm::perspective(verticalFOV, aspectRatio, 1.f, 100.f); };
gfx::HandleU crosshairVBO;
gfx::HandleU crosshairVAO;
auto makeCrosshair = [&]()
{
gl::BindVertexArray(crosshairVAO);
{
float data[] =
{
// vertices // colors
-1, 0, 0, 1, 0.7f, 0.7f, 0.7f, 0.7f,
1, 0, 0, 1, 0.7f, 0.7f, 0.7f, 0.7f,
0, -1, 0, 1, 0.7f, 0.7f, 0.7f, 0.7f,
0, 1, 0, 1, 0.7f, 0.7f, 0.7f, 0.7f,
};
data[0] *= 1.f / aspectRatio;
data[8] *= 1.f / aspectRatio;
gl::BindBuffer(gl::ARRAY_BUFFER, crosshairVBO);
gl::BufferData(gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);
gl::VertexAttribPointer(0, 4, gl::FLOAT, gl::FALSE_, sizeof(float) * 8, nullptr);
gl::EnableVertexAttribArray(0);
gl::VertexAttribPointer(1, 4, gl::FLOAT, gl::FALSE_, sizeof(float) * 8, reinterpret_cast<void*>(sizeof(float) * 4));
gl::EnableVertexAttribArray(1);
}
gl::BindVertexArray(0);
};
bool run = true;
constexpr glm::vec3 cameraInitialPosition{0.f, 0.f, -10.f};
constexpr glm::vec3 cameraInitialFace{0.f, 0.f, 1.f};
constexpr glm::vec3 cameraInitialUp{0.f, 1.f, 0.f};
float yaw = 0.f;
float pitch = 0.f;
float roll = glm::half_pi<float>();
glm::vec3 cameraPosition = cameraInitialPosition;
glm::vec3 cameraFace = cameraInitialFace;
glm::vec3 cameraUp = cameraInitialUp;
glm::mat4 view = glm::lookAt(cameraPosition, cameraPosition + cameraFace, cameraUp);
glm::mat4 projection = calcProjMat();
glm::mat4 targetModel = glm::rotate(glm::mat4{}, glm::quarter_pi<float>(), glm::vec3{0, 0, 1});
// glm::quat cameraRotation = glm::angleAxis(0.f, cameraFace);
win::Window window;
window.resized += [](int w, int h)
{
gl::Viewport(0, 0, w, h);
};
window.frameBufferResized += [&](int w, int h)
{
aspectRatio = static_cast<float>(w) / h;
projection = calcProjMat();
makeCrosshair();
};
bool moveForward = false;
bool moveBackward = false;
bool moveLeft = false;
bool moveRight = false;
bool moveUp = false;
bool moveDown = false;
bool rotateCW = false;
bool rotateCCW = false;
bool boost = false;
bool mouseMoved = false;
window.key += [&](win::Keyboard key, int /*scancode*/, win::Events::Button action, win::Modifiers mods)
{
bool act = action != win::Events::Button::Release;
boost = (mods & win::Modifiers::Shift) != win::Modifiers::None;
switch (key)
{
case win::Keyboard::W:
moveForward = act;
break;
case win::Keyboard::S:
moveBackward = act;
break;
case win::Keyboard::A:
moveLeft = act;
break;
case win::Keyboard::D:
moveRight = act;
break;
case win::Keyboard::R:
moveUp = act;
break;
case win::Keyboard::F:
moveDown = act;
break;
case win::Keyboard::Q:
rotateCCW = act;
break;
case win::Keyboard::E:
rotateCW = act;
break;
case win::Keyboard::Escape:
run = false;
break;
default:
// nope
break;
}
};
glm::vec2 mouseLast{windowWidth / 2, windowHeight / 2};
glm::vec2 mouseNow = mouseLast;
window.mouseMoved += [&](double x, double y)
{
mouseNow = {x, y};
mouseMoved = true;
};
window.open(windowWidth, windowHeight, "OpenGL");
window.lockCursor();
gfx::Program basicProgram;
{
gfx::Shader basicVert(gfx::Shader::Type::Vertex);
gfx::Shader basicFrag(gfx::Shader::Type::Fragment);
std::ifstream finBasicVert("shaders/basic.vert");
std::ifstream finBasicFrag("shaders/basic.frag");
basicVert.load(finBasicVert);
basicFrag.load(finBasicFrag);
basicProgram.link(basicVert, basicFrag);
}
gl::Enable(gl::DEPTH_TEST);
// gl::Disable(gl::CULL_FACE);
gfx::BufferManager bufferManager(gl::GenBuffers, gl::DeleteBuffers);
gfx::BufferManager arrayManager(gl::GenVertexArrays, gl::DeleteVertexArrays);
bufferManager.request(2);
arrayManager.request(2);
gfx::HandleU squareVBO = bufferManager.next();
gfx::HandleU squareVAO = arrayManager.next();
gl::BindVertexArray(squareVAO);
{
constexpr float data[] =
{
// vertices // colors
-1, -1, 0, 1, 1, 0, 0, 1,
1, -1, 0, 1, 0, 1, 0, 1,
-1, 1, 0, 1, 0, 0, 1, 1,
1, 1, 0, 1, 1, 1, 1, 1,
};
gl::BindBuffer(gl::ARRAY_BUFFER, squareVBO);
gl::BufferData(gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);
gl::VertexAttribPointer(0, 4, gl::FLOAT, gl::FALSE_, sizeof(float) * 8, nullptr);
gl::EnableVertexAttribArray(0);
gl::VertexAttribPointer(1, 4, gl::FLOAT, gl::FALSE_, sizeof(float) * 8, reinterpret_cast<void*>(sizeof(float) * 4));
gl::EnableVertexAttribArray(1);
}
gl::BindVertexArray(0);
crosshairVBO = bufferManager.next();
crosshairVAO = arrayManager.next();
makeCrosshair();
auto transform = basicProgram.getUniform("transform");
using Tick = std::chrono::steady_clock::duration;
// 60 ticks occur every second: cast to nanoseconds per tick
constexpr Tick DT = std::chrono::duration_cast<Tick>(std::chrono::duration<Tick::rep, std::ratio<1, 60>>{1});
constexpr auto DT_SEC = DT.count() / static_cast<float>(std::chrono::nanoseconds{std::chrono::seconds{1}}.count());
auto lastTime = std::chrono::steady_clock::now();
Tick lag = Tick::zero();
while (run)
{
auto nowTime = std::chrono::steady_clock::now();
Tick frameTime = nowTime - lastTime;
lastTime = nowTime;
lag += frameTime;
// Updating
while (lag >= DT)
{
window.pollEvents();
// 0.25 seems to work well
constexpr float MOUSE_SENSITIVITY = 0.25f;
constexpr float BOOST_SPEED = 4.f;
constexpr float MOVE_SPEED = 2.f;
constexpr float ROLL_SPEED = glm::quarter_pi<float>();
// a little less than 90 deg
constexpr float MAX_PITCH = glm::half_pi<float>() * 0.98f;
constexpr float MIN_PITCH = -MAX_PITCH;
// TODO
// rotation is funny.
// yaw/pitch are not respecting the roll. Lel.
// may be time to dig into quaternions
// yaw/pitch
if (mouseMoved)
{
auto offset = mouseNow - mouseLast;
mouseLast = mouseNow;
offset *= MOUSE_SENSITIVITY;
yaw += glm::radians(offset.x);
pitch += glm::radians(offset.y);
pitch = glm::max(MIN_PITCH, glm::min(MAX_PITCH, pitch));
auto cosYaw = glm::cos(yaw);
auto cosPitch = glm::cos(pitch);
auto sinYaw = glm::sin(yaw);
auto sinPitch = glm::sin(pitch);
cameraFace.x = cosPitch * sinYaw;
cameraFace.z = cosPitch * cosYaw;
#ifndef INVERT_MOUSE_Y
cameraFace.y = -sinPitch;
#else
cameraFace.y = sinPitch;
#endif
cameraFace = glm::normalize(cameraFace);
mouseMoved = false;
}
// roll
{
if (rotateCW)
roll -= ROLL_SPEED * DT_SEC;
if (rotateCCW)
roll += ROLL_SPEED * DT_SEC;
cameraUp.x = std::cos(roll);
cameraUp.y = std::sin(roll);
}
// movement
{
const glm::vec3 cameraFaceRight{cameraFace.z, cameraFace.y, -cameraFace.x};
const glm::vec3 cameraFaceUp{cameraFace.x, cameraFace.z, -cameraFace.y};
glm::vec3 dir{0, 0, 0};
if (moveForward)
dir += cameraFace;
if (moveBackward)
dir -= cameraFace;
if (moveRight)
dir += cameraFaceRight;
if (moveLeft)
dir -= cameraFaceRight;
if (moveUp)
dir += cameraFaceUp;
if (moveDown)
dir -= cameraFaceUp;
if (glm::length(dir) != 0)
cameraPosition += glm::normalize(dir) * (boost ? BOOST_SPEED : MOVE_SPEED) * DT_SEC;
}
view = glm::lookAt(cameraPosition, cameraPosition + cameraFace, cameraUp);
if (!window.isOpen())
run = false;
lag -= DT;
}
// Drawing
window.clear();
basicProgram.use();
transform.set(projection * view * targetModel);
gl::BindVertexArray(squareVAO);
gl::DrawArrays(gl::TRIANGLE_STRIP, 0, 4);
transform.set(glm::scale(glm::mat4{}, glm::vec3{0.1f}));
gl::BindVertexArray(crosshairVAO);
gl::DrawArrays(gl::LINES, 0, 4);
gl::BindVertexArray(0);
window.display();
}
window.close();
return 0;
}
| {
"content_hash": "60997cbc4a67a429fd8bf7dc50613e1f",
"timestamp": "",
"source": "github",
"line_count": 361,
"max_line_length": 128,
"avg_line_length": 28.437673130193907,
"alnum_prop": 0.5249366842002727,
"repo_name": "dabbertorres/WindowingOpenGL",
"id": "e85ca32f328cb1cf93964308aa71ba620e4a7a88",
"size": "10266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/src/main.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "206961"
},
{
"name": "C++",
"bytes": "227877"
},
{
"name": "CMake",
"bytes": "286"
},
{
"name": "GLSL",
"bytes": "780"
}
],
"symlink_target": ""
} |
namespace v8 {
namespace internal {
class AstType;
const int kMaxKeyedPolymorphism = 4;
class ICUtility : public AllStatic {
public:
// Clear the inline cache to initial state.
static void Clear(Isolate* isolate, Address address, Address constant_pool);
};
class BinaryOpICState final BASE_EMBEDDED {
public:
BinaryOpICState(Isolate* isolate, ExtraICState extra_ic_state);
BinaryOpICState(Isolate* isolate, Token::Value op)
: op_(op),
left_kind_(NONE),
right_kind_(NONE),
result_kind_(NONE),
fixed_right_arg_(Nothing<int>()),
isolate_(isolate) {
DCHECK_LE(FIRST_TOKEN, op);
DCHECK_LE(op, LAST_TOKEN);
}
InlineCacheState GetICState() const {
if (Max(left_kind_, right_kind_) == NONE) {
return ::v8::internal::UNINITIALIZED;
}
if (Max(left_kind_, right_kind_) == GENERIC) {
return ::v8::internal::MEGAMORPHIC;
}
if (Min(left_kind_, right_kind_) == GENERIC) {
return ::v8::internal::GENERIC;
}
return ::v8::internal::MONOMORPHIC;
}
ExtraICState GetExtraICState() const;
std::string ToString() const;
static void GenerateAheadOfTime(Isolate*,
void (*Generate)(Isolate*,
const BinaryOpICState&));
// Returns true if the IC _could_ create allocation mementos.
bool CouldCreateAllocationMementos() const {
if (left_kind_ == STRING || right_kind_ == STRING) {
DCHECK_EQ(Token::ADD, op_);
return true;
}
return false;
}
// Returns true if the IC _should_ create allocation mementos.
bool ShouldCreateAllocationMementos() const {
return FLAG_allocation_site_pretenuring && CouldCreateAllocationMementos();
}
bool HasSideEffects() const {
return Max(left_kind_, right_kind_) == GENERIC;
}
// Returns true if the IC should enable the inline smi code (i.e. if either
// parameter may be a smi).
bool UseInlinedSmiCode() const {
return KindMaybeSmi(left_kind_) || KindMaybeSmi(right_kind_);
}
static const int FIRST_TOKEN = Token::BIT_OR;
static const int LAST_TOKEN = Token::MOD;
Token::Value op() const { return op_; }
Maybe<int> fixed_right_arg() const { return fixed_right_arg_; }
AstType* GetLeftType() const { return KindToType(left_kind_); }
AstType* GetRightType() const { return KindToType(right_kind_); }
AstType* GetResultType() const;
void Update(Handle<Object> left, Handle<Object> right, Handle<Object> result);
Isolate* isolate() const { return isolate_; }
enum Kind { NONE, SMI, INT32, NUMBER, STRING, GENERIC };
Kind kind() const {
return KindGeneralize(KindGeneralize(left_kind_, right_kind_),
result_kind_);
}
private:
friend std::ostream& operator<<(std::ostream& os, const BinaryOpICState& s);
Kind UpdateKind(Handle<Object> object, Kind kind) const;
static const char* KindToString(Kind kind);
static AstType* KindToType(Kind kind);
static bool KindMaybeSmi(Kind kind) {
return (kind >= SMI && kind <= NUMBER) || kind == GENERIC;
}
static bool KindLessGeneralThan(Kind kind1, Kind kind2) {
if (kind1 == NONE) return true;
if (kind1 == kind2) return true;
if (kind2 == GENERIC) return true;
if (kind2 == STRING) return false;
return kind1 <= kind2;
}
static Kind KindGeneralize(Kind kind1, Kind kind2) {
if (KindLessGeneralThan(kind1, kind2)) return kind2;
if (KindLessGeneralThan(kind2, kind1)) return kind1;
return GENERIC;
}
// We truncate the last bit of the token.
STATIC_ASSERT(LAST_TOKEN - FIRST_TOKEN < (1 << 4));
class OpField : public BitField<int, 0, 4> {};
class ResultKindField : public BitField<Kind, 4, 3> {};
class LeftKindField : public BitField<Kind, 7, 3> {};
// When fixed right arg is set, we don't need to store the right kind.
// Thus the two fields can overlap.
class HasFixedRightArgField : public BitField<bool, 10, 1> {};
class FixedRightArgValueField : public BitField<int, 11, 4> {};
class RightKindField : public BitField<Kind, 11, 3> {};
Token::Value op_;
Kind left_kind_;
Kind right_kind_;
Kind result_kind_;
Maybe<int> fixed_right_arg_;
Isolate* isolate_;
};
std::ostream& operator<<(std::ostream& os, const BinaryOpICState& s);
class CompareICState {
public:
// The type/state lattice is defined by the following inequations:
// UNINITIALIZED < ...
// ... < GENERIC
// SMI < NUMBER
// INTERNALIZED_STRING < STRING
// INTERNALIZED_STRING < UNIQUE_NAME
// KNOWN_RECEIVER < RECEIVER
enum State {
UNINITIALIZED,
BOOLEAN,
SMI,
NUMBER,
STRING,
INTERNALIZED_STRING,
UNIQUE_NAME, // Symbol or InternalizedString
RECEIVER, // JSReceiver
KNOWN_RECEIVER, // JSReceiver with specific map (faster check)
GENERIC
};
static AstType* StateToType(Zone* zone, State state,
Handle<Map> map = Handle<Map>());
static State NewInputState(State old_state, Handle<Object> value);
static const char* GetStateName(CompareICState::State state);
static State TargetState(Isolate* isolate, State old_state, State old_left,
State old_right, Token::Value op,
bool has_inlined_smi_code, Handle<Object> x,
Handle<Object> y);
};
} // namespace internal
} // namespace v8
#endif // V8_IC_STATE_H_
| {
"content_hash": "ad6ff4af7e3adcb8bc7911671a4d0a80",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 80,
"avg_line_length": 30.629213483146067,
"alnum_prop": 0.6467351430667645,
"repo_name": "hoho/dosido",
"id": "16651c562378094ed6e1ce5220e41795fc5ece66",
"size": "5732",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "nodejs/deps/v8/src/ic/ic-state.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "89079"
},
{
"name": "Assembly",
"bytes": "11425802"
},
{
"name": "Batchfile",
"bytes": "94847"
},
{
"name": "C",
"bytes": "30811999"
},
{
"name": "C#",
"bytes": "54013"
},
{
"name": "C++",
"bytes": "83386616"
},
{
"name": "CMake",
"bytes": "9844"
},
{
"name": "CSS",
"bytes": "25150"
},
{
"name": "DIGITAL Command Language",
"bytes": "349320"
},
{
"name": "DTrace",
"bytes": "37428"
},
{
"name": "Emacs Lisp",
"bytes": "19654"
},
{
"name": "HTML",
"bytes": "832204"
},
{
"name": "JavaScript",
"bytes": "33679091"
},
{
"name": "Lua",
"bytes": "17899"
},
{
"name": "M4",
"bytes": "64602"
},
{
"name": "Makefile",
"bytes": "952350"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NSIS",
"bytes": "2860"
},
{
"name": "Nginx",
"bytes": "2656"
},
{
"name": "Objective-C",
"bytes": "46200"
},
{
"name": "POV-Ray SDL",
"bytes": "88241"
},
{
"name": "Pascal",
"bytes": "75208"
},
{
"name": "Perl",
"bytes": "685097"
},
{
"name": "Perl 6",
"bytes": "2420216"
},
{
"name": "Prolog",
"bytes": "326894"
},
{
"name": "Protocol Buffer",
"bytes": "2764"
},
{
"name": "Python",
"bytes": "2954969"
},
{
"name": "R",
"bytes": "10482"
},
{
"name": "Roff",
"bytes": "329990"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Scheme",
"bytes": "14853"
},
{
"name": "Shell",
"bytes": "275277"
},
{
"name": "Vim script",
"bytes": "128495"
},
{
"name": "XS",
"bytes": "25677"
},
{
"name": "XSLT",
"bytes": "5400"
},
{
"name": "eC",
"bytes": "5158"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace InternationalCompany.Views.Bulgaria
{
public partial class About
{
}
}
| {
"content_hash": "ca5f8437fc333f90e5144dfe3ca0da97",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 81,
"avg_line_length": 26.705882352941178,
"alnum_prop": 0.42951541850220265,
"repo_name": "AdrianApostolov/TelerikAcademy",
"id": "2e682ed5484e0ee58fec7ab56b63590c15bf5c89",
"size": "456",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Homeworks/ASP.NET Web Forms/04.ASP.NETMasterPages/InternationalCompany/Views/Bulgaria/About.aspx.designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "21510"
},
{
"name": "C#",
"bytes": "1819391"
},
{
"name": "CSS",
"bytes": "158896"
},
{
"name": "HTML",
"bytes": "6010402"
},
{
"name": "JavaScript",
"bytes": "1395750"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "SQLPL",
"bytes": "941"
},
{
"name": "Shell",
"bytes": "111"
},
{
"name": "XSLT",
"bytes": "3922"
}
],
"symlink_target": ""
} |
SpecBegin(Fair)
afterEach(^{
[OHHTTPStubs removeAllStubs];
});
it(@"initialize", ^{
Fair *fair = [Fair modelWithJSON:@{ @"id" : @"fair-id" }];
expect(fair.fairID).to.equal(@"fair-id");
expect(fair.organizer).to.beNil();
expect(fair.networkModel).to.beKindOf([ARFairNetworkModel class]);
});
describe(@"generates a location", ^{
it(@"has no location", ^{
Fair *fair = [Fair modelWithJSON:@{
@"id" : @"fair-id",
}];
expect(fair.location).to.beNil();
});
it(@"as a city", ^{
Fair *fair = [Fair modelWithJSON:@{
@"id" : @"fair-id",
@"location" : @{ @"city": @"Toronto" }
}];
expect(fair.location).to.equal(@"Toronto");
});
it(@"has a state", ^{
Fair *fair = [Fair modelWithJSON:@{
@"id" : @"fair-id",
@"location" : @{ @"state": @"ON" }
}];
expect(fair.location).to.equal(@"ON");
});
it(@"has a city and a state", ^{
Fair *fair = [Fair modelWithJSON:@{
@"id" : @"fair-id",
@"location" : @{ @"city": @"Toronto", @"state" : @"ON" }
}];
expect(fair.location).to.equal(@"Toronto, ON");
});
});
describe(@"getting image URL string", ^{
it(@"gets nil for no image urls", ^{
Fair *fair = [Fair modelFromDictionary:@{ @"fairID" : @"fair-id" }];
expect([fair bannerAddress]).to.beNil();
});
it(@"says it doesnt have a new banner format without banner URLs", ^{
Fair *fair = [Fair modelFromDictionary:@{ @"fairID" : @"fair-id" }];
expect([fair usesBrandedBanners]).to.beFalsy();
});
it (@"gets nil for non-existent image version", ^{
Fair *fair = [Fair modelFromDictionary:@{
@"fairID" : @"fair-id",
@"imageURLs": @{
@"something_that_we_do_not_support" : @"http://something/something_that_we_do_not_support.jpg"
}
}];
expect([fair bannerAddress]).to.beNil();
});
it (@"gets wide if availble", ^{
Fair *fair = [Fair modelFromDictionary:@{
@"fairID" : @"fair-id",
@"imageURLs": @{
@"wide": @"http://something/wide.jpg",
@"square" : @"http://something/square.jpg"
}
}];
expect([fair bannerAddress]).to.equal(@"http://something/wide.jpg");
});
it (@"prioritises banners if availble", ^{
Fair *fair = [Fair modelFromDictionary:@{
@"fairID" : @"fair-id",
@"imageURLs": @{
@"wide": @"http://something/wide.jpg",
@"square" : @"http://something/square.jpg"
},
@"bannerURLs": @{
@"wide": @"http://something/banner_wide.jpg",
}
}];
expect([fair bannerAddress]).to.equal(@"http://something/banner_wide.jpg");
});
it (@"can work with just banners", ^{
Fair *fair = [Fair modelFromDictionary:@{
@"fairID" : @"fair-id",
@"bannerURLs": @{
@"wide": @"http://something/banner_wide.jpg",
}
}];
expect([fair bannerAddress]).to.equal(@"http://something/banner_wide.jpg");
});
});
SpecEnd
| {
"content_hash": "a902921101473174d9c36bb215f258ad",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 110,
"avg_line_length": 31.228571428571428,
"alnum_prop": 0.4906983836535529,
"repo_name": "1aurabrown/eigen",
"id": "6d02e538c77c7ed8f972734803061541fc853aef",
"size": "3304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Artsy Tests/FairTests.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1628"
},
{
"name": "HTML",
"bytes": "624"
},
{
"name": "JavaScript",
"bytes": "2463"
},
{
"name": "Makefile",
"bytes": "5189"
},
{
"name": "Objective-C",
"bytes": "1952166"
},
{
"name": "Ruby",
"bytes": "12010"
},
{
"name": "VimL",
"bytes": "428"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends CI_Controller {
public function index()
{
if($this->login->checkLogin()){
$title['title'] = 'Dashboard | Optimise Hotpsot';
//get aantal bezoekers
$this->load->model('Checkin_model');
$data['numberVisitors'] = $this->Checkin_model->numberVisitorsCurrentWeek();
$data['visits'] = $this->Checkin_model->NumberVisitorsLastMonth();
$this->load->view('templates/head', $title);
$this->load->view('pages/home', $data);
$this->load->view('templates/footer');
$this->load->view('templates/homeScripts');
}
}
}
| {
"content_hash": "450e020590cac41d8a9320a6fd4b5957",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 88,
"avg_line_length": 33.22727272727273,
"alnum_prop": 0.5718194254445964,
"repo_name": "svenhabex/dashboard-hotspot",
"id": "a1ee4bdc788b497bb10723012ca2b82b98338753",
"size": "731",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/controllers/Home.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "399"
},
{
"name": "CSS",
"bytes": "1650952"
},
{
"name": "HTML",
"bytes": "5633"
},
{
"name": "JavaScript",
"bytes": "147496"
},
{
"name": "PHP",
"bytes": "3103838"
},
{
"name": "Shell",
"bytes": "1932"
}
],
"symlink_target": ""
} |
<?php
namespace NetSuite\Classes;
class SolutionSearchRow extends SearchRow {
public $basic;
public $caseJoin;
public $relatedSolutionJoin;
public $topicJoin;
public $userJoin;
public $userNotesJoin;
public $customSearchJoin;
static $paramtypesmap = array(
"basic" => "SolutionSearchRowBasic",
"caseJoin" => "SupportCaseSearchRowBasic",
"relatedSolutionJoin" => "SolutionSearchRowBasic",
"topicJoin" => "TopicSearchRowBasic",
"userJoin" => "EmployeeSearchRowBasic",
"userNotesJoin" => "NoteSearchRowBasic",
"customSearchJoin" => "CustomSearchRowBasic[]",
);
}
| {
"content_hash": "d5c61745b00b0459d2acd4c4fa9ad2e0",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 58,
"avg_line_length": 28.47826086956522,
"alnum_prop": 0.6641221374045801,
"repo_name": "fungku/netsuite-php",
"id": "bde873b3f97ea983998a744ce84fe4752665c1ee",
"size": "1375",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Classes/SolutionSearchRow.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "2828253"
}
],
"symlink_target": ""
} |
@interface MockCompanyEntity : WSBaseEntity
@property(nonatomic, copy) NSString *name;
@property(nonatomic, strong) NSArray *employees;
@end | {
"content_hash": "119dba9756413d1680b14d0916b5427f",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 48,
"avg_line_length": 23.666666666666668,
"alnum_prop": 0.795774647887324,
"repo_name": "Handbid/WallStreet-Objc",
"id": "9daa5c7dccad62a83788134c1c7519c2b525e723",
"size": "306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WallStreet-Objc/Fixtures/MockCompanyEntity.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "244580"
},
{
"name": "Ruby",
"bytes": "5215"
}
],
"symlink_target": ""
} |
package com.graphhopper.reader.overlaydata;
import com.graphhopper.json.GHson;
import com.graphhopper.json.geo.Geometry;
import com.graphhopper.json.geo.JsonFeature;
import com.graphhopper.json.geo.JsonFeatureCollection;
import com.graphhopper.routing.util.DefaultEdgeFilter;
import com.graphhopper.routing.util.EdgeFilter;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.FlagEncoder;
import com.graphhopper.storage.Graph;
import com.graphhopper.storage.NodeAccess;
import com.graphhopper.storage.index.LocationIndex;
import com.graphhopper.storage.index.QueryResult;
import com.graphhopper.util.BreadthFirstSearch;
import com.graphhopper.util.EdgeIteratorState;
import com.graphhopper.util.PointList;
import com.graphhopper.util.shapes.BBox;
import com.graphhopper.util.shapes.GHPoint;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.List;
import java.util.Map;
/**
* @author Peter Karich
*/
public class FeedOverlayData {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Graph graph;
private final LocationIndex locationIndex;
private final GHson ghson;
private final EncodingManager em;
private boolean enableLogging = false;
public FeedOverlayData(Graph graph, EncodingManager em, LocationIndex locationIndex, GHson ghson) {
this.ghson = ghson;
this.graph = graph;
this.em = em;
this.locationIndex = locationIndex;
}
public void setLogging(boolean log) {
enableLogging = log;
}
public long applyChanges(String fileOrFolderStr) {
File fileOrFolder = new File(fileOrFolderStr);
try {
if (fileOrFolder.isFile()) {
return applyChanges(new FileReader(fileOrFolder));
}
long sum = 0;
File[] fList = new File(fileOrFolderStr).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
});
for (File f : fList) {
sum += applyChanges(new FileReader(f));
}
return sum;
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
/**
* This method applies changes to the graph, specified by the reader.
*
* @return number of successfully applied edge changes
*/
public long applyChanges(Reader reader) {
// read full file, later support one json feature or collection per line to avoid high mem consumption
JsonFeatureCollection data = ghson.fromJson(reader, JsonFeatureCollection.class);
long updates = 0;
for (JsonFeature jsonFeature : data.getFeatures()) {
if (!jsonFeature.hasProperties())
throw new IllegalArgumentException("One feature has no properties, please specify properties e.g. speed or access");
List<String> encodersAsStr = (List) jsonFeature.getProperty("vehicles");
if (encodersAsStr == null) {
for (FlagEncoder encoder : em.fetchEdgeEncoders()) {
updates += applyChange(jsonFeature, encoder);
}
} else {
for (String encoderStr : encodersAsStr) {
updates += applyChange(jsonFeature, em.getEncoder(encoderStr));
}
}
}
return updates;
}
private long applyChange(JsonFeature jsonFeature, FlagEncoder encoder) {
long updates = 0;
EdgeFilter filter = new DefaultEdgeFilter(encoder);
TIntSet edges = new TIntHashSet();
if (jsonFeature.hasGeometry()) {
fillEdgeIDs(edges, jsonFeature.getGeometry(), filter);
} else if (jsonFeature.getBBox() != null) {
fillEdgeIDs(edges, jsonFeature.getBBox(), filter);
} else
throw new IllegalArgumentException("Feature " + jsonFeature.getId() + " has no geometry and no bbox");
TIntIterator iter = edges.iterator();
Map<String, Object> props = jsonFeature.getProperties();
while (iter.hasNext()) {
int edgeId = iter.next();
EdgeIteratorState edge = graph.getEdgeIteratorState(edgeId, Integer.MIN_VALUE);
if (props.containsKey("access")) {
boolean value = (boolean) props.get("access");
updates++;
if (enableLogging)
logger.info(encoder.toString() + " - access change via feature " + jsonFeature.getId());
edge.setFlags(encoder.setAccess(edge.getFlags(), value, value));
} else if (props.containsKey("speed")) {
// TODO use different speed for the different directions (see e.g. Bike2WeightFlagEncoder)
double value = ((Number) props.get("speed")).doubleValue();
double oldSpeed = encoder.getSpeed(edge.getFlags());
if (oldSpeed != value) {
updates++;
if (enableLogging)
logger.info(encoder.toString() + " - speed change via feature " + jsonFeature.getId() + ". Old: " + oldSpeed + ", new:" + value);
edge.setFlags(encoder.setSpeed(edge.getFlags(), value));
}
}
}
return updates;
}
public void fillEdgeIDs(TIntSet edgeIds, Geometry geometry, EdgeFilter filter) {
if (geometry.isPoint()) {
GHPoint point = geometry.asPoint();
QueryResult qr = locationIndex.findClosest(point.lat, point.lon, filter);
if (qr.isValid())
edgeIds.add(qr.getClosestEdge().getEdge());
} else if (geometry.isPointList()) {
PointList pl = geometry.asPointList();
if (geometry.getType().equals("LineString")) {
// TODO do map matching or routing
int lastIdx = pl.size() - 1;
if (pl.size() >= 2) {
double meanLat = (pl.getLatitude(0) + pl.getLatitude(lastIdx)) / 2;
double meanLon = (pl.getLongitude(0) + pl.getLongitude(lastIdx)) / 2;
QueryResult qr = locationIndex.findClosest(meanLat, meanLon, filter);
if (qr.isValid())
edgeIds.add(qr.getClosestEdge().getEdge());
}
} else {
for (int i = 0; i < pl.size(); i++) {
QueryResult qr = locationIndex.findClosest(pl.getLatitude(i), pl.getLongitude(i), filter);
if (qr.isValid())
edgeIds.add(qr.getClosestEdge().getEdge());
}
}
}
}
public void fillEdgeIDs(final TIntSet edgeIds, final BBox bbox, EdgeFilter filter) {
QueryResult qr = locationIndex.findClosest((bbox.maxLat + bbox.minLat) / 2, (bbox.maxLon + bbox.minLon) / 2, filter);
if (!qr.isValid())
return;
BreadthFirstSearch bfs = new BreadthFirstSearch() {
final NodeAccess na = graph.getNodeAccess();
final BBox localBBox = bbox;
@Override
protected boolean goFurther(int nodeId) {
return localBBox.contains(na.getLatitude(nodeId), na.getLongitude(nodeId));
}
@Override
protected boolean checkAdjacent(EdgeIteratorState edge) {
if (localBBox.contains(na.getLatitude(edge.getAdjNode()), na.getLongitude(edge.getAdjNode()))) {
edgeIds.add(edge.getEdge());
return true;
}
return false;
}
};
bfs.start(graph.createEdgeExplorer(filter), qr.getClosestNode());
}
}
| {
"content_hash": "1192821cb71fb2cc1dda20c0ecf78aa8",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 153,
"avg_line_length": 40.51776649746193,
"alnum_prop": 0.6004760711601103,
"repo_name": "PGWelch/graphhopper",
"id": "3ea9cf8933a1e8d59a3e020e81295d7729c45185",
"size": "8792",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "reader-overlay-data/src/main/java/com/graphhopper/reader/overlaydata/FeedOverlayData.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "21997"
},
{
"name": "HTML",
"bytes": "5938"
},
{
"name": "Java",
"bytes": "2442042"
},
{
"name": "JavaScript",
"bytes": "135222"
},
{
"name": "Shell",
"bytes": "12619"
}
],
"symlink_target": ""
} |
<div class="input-append date datepicker" data-date="0d" data-date-format="yyyy-mm-dd" data-provide="datepicker">
<input size="16" type="text" value="" readonly><span class="add-on"><i class="icon-th"></i></span>
</div>
<input id="useSearch" style="width: 130px; height: 40px "> | {
"content_hash": "0609f510523ccf2252ce74c02bc08648",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 113,
"avg_line_length": 70.5,
"alnum_prop": 0.6843971631205674,
"repo_name": "allanfish/facetime-demo",
"id": "b7e135add459edbdefd48915289493dbe92f38df",
"size": "282",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "oatos_project/oatos_web/oatos_web/src/main/webapp/assets/website/templates-website/DemoView.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "461840"
},
{
"name": "IDL",
"bytes": "4309"
},
{
"name": "Java",
"bytes": "3404939"
},
{
"name": "JavaScript",
"bytes": "8277483"
},
{
"name": "Shell",
"bytes": "497"
}
],
"symlink_target": ""
} |
In this /DE/ folder we have subfolders for /00/ (common materials) and for /Stock/ (for profit corporations) and /NonStock/ (not-for-profit corporations). The /Stock/ and /NonStock/ both use a basic template at /00/ will be subfolders for each type of corporation.
Currently, we have only examples for the Certificate of Incorporation.
The repository for this is at github.com/CommonAccord/US-Incorp.
It can be viewed at www.CommonAccord.Org/index.php?action=list&file=G/US-Incorporate/DE/
Delaware Incorporation Resources
Various standard forms from the State of Delaware. They include instructions, recommendations, cover letters, etc. https://corp.delaware.gov/newentit09/
| {
"content_hash": "4669e7bacff6fa0383f8249724f4d72f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 266,
"avg_line_length": 52.92307692307692,
"alnum_prop": 0.7834302325581395,
"repo_name": "CommonAccord/Cmacc-Org",
"id": "b4199e08634213180941dad34fa601328f24183c",
"size": "688",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Doc/G/US-Incorporate/DE/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4996"
},
{
"name": "HTML",
"bytes": "130299"
},
{
"name": "PHP",
"bytes": "1463"
}
],
"symlink_target": ""
} |
package LogReporter::Service::zz_uptime;
use Moose;
extends 'LogReporter::Service';
no warnings 'misc';
override get_output => sub {
my ($self) = @_;
print `uptime`;
};
__PACKAGE__->meta->make_immutable;
1;
| {
"content_hash": "42b2f913a10427fabac5aee1aca5b9ff",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 40,
"avg_line_length": 16.76923076923077,
"alnum_prop": 0.6513761467889908,
"repo_name": "imMute/LogReporter",
"id": "2aeeca66d53ed116a3d0effab5fa1807242af933",
"size": "218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/LogReporter/Service/zz_uptime.pm",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Perl",
"bytes": "153908"
}
],
"symlink_target": ""
} |
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BTC);
unitlist.append(mBTC);
unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case BTC: return QString("XCO");
case mBTC: return QString("mXCO");
case uBTC: return QString::fromUtf8("μXCO");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case BTC: return QString("Xcoins");
case mBTC: return QString("Milli-Xcoins (1 / 1,000)");
case uBTC: return QString("Micro-Xcoins (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
| {
"content_hash": "4a0f893a9e8692fcd779f5ea95911f61",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 89,
"avg_line_length": 23.858757062146893,
"alnum_prop": 0.6062041202936301,
"repo_name": "jimblasko/xcoin",
"id": "323b103272a0d8be8a8ec07a3827342e814adb52",
"size": "4275",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/qt/bitcoinunits.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "51312"
},
{
"name": "C",
"bytes": "33280"
},
{
"name": "C++",
"bytes": "2599810"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "HTML",
"bytes": "50620"
},
{
"name": "M4",
"bytes": "80821"
},
{
"name": "Makefile",
"bytes": "575130"
},
{
"name": "NSIS",
"bytes": "5914"
},
{
"name": "Objective-C",
"bytes": "858"
},
{
"name": "Objective-C++",
"bytes": "3537"
},
{
"name": "Python",
"bytes": "69973"
},
{
"name": "QMake",
"bytes": "27883"
},
{
"name": "Roff",
"bytes": "575804"
},
{
"name": "Shell",
"bytes": "64109"
}
],
"symlink_target": ""
} |
id: 934
title: Printer Canon Driver PPA
author: Stefano Marzorati
layout: post
guid: http://ubbunti.wordpress.com/?p=934
permalink: /printer-canon-driver-ppa/
authorsure_include_css:
-
dsq_thread_id:
- 2092216891
categories:
- Linux
tags:
- Canon
- driver
- ppa
- printer
- stampante
---
`sudo add-apt-repository ppa:michael-gruz/canon`
`sudo apt-get update` | {
"content_hash": "2b23b027a8bd648ea9ed6c8b5f074a3e",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 50,
"avg_line_length": 17.952380952380953,
"alnum_prop": 0.713527851458886,
"repo_name": "marste/Blog",
"id": "2e28e3de2efc893be0d07c7ef4d7049ba1a3b6d4",
"size": "381",
"binary": false,
"copies": "2",
"ref": "refs/heads/gh-pages",
"path": "_posts/2011-07-18-printer-canon-driver-ppa.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "115"
},
{
"name": "CSS",
"bytes": "40033"
},
{
"name": "HTML",
"bytes": "18553"
},
{
"name": "JavaScript",
"bytes": "6907"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:background="#8000">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:text="空气质量"
android:textColor="#fff"
android:textSize="20sp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="@+id/aqi_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#fff"
android:textSize="40sp"/>
<TextView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AQI指数"
android:textColor="#fff"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="@+id/pm25_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#fff"
android:textSize="40sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#fff"
android:text="PM2.5指数"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</LinearLayout> | {
"content_hash": "fad9b91b37d8de4019a55e6fe0111878",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 72,
"avg_line_length": 41.231884057971016,
"alnum_prop": 0.5398945518453427,
"repo_name": "xuan86883/coolweather",
"id": "e1a3149b868b741959bbc06ee8727d015da8c0fa",
"size": "2861",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/aqi.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "31849"
}
],
"symlink_target": ""
} |
FROM debian:stable-slim
MAINTAINER Apiary <sre@apiary.io>
ENV REFRESHED_AT 2020-11-02
COPY requirements.txt /tmp/
RUN apt-get update && \
apt-get install -y --no-install-recommends \
python-sphinx \
python-yaml \
python-setuptools \
graphviz \
make \
python-pip \
git && \
pip install --upgrade pip setuptools wheel && \
pip install -r /tmp/requirements.txt
RUN mkdir /mnt/docs
WORKDIR /mnt/docs
VOLUME ["/mnt/docs"]
CMD ["make", "clean", "html"]
| {
"content_hash": "93bd30e1ca90367f05b903a3b423213d",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 51,
"avg_line_length": 21.16,
"alnum_prop": 0.610586011342155,
"repo_name": "apiaryio/docker-base-images",
"id": "5fc690cf90bc75c5a8ff32508821077e5d41587d",
"size": "529",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sphinx-doc/Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "24770"
},
{
"name": "JavaScript",
"bytes": "347"
},
{
"name": "Python",
"bytes": "5446"
},
{
"name": "Shell",
"bytes": "3037"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'/>
<title>Vibration API: test that the vibrate() method is present (with or without vendor prefix)</title>
<link rel='author' title='Robin Berjon' href='mailto:robin@berjon.com'/>
<link rel='help' href='http://www.w3.org/TR/vibration/#methods'/>
<meta name='flags' content='dom'/>
<meta name='assert' content='Check that the vibrate() method is present.'/>
</head>
<body>
<h1>Description</h1>
<p>
This test checks for the presence of the <code>vibrate()</code> method, taking
vendor prefixes into account.
</p>
<div id='log'></div>
<script src='/resources/testharness.js'></script>
<script src='/resources/testharnessreport.js'></script>
<script>
test(function () {
assert_not_equals(undefined, navigator.vibrate, "navigator.vibrate exists");
}, "vibrate() is present on navigator");
</script>
</body>
</html>
| {
"content_hash": "99155567b5d0c84ea7007454bab1182c",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 107,
"avg_line_length": 36.88461538461539,
"alnum_prop": 0.6381647549530761,
"repo_name": "chromium/chromium",
"id": "70aa4047e11b9708aa300c878164cde0da811ec1",
"size": "959",
"binary": false,
"copies": "21",
"ref": "refs/heads/main",
"path": "third_party/blink/web_tests/external/wpt/vibration/api-is-present.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
module ProMotion
class WebScreen < ViewController
include ProMotion::WebScreenModule
end
end
| {
"content_hash": "55a07357209e47350f4a24e08452a01a",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 38,
"avg_line_length": 20.2,
"alnum_prop": 0.7920792079207921,
"repo_name": "silasjmatson/ProMotion",
"id": "9f1365b03e162ed5c1762e043d5140f57fd1ff4e",
"size": "101",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/ProMotion/web/web_screen.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "136904"
}
],
"symlink_target": ""
} |
#ifndef gpe_editor_globals_h
#define gpe_editor_globals_h
#include "../pawgui/pawgui_theme_controller.h"
#include "../pawgui/pawgui_dock_system.h"
#include "gpe_editor_splash_page.h"
extern int release_current_mode;
extern pawgui::themes_controller * editor_theme_controller;
extern pawgui::widget_dock * gpe_dock;
extern pawgui::widget_dock_panel * panel_center_area;
extern pawgui::widget_dock_panel * panel_resource_tree;
extern pawgui::widget_dock_panel * panel_main_editor;
extern pawgui::widget_dock_panel * panel_inspector;
extern pawgui::widget_dock_panel * panel_meta;
#endif // gpe_editor_globals_hpawgui::
| {
"content_hash": "c3f5032ee1bfe5588c217f37552ec012",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 59,
"avg_line_length": 33.73684210526316,
"alnum_prop": 0.7425897035881436,
"repo_name": "pawbyte/Game-Pencil-Engine",
"id": "fe9f0439c56a10b8aa633ec70300f54ba6aa8737",
"size": "2043",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/gpe_editor/gpe_editor_globals.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "10522"
},
{
"name": "C++",
"bytes": "4895948"
},
{
"name": "CSS",
"bytes": "438"
},
{
"name": "HTML",
"bytes": "203"
},
{
"name": "JavaScript",
"bytes": "1663572"
},
{
"name": "Makefile",
"bytes": "10465"
},
{
"name": "Meson",
"bytes": "1375"
}
],
"symlink_target": ""
} |
package org.apache.flink.table.runtime.types
import org.apache.flink.api.common.typeutils._
import org.apache.flink.core.memory.{DataInputView, DataOutputView}
import org.apache.flink.types.Row
class CRowSerializer(val rowSerializer: TypeSerializer[Row]) extends TypeSerializer[CRow] {
override def isImmutableType: Boolean = false
override def duplicate(): TypeSerializer[CRow] = new CRowSerializer(rowSerializer.duplicate())
override def createInstance(): CRow = new CRow(rowSerializer.createInstance(), true)
override def copy(from: CRow): CRow = new CRow(rowSerializer.copy(from.row), from.change)
override def copy(from: CRow, reuse: CRow): CRow = {
rowSerializer.copy(from.row, reuse.row)
reuse.change = from.change
reuse
}
override def getLength: Int = -1
override def serialize(record: CRow, target: DataOutputView): Unit = {
rowSerializer.serialize(record.row, target)
target.writeBoolean(record.change)
}
override def deserialize(source: DataInputView): CRow = {
val row = rowSerializer.deserialize(source)
val change = source.readBoolean()
new CRow(row, change)
}
override def deserialize(reuse: CRow, source: DataInputView): CRow = {
rowSerializer.deserialize(reuse.row, source)
reuse.change = source.readBoolean()
reuse
}
override def copy(source: DataInputView, target: DataOutputView): Unit = {
rowSerializer.copy(source, target)
target.writeBoolean(source.readBoolean())
}
override def canEqual(obj: Any): Boolean = obj.isInstanceOf[CRowSerializer]
override def equals(obj: Any): Boolean = {
if (canEqual(obj)) {
val other = obj.asInstanceOf[CRowSerializer]
rowSerializer.equals(other.rowSerializer)
} else {
false
}
}
override def hashCode: Int = rowSerializer.hashCode() * 13
// --------------------------------------------------------------------------------------------
// Serializer configuration snapshotting & compatibility
// --------------------------------------------------------------------------------------------
override def snapshotConfiguration(): TypeSerializerConfigSnapshot = {
new CRowSerializer.CRowSerializerConfigSnapshot(rowSerializer)
}
override def ensureCompatibility(
configSnapshot: TypeSerializerConfigSnapshot): CompatibilityResult[CRow] = {
configSnapshot match {
case crowSerializerConfigSnapshot: CRowSerializer.CRowSerializerConfigSnapshot =>
val compatResult = CompatibilityUtil.resolveCompatibilityResult(
crowSerializerConfigSnapshot.getSingleNestedSerializerAndConfig.f0,
classOf[UnloadableDummyTypeSerializer[_]],
crowSerializerConfigSnapshot.getSingleNestedSerializerAndConfig.f1,
rowSerializer)
if (compatResult.isRequiresMigration) {
if (compatResult.getConvertDeserializer != null) {
CompatibilityResult.requiresMigration(
new CRowSerializer(
new TypeDeserializerAdapter(compatResult.getConvertDeserializer))
)
} else {
CompatibilityResult.requiresMigration()
}
} else {
CompatibilityResult.compatible()
}
case _ => CompatibilityResult.requiresMigration()
}
}
}
object CRowSerializer {
class CRowSerializerConfigSnapshot(
private val rowSerializer: TypeSerializer[Row])
extends CompositeTypeSerializerConfigSnapshot(rowSerializer) {
/** This empty nullary constructor is required for deserializing the configuration. */
def this() = this(null)
override def getVersion: Int = CRowSerializerConfigSnapshot.VERSION
}
object CRowSerializerConfigSnapshot {
val VERSION = 1
}
}
| {
"content_hash": "954e1ed98de34ef802fd1eb79b354811",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 97,
"avg_line_length": 32.23275862068966,
"alnum_prop": 0.6833377908531693,
"repo_name": "oscarceballos/flink-1.3.2",
"id": "caf346c3430bdbcb0278d6022f244bb75e6cdf9f",
"size": "4544",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "flink-libraries/flink-table/src/main/scala/org/apache/flink/table/runtime/types/CRowSerializer.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9820"
},
{
"name": "CSS",
"bytes": "18100"
},
{
"name": "CoffeeScript",
"bytes": "89458"
},
{
"name": "HTML",
"bytes": "326027"
},
{
"name": "Java",
"bytes": "31370736"
},
{
"name": "JavaScript",
"bytes": "8267"
},
{
"name": "Python",
"bytes": "328555"
},
{
"name": "Scala",
"bytes": "5559847"
},
{
"name": "Shell",
"bytes": "192049"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en" ng-app="nApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>SoccerChain Game for Lovers of Live Soccer Betting</title>
<meta name="description"
content="Try how good you are at guessing soccer outcomes by competing against other players in making predictions on real-time soccer games.">
<meta name="author" content="Dmitry Nosov">
<link href="https://fonts.googleapis.com/css?family=Quattrocento:400,700" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Patua+One" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<link rel="shortcut icon" href="./images/favicon.ico">
<link rel="stylesheet" href="./libs/normalize.css">
<link rel="stylesheet" href="./styles/styles.css">
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/ru_RU/sdk.js#xfbml=1&version=v2.9";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<sidebar class="is-mobile" id="sidebar-menu" size="400" position="left" is-expanded="true">
<h2 class="header-logo">
<a href="#video" offset="0" du-smooth-scroll du-scrollspy sidebar-toggle="sidebar-menu">SoccerChain</a>
</h2>
<a class="header-menu-close" sidebar-toggle="sidebar-menu">
<img src="./images/close.png" srcset="./images/close@2x.png 2x, ./images/close@3x.png 3x" alt="close" />
</a>
<nav class="header-menu">
<ul class="header-menu__list" du-spy-context>
<li class="header-menu__list-item">
<a href="#block-1" du-smooth-scroll du-scrollspy sidebar-toggle="sidebar-menu">Block #1</a>
</li>
<li class="header-menu__list-item">
<a href="#block-2" du-smooth-scroll du-scrollspy sidebar-toggle="sidebar-menu">Block #2</a>
</li>
</ul>
</nav >
</sidebar>
<div class="page-wrap">
<div class="page-content" ng-controller="landingCtrl">
<div id="video"></div>
<header class="page-header header" scroll-fixed>
<section class="header-top">
<h2 class="header-logo">
<a href="#video" offset="0" du-smooth-scroll du-scrollspy>SoccerChain</a>
</h2>
<ul class="header-social">
<li class="header-social__item">
<div data-href="https://goodwilldarina.github.io/blockdmitry/app/index.html" data-layout="button" data-size="small" data-mobile-iframe="false">
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fgoodwilldarina.github.io%2Fblockdmitry%2Fapp%2Findex.html&src=sdkpreparse">facebook</a>
</div>
</li>
<li class="header-social__item">
<a class="twitter-share-button"
href="https://twitter.com/intent/tweet?text=Hello%20world" target="_blank">
Tweet</a>
</li>
</ul>
<div class="header-menu-mobile">
<div class="header-menu-btn">
<a sidebar-toggle="sidebar-menu">Menu</a>
</div>
</div>
<p class="header-description is-mobile hidden-scroll">
SoccerChain multiplayer game based on soccer results predition
</p>
<nav class="header-menu is-not-mobile">
<ul class="header-menu__list" du-spy-context>
<li class="header-menu__list-item">
<a href="#block-1" du-smooth-scroll du-scrollspy>Block #1</a>
</li>
<li class="header-menu__list-item">
<a href="#block-2" du-smooth-scroll du-scrollspy>Block #2</a>
</li>
</ul>
</nav >
</section>
<section class="header-bottom">
<p class="header-description is-not-mobile hidden-scroll">
SoccerChain multiplayer game based on soccer results predition
</p>
</section>
</header>
<main class="page-main">
<section class="video-container">
<div class="container">
<article class="counter">
<div class="counter-item">{{countdown.days}}</div>
<div class="counter-item">{{countdown.hours}}</div>
<div class="counter-item">{{countdown.minutes}}</div>
<div class="counter-item">{{countdown.seconds}}</div>
</article>
<h2>Видео Блок</h2>
<div class="video-row row">
<div class="video-item col-md-6 col-sm-12">
<iframe width="100%"
height="200"
src="https://www.youtube.com/embed/mJ_fkw5j-t0"
frameborder="0"
allowfullscreen></iframe>
<p class="video-title">Video #1</p>
</div>
<div class="video-item col-md-6 col-sm-12">
<iframe width="100%"
height="200"
src="https://www.youtube.com/embed/mJ_fkw5j-t0"
frameborder="0"
allowfullscreen></iframe>
<p class="video-title">Video #2</p>
</div>
</div>
<div class="video-row row">
<div class="video-item col-md-6 col-sm-12">
<iframe width="100%"
height="200"
src="https://www.youtube.com/embed/mJ_fkw5j-t0"
frameborder="0"
allowfullscreen></iframe>
<p class="video-title">Video #3</p>
</div>
<div class="video-item col-md-6 col-sm-12">
<iframe width="100%"
height="200"
src="https://www.youtube.com/embed/mJ_fkw5j-t0"
frameborder="0"
allowfullscreen></iframe>
<p class="video-title">Video #4</p>
</div>
</div>
</div>
</section>
<section class="block-1" id="block-1">
<div class="container">
<h2>Block #1</h2>
<div class="row">
<div class="token-cap col-md-5 col-sm-12">
<p class="title">Token Cap</p>
<p class="big-text">117 337 ETH</p>
<p class="big-text">41 MLN USD</p>
<div class="color-block">
<div>
<span>Current rate: </span>
<span class="info">i</span>
</div>
<div>
<span>1 EHT = 2824 SNM</span>
<span>1 USD = 8 SNM</span>
</div>
</div>
</div>
<div class="total-amount col-md-7 col-sm-12">
<p class="title">total amount of tokens issued on ico:</p>
<p class="big-text">331.360.000 SNM</p>
<p>
Значимость этих проблем настолько очевидна, что консультация с широким активом способствует
подготовки и
реализации модели развития. Равным образом дальнейшее развитие различных форм деятельности
позволяет
выполнять важные задания по разработке направлений прогрессивного развития. Равным образом
постоянный
количественный рост и сфера нашей активности способствует подготовки и реализации
соответствующий
условий активизации.
</p>
<p>
Равным образом рамки и место обучения кадров позволяет выполнять важные задания по
разработке форм
развития <a href>link</a>
</p>
</div>
</div>
</div>
</section>
<section class="block-2" id="block-2">
<div class="container">
<h2>Блок №2</h2>
<div class="row">
<p class="col-md-12">
Равным образом рамки и место обучения кадров позволяет выполнять важные задания по разработке форм
развития.
Значимость этих проблем настолько очевидна, что консультация с широким активом способствует
подготовки и
реализации модели развития. Равным образом дальнейшее развитие различных форм деятельности позволяет
выполнять важные задания по разработке направлений прогрессивного развития. Равным образом
постоянный
количественный рост и сфера нашей активности способствует подготовки и реализации соответствующий
условий активизации.
</p>
<p class="col-md-12">
Значимость этих проблем настолько очевидна, что дальнейшее развитие различных форм деятельности
представляет
собой интересный эксперимент проверки системы обучения кадров, соответствует насущным потребностям.
Повседневная практика показывает, что консультация с широким активом способствует подготовки и
реализации
позиций, занимаемых участниками в отношении поставленных задач. Равным образом укрепление и развитие
структуры представляет собой интересный эксперимент проверки позиций, занимаемых участниками в
отношении
поставленных задач. Равным образом сложившаяся структура организации обеспечивает широкому кругу
(специалистов) участие в формировании форм развития. Повседневная практика показывает, что
реализация
намеченных плановых заданий влечет за собой процесс внедрения и модернизации модели развития.
Повседневная
практика показывает, что постоянный количественный рост и сфера нашей активности обеспечивает
широкому
кругу
(специалистов) участие в формировании дальнейших направлений развития.
</p>
</div>
</div>
</section>
</main>
</div>
<footer class="page-footer">
<small>© 2014 BetFlock. All rights reserved.</small>
</footer>
</div>
<script src="./libs/angular.min.js"></script>
<script src="./app.js"></script>
</body>
</html> | {
"content_hash": "68c2fdf96652067821b32230a767362f",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 207,
"avg_line_length": 56.69787234042553,
"alnum_prop": 0.4473881717202041,
"repo_name": "GoodwillDarina/blockdmitry",
"id": "d4514a8e0fea8806554e9ea23d275abfda84e2d9",
"size": "15154",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "source/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "68342"
},
{
"name": "HTML",
"bytes": "30308"
},
{
"name": "JavaScript",
"bytes": "7667"
}
],
"symlink_target": ""
} |
package com.microsoft.azure.management.network.v2019_02_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The ARP table associated with the ExpressRouteCircuit.
*/
public class ExpressRouteCircuitArpTable {
/**
* Entry age in minutes.
*/
@JsonProperty(value = "age")
private Integer age;
/**
* Interface address.
*/
@JsonProperty(value = "interface")
private String interfaceProperty;
/**
* The IP address.
*/
@JsonProperty(value = "ipAddress")
private String ipAddress;
/**
* The MAC address.
*/
@JsonProperty(value = "macAddress")
private String macAddress;
/**
* Get entry age in minutes.
*
* @return the age value
*/
public Integer age() {
return this.age;
}
/**
* Set entry age in minutes.
*
* @param age the age value to set
* @return the ExpressRouteCircuitArpTable object itself.
*/
public ExpressRouteCircuitArpTable withAge(Integer age) {
this.age = age;
return this;
}
/**
* Get interface address.
*
* @return the interfaceProperty value
*/
public String interfaceProperty() {
return this.interfaceProperty;
}
/**
* Set interface address.
*
* @param interfaceProperty the interfaceProperty value to set
* @return the ExpressRouteCircuitArpTable object itself.
*/
public ExpressRouteCircuitArpTable withInterfaceProperty(String interfaceProperty) {
this.interfaceProperty = interfaceProperty;
return this;
}
/**
* Get the IP address.
*
* @return the ipAddress value
*/
public String ipAddress() {
return this.ipAddress;
}
/**
* Set the IP address.
*
* @param ipAddress the ipAddress value to set
* @return the ExpressRouteCircuitArpTable object itself.
*/
public ExpressRouteCircuitArpTable withIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
return this;
}
/**
* Get the MAC address.
*
* @return the macAddress value
*/
public String macAddress() {
return this.macAddress;
}
/**
* Set the MAC address.
*
* @param macAddress the macAddress value to set
* @return the ExpressRouteCircuitArpTable object itself.
*/
public ExpressRouteCircuitArpTable withMacAddress(String macAddress) {
this.macAddress = macAddress;
return this;
}
}
| {
"content_hash": "34dbc5af695d859742d8e90b27b56820",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 88,
"avg_line_length": 22.11304347826087,
"alnum_prop": 0.6134486826582777,
"repo_name": "selvasingh/azure-sdk-for-java",
"id": "56ba9b0b9ba13994ec29db41a4c2c6ccd8b3ca8c",
"size": "2773",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sdk/network/mgmt-v2019_02_01/src/main/java/com/microsoft/azure/management/network/v2019_02_01/ExpressRouteCircuitArpTable.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "29891970"
},
{
"name": "JavaScript",
"bytes": "6198"
},
{
"name": "PowerShell",
"bytes": "160"
},
{
"name": "Shell",
"bytes": "609"
}
],
"symlink_target": ""
} |
namespace IGCS
{
struct Settings
{
// settings written to config file
bool invertY;
float fastMovementMultiplier;
float slowMovementMultiplier;
float movementUpMultiplier;
float movementSpeed;
float rotationSpeed;
float fovChangeSpeed;
int cameraControlDevice; // 0==keyboard/mouse, 1 == gamepad, 2 == both, see Defaults.h
bool allowCameraMovementWhenMenuIsUp;
bool disableInGameDofWhenCameraIsEnabled;
// screenshot settings
int numberOfFramesToWaitBetweenSteps;
float distanceBetweenLightfieldShots;
int numberOfShotsToTake;
int typeOfScreenshot;
float totalPanoAngleDegrees;
float overlapPercentagePerPanoShot;
char screenshotFolder[_MAX_PATH+1] = { 0 };
// settings not persisted to config file.
// add settings to edit here.
float resolutionScale; // 0.5-4.0
int todHour; // 0-23
int todMinute; // 0-59
float fogStrength; // 0-200. 0 is no fog (ugly), 200 is thick fog all around you. Can go higher if one wants.
float fogStartCurve; // 0-1. 1 is default.
void loadFromFile(map<ActionType, ActionData*> keyBindingPerActionType)
{
CDataFile iniFile;
if (!iniFile.Load(IGCS_SETTINGS_INI_FILENAME))
{
// doesn't exist
return;
}
invertY = iniFile.GetBool("invertY", "CameraSettings");
allowCameraMovementWhenMenuIsUp = iniFile.GetBool("allowCameraMovementWhenMenuIsUp", "CameraSettings");
disableInGameDofWhenCameraIsEnabled = iniFile.GetBool("disableInGameDofWhenCameraIsEnabled", "CameraSettings");
fastMovementMultiplier = Utils::clamp(iniFile.GetFloat("fastMovementMultiplier", "CameraSettings"), 0.0f, FASTER_MULTIPLIER);
slowMovementMultiplier = Utils::clamp(iniFile.GetFloat("slowMovementMultiplier", "CameraSettings"), 0.0f, SLOWER_MULTIPLIER);
movementUpMultiplier = Utils::clamp(iniFile.GetFloat("movementUpMultiplier", "CameraSettings"), 0.0f, DEFAULT_UP_MOVEMENT_MULTIPLIER);
movementSpeed = Utils::clamp(iniFile.GetFloat("movementSpeed", "CameraSettings"), 0.0f, DEFAULT_MOVEMENT_SPEED);
rotationSpeed = Utils::clamp(iniFile.GetFloat("rotationSpeed", "CameraSettings"), 0.0f, DEFAULT_ROTATION_SPEED);
fovChangeSpeed = Utils::clamp(iniFile.GetFloat("fovChangeSpeed", "CameraSettings"), 0.0f, DEFAULT_FOV_SPEED);
cameraControlDevice = Utils::clamp(iniFile.GetInt("cameraControlDevice", "CameraSettings"), 0, DEVICE_ID_ALL, DEVICE_ID_ALL);
// screenshot settings
numberOfFramesToWaitBetweenSteps = Utils::clamp(iniFile.GetInt("numberOfFramesToWaitBetweenSteps", "ScreenshotSettings"), 1, 100);
distanceBetweenLightfieldShots = Utils::clamp(iniFile.GetFloat("distanceBetweenLightfieldShots", "ScreenshotSettings"), 0.0f, 100.0f);
numberOfShotsToTake = Utils::clamp(iniFile.GetInt("numberOfShotsToTake", "ScreenshotSettings"), 0, 45);
typeOfScreenshot = Utils::clamp(iniFile.GetInt("typeOfScreenshot", "ScreenshotSettings"), 0, ((int)ScreenshotType::Amount)-1);
totalPanoAngleDegrees = Utils::clamp(iniFile.GetFloat("totalPanoAngleDegrees", "ScreenshotSettings"), 30.0f, 360.0f, 110.0f);
overlapPercentagePerPanoShot = Utils::clamp(iniFile.GetFloat("overlapPercentagePerPanoShot", "ScreenshotSettings"), 0.1f, 99.0f, 80.0f);
std::string folder = iniFile.GetValue("screenshotFolder", "ScreenshotSettings");
folder.copy(screenshotFolder, folder.length());
screenshotFolder[folder.length()] = '\0';
// load keybindings. They might not be there, or incomplete.
for (std::pair<ActionType, ActionData*> kvp : keyBindingPerActionType)
{
int valueFromIniFile = iniFile.GetInt(kvp.second->getName(), "KeyBindings");
if (valueFromIniFile == INT_MIN)
{
// not found
continue;
}
kvp.second->setValuesFromIniFileValue(valueFromIniFile);
}
}
void saveToFile(map<ActionType, ActionData*> keyBindingPerActionType)
{
CDataFile iniFile;
iniFile.SetBool("invertY", invertY, "", "CameraSettings");
iniFile.SetBool("allowCameraMovementWhenMenuIsUp", allowCameraMovementWhenMenuIsUp, "", "CameraSettings");
iniFile.SetBool("disableInGameDofWhenCameraIsEnabled", disableInGameDofWhenCameraIsEnabled, "", "CameraSettings");
iniFile.SetFloat("fastMovementMultiplier", fastMovementMultiplier, "", "CameraSettings");
iniFile.SetFloat("slowMovementMultiplier", slowMovementMultiplier, "", "CameraSettings");
iniFile.SetFloat("movementUpMultiplier", movementUpMultiplier, "", "CameraSettings");
iniFile.SetFloat("movementSpeed", movementSpeed, "", "CameraSettings");
iniFile.SetFloat("rotationSpeed", rotationSpeed, "", "CameraSettings");
iniFile.SetFloat("fovChangeSpeed", fovChangeSpeed, "", "CameraSettings");
iniFile.SetInt("cameraControlDevice", cameraControlDevice, "", "CameraSettings");
// screenshot settings
iniFile.SetInt("numberOfFramesToWaitBetweenSteps", numberOfFramesToWaitBetweenSteps, "", "ScreenshotSettings");
iniFile.SetFloat("distanceBetweenLightfieldShots", distanceBetweenLightfieldShots, "", "ScreenshotSettings");
iniFile.SetInt("numberOfShotsToTake", numberOfShotsToTake, "", "ScreenshotSettings");
iniFile.SetInt("typeOfScreenshot", typeOfScreenshot, "", "ScreenshotSettings");
iniFile.SetFloat("totalPanoAngleDegrees", totalPanoAngleDegrees, "", "ScreenshotSettings");
iniFile.SetFloat("overlapPercentagePerPanoShot", overlapPercentagePerPanoShot, "", "ScreenshotSettings");
iniFile.SetValue("screenshotFolder", screenshotFolder, "", "ScreenshotSettings");
// save keybindings
if (!keyBindingPerActionType.empty())
{
for (std::pair<ActionType, ActionData*> kvp : keyBindingPerActionType)
{
// we're going to write 4 bytes, the keycode is 1 byte, and for each bool we'll shift in a 1 or 0, depending on whether it's true (1) or false (0).
int value = kvp.second->getIniFileValue();
iniFile.SetInt(kvp.second->getName(), value, "", "KeyBindings");
}
iniFile.SetSectionComment("KeyBindings", "Values are 4-byte ints: A|B|C|D, where A is byte for VT keycode, B, C and D are bools if resp. Alt, Ctrl or Shift is required");
}
iniFile.SetFileName(IGCS_SETTINGS_INI_FILENAME);
iniFile.Save();
}
void init(bool persistedOnly)
{
invertY = CONTROLLER_Y_INVERT;
fastMovementMultiplier = FASTER_MULTIPLIER;
slowMovementMultiplier = SLOWER_MULTIPLIER;
movementUpMultiplier = DEFAULT_UP_MOVEMENT_MULTIPLIER;
movementSpeed = DEFAULT_MOVEMENT_SPEED;
rotationSpeed = DEFAULT_ROTATION_SPEED;
fovChangeSpeed = DEFAULT_FOV_SPEED;
cameraControlDevice = DEVICE_ID_ALL;
allowCameraMovementWhenMenuIsUp = false;
disableInGameDofWhenCameraIsEnabled = false;
numberOfFramesToWaitBetweenSteps = 1;
// Screenshot settings
distanceBetweenLightfieldShots = 1.0f;
numberOfShotsToTake= 45;
typeOfScreenshot = (int)ScreenshotType::Lightfield;
totalPanoAngleDegrees = 110.0f;
overlapPercentagePerPanoShot = 80.0f;
strcpy(screenshotFolder, "c:\\");
if (!persistedOnly)
{
resolutionScale = 1.0f;
todHour = 12;
todMinute = 0;
fogStrength = 1.0f;
fogStartCurve = 1.0f;
}
}
};
} | {
"content_hash": "d6d8a14697e5586d13ed1c474a3a36aa",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 174,
"avg_line_length": 48.35616438356164,
"alnum_prop": 0.7461756373937677,
"repo_name": "FransBouma/InjectableGenericCameraSystem",
"id": "3e482fb0dd918e036ef91382c25e997fbd34a452",
"size": "7263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Cameras/AssassinsCreedOdyssey/InjectableGenericCameraSystem/Settings.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "446746"
},
{
"name": "C",
"bytes": "2569785"
},
{
"name": "C#",
"bytes": "843174"
},
{
"name": "C++",
"bytes": "16433213"
}
],
"symlink_target": ""
} |
<?php
namespace MathPHP\Tests\NumericalAnalysis\NumericalDifferentiation;
use MathPHP\NumericalAnalysis\NumericalDifferentiation\NumericalDifferentiation;
use MathPHP\Exception;
class NumericalDifferentiationTest extends \PHPUnit\Framework\TestCase
{
/**
* @test getPoints data is not a callback nor set of arrays
* @throws \Exception
*/
public function testIncorrectInput()
{
// Given
$x = 10;
$incorrectFunction = $x ** 2 + 2 * $x + 1;
// Then
$this->expectException(Exception\BadDataException::class);
// When
NumericalDifferentiation::getPoints($incorrectFunction, [0,4,5]);
}
/**
* @test validate an array doesn't have precisely two numbers (coordinates)
* @throws \Exception
*/
public function testNotCoordinatesException()
{
// Given
$points = [[0,0], [1,2,3], [2,2]];
$degree = 3;
// Then
$this->expectException(Exception\BadDataException::class);
// When
NumericalDifferentiation::validate($points, $degree);
}
/**
* @test validate there are not enough arrays in the input
* @throws \Exception
*/
public function testNotEnoughArraysException()
{
// Given
$points = [[0,0]];
$degree = 3;
// Then
$this->expectException(Exception\BadDataException::class);
// When
NumericalDifferentiation::validate($points, $degree);
}
/**
* @test validate two arrays share the same first number (x-component)
* @throws \Exception
*/
public function testNotAFunctionException()
{
// Given
$points = [[0,0], [0,5], [1,1]];
$degree = 3;
// Then
$this->expectException(Exception\BadDataException::class);
// When
NumericalDifferentiation::validate($points, $degree);
}
/**
* @test isSpacingConstant when there is not constant spacing between points
* @throws \Exception
*/
public function testSpacingNonConstant()
{
// Given
$sortedPoints = [[0,0], [3,3], [2,2]];
// Then
$this->expectException(Exception\BadDataException::class);
// When
NumericalDifferentiation::isSpacingConstant($sortedPoints);
}
/**
* @test isTargetInPoints target is not the x-component of one of the points
* @throws \Exception
*/
public function testTargetNotInPoints()
{
// Given
$target = 1;
$sortedPoints = [[0,0], [3,3], [2,2]];
// Then
$this->expectException(Exception\BadDataException::class);
// When
NumericalDifferentiation::isTargetInPoints($target, $sortedPoints);
}
}
| {
"content_hash": "811c43bfa4110e58286d05ed4b49612f",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 82,
"avg_line_length": 25.554545454545455,
"alnum_prop": 0.5884027036641765,
"repo_name": "markrogoyski/math-php",
"id": "e54fabcc623e1eebaa8d8d3a269a75585ac749e0",
"size": "2811",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/NumericalAnalysis/NumericalDifferentiation/NumericalDifferentiationTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "691"
},
{
"name": "PHP",
"bytes": "3833018"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UniShop.Common
{
public class ConfigHelper
{
public static string GetValueByKey(string key)
{
return ConfigurationManager.AppSettings[key].ToString();
}
}
}
| {
"content_hash": "2615db5acc224499996cbce350b39d0e",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 68,
"avg_line_length": 21.235294117647058,
"alnum_prop": 0.6980609418282548,
"repo_name": "tonnystark/unishop",
"id": "7ee0403d45aad0fab1de34f3451fd44d82e1e66e",
"size": "363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UniShop.Common/ConfigHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "102"
},
{
"name": "C#",
"bytes": "64861"
},
{
"name": "CSS",
"bytes": "513"
},
{
"name": "HTML",
"bytes": "5238"
},
{
"name": "JavaScript",
"bytes": "10918"
}
],
"symlink_target": ""
} |
@class ConfirmBubbleController;
// A view class that implements a bubble consisting of the following items:
// * one icon ("icon")
// * one title text ("title")
// * one message text ("message")
// * one optional link ("link")
// * two optional buttons ("ok" and "cancel")
//
// This bubble is convenient when we wish to ask transient, non-blocking
// questions. Unlike a dialog, a bubble menu disappears when we click outside of
// its window to avoid blocking user operations. A bubble is laid out as
// follows:
//
// +------------------------+
// | icon title |
// | message |
// | link |
// | [Cancel] [OK] |
// +------------------------+
//
@interface ConfirmBubbleCocoa : NSView<NSTextViewDelegate> {
@private
NSView* parent_; // weak
ConfirmBubbleController* controller_; // weak
// Controls used in this bubble.
base::scoped_nsobject<NSImageView> icon_;
base::scoped_nsobject<NSTextView> titleLabel_;
base::scoped_nsobject<NSTextView> messageLabel_;
base::scoped_nsobject<NSButton> okButton_;
base::scoped_nsobject<NSButton> cancelButton_;
}
// Initializes a bubble view. Since this initializer programmatically creates a
// custom NSView (i.e. without using a nib file), this function should be called
// from loadView: of the controller object which owns this view.
- (id)initWithParent:(NSView*)parent
controller:(ConfirmBubbleController*)controller;
@end
// Exposed only for unit testing.
@interface ConfirmBubbleCocoa (ExposedForUnitTesting)
- (void)clickOk;
- (void)clickCancel;
- (void)clickLink;
@end
#endif // CHROME_BROWSER_UI_COCOA_CONFIRM_BUBBLE_COCOA_H_
| {
"content_hash": "e094b0450daea2d518787cd38a19094e",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 80,
"avg_line_length": 33.56,
"alnum_prop": 0.6692491060786651,
"repo_name": "google-ar/WebARonARCore",
"id": "10d00ffdae509c34d855db3cf0373447bec7e5c6",
"size": "2025",
"binary": false,
"copies": "3",
"ref": "refs/heads/webarcore_57.0.2987.5",
"path": "chrome/browser/ui/cocoa/confirm_bubble_cocoa.h",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.camel</groupId>
<artifactId>components</artifactId>
<version>3.20.0-SNAPSHOT</version>
</parent>
<artifactId>camel-cmis</artifactId>
<packaging>jar</packaging>
<name>Camel :: CMIS (deprecated)</name>
<description>Camel CMIS which is based on Apache Chemistry support</description>
<properties>
<camel.osgi.import>
!org.apache.chemistry.opencmis.client.runtime,*
</camel.osgi.import>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-support</artifactId>
</dependency>
<dependency>
<groupId>org.apache.chemistry.opencmis</groupId>
<artifactId>chemistry-opencmis-client-impl</artifactId>
<version>${cmis-version}</version>
</dependency>
<!-- for testing -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.chemistry.opencmis</groupId>
<artifactId>chemistry-opencmis-server-inmemory</artifactId>
<version>${cmis-version}</version>
<type>war</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId>
<version>${jetty-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<!-- Eclipse m2e Lifecycle Management -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>${lifecycle-mapping-version}</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>${maven-dependency-plugin-version}</versionRange>
<goals>
<goal>copy</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-war</id>
<phase>generate-test-resources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>target/dependency</outputDirectory>
<stripVersion>true</stripVersion>
<artifactItems>
<artifactItem>
<groupId>org.apache.chemistry.opencmis</groupId>
<artifactId>chemistry-opencmis-server-inmemory</artifactId>
<version>${cmis-version}</version>
<type>war</type>
<overWrite>false</overWrite>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>jdk17-build</id>
<activation>
<jdk>[17,)</jdk>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--add-opens java.base/java.lang=ALL-UNNAMED</argLine>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
| {
"content_hash": "397d4793bceee99b4625f40f9df5f96b",
"timestamp": "",
"source": "github",
"line_count": 156,
"max_line_length": 201,
"avg_line_length": 40.34615384615385,
"alnum_prop": 0.4955513187162377,
"repo_name": "christophd/camel",
"id": "7dc06a9ea97b8da129bde302345fb10363e368ac",
"size": "6294",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "components/camel-cmis/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6695"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Dockerfile",
"bytes": "5676"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "405043"
},
{
"name": "HTML",
"bytes": "212954"
},
{
"name": "Java",
"bytes": "114730615"
},
{
"name": "JavaScript",
"bytes": "103655"
},
{
"name": "Jsonnet",
"bytes": "1734"
},
{
"name": "Kotlin",
"bytes": "41869"
},
{
"name": "Mustache",
"bytes": "525"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Ruby",
"bytes": "88"
},
{
"name": "Shell",
"bytes": "15327"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "699"
},
{
"name": "XSLT",
"bytes": "276597"
}
],
"symlink_target": ""
} |
package org.motechproject.openmrs.resource;
import org.motechproject.openmrs.config.Config;
import org.motechproject.openmrs.domain.RelationshipListResult;
/**
* Interface for relationships management.
*/
public interface RelationshipResource {
/**
* Returns the {@link RelationshipListResult} of all relationships that the person with the given {@code personUuid}
* is part of.
*
* @param config the configuration to be used while performing this action
* @param personUuid the UUID of the person
* @return the list of all relationships the person with the given {@code personUuid} is part of
*/
RelationshipListResult getByPersonUuid(Config config, String personUuid);
}
| {
"content_hash": "5d5a48e82edffed45f10b52e7316f8d2",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 120,
"avg_line_length": 36.15,
"alnum_prop": 0.7455048409405256,
"repo_name": "1stmateusz/modules",
"id": "dd4ca5d5024dc8707baf09c779574de0c4291193",
"size": "723",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "openmrs/src/main/java/org/motechproject/openmrs/resource/RelationshipResource.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "9398"
},
{
"name": "Groovy",
"bytes": "596"
},
{
"name": "HTML",
"bytes": "169855"
},
{
"name": "Java",
"bytes": "4397985"
},
{
"name": "JavaScript",
"bytes": "199255"
},
{
"name": "Shell",
"bytes": "1401"
}
],
"symlink_target": ""
} |
'use strict';
// Register `phoneList` component, along with its associated controller and template
angular.
module('view2').
component('view2', {
templateUrl: 'view2/view2.template.html',
controller: ['$routeParams',
function View2Controller() {
}
]
});
| {
"content_hash": "3360f30494631bed55be8043572559ac",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 84,
"avg_line_length": 22.76923076923077,
"alnum_prop": 0.6317567567567568,
"repo_name": "Arkadij24/HTML5ApplicationTest",
"id": "34f8cc1f562522929990c76404be6c58b2f92db9",
"size": "296",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/view2/view2.component.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "366"
},
{
"name": "HTML",
"bytes": "5993"
},
{
"name": "JavaScript",
"bytes": "10027"
}
],
"symlink_target": ""
} |
package edu.berkeley.velox.storage
import com.typesafe.scalalogging.slf4j.Logging
import edu.berkeley.velox._
import edu.berkeley.velox.datamodel._
import edu.berkeley.velox.trigger.TriggerManager
import edu.berkeley.velox.catalog.Catalog
import edu.berkeley.velox.trigger.server._
trait StorageManager {
/**
* Create a new database. No-op if db already exists.
*
* @param dbName Name of the database to create
*/
def createDatabase(dbName: DatabaseName)
/**
* Create a table within a database. No-op if table already exists
*
* @param dbName Database to create table in
* @param tableName Name of Table to create
*/
final def createTable(dbName: DatabaseName, tableName: TableName) {
_createTable(dbName, tableName)
val schema = Catalog.getSchema(dbName, tableName)
// If table has indexes, add trigger to update indexes.
// TODO: support alternative index update methods (specified by table schema).
// Assuming '.' is delimiter "tableName.indexName".
val parts = tableName.split("\\.")
if (parts.length > 1) {
// This "table" is an index for a table.
// Add (or re-add) a trigger for the table.
val baseTable = parts(0)
val tableSchema = Catalog.getSchema(dbName, baseTable)
val trigger = new IndexUpdateTrigger(dbName, baseTable)
val triggerName = trigger.getClass.getName
TriggerManager.addTriggerInstance(dbName, baseTable, triggerName, trigger)
} else {
// This "table" is a table.
// If table schema contains indexes, add (or re-add) a trigger for the table.
if (!schema.indexes.isEmpty) {
val trigger = new IndexUpdateTrigger(dbName, tableName)
val triggerName = trigger.getClass.getName
TriggerManager.addTriggerInstance(dbName, tableName, triggerName, trigger)
}
}
}
/**
* Insert a set of values into a table.
*
* @param databaseName Database to insert into
* @param tableName Table to insert into
* @param insertSet Set of values to insert
*
* @return The number of rows inserted
*/
final def insert(databaseName: DatabaseName, tableName: TableName, insertSet: InsertSet): Int = {
_insert(databaseName, tableName, insertSet)
}
/**
* Run a query against a table.
*
* @param databaseName Database to query
* @param tableName Table to query
* @param query Query to run
*
* @return Set of values that answer the query
*/
final def query(query: Query): ResultSet = {
_query(query)
}
/*
* Implementors of storage engines should implement the following methods.
*/
protected def _createTable(dbName: DatabaseName, tableName: TableName)
protected def _insert(databaseName: DatabaseName, tableName: TableName, insertSet: InsertSet): Int
protected def _query(query: Query): ResultSet
}
| {
"content_hash": "f77f239011db85c369aac7b379a7aeca",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 100,
"avg_line_length": 33.395348837209305,
"alnum_prop": 0.6901114206128134,
"repo_name": "pbailis/fast-tpcc-repo",
"id": "b953b50eb471852e865a3f3f0f8e831dcbde88e2",
"size": "2872",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/scala/edu/berkeley/velox/storage/StorageManager.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "8516"
},
{
"name": "Python",
"bytes": "42408"
},
{
"name": "Scala",
"bytes": "215274"
},
{
"name": "Shell",
"bytes": "86"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct base_unit_info<us::tablespoon_base_unit></title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../boost_units/Reference.html#header.boost.units.base_units.us.tablespoon_hpp" title="Header <boost/units/base_units/us/tablespoon.hpp>">
<link rel="prev" href="base_unit_inf_idp110822640.html" title="Struct base_unit_info<us::quart_base_unit>">
<link rel="next" href="base_unit_inf_idp110828928.html" title="Struct base_unit_info<us::teaspoon_base_unit>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="base_unit_inf_idp110822640.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.us.tablespoon_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="base_unit_inf_idp110828928.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.units.base_unit_inf_idp110825776"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct base_unit_info<us::tablespoon_base_unit></span></h2>
<p>boost::units::base_unit_info<us::tablespoon_base_unit></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../boost_units/Reference.html#header.boost.units.base_units.us.tablespoon_hpp" title="Header <boost/units/base_units/us/tablespoon.hpp>">boost/units/base_units/us/tablespoon.hpp</a>>
</span>
<span class="keyword">struct</span> <a class="link" href="base_unit_inf_idp110825776.html" title="Struct base_unit_info<us::tablespoon_base_unit>">base_unit_info</a><span class="special"><</span><span class="identifier">us</span><span class="special">::</span><span class="identifier">tablespoon_base_unit</span><span class="special">></span> <span class="special">{</span>
<span class="comment">// <a class="link" href="base_unit_inf_idp110825776.html#idp110826336-bb">public static functions</a></span>
<span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_inf_idp110825776.html#idp110826544-bb"><span class="identifier">name</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_inf_idp110825776.html#idp110827024-bb"><span class="identifier">symbol</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp195865312"></a><h2>Description</h2>
<div class="refsect2">
<a name="idp195865520"></a><h3>
<a name="idp110826336-bb"></a><code class="computeroutput">base_unit_info</code> public static functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="idp110826544-bb"></a><span class="identifier">name</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="idp110827024-bb"></a><span class="identifier">symbol</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2008 Matthias Christian Schabel<br>Copyright © 2007-2010 Steven
Watanabe<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="base_unit_inf_idp110822640.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.us.tablespoon_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="base_unit_inf_idp110828928.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "50a42da592da7c7c425953be343ecfcf",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 502,
"avg_line_length": 92.19402985074628,
"alnum_prop": 0.6799417192812045,
"repo_name": "hand-iemura/lightpng",
"id": "0c265e30d3cfa9447e5cf8fbca4d46eae09372b2",
"size": "6177",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "boost_1_53_0/doc/html/boost/units/base_unit_inf_idp110825776.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "139512"
},
{
"name": "Batchfile",
"bytes": "43970"
},
{
"name": "C",
"bytes": "2306793"
},
{
"name": "C#",
"bytes": "40804"
},
{
"name": "C++",
"bytes": "139009726"
},
{
"name": "CMake",
"bytes": "1741"
},
{
"name": "CSS",
"bytes": "309758"
},
{
"name": "Cuda",
"bytes": "26749"
},
{
"name": "FORTRAN",
"bytes": "1387"
},
{
"name": "Groff",
"bytes": "8039"
},
{
"name": "HTML",
"bytes": "139153356"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "JavaScript",
"bytes": "132031"
},
{
"name": "Lex",
"bytes": "1255"
},
{
"name": "M4",
"bytes": "29689"
},
{
"name": "Makefile",
"bytes": "1074346"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "3745"
},
{
"name": "PHP",
"bytes": "59030"
},
{
"name": "Perl",
"bytes": "29502"
},
{
"name": "Perl6",
"bytes": "2053"
},
{
"name": "Python",
"bytes": "1710815"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Shell",
"bytes": "376263"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "13404"
},
{
"name": "XSLT",
"bytes": "761090"
},
{
"name": "Yacc",
"bytes": "18910"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.