text
stringlengths 2
100k
| meta
dict |
---|---|
/*
* Copyright © 2014 - 2020 Leipzig University (Database Research Group)
*
* 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 org.gradoop.flink.algorithms.fsm.transactional.tle.functions;
import com.google.common.collect.Sets;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.util.Collector;
import org.gradoop.flink.algorithms.fsm.transactional.tle.pojos.CCSGraph;
import org.gradoop.flink.algorithms.fsm.transactional.tle.tuples.CategoryCountableLabel;
import org.gradoop.flink.algorithms.fsm.transactional.tle.pojos.FSMEdge;
import java.util.Set;
/**
* {@code graph => (category, label, 1)}
*/
public class CategoryEdgeLabels implements
FlatMapFunction<CCSGraph, CategoryCountableLabel> {
/**
* reuse tuple to avoid instantiations
*/
private CategoryCountableLabel reuseTuple =
new CategoryCountableLabel(null, null, 1L);
@Override
public void flatMap(CCSGraph graph,
Collector<CategoryCountableLabel> out) throws Exception {
Set<String> edgeLabels =
Sets.newHashSetWithExpectedSize(graph.getEdges().size());
for (FSMEdge edge : graph.getEdges().values()) {
edgeLabels.add(edge.getLabel());
}
for (String label : edgeLabels) {
reuseTuple.setCategory(graph.getCategory());
reuseTuple.setLabel(label);
out.collect(reuseTuple);
}
}
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NLog;
using NutzCode.CloudFileSystem;
using NutzCode.CloudFileSystem.Plugins.LocalFileSystem;
using Shoko.Commons.Extensions;
using Shoko.Models;
using Shoko.Models.Client;
using Shoko.Models.Enums;
using Shoko.Models.Interfaces;
using Shoko.Models.Server;
using Shoko.Server.API.Annotations;
using Shoko.Server.Commands;
using Shoko.Server.Extensions;
using Shoko.Server.Models;
using Shoko.Server.Plex;
using Shoko.Server.Repositories;
using Shoko.Server.Server;
using Shoko.Server.Settings;
namespace Shoko.Server
{
[EmitEmptyEnumerableInsteadOfNull]
[ApiController, Route("/v1"), ApiExplorerSettings(IgnoreApi = true)]
public partial class ShokoServiceImplementation : Controller, IShokoServer, IHttpContextAccessor
{
public new HttpContext HttpContext { get; set; }
//TODO Split this file into subfiles with partial class, Move #region functionality from the interface to those subfiles
private static Logger logger = LogManager.GetCurrentClassLogger();
#region Bookmarks
[HttpGet("Bookmark")]
public List<CL_BookmarkedAnime> GetAllBookmarkedAnime()
{
List<CL_BookmarkedAnime> baList = new List<CL_BookmarkedAnime>();
try
{
return RepoFactory.BookmarkedAnime.GetAll().Select(a => a.ToClient()).ToList();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return baList;
}
[HttpPost("Bookmark")]
public CL_Response<CL_BookmarkedAnime> SaveBookmarkedAnime(CL_BookmarkedAnime contract)
{
CL_Response<CL_BookmarkedAnime> contractRet = new CL_Response<CL_BookmarkedAnime>
{
ErrorMessage = string.Empty
};
try
{
BookmarkedAnime ba = null;
if (contract.BookmarkedAnimeID != 0)
{
ba = RepoFactory.BookmarkedAnime.GetByID(contract.BookmarkedAnimeID);
if (ba == null)
{
contractRet.ErrorMessage = "Could not find existing Bookmark with ID: " +
contract.BookmarkedAnimeID;
return contractRet;
}
}
else
{
// if a new record, check if it is allowed
BookmarkedAnime baTemp = RepoFactory.BookmarkedAnime.GetByAnimeID(contract.AnimeID);
if (baTemp != null)
{
contractRet.ErrorMessage = "A bookmark with the AnimeID already exists: " +
contract.AnimeID;
return contractRet;
}
ba = new BookmarkedAnime();
}
ba.AnimeID = contract.AnimeID;
ba.Priority = contract.Priority;
ba.Notes = contract.Notes;
ba.Downloading = contract.Downloading;
RepoFactory.BookmarkedAnime.Save(ba);
contractRet.Result = ba.ToClient();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
contractRet.ErrorMessage = ex.Message;
return contractRet;
}
return contractRet;
}
[HttpDelete("Bookmark/{bookmarkedAnimeID}")]
public string DeleteBookmarkedAnime(int bookmarkedAnimeID)
{
try
{
BookmarkedAnime ba = RepoFactory.BookmarkedAnime.GetByID(bookmarkedAnimeID);
if (ba == null)
return "Bookmarked not found";
RepoFactory.BookmarkedAnime.Delete(bookmarkedAnimeID);
return string.Empty;
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
return ex.Message;
}
}
[HttpGet("Bookmark/{bookmarkedAnimeID}")]
public CL_BookmarkedAnime GetBookmarkedAnime(int bookmarkedAnimeID)
{
try
{
return RepoFactory.BookmarkedAnime.GetByID(bookmarkedAnimeID).ToClient();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
return null;
}
}
#endregion
#region Status and Changes
[HttpGet("Changes/{date}/{userID}")]
public CL_MainChanges GetAllChanges(DateTime date, int userID)
{
CL_MainChanges c = new CL_MainChanges();
try
{
List<Changes<int>> changes = ChangeTracker<int>.GetChainedChanges(new List<ChangeTracker<int>>
{
RepoFactory.GroupFilter.GetChangeTracker(),
RepoFactory.AnimeGroup.GetChangeTracker(),
RepoFactory.AnimeGroup_User.GetChangeTracker(userID),
RepoFactory.AnimeSeries.GetChangeTracker(),
RepoFactory.AnimeSeries_User.GetChangeTracker(userID)
}, date);
c.Filters = new CL_Changes<CL_GroupFilter>
{
ChangedItems = changes[0]
.ChangedItems.Select(a => RepoFactory.GroupFilter.GetByID(a)?.ToClient())
.Where(a => a != null)
.ToList(),
RemovedItems = changes[0].RemovedItems.ToList(),
LastChange = changes[0].LastChange
};
//Add Group Filter that one of his child changed.
bool end;
do
{
end = true;
foreach (CL_GroupFilter ag in c.Filters.ChangedItems
.Where(a => a.ParentGroupFilterID.HasValue && a.ParentGroupFilterID.Value != 0)
.ToList())
{
if (!c.Filters.ChangedItems.Any(a => a.GroupFilterID == ag.ParentGroupFilterID.Value))
{
end = false;
CL_GroupFilter cag = RepoFactory.GroupFilter.GetByID(ag.ParentGroupFilterID.Value)?
.ToClient();
if (cag != null)
c.Filters.ChangedItems.Add(cag);
}
}
} while (!end);
c.Groups = new CL_Changes<CL_AnimeGroup_User>();
changes[1].ChangedItems.UnionWith(changes[2].ChangedItems);
changes[1].ChangedItems.UnionWith(changes[2].RemovedItems);
if (changes[2].LastChange > changes[1].LastChange)
changes[1].LastChange = changes[2].LastChange;
c.Groups.ChangedItems = changes[1]
.ChangedItems.Select(a => RepoFactory.AnimeGroup.GetByID(a))
.Where(a => a != null)
.Select(a => a.GetUserContract(userID))
.ToList();
c.Groups.RemovedItems = changes[1].RemovedItems.ToList();
c.Groups.LastChange = changes[1].LastChange;
c.Series = new CL_Changes<CL_AnimeSeries_User>();
changes[3].ChangedItems.UnionWith(changes[4].ChangedItems);
changes[3].ChangedItems.UnionWith(changes[4].RemovedItems);
if (changes[4].LastChange > changes[3].LastChange)
changes[3].LastChange = changes[4].LastChange;
c.Series.ChangedItems = changes[3]
.ChangedItems.Select(a => RepoFactory.AnimeSeries.GetByID(a))
.Where(a => a != null)
.Select(a => a.GetUserContract(userID))
.ToList();
c.Series.RemovedItems = changes[3].RemovedItems.ToList();
c.Series.LastChange = changes[3].LastChange;
c.LastChange = c.Filters.LastChange;
if (c.Groups.LastChange > c.LastChange)
c.LastChange = c.Groups.LastChange;
if (c.Series.LastChange > c.LastChange)
c.LastChange = c.Series.LastChange;
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return c;
}
[HttpGet("GroupFilter/Changes/{date}")]
public CL_Changes<CL_GroupFilter> GetGroupFilterChanges(DateTime date)
{
CL_Changes<CL_GroupFilter> c = new CL_Changes<CL_GroupFilter>();
try
{
Changes<int> changes = RepoFactory.GroupFilter.GetChangeTracker().GetChanges(date);
c.ChangedItems = changes.ChangedItems.Select(a => RepoFactory.GroupFilter.GetByID(a).ToClient())
.Where(a => a != null)
.ToList();
c.RemovedItems = changes.RemovedItems.ToList();
c.LastChange = changes.LastChange;
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return c;
}
[DatabaseBlockedExempt]
[HttpGet("Server")]
public CL_ServerStatus GetServerStatus()
{
CL_ServerStatus contract = new CL_ServerStatus();
try
{
contract.HashQueueCount = ShokoService.CmdProcessorHasher.QueueCount;
contract.HashQueueState =
ShokoService.CmdProcessorHasher.QueueState.formatMessage(); //Deprecated since 3.6.0.0
contract.HashQueueStateId = (int) ShokoService.CmdProcessorHasher.QueueState.queueState;
contract.HashQueueStateParams = ShokoService.CmdProcessorHasher.QueueState.extraParams;
contract.GeneralQueueCount = ShokoService.CmdProcessorGeneral.QueueCount;
contract.GeneralQueueState =
ShokoService.CmdProcessorGeneral.QueueState.formatMessage(); //Deprecated since 3.6.0.0
contract.GeneralQueueStateId = (int) ShokoService.CmdProcessorGeneral.QueueState.queueState;
contract.GeneralQueueStateParams = ShokoService.CmdProcessorGeneral.QueueState.extraParams;
contract.ImagesQueueCount = ShokoService.CmdProcessorImages.QueueCount;
contract.ImagesQueueState =
ShokoService.CmdProcessorImages.QueueState.formatMessage(); //Deprecated since 3.6.0.0
contract.ImagesQueueStateId = (int) ShokoService.CmdProcessorImages.QueueState.queueState;
contract.ImagesQueueStateParams = ShokoService.CmdProcessorImages.QueueState.extraParams;
var helper = ShokoService.AnidbProcessor;
if (helper.IsHttpBanned)
{
contract.IsBanned = true;
contract.BanReason = helper.HttpBanTime.ToString();
contract.BanOrigin = @"HTTP";
}
else if (helper.IsUdpBanned)
{
contract.IsBanned = true;
contract.BanReason = helper.UdpBanTime.ToString();
contract.BanOrigin = @"UDP";
}
else
{
contract.IsBanned = false;
contract.BanReason = string.Empty;
contract.BanOrigin = string.Empty;
}
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return contract;
}
[HttpGet("Server/Versions")]
public CL_AppVersions GetAppVersions()
{
try
{
//TODO WHEN WE HAVE A STABLE VERSION REPO, WE NEED TO CODE THE RETRIEVAL HERE.
return new CL_AppVersions();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return null;
}
#endregion
[HttpGet("Years")]
public List<string> GetAllYears()
{
List<CL_AnimeSeries_User> grps =
RepoFactory.AnimeSeries.GetAll().Select(a => a.Contract).Where(a => a != null).ToList();
var allyears = new HashSet<string>(StringComparer.Ordinal);
foreach (CL_AnimeSeries_User ser in grps)
{
int endyear = ser.AniDBAnime?.AniDBAnime?.EndYear ?? 0;
int startyear = ser.AniDBAnime?.AniDBAnime?.BeginYear ?? 0;
if (startyear == 0) continue;
if (endyear == 0) endyear = DateTime.Today.Year;
if (startyear > endyear) endyear = startyear;
if (startyear == endyear)
allyears.Add(startyear.ToString());
else
allyears.UnionWith(Enumerable.Range(startyear,
endyear - startyear + 1)
.Select(a => a.ToString()));
}
return allyears.OrderBy(a => a).ToList();
}
[HttpGet("Seasons")]
public List<string> GetAllSeasons()
{
List<CL_AnimeSeries_User> grps =
RepoFactory.AnimeSeries.GetAll().Select(a => a.Contract).Where(a => a != null).ToList();
var allseasons = new SortedSet<string>(new SeasonComparator());
foreach (CL_AnimeSeries_User ser in grps)
{
allseasons.UnionWith(ser.AniDBAnime.Stat_AllSeasons);
}
return allseasons.ToList();
}
[HttpGet("Tags")]
public List<string> GetAllTagNames()
{
List<string> allTagNames = new List<string>();
try
{
DateTime start = DateTime.Now;
foreach (AniDB_Tag tag in RepoFactory.AniDB_Tag.GetAll())
{
allTagNames.Add(tag.TagName);
}
allTagNames.Sort();
TimeSpan ts = DateTime.Now - start;
logger.Info("GetAllTagNames in {0} ms", ts.TotalMilliseconds);
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return allTagNames;
}
[HttpPost("CloudAccount/Directory/{cloudaccountid}")]
public List<string> DirectoriesFromImportFolderPath(int cloudaccountid, [FromForm]string path)
{
if (path == null) path = "null";
List<string> result = new List<string>();
try
{
IFileSystem n = null;
if (cloudaccountid == 0)
{
FileSystemResult<IFileSystem> ff = CloudFileSystemPluginFactory.Instance.List
.FirstOrDefault(a => a.Name.EqualsInvariantIgnoreCase("Local File System"))
?.Init("", null, null);
if (ff?.IsOk ?? false)
n = ff.Result;
}
else
{
SVR_CloudAccount cl = RepoFactory.CloudAccount.GetByID(cloudaccountid);
if (cl != null)
n = cl.FileSystem;
}
if (n != null)
{
FileSystemResult<IObject> dirr;
if ((n as LocalFileSystem) != null && path.Equals("null"))
{
if (n.Directories == null) return result;
return n.Directories.Select(a => a.FullName).OrderByNatural(a => a).ToList();
}
if (path.Equals("null"))
{
path = string.Empty;
}
dirr = n.Resolve(path);
if (dirr == null || !dirr.IsOk || dirr.Result is IFile)
return null;
IDirectory dir = dirr.Result as IDirectory;
FileSystemResult fr = dir.Populate();
if (!fr?.IsOk ?? true)
return result;
return dir?.Directories?.Select(a => a.FullName).OrderByNatural(a => a).ToList();
}
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return result;
}
[HttpGet("CloudAccount")]
public List<CL_CloudAccount> GetCloudProviders()
{
List<CL_CloudAccount> ls = new List<CL_CloudAccount>();
try
{
ls.Add(SVR_CloudAccount.CreateLocalFileSystemAccount().ToClient());
RepoFactory.CloudAccount.GetAll().ForEach(a => ls.Add(a.ToClient()));
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return ls;
}
#region Settings
[HttpPost("Server/Settings")]
public CL_Response SaveServerSettings(CL_ServerSettings contractIn)
{
CL_Response contract = new CL_Response
{
ErrorMessage = string.Empty
};
try
{
// validate the settings
bool anidbSettingsChanged = false;
if (ushort.TryParse(contractIn.AniDB_ClientPort, out ushort newAniDB_ClientPort) && newAniDB_ClientPort != ServerSettings.Instance.AniDb.ClientPort)
{
anidbSettingsChanged = true;
contract.ErrorMessage += "AniDB Client Port must be numeric and greater than 0" +
Environment.NewLine;
}
if (ushort.TryParse(contractIn.AniDB_ServerPort, out ushort newAniDB_ServerPort) && newAniDB_ServerPort != ServerSettings.Instance.AniDb.ServerPort)
{
anidbSettingsChanged = true;
contract.ErrorMessage += "AniDB Server Port must be numeric and greater than 0" +
Environment.NewLine;
}
if (contractIn.AniDB_Username != ServerSettings.Instance.AniDb.Username)
{
anidbSettingsChanged = true;
if (string.IsNullOrEmpty(contractIn.AniDB_Username))
{
contract.ErrorMessage += "AniDB User Name must have a value" + Environment.NewLine;
}
}
if (contractIn.AniDB_Password != ServerSettings.Instance.AniDb.Password)
{
anidbSettingsChanged = true;
if (string.IsNullOrEmpty(contractIn.AniDB_Password))
{
contract.ErrorMessage += "AniDB Password must have a value" + Environment.NewLine;
}
}
if (contractIn.AniDB_ServerAddress != ServerSettings.Instance.AniDb.ServerAddress)
{
anidbSettingsChanged = true;
if (string.IsNullOrEmpty(contractIn.AniDB_ServerAddress))
{
contract.ErrorMessage += "AniDB Server Address must have a value" + Environment.NewLine;
}
}
if (!ushort.TryParse(contractIn.AniDB_AVDumpClientPort, out ushort newAniDB_AVDumpClientPort))
{
contract.ErrorMessage += "AniDB AVDump port must be a valid port" + Environment.NewLine;
}
if (contract.ErrorMessage.Length > 0) return contract;
ServerSettings.Instance.AniDb.ClientPort = newAniDB_ClientPort;
ServerSettings.Instance.AniDb.Password = contractIn.AniDB_Password;
ServerSettings.Instance.AniDb.ServerAddress = contractIn.AniDB_ServerAddress;
ServerSettings.Instance.AniDb.ServerPort = newAniDB_ServerPort;
ServerSettings.Instance.AniDb.Username = contractIn.AniDB_Username;
ServerSettings.Instance.AniDb.AVDumpClientPort = newAniDB_AVDumpClientPort;
ServerSettings.Instance.AniDb.AVDumpKey = contractIn.AniDB_AVDumpKey;
ServerSettings.Instance.AniDb.DownloadRelatedAnime = contractIn.AniDB_DownloadRelatedAnime;
ServerSettings.Instance.AniDb.DownloadReleaseGroups = contractIn.AniDB_DownloadReleaseGroups;
ServerSettings.Instance.AniDb.DownloadReviews = contractIn.AniDB_DownloadReviews;
ServerSettings.Instance.AniDb.DownloadSimilarAnime = contractIn.AniDB_DownloadSimilarAnime;
ServerSettings.Instance.AniDb.MyList_AddFiles = contractIn.AniDB_MyList_AddFiles;
ServerSettings.Instance.AniDb.MyList_ReadUnwatched = contractIn.AniDB_MyList_ReadUnwatched;
ServerSettings.Instance.AniDb.MyList_ReadWatched = contractIn.AniDB_MyList_ReadWatched;
ServerSettings.Instance.AniDb.MyList_SetUnwatched = contractIn.AniDB_MyList_SetUnwatched;
ServerSettings.Instance.AniDb.MyList_SetWatched = contractIn.AniDB_MyList_SetWatched;
ServerSettings.Instance.AniDb.MyList_StorageState = (AniDBFile_State) contractIn.AniDB_MyList_StorageState;
ServerSettings.Instance.AniDb.MyList_DeleteType = (AniDBFileDeleteType) contractIn.AniDB_MyList_DeleteType;
//ServerSettings.Instance.AniDb.MaxRelationDepth = contractIn.AniDB_MaxRelationDepth;
ServerSettings.Instance.AniDb.MyList_UpdateFrequency =
(ScheduledUpdateFrequency) contractIn.AniDB_MyList_UpdateFrequency;
ServerSettings.Instance.AniDb.Calendar_UpdateFrequency =
(ScheduledUpdateFrequency) contractIn.AniDB_Calendar_UpdateFrequency;
ServerSettings.Instance.AniDb.Anime_UpdateFrequency =
(ScheduledUpdateFrequency) contractIn.AniDB_Anime_UpdateFrequency;
ServerSettings.Instance.AniDb.MyListStats_UpdateFrequency =
(ScheduledUpdateFrequency) contractIn.AniDB_MyListStats_UpdateFrequency;
ServerSettings.Instance.AniDb.File_UpdateFrequency =
(ScheduledUpdateFrequency) contractIn.AniDB_File_UpdateFrequency;
ServerSettings.Instance.AniDb.DownloadCharacters = contractIn.AniDB_DownloadCharacters;
ServerSettings.Instance.AniDb.DownloadCreators = contractIn.AniDB_DownloadCreators;
// Web Cache
ServerSettings.Instance.WebCache.Address = contractIn.WebCache_Address;
ServerSettings.Instance.WebCache.XRefFileEpisode_Get = contractIn.WebCache_XRefFileEpisode_Get;
ServerSettings.Instance.WebCache.XRefFileEpisode_Send = contractIn.WebCache_XRefFileEpisode_Send;
ServerSettings.Instance.WebCache.TvDB_Get = contractIn.WebCache_TvDB_Get;
ServerSettings.Instance.WebCache.TvDB_Send = contractIn.WebCache_TvDB_Send;
ServerSettings.Instance.WebCache.Trakt_Get = contractIn.WebCache_Trakt_Get;
ServerSettings.Instance.WebCache.Trakt_Send = contractIn.WebCache_Trakt_Send;
// TvDB
ServerSettings.Instance.TvDB.AutoLink = contractIn.TvDB_AutoLink;
ServerSettings.Instance.TvDB.AutoFanart = contractIn.TvDB_AutoFanart;
ServerSettings.Instance.TvDB.AutoFanartAmount = contractIn.TvDB_AutoFanartAmount;
ServerSettings.Instance.TvDB.AutoPosters = contractIn.TvDB_AutoPosters;
ServerSettings.Instance.TvDB.AutoPostersAmount = contractIn.TvDB_AutoPostersAmount;
ServerSettings.Instance.TvDB.AutoWideBanners = contractIn.TvDB_AutoWideBanners;
ServerSettings.Instance.TvDB.AutoWideBannersAmount = contractIn.TvDB_AutoWideBannersAmount;
ServerSettings.Instance.TvDB.UpdateFrequency = (ScheduledUpdateFrequency) contractIn.TvDB_UpdateFrequency;
ServerSettings.Instance.TvDB.Language = contractIn.TvDB_Language;
// MovieDB
ServerSettings.Instance.MovieDb.AutoFanart = contractIn.MovieDB_AutoFanart;
ServerSettings.Instance.MovieDb.AutoFanartAmount = contractIn.MovieDB_AutoFanartAmount;
ServerSettings.Instance.MovieDb.AutoPosters = contractIn.MovieDB_AutoPosters;
ServerSettings.Instance.MovieDb.AutoPostersAmount = contractIn.MovieDB_AutoPostersAmount;
// Import settings
ServerSettings.Instance.Import.VideoExtensions = contractIn.VideoExtensions.Split(',').ToList();
ServerSettings.Instance.Import.UseExistingFileWatchedStatus = contractIn.Import_UseExistingFileWatchedStatus;
ServerSettings.Instance.AutoGroupSeries = contractIn.AutoGroupSeries;
ServerSettings.Instance.AutoGroupSeriesUseScoreAlgorithm = contractIn.AutoGroupSeriesUseScoreAlgorithm;
ServerSettings.Instance.AutoGroupSeriesRelationExclusions = contractIn.AutoGroupSeriesRelationExclusions;
ServerSettings.Instance.FileQualityFilterEnabled = contractIn.FileQualityFilterEnabled;
if (!string.IsNullOrEmpty(contractIn.FileQualityFilterPreferences))
ServerSettings.Instance.FileQualityPreferences =
ServerSettings.Deserialize<FileQualityPreferences>(contractIn.FileQualityFilterPreferences);
ServerSettings.Instance.Import.RunOnStart = contractIn.RunImportOnStart;
ServerSettings.Instance.Import.ScanDropFoldersOnStart = contractIn.ScanDropFoldersOnStart;
ServerSettings.Instance.Import.Hash_CRC32 = contractIn.Hash_CRC32;
ServerSettings.Instance.Import.Hash_MD5 = contractIn.Hash_MD5;
ServerSettings.Instance.Import.Hash_SHA1 = contractIn.Hash_SHA1;
// Language
ServerSettings.Instance.LanguagePreference = contractIn.LanguagePreference.Split(',').ToList();
ServerSettings.Instance.LanguageUseSynonyms = contractIn.LanguageUseSynonyms;
ServerSettings.Instance.EpisodeTitleSource = (DataSourceType) contractIn.EpisodeTitleSource;
ServerSettings.Instance.SeriesDescriptionSource = (DataSourceType) contractIn.SeriesDescriptionSource;
ServerSettings.Instance.SeriesNameSource = (DataSourceType) contractIn.SeriesNameSource;
// Trakt
ServerSettings.Instance.TraktTv.Enabled = contractIn.Trakt_IsEnabled;
ServerSettings.Instance.TraktTv.AuthToken = contractIn.Trakt_AuthToken;
ServerSettings.Instance.TraktTv.RefreshToken = contractIn.Trakt_RefreshToken;
ServerSettings.Instance.TraktTv.TokenExpirationDate = contractIn.Trakt_TokenExpirationDate;
ServerSettings.Instance.TraktTv.UpdateFrequency = (ScheduledUpdateFrequency) contractIn.Trakt_UpdateFrequency;
ServerSettings.Instance.TraktTv.SyncFrequency = (ScheduledUpdateFrequency) contractIn.Trakt_SyncFrequency;
//Plex
ServerSettings.Instance.Plex.Server = contractIn.Plex_ServerHost;
ServerSettings.Instance.Plex.Libraries = contractIn.Plex_Sections.Length > 0
? contractIn.Plex_Sections.Split(',').Select(int.Parse).ToArray()
: new int[0];
// SAVE!
ServerSettings.Instance.SaveSettings();
if (anidbSettingsChanged)
{
ShokoService.AnidbProcessor.ForceLogout();
ShokoService.AnidbProcessor.CloseConnections();
Thread.Sleep(1000);
ShokoService.AnidbProcessor.Init(ServerSettings.Instance.AniDb.Username, ServerSettings.Instance.AniDb.Password,
ServerSettings.Instance.AniDb.ServerAddress,
ServerSettings.Instance.AniDb.ServerPort, ServerSettings.Instance.AniDb.ClientPort);
}
}
catch (Exception ex)
{
logger.Error(ex, "Save server settings exception:\n " + ex);
contract.ErrorMessage = ex.Message;
}
return contract;
}
[HttpGet("Server/Settings")]
public CL_ServerSettings GetServerSettings()
{
CL_ServerSettings contract = new CL_ServerSettings();
try
{
return ServerSettings.Instance.ToContract();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return contract;
}
#endregion
#region Actions
[HttpPost("Folder/Import")]
public void RunImport()
{
ShokoServer.RunImport();
}
[HttpPost("File/Hashes/Sync")]
public void SyncHashes()
{
ShokoServer.SyncHashes();
}
[HttpPost("Folder/Scan")]
public void ScanDropFolders()
{
Importer.RunImport_DropFolders();
}
[HttpPost("Folder/Scan/{importFolderID}")]
public void ScanFolder(int importFolderID)
{
ShokoServer.ScanFolder(importFolderID);
}
[HttpPost("Folder/RemoveMissing")]
public void RemoveMissingFiles()
{
ShokoServer.RemoveMissingFiles();
}
[HttpPost("Folder/RefreshMediaInfo")]
public void RefreshAllMediaInfo()
{
ShokoServer.RefreshAllMediaInfo();
}
[HttpPost("AniDB/MyList/Sync")]
public void SyncMyList()
{
ShokoServer.SyncMyList();
}
[HttpPost("AniDB/Vote/Sync")]
public void SyncVotes()
{
CommandRequest_SyncMyVotes cmdVotes = new CommandRequest_SyncMyVotes();
cmdVotes.Save();
}
#endregion
#region Queue Actions
[HttpPost("CommandQueue/Hasher/{paused}")]
public void SetCommandProcessorHasherPaused(bool paused)
{
ShokoService.CmdProcessorHasher.Paused = paused;
}
[HttpPost("CommandQueue/General/{paused}")]
public void SetCommandProcessorGeneralPaused(bool paused)
{
ShokoService.CmdProcessorGeneral.Paused = paused;
}
[HttpPost("CommandQueue/Images/{paused}")]
public void SetCommandProcessorImagesPaused(bool paused)
{
ShokoService.CmdProcessorImages.Paused = paused;
}
[HttpDelete("CommandQueue/Hasher")]
public void ClearHasherQueue()
{
try
{
ShokoService.CmdProcessorHasher.Stop();
RepoFactory.CommandRequest.ClearHasherQueue();
ShokoService.CmdProcessorHasher.Init();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
}
[HttpDelete("CommandQueue/Images")]
public void ClearImagesQueue()
{
try
{
ShokoService.CmdProcessorImages.Stop();
RepoFactory.CommandRequest.ClearImageQueue();
ShokoService.CmdProcessorImages.Init();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
}
[HttpDelete("CommandQueue/General")]
public void ClearGeneralQueue()
{
try
{
ShokoService.CmdProcessorGeneral.Stop();
RepoFactory.CommandRequest.ClearGeneralQueue();
ShokoService.CmdProcessorGeneral.Init();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
}
#endregion
[HttpPost("AniDB/Status")]
public string TestAniDBConnection()
{
string log = string.Empty;
try
{
log += "Disposing..." + Environment.NewLine;
ShokoService.AnidbProcessor.ForceLogout();
ShokoService.AnidbProcessor.CloseConnections();
Thread.Sleep(1000);
log += "Init..." + Environment.NewLine;
ShokoService.AnidbProcessor.Init(ServerSettings.Instance.AniDb.Username, ServerSettings.Instance.AniDb.Password,
ServerSettings.Instance.AniDb.ServerAddress,
ServerSettings.Instance.AniDb.ServerPort, ServerSettings.Instance.AniDb.ClientPort);
log += "Login..." + Environment.NewLine;
if (ShokoService.AnidbProcessor.Login())
{
log += "Login Success!" + Environment.NewLine;
log += "Logout..." + Environment.NewLine;
ShokoService.AnidbProcessor.ForceLogout();
log += "Logged out" + Environment.NewLine;
}
else
{
log += "Login FAILED!" + Environment.NewLine;
}
return log;
}
catch (Exception ex)
{
log += ex.Message + Environment.NewLine;
}
return log;
}
[HttpGet("MediaInfo/Quality")]
public List<string> GetAllUniqueVideoQuality()
{
try
{
return RepoFactory.Adhoc.GetAllVideoQuality();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
return new List<string>();
}
}
[HttpGet("MediaInfo/AudioLanguages")]
public List<string> GetAllUniqueAudioLanguages()
{
try
{
return RepoFactory.Adhoc.GetAllUniqueAudioLanguages();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
return new List<string>();
}
}
[HttpGet("MediaInfo/SubtitleLanguages")]
public List<string> GetAllUniqueSubtitleLanguages()
{
try
{
return RepoFactory.Adhoc.GetAllUniqueSubtitleLanguages();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
return new List<string>();
}
}
#region Plex
[HttpGet("User/Plex/LoginUrl/{userID}")]
public string LoginUrl(int userID)
{
JMMUser user = RepoFactory.JMMUser.GetByID(userID);
return PlexHelper.GetForUser(user).LoginUrl;
}
[HttpGet("User/Plex/Authenticated/{userID}")]
public bool IsPlexAuthenticated(int userID)
{
JMMUser user = RepoFactory.JMMUser.GetByID(userID);
return PlexHelper.GetForUser(user).IsAuthenticated;
}
[HttpGet("User/Plex/Remove/{userID}")]
public bool RemovePlexAuth(int userID)
{
JMMUser user = RepoFactory.JMMUser.GetByID(userID);
PlexHelper.GetForUser(user).InvalidateToken();
return true;
}
#endregion
[HttpPost("Image/Enable/{enabled}/{imageID}/{imageType}")]
public string EnableDisableImage(bool enabled, int imageID, int imageType)
{
try
{
ImageEntityType imgType = (ImageEntityType) imageType;
switch (imgType)
{
case ImageEntityType.AniDB_Cover:
SVR_AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(imageID);
if (anime == null) return "Could not find anime";
anime.ImageEnabled = enabled ? 1 : 0;
RepoFactory.AniDB_Anime.Save(anime);
break;
case ImageEntityType.TvDB_Banner:
TvDB_ImageWideBanner banner = RepoFactory.TvDB_ImageWideBanner.GetByID(imageID);
if (banner == null) return "Could not find image";
banner.Enabled = enabled ? 1 : 0;
RepoFactory.TvDB_ImageWideBanner.Save(banner);
break;
case ImageEntityType.TvDB_Cover:
TvDB_ImagePoster poster = RepoFactory.TvDB_ImagePoster.GetByID(imageID);
if (poster == null) return "Could not find image";
poster.Enabled = enabled ? 1 : 0;
RepoFactory.TvDB_ImagePoster.Save(poster);
break;
case ImageEntityType.TvDB_FanArt:
TvDB_ImageFanart fanart = RepoFactory.TvDB_ImageFanart.GetByID(imageID);
if (fanart == null) return "Could not find image";
fanart.Enabled = enabled ? 1 : 0;
RepoFactory.TvDB_ImageFanart.Save(fanart);
break;
case ImageEntityType.MovieDB_Poster:
MovieDB_Poster moviePoster = RepoFactory.MovieDB_Poster.GetByID(imageID);
if (moviePoster == null) return "Could not find image";
moviePoster.Enabled = enabled ? 1 : 0;
RepoFactory.MovieDB_Poster.Save(moviePoster);
break;
case ImageEntityType.MovieDB_FanArt:
MovieDB_Fanart movieFanart = RepoFactory.MovieDB_Fanart.GetByID(imageID);
if (movieFanart == null) return "Could not find image";
movieFanart.Enabled = enabled ? 1 : 0;
RepoFactory.MovieDB_Fanart.Save(movieFanart);
break;
}
return string.Empty;
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
return ex.Message;
}
}
[HttpPost("Image/Default/{isDefault}/{animeID}/{imageID}/{imageType}/{imageSizeType}")]
public string SetDefaultImage(bool isDefault, int animeID, int imageID, int imageType, int imageSizeType)
{
try
{
ImageEntityType imgType = (ImageEntityType) imageType;
ImageSizeType sizeType = ImageSizeType.Poster;
switch (imgType)
{
case ImageEntityType.AniDB_Cover:
case ImageEntityType.TvDB_Cover:
case ImageEntityType.MovieDB_Poster:
sizeType = ImageSizeType.Poster;
break;
case ImageEntityType.TvDB_Banner:
sizeType = ImageSizeType.WideBanner;
break;
case ImageEntityType.TvDB_FanArt:
case ImageEntityType.MovieDB_FanArt:
sizeType = ImageSizeType.Fanart;
break;
}
if (!isDefault)
{
// this mean we are removing an image as deafult
// which esssential means deleting the record
AniDB_Anime_DefaultImage img =
RepoFactory.AniDB_Anime_DefaultImage.GetByAnimeIDAndImagezSizeType(animeID, (int) sizeType);
if (img != null)
RepoFactory.AniDB_Anime_DefaultImage.Delete(img.AniDB_Anime_DefaultImageID);
}
else
{
// making the image the default for it's type (poster, fanart etc)
AniDB_Anime_DefaultImage img =
RepoFactory.AniDB_Anime_DefaultImage.GetByAnimeIDAndImagezSizeType(animeID, (int) sizeType);
if (img == null)
img = new AniDB_Anime_DefaultImage();
img.AnimeID = animeID;
img.ImageParentID = imageID;
img.ImageParentType = (int) imgType;
img.ImageType = (int) sizeType;
RepoFactory.AniDB_Anime_DefaultImage.Save(img);
}
SVR_AnimeSeries series = RepoFactory.AnimeSeries.GetByAnimeID(animeID);
RepoFactory.AnimeSeries.Save(series, false);
return string.Empty;
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
return ex.Message;
}
}
#region Calendar (Dashboard)
[HttpGet("AniDB/Anime/Calendar/{userID}/{numberOfDays}")]
public List<CL_AniDB_Anime> GetMiniCalendar(int userID, int numberOfDays)
{
// get all the series
List<CL_AniDB_Anime> animeList = new List<CL_AniDB_Anime>();
try
{
SVR_JMMUser user = RepoFactory.JMMUser.GetByID(userID);
if (user == null) return animeList;
List<SVR_AniDB_Anime> animes = RepoFactory.AniDB_Anime.GetForDate(
DateTime.Today.AddDays(0 - numberOfDays),
DateTime.Today.AddDays(numberOfDays));
foreach (SVR_AniDB_Anime anime in animes)
{
if (anime?.Contract?.AniDBAnime == null)
continue;
if (!user.GetHideCategories().FindInEnumerable(anime.Contract.AniDBAnime.GetAllTags()))
animeList.Add(anime.Contract.AniDBAnime);
}
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return animeList;
}
[HttpGet("AniDB/Anime/ForMonth/{userID}/{month}/{year}")]
public List<CL_AniDB_Anime> GetAnimeForMonth(int userID, int month, int year)
{
// get all the series
List<CL_AniDB_Anime> animeList = new List<CL_AniDB_Anime>();
try
{
SVR_JMMUser user = RepoFactory.JMMUser.GetByID(userID);
if (user == null) return animeList;
DateTime startDate = new DateTime(year, month, 1, 0, 0, 0);
DateTime endDate = startDate.AddMonths(1);
endDate = endDate.AddMinutes(-10);
List<SVR_AniDB_Anime> animes = RepoFactory.AniDB_Anime.GetForDate(startDate, endDate);
foreach (SVR_AniDB_Anime anime in animes)
{
if (anime?.Contract?.AniDBAnime == null)
continue;
if (!user.GetHideCategories().FindInEnumerable(anime.Contract.AniDBAnime.GetAllTags()))
animeList.Add(anime.Contract.AniDBAnime);
}
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return animeList;
}
[HttpPost("AniDB/Anime/Calendar/Update")]
public string UpdateCalendarData()
{
try
{
Importer.CheckForCalendarUpdate(true);
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return string.Empty;
}
/*public List<Contract_AniDBAnime> GetMiniCalendar(int numberOfDays)
{
AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
JMMUserRepository repUsers = new JMMUserRepository();
// get all the series
List<Contract_AniDBAnime> animeList = new List<Contract_AniDBAnime>();
try
{
List<AniDB_Anime> animes = repAnime.GetForDate(DateTime.Today.AddDays(0 - numberOfDays), DateTime.Today.AddDays(numberOfDays));
foreach (AniDB_Anime anime in animes)
{
animeList.Add(anime.ToContract());
}
}
catch (Exception ex)
{
logger.Error( ex,ex.ToString());
}
return animeList;
}*/
#endregion
/// <summary>
/// Returns a list of recommendations based on the users votes
/// </summary>
/// <param name="maxResults"></param>
/// <param name="userID"></param>
/// <param name="recommendationType">1 = to watch, 2 = to download</param>
[HttpGet("Recommendation/{maxResults}/{userID}/{recommendationType}")]
public List<CL_Recommendation> GetRecommendations(int maxResults, int userID, int recommendationType)
{
List<CL_Recommendation> recs = new List<CL_Recommendation>();
try
{
SVR_JMMUser juser = RepoFactory.JMMUser.GetByID(userID);
if (juser == null) return recs;
// get all the anime the user has chosen to ignore
int ignoreType = 1;
switch (recommendationType)
{
case 1:
ignoreType = 1;
break;
case 2:
ignoreType = 2;
break;
}
List<IgnoreAnime> ignored = RepoFactory.IgnoreAnime.GetByUserAndType(userID, ignoreType);
Dictionary<int, IgnoreAnime> dictIgnored = new Dictionary<int, IgnoreAnime>();
foreach (IgnoreAnime ign in ignored)
dictIgnored[ign.AnimeID] = ign;
// find all the series which the user has rated
List<AniDB_Vote> allVotes = RepoFactory.AniDB_Vote.GetAll()
.OrderByDescending(a => a.VoteValue)
.ToList();
if (allVotes.Count == 0) return recs;
Dictionary<int, CL_Recommendation> dictRecs = new Dictionary<int, CL_Recommendation>();
List<AniDB_Vote> animeVotes = new List<AniDB_Vote>();
foreach (AniDB_Vote vote in allVotes)
{
if (vote.VoteType != (int) AniDBVoteType.Anime &&
vote.VoteType != (int) AniDBVoteType.AnimeTemp)
continue;
if (dictIgnored.ContainsKey(vote.EntityID)) continue;
// check if the user has this anime
SVR_AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(vote.EntityID);
if (anime == null) continue;
// get similar anime
List<AniDB_Anime_Similar> simAnime = anime.GetSimilarAnime()
.OrderByDescending(a => a.GetApprovalPercentage())
.ToList();
// sort by the highest approval
foreach (AniDB_Anime_Similar link in simAnime)
{
if (dictIgnored.ContainsKey(link.SimilarAnimeID)) continue;
SVR_AniDB_Anime animeLink = RepoFactory.AniDB_Anime.GetByAnimeID(link.SimilarAnimeID);
if (animeLink != null)
if (!juser.AllowedAnime(animeLink)) continue;
// don't recommend to watch anime that the user doesn't have
if (animeLink == null && recommendationType == 1) continue;
// don't recommend to watch series that the user doesn't have
SVR_AnimeSeries ser = RepoFactory.AnimeSeries.GetByAnimeID(link.SimilarAnimeID);
if (ser == null && recommendationType == 1) continue;
if (ser != null)
{
// don't recommend to watch series that the user has already started watching
AnimeSeries_User userRecord = ser.GetUserRecord(userID);
if (userRecord != null)
{
if (userRecord.WatchedEpisodeCount > 0 && recommendationType == 1) continue;
}
// don't recommend to download anime that the user has files for
if (ser.LatestLocalEpisodeNumber > 0 && recommendationType == 2) continue;
}
CL_Recommendation rec = new CL_Recommendation
{
BasedOnAnimeID = anime.AnimeID,
RecommendedAnimeID = link.SimilarAnimeID
};
// if we don't have the anime locally. lets assume the anime has a high rating
decimal animeRating = 850;
if (animeLink != null) animeRating = animeLink.GetAniDBRating();
rec.Score =
CalculateRecommendationScore(vote.VoteValue, link.GetApprovalPercentage(), animeRating);
rec.BasedOnVoteValue = vote.VoteValue;
rec.RecommendedApproval = link.GetApprovalPercentage();
// check if we have added this recommendation before
// this might happen where animes are recommended based on different votes
// and could end up with different scores
if (dictRecs.ContainsKey(rec.RecommendedAnimeID))
{
if (rec.Score < dictRecs[rec.RecommendedAnimeID].Score) continue;
}
rec.Recommended_AniDB_Anime = null;
if (animeLink != null)
rec.Recommended_AniDB_Anime = animeLink.Contract.AniDBAnime;
rec.BasedOn_AniDB_Anime = anime.Contract.AniDBAnime;
rec.Recommended_AnimeSeries = null;
if (ser != null)
rec.Recommended_AnimeSeries = ser.GetUserContract(userID);
SVR_AnimeSeries serBasedOn = RepoFactory.AnimeSeries.GetByAnimeID(anime.AnimeID);
if (serBasedOn == null) continue;
rec.BasedOn_AnimeSeries = serBasedOn.GetUserContract(userID);
dictRecs[rec.RecommendedAnimeID] = rec;
}
}
List<CL_Recommendation> tempRecs = new List<CL_Recommendation>();
foreach (CL_Recommendation rec in dictRecs.Values)
tempRecs.Add(rec);
// sort by the highest score
int numRecs = 0;
foreach (CL_Recommendation rec in tempRecs.OrderByDescending(a => a.Score))
{
if (numRecs == maxResults) break;
recs.Add(rec);
numRecs++;
}
if (recs.Count == 0) return recs;
return recs;
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
return recs;
}
}
private double CalculateRecommendationScore(int userVoteValue, double approvalPercentage, decimal animeRating)
{
double score = userVoteValue;
score = score + approvalPercentage;
if (approvalPercentage > 90) score = score + 100;
if (approvalPercentage > 80) score = score + 100;
if (approvalPercentage > 70) score = score + 100;
if (approvalPercentage > 60) score = score + 100;
if (approvalPercentage > 50) score = score + 100;
if (animeRating > 900) score = score + 100;
if (animeRating > 800) score = score + 100;
if (animeRating > 700) score = score + 100;
if (animeRating > 600) score = score + 100;
if (animeRating > 500) score = score + 100;
return score;
}
[HttpGet("AniDB/ReleaseGroup/{animeID}")]
public List<CL_AniDB_GroupStatus> GetReleaseGroupsForAnime(int animeID)
{
List<CL_AniDB_GroupStatus> relGroups = new List<CL_AniDB_GroupStatus>();
try
{
SVR_AnimeSeries series = RepoFactory.AnimeSeries.GetByAnimeID(animeID);
if (series == null) return relGroups;
// get a list of all the release groups the user is collecting
//List<int> userReleaseGroups = new List<int>();
Dictionary<int, int> userReleaseGroups = new Dictionary<int, int>();
foreach (SVR_AnimeEpisode ep in series.GetAnimeEpisodes())
{
List<SVR_VideoLocal> vids = ep.GetVideoLocals();
List<string> hashes = vids.Where(a => !string.IsNullOrEmpty(a.Hash)).Select(a => a.Hash).ToList();
foreach (string h in hashes)
{
SVR_VideoLocal vid = vids.First(a => a.Hash == h);
AniDB_File anifile = vid.GetAniDBFile();
if (anifile != null)
{
if (!userReleaseGroups.ContainsKey(anifile.GroupID))
userReleaseGroups[anifile.GroupID] = 0;
userReleaseGroups[anifile.GroupID] = userReleaseGroups[anifile.GroupID] + 1;
}
}
}
// get all the release groups for this series
List<AniDB_GroupStatus> grpStatuses = RepoFactory.AniDB_GroupStatus.GetByAnimeID(animeID);
foreach (AniDB_GroupStatus gs in grpStatuses)
{
CL_AniDB_GroupStatus cl = gs.ToClient();
if (userReleaseGroups.ContainsKey(gs.GroupID))
{
cl.UserCollecting = true;
cl.FileCount = userReleaseGroups[gs.GroupID];
}
else
{
cl.UserCollecting = false;
cl.FileCount = 0;
}
relGroups.Add(cl);
}
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return relGroups;
}
[HttpGet("AniDB/Character/{animeID}")]
public List<CL_AniDB_Character> GetCharactersForAnime(int animeID)
{
List<CL_AniDB_Character> chars = new List<CL_AniDB_Character>();
try
{
SVR_AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(animeID);
return anime.GetCharactersContract();
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return chars;
}
[HttpGet("AniDB/Character/FromSeiyuu/{seiyuuID}")]
public List<CL_AniDB_Character> GetCharactersForSeiyuu(int seiyuuID)
{
List<CL_AniDB_Character> chars = new List<CL_AniDB_Character>();
try
{
AniDB_Seiyuu seiyuu = RepoFactory.AniDB_Seiyuu.GetByID(seiyuuID);
if (seiyuu == null) return chars;
List<AniDB_Character_Seiyuu> links = RepoFactory.AniDB_Character_Seiyuu.GetBySeiyuuID(seiyuu.SeiyuuID);
foreach (AniDB_Character_Seiyuu chrSei in links)
{
AniDB_Character chr = RepoFactory.AniDB_Character.GetByID(chrSei.CharID);
if (chr != null)
{
List<AniDB_Anime_Character> aniChars =
RepoFactory.AniDB_Anime_Character.GetByCharID(chr.CharID);
if (aniChars.Count > 0)
{
SVR_AniDB_Anime anime = RepoFactory.AniDB_Anime.GetByAnimeID(aniChars[0].AnimeID);
if (anime != null)
{
CL_AniDB_Character cl = chr.ToClient(aniChars[0].CharType);
chars.Add(cl);
}
}
}
}
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return chars;
}
[HttpGet("AniDB/Seiyuu/{seiyuuID}")]
public AniDB_Seiyuu GetAniDBSeiyuu(int seiyuuID)
{
try
{
return RepoFactory.AniDB_Seiyuu.GetByID(seiyuuID);
}
catch (Exception ex)
{
logger.Error(ex, ex.ToString());
}
return null;
}
}
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright 2014 Google Inc.
*
* 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.
*/
/**
* A task runner with exponential backoff support.
*
* @see https://developers.google.com/drive/web/handle-errors#implementing_exponential_backoff
*/
class Google_Task_Runner
{
const TASK_RETRY_NEVER = 0;
const TASK_RETRY_ONCE = 1;
const TASK_RETRY_ALWAYS = -1;
/**
* @var integer $maxDelay The max time (in seconds) to wait before a retry.
*/
private $maxDelay = 60;
/**
* @var integer $delay The previous delay from which the next is calculated.
*/
private $delay = 1;
/**
* @var integer $factor The base number for the exponential back off.
*/
private $factor = 2;
/**
* @var float $jitter A random number between -$jitter and $jitter will be
* added to $factor on each iteration to allow for a better distribution of
* retries.
*/
private $jitter = 0.5;
/**
* @var integer $attempts The number of attempts that have been tried so far.
*/
private $attempts = 0;
/**
* @var integer $maxAttempts The max number of attempts allowed.
*/
private $maxAttempts = 1;
/**
* @var callable $action The task to run and possibly retry.
*/
private $action;
/**
* @var array $arguments The task arguments.
*/
private $arguments;
/**
* @var array $retryMap Map of errors with retry counts.
*/
protected $retryMap = [
'500' => self::TASK_RETRY_ALWAYS,
'503' => self::TASK_RETRY_ALWAYS,
'rateLimitExceeded' => self::TASK_RETRY_ALWAYS,
'userRateLimitExceeded' => self::TASK_RETRY_ALWAYS,
6 => self::TASK_RETRY_ALWAYS, // CURLE_COULDNT_RESOLVE_HOST
7 => self::TASK_RETRY_ALWAYS, // CURLE_COULDNT_CONNECT
28 => self::TASK_RETRY_ALWAYS, // CURLE_OPERATION_TIMEOUTED
35 => self::TASK_RETRY_ALWAYS, // CURLE_SSL_CONNECT_ERROR
52 => self::TASK_RETRY_ALWAYS // CURLE_GOT_NOTHING
];
/**
* Creates a new task runner with exponential backoff support.
*
* @param array $config The task runner config
* @param string $name The name of the current task (used for logging)
* @param callable $action The task to run and possibly retry
* @param array $arguments The task arguments
* @throws Google_Task_Exception when misconfigured
*/
public function __construct(
$config,
$name,
$action,
array $arguments = array()
) {
if (isset($config['initial_delay'])) {
if ($config['initial_delay'] < 0) {
throw new Google_Task_Exception(
'Task configuration `initial_delay` must not be negative.'
);
}
$this->delay = $config['initial_delay'];
}
if (isset($config['max_delay'])) {
if ($config['max_delay'] <= 0) {
throw new Google_Task_Exception(
'Task configuration `max_delay` must be greater than 0.'
);
}
$this->maxDelay = $config['max_delay'];
}
if (isset($config['factor'])) {
if ($config['factor'] <= 0) {
throw new Google_Task_Exception(
'Task configuration `factor` must be greater than 0.'
);
}
$this->factor = $config['factor'];
}
if (isset($config['jitter'])) {
if ($config['jitter'] <= 0) {
throw new Google_Task_Exception(
'Task configuration `jitter` must be greater than 0.'
);
}
$this->jitter = $config['jitter'];
}
if (isset($config['retries'])) {
if ($config['retries'] < 0) {
throw new Google_Task_Exception(
'Task configuration `retries` must not be negative.'
);
}
$this->maxAttempts += $config['retries'];
}
if (!is_callable($action)) {
throw new Google_Task_Exception(
'Task argument `$action` must be a valid callable.'
);
}
$this->action = $action;
$this->arguments = $arguments;
}
/**
* Checks if a retry can be attempted.
*
* @return boolean
*/
public function canAttempt()
{
return $this->attempts < $this->maxAttempts;
}
/**
* Runs the task and (if applicable) automatically retries when errors occur.
*
* @return mixed
* @throws Google_Task_Retryable on failure when no retries are available.
*/
public function run()
{
while ($this->attempt()) {
try {
return call_user_func_array($this->action, $this->arguments);
} catch (Google_Service_Exception $exception) {
$allowedRetries = $this->allowedRetries(
$exception->getCode(),
$exception->getErrors()
);
if (!$this->canAttempt() || !$allowedRetries) {
throw $exception;
}
if ($allowedRetries > 0) {
$this->maxAttempts = min(
$this->maxAttempts,
$this->attempts + $allowedRetries
);
}
}
}
}
/**
* Runs a task once, if possible. This is useful for bypassing the `run()`
* loop.
*
* NOTE: If this is not the first attempt, this function will sleep in
* accordance to the backoff configurations before running the task.
*
* @return boolean
*/
public function attempt()
{
if (!$this->canAttempt()) {
return false;
}
if ($this->attempts > 0) {
$this->backOff();
}
$this->attempts++;
return true;
}
/**
* Sleeps in accordance to the backoff configurations.
*/
private function backOff()
{
$delay = $this->getDelay();
usleep($delay * 1000000);
}
/**
* Gets the delay (in seconds) for the current backoff period.
*
* @return float
*/
private function getDelay()
{
$jitter = $this->getJitter();
$factor = $this->attempts > 1 ? $this->factor + $jitter : 1 + abs($jitter);
return $this->delay = min($this->maxDelay, $this->delay * $factor);
}
/**
* Gets the current jitter (random number between -$this->jitter and
* $this->jitter).
*
* @return float
*/
private function getJitter()
{
return $this->jitter * 2 * mt_rand() / mt_getrandmax() - $this->jitter;
}
/**
* Gets the number of times the associated task can be retried.
*
* NOTE: -1 is returned if the task can be retried indefinitely
*
* @return integer
*/
public function allowedRetries($code, $errors = array())
{
if (isset($this->retryMap[$code])) {
return $this->retryMap[$code];
}
if (
!empty($errors) &&
isset($errors[0]['reason'], $this->retryMap[$errors[0]['reason']])
) {
return $this->retryMap[$errors[0]['reason']];
}
return 0;
}
public function setRetryMap($retryMap)
{
$this->retryMap = $retryMap;
}
}
| {
"pile_set_name": "Github"
} |
<?php namespace Illuminate\Database\Eloquent;
class MassAssignmentException extends \RuntimeException {}
| {
"pile_set_name": "Github"
} |
import { Content, LabelsLeftLayout } from 'cx/ui';
import { HtmlElement, DateField } from 'cx/widgets';
import {Md} from '../../components/Md';
import {CodeSplit} from '../../components/CodeSplit';
import {CodeSnippet} from '../../components/CodeSnippet';
import {ConfigTable} from '../../components/ConfigTable';
import {ImportPath} from '../../components/ImportPath';
import configs from './configs/DateField';
export const DateFields = <cx>
<Md>
# Date Field
<ImportPath path="import {DateField} from 'cx/widgets';" />
Date field control is used for selecting dates. It supports textual input and picking
from a dropdown.
<CodeSplit>
<div class="widgets">
<div layout={LabelsLeftLayout}>
<DateField label="Standard" value:bind="$page.date" format="datetime;yyyyMMMMdd" autoFocus />
<DateField label="Disabled" value:bind="$page.date" disabled />
<DateField label="Readonly" value:bind="$page.date" readOnly />
<DateField label="Placeholder" value:bind="$page.date" placeholder="Type something here..." />
</div>
<div layout={LabelsLeftLayout}>
<DateField label="Required" value:bind="$page.date" required />
<DateField label="Styled" value:bind="$page.date" inputStyle={{border: '1px solid green'}} icon="clock-o"/>
<DateField label="View" value:bind="$page.date" mode="view" />
<DateField label="EmptyText" value:bind="$page.date" mode="view" emptyText="N/A" />
</div>
</div>
<Content name="code">
<CodeSnippet fiddle="oUVatu1E">{`
<div layout={LabelsLeftLayout}>
<DateField label="Standard" value:bind="$page.date" format="datetime;yyyyMMMMdd" autoFocus/>
<DateField label="Disabled" value:bind="$page.date" disabled />
<DateField label="Readonly" value:bind="$page.date" readOnly />
<DateField label="Placeholder" value:bind="$page.date" placeholder="Type something here..." />
</div>
<div layout={LabelsLeftLayout}>
<DateField label="Required" value:bind="$page.date" />
<DateField label="Styled" value:bind="$page.date" inputStyle={{border: '1px solid green'}} icon="clock-o"/>
<DateField label="View" value:bind="$page.date" mode="view" />
<DateField label="EmptyText" value:bind="$page.date" mode="view" emptyText="N/A" />
</div>
`}</CodeSnippet>
</Content>
</CodeSplit>
## Configuration
<ConfigTable props={configs} />
</Md>
</cx>
| {
"pile_set_name": "Github"
} |
from libsaas.services import base
from libsaas import parsers, http
from . import resource
class LineItems(resource.StripeResource):
path = 'lines'
@base.apimethod
def get(self, customer=None, limit=None, ending_before=None,
starting_after=None):
"""
Fetch all of the objects.
:var customer: In the case of upcoming invoices, the customer of the
upcoming invoice is required. In other cases it is ignored.
:vartype customer: str
:var limit: A limit on the number of objects to be returned.
Count can range between 1 and 100 objects.
:vartype count: int
:var ending_before: A cursor (object ID) for use in pagination. Fetched
objetcs will be newer than the given object.
:vartype ending_before: str
:var starting_after: A cursor (object ID) for use in pagination.
Fetched objetcs will be older than the given object.
:vartype starting_after: str
"""
params = base.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return request, parsers.parse_json
def create(self, *args, **kwargs):
raise base.MethodNotSupported()
def update(self, *args, **kwargs):
raise base.MethodNotSupported()
def delete(self, *args, **kwargs):
raise base.MethodNotSupported()
class InvoicesBaseResource(resource.StripeResource):
path = 'invoices'
def delete(self, *args, **kwargs):
raise base.MethodNotSupported()
class Invoice(InvoicesBaseResource):
def create(self, *args, **kwargs):
raise base.MethodNotSupported()
@base.resource(LineItems)
def lines(self):
"""
Return the resource corresponding to all invoice's lines.
"""
return LineItems(self)
@base.apimethod
def pay(self):
"""
Paying an invoice
"""
self.require_item()
url = '{0}/{1}'.format(self.get_url(), 'pay')
request = http.Request('POST', url, {})
return request, parsers.parse_json
class Invoices(InvoicesBaseResource):
@base.apimethod
def get(self, customer=None, limit=None, ending_before=None,
starting_after=None):
"""
Fetch all of the objects.
:var customer: The identifier of the customer whose invoices to return.
If none is provided, all invoices will be returned.
:vartype customer: str
:var limit: A limit on the number of objects to be returned.
Count can range between 1 and 100 objects.
:vartype count: int
:var ending_before: A cursor (object ID) for use in pagination. Fetched
objetcs will be newer than the given object.
:vartype ending_before: str
:var starting_after: A cursor (object ID) for use in pagination.
Fetched objetcs will be older than the given object.
:vartype starting_after: str
"""
params = base.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return request, parsers.parse_json
def update(self, *args, **kwargs):
raise base.MethodNotSupported()
@base.apimethod
def upcoming(self, customer):
"""
Fetch a customer's upcoming invoice.
:var customer: The identifier of the customer whose invoices to return.
If none is provided, all invoices will be returned.
:vartype customer: str
"""
params = base.get_params(None, locals())
url = '{0}/{1}'.format(self.get_url(), 'upcoming')
request = http.Request('GET', url, params)
return request, parsers.parse_json
class InvoiceItemBaseResource(resource.StripeResource):
path = 'invoiceitems'
def update(self, *args, **kwargs):
raise base.MethodNotSupported()
class InvoiceItem(InvoiceItemBaseResource):
def create(self, *args, **kwargs):
raise base.MethodNotSupported()
class InvoiceItems(InvoiceItemBaseResource):
@base.apimethod
def get(self, customer=None, limit=None, ending_before=None,
starting_after=None):
"""
Fetch all of the objects.
:var customer: The identifier of the customer whose invoice items to return.
If none is provided, all invoices will be returned.
:vartype customer: str
:var limit: A limit on the number of objects to be returned.
Count can range between 1 and 100 objects.
:vartype count: int
:var ending_before: A cursor (object ID) for use in pagination. Fetched
objetcs will be newer than the given object.
:vartype ending_before: str
:var starting_after: A cursor (object ID) for use in pagination.
Fetched objetcs will be older than the given object.
:vartype starting_after: str
"""
params = base.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return request, parsers.parse_json
def delete(self, *args, **kwargs):
raise base.MethodNotSupported()
| {
"pile_set_name": "Github"
} |
<div style="background: radial-gradient(ellipse closest-side at top, red, white 100px, black); width: 300px; height: 300px;"></div>
<div style="background: repeating-radial-gradient(closest-side ellipse at top, red, white 100px, black); width: 300px; height: 300px;"></div>
| {
"pile_set_name": "Github"
} |
; RUN: opt -mtriple=amdgcn-amd-amdhsa -S -inline < %s | FileCheck %s
; RUN: opt -mtriple=amdgcn-amd-amdhsa -S -passes='cgscc(inline)' < %s | FileCheck %s
; CHECK-LABEL: @func_no_target_cpu(
define i32 @func_no_target_cpu() #0 {
ret i32 0
}
; CHECK-LABEL: @target_cpu_call_no_target_cpu(
; CHECK-NEXT: ret i32 0
define i32 @target_cpu_call_no_target_cpu() #1 {
%call = call i32 @func_no_target_cpu()
ret i32 %call
}
; CHECK-LABEL: @target_cpu_target_features_call_no_target_cpu(
; CHECK-NEXT: ret i32 0
define i32 @target_cpu_target_features_call_no_target_cpu() #2 {
%call = call i32 @func_no_target_cpu()
ret i32 %call
}
; CHECK-LABEL: @fp32_denormals(
define i32 @fp32_denormals() #3 {
ret i32 0
}
; CHECK-LABEL: @no_fp32_denormals_call_f32_denormals(
; CHECK-NEXT: call i32 @fp32_denormals()
define i32 @no_fp32_denormals_call_f32_denormals() #4 {
%call = call i32 @fp32_denormals()
ret i32 %call
}
; Make sure gfx9 can call unspecified functions because of movrel
; feature change.
; CHECK-LABEL: @gfx9_target_features_call_no_target_cpu(
; CHECK-NEXT: ret i32 0
define i32 @gfx9_target_features_call_no_target_cpu() #5 {
%call = call i32 @func_no_target_cpu()
ret i32 %call
}
define i32 @func_no_halfrate64ops() #6 {
ret i32 0
}
define i32 @func_with_halfrate64ops() #7 {
ret i32 0
}
; CHECK-LABEL: @call_func_without_halfrate64ops(
; CHECK-NEXT: ret i32 0
define i32 @call_func_without_halfrate64ops() #7 {
%call = call i32 @func_no_halfrate64ops()
ret i32 %call
}
; CHECK-LABEL: @call_func_with_halfrate64ops(
; CHECK-NEXT: ret i32 0
define i32 @call_func_with_halfrate64ops() #6 {
%call = call i32 @func_with_halfrate64ops()
ret i32 %call
}
define i32 @func_no_loadstoreopt() #8 {
ret i32 0
}
define i32 @func_with_loadstoreopt() #9 {
ret i32 0
}
; CHECK-LABEL: @call_func_without_loadstoreopt(
; CHECK-NEXT: ret i32 0
define i32 @call_func_without_loadstoreopt() #9 {
%call = call i32 @func_no_loadstoreopt()
ret i32 %call
}
attributes #0 = { nounwind }
attributes #1 = { nounwind "target-cpu"="fiji" }
attributes #2 = { nounwind "target-cpu"="fiji" "target-features"="+fp32-denormals" }
attributes #3 = { nounwind "target-features"="+fp32-denormals" }
attributes #4 = { nounwind "target-features"="-fp32-denormals" }
attributes #5 = { nounwind "target-cpu"="gfx900" }
attributes #6 = { nounwind "target-features"="-half-rate-64-ops" }
attributes #7 = { nounwind "target-features"="+half-rate-64-ops" }
attributes #8 = { nounwind "target-features"="-load-store-opt" }
attributes #9 = { nounwind "target-features"="+load-store-opt" }
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2017 Google 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
*
* 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 ai.api.util;
import android.content.Context;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import ai.api.android.GsonFactory;
public class VersionConfig {
private static final String TAG = VersionConfig.class.getName();
private static final Pattern DOT_PATTERN = Pattern.compile(".", Pattern.LITERAL);
private static final Map<String, VersionConfig> configuration = new HashMap<>();
static {
configuration.put("5.9.26", new VersionConfig(true, true));
configuration.put("4.7.13", new VersionConfig(false, false));
}
private boolean destroyRecognizer = true;
private boolean autoStopRecognizer = false;
private VersionConfig() {
}
private VersionConfig(final boolean destroyRecognizer, final boolean autoStopRecognizer) {
this.destroyRecognizer = destroyRecognizer;
this.autoStopRecognizer = autoStopRecognizer;
}
public static VersionConfig init(final Context context) {
return getConfigByVersion(context);
}
private static VersionConfig getConfigByVersion(final Context context) {
final long number = numberFromBuildVersion(RecognizerChecker.getGoogleRecognizerVersion(context));
final VersionConfig config = new VersionConfig();
long prevVersionNumber = 0;
for (final Map.Entry<String, VersionConfig> configEntry : configuration.entrySet()) {
final String versionName = configEntry.getKey();
if (!TextUtils.isEmpty(versionName)) {
final long versionNumber = numberFromBuildVersion(versionName);
if (number >= versionNumber && prevVersionNumber < versionNumber) {
config.destroyRecognizer = configEntry.getValue().destroyRecognizer;
config.autoStopRecognizer = configEntry.getValue().autoStopRecognizer;
prevVersionNumber = versionNumber;
}
}
}
return config;
}
public boolean isDestroyRecognizer() {
return destroyRecognizer;
}
public boolean isAutoStopRecognizer() {
return autoStopRecognizer;
}
private static long numberFromBuildVersion(final String buildVersion) {
if (TextUtils.isEmpty(buildVersion))
return 0;
final String[] parts = DOT_PATTERN.split(buildVersion);
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < Math.min(3, parts.length); i++) {
builder.append(parts[i]);
}
try {
return Long.parseLong(builder.toString());
} catch (final NumberFormatException ignored) {
return 0;
}
}
@Override
public String toString() {
return GsonFactory.getGson().toJson(this);
}
} | {
"pile_set_name": "Github"
} |
\documentclass[10pt]{amsart}
\usepackage{amsmath, amssymb, mathrsfs}
\usepackage[mathscr]{euscript}
\newlength{\mylength}
\setlength{\mylength}{0.25cm}
\usepackage{enumitem}
\setlist{listparindent=\parindent, itemsep=0cm, parsep=\mylength, topsep=0cm}
\usepackage[final]{todonotes}
\usepackage[final]{showkeys}
\usepackage[breaklinks=true]{hyperref}
\usepackage{comment}
\usepackage{url}
\usepackage{tikz-cd}
\usepackage{amsthm}
\makeatletter
\renewenvironment{proof}[1][\proofname]{\par
\pushQED{\qed}%
\normalfont \topsep6\p@\@plus6\p@\relax
\noindent\emph{#1.}
\ignorespaces
}{%
\popQED\endtrivlist\@endpefalse
}
\makeatother
\newtheoremstyle{mythm}% name of the style to be used
{\mylength}% measure of space to leave above the theorem. E.g.: 3pt
{0pt}% measure of space to leave below the theorem. E.g.: 3pt
{\itshape}% name of font to use in the body of the theorem
{0pt}% measure of space to indent
{\bfseries}% name of head font
{.\ }% punctuation between head and body
{ }% space after theorem head; " " = normal interword space
{\thmname{#1}\thmnumber{ #2}\thmnote{ (#3)}}
\newtheoremstyle{myrmk}% name of the style to be used
{\mylength}% measure of space to leave above the theorem. E.g.: 3pt
{0pt}% measure of space to leave below the theorem. E.g.: 3pt
{}% name of font to use in the body of the theorem
{0pt}% measure of space to indent
{\itshape}% name of head font
{.\ }% punctuation between head and body
{ }% space after theorem head; " " = normal interword space
{\thmname{#1}\thmnumber{ #2}\thmnote{ (#3)}}
\theoremstyle{mythm}
%\newtheorem{thm}[subsubsection]{Theorem}
%\newtheorem*{claim}{Claim}
%\newtheorem*{thm}{Theorem}
\newtheorem{thm}{Theorem}
\newtheorem{lem}[thm]{Lemma}
\newtheorem{cor}[thm]{Corollary}
\newtheorem{claim}[thm]{Claim}
\newtheorem{prop}[thm]{Proposition}
%\newtheorem*{mthm}{Main Theorem}
%\newtheorem{prop}[subsubsection]{Proposition}
%\newtheorem*{prop}{Proposition}
%\newtheorem*{lem}{Lemma}
%\newtheorem*{klem}{Key Lemma}
%\newtheorem*{cor}{Corollary}
\theoremstyle{definition}
%\newtheorem{defn}[subsubsection]{Definition}
\newtheorem*{defn}{Definition}
\newtheorem{prob}[thm]{Problem}
%\newtheorem{que}[subsubsection]{Question}
\theoremstyle{myrmk}
%\newtheorem{rmk}[subsubsection]{Remark}
\newtheorem*{rmk}{Remark}
%\newtheorem{note}[subsubsection]{Note}
\newtheorem*{ex}{Example}
\newcommand{\nc}{\newcommand}
\nc{\on}{\operatorname}
\nc{\rnc}{\renewcommand}
\rnc{\setminus}{\smallsetminus}
\nc{\wt}{\widetilde}
\nc{\wh}{\widehat}
\nc{\ol}{\overline}
\nc{\Frob}{\on{Frob}}
\nc{\Gal}{\on{Gal}}
\nc{\BN}{\mathbb{N}}
\nc{\BZ}{\mathbb{Z}}
\nc{\BQ}{\mathbb{Q}}
\nc{\BR}{\mathbb{R}}
\nc{\BC}{\mathbb{C}}
\nc{\id}{\on{id}}
\nc{\Id}{\on{Id}}
\nc{\Tr}{\on{Tr}}
\nc{\la}{\langle}
\nc{\ra}{\rangle}
\nc{\lV}{\lVert}
\nc{\rV}{\rVert}
\nc{\mb}{\mathbf}
\nc{\mf}{\mathfrak}
%\nc{\cur}{\mathscr}
\nc{\mc}{\mathscr}
\nc{\ira}{\hookrightarrow}
\nc{\hra}{\hookrightarrow}
\nc{\sra}{\twoheadrightarrow}
\rnc{\Re}{\on{Re}}
\nc{\coker}{\on{coker}}
\nc{\End}{\on{End}}
\rnc{\Im}{\on{Im}}
%\rnc{\Re}{\on{Re}}
\nc{\Hom}{\on{Hom}}
\DeclareMathOperator*{\argmin}{arg\,min}
\DeclareMathOperator*{\argmax}{arg\,max}
\usepackage{marginnote}
\nc{\acts}{\curvearrowright}
\nc{\Mat}{\on{Mat}}
\newenvironment{cd}{\begin{equation*}\begin{tikzcd}}{\end{tikzcd}\end{equation*}\ignorespacesafterend}
\nc{\pfrac}[2]{\frac{\partial #1}{\partial #2}}
\nc{\e}[1]{\begin{align*} #1 \end{align*}}
\usepackage[margin=1in]{geometry}
\makeatletter
\def\blfootnote{\gdef\@thefnmark{}\@footnotetext}
\makeatother
%\renewcommand*{\arraystretch}{1.4}
\setlength{\parskip}{0.25cm}
\definecolor{myblue}{rgb}{0,0.15,0.45}
\newenvironment{myproof}{\color{myblue}\begin{proof}}{\end{proof}}
\usepackage{bm}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhead[L]{James Tao}
\fancyhead[C]{18.06 -- Week 10 Recitation}
\fancyhead[R]{Apr.\ 21, 2020}
\fancyfoot[C]{}
\newcounter{part-count}
\setcounter{part-count}{0}
\newenvironment{me}[1]{\begin{enumerate}[#1]\setcounter{enumi}{\value{part-count}}}{\setcounter{part-count}{\value{enumi}}\end{enumerate}}
\nc{\myhead}[1]{\noindent\emph{#1}.}
\begin{document}
\thispagestyle{fancy}
\section{Markov matrices}
\myhead{Definition} We say a matrix or vector is \emph{positive} if its entries are positive.
\myhead{Theorem} (Perron--Frobenius) If $A$ is a \emph{positive} square matrix, then it has an eigenvalue $\lambda_{\on{max}}$ with the following properties:
\begin{enumerate}[label=(\roman*)]
\item $\lambda_{\on{max}}$ is a positive real number.
\item The algebraic multiplicity of $\lambda_{\on{max}}$ is 1, and all other eigenvalues have absolute value $< \lambda_{\on{max}}$.
\item There is a \emph{positive} vector $x$ with eigenvalue $\lambda_{\on{max}}$.
\item $x$ and its multiples are the only \emph{positive} eigenvectors of $A$.
\end{enumerate}
\myhead{Definition} A square matrix $A$ is \emph{Markov} if it is positive and each column has entries summing to 1.
Let $\mathbf{1}$ be the all-ones column vector. The condition that each column of $A$ has entries summing to $1$ can be expressed as $\mathbf{1}^\top A = \mathbf{1}^\top$.
\myhead{Lemma} If $A$ is Markov, and $v$ is any vector, then the sum of entries of $v$ equals that of $Av$.
\begin{myproof}
Since $A$ is Markov, $\mathbf{1}^\top A = \mathbf{1}^\top$. Therefore
$
\mathbf{1}^\top (Av) = \mathbf{1}^\top v,
$
as desired.
\end{myproof}
\myhead{Proposition} If $A$ is Markov, then $\lambda_{\on{max}} = 1$.
\begin{myproof}
Let $x$ be the corresponding eigenvector, so $Ax = \lambda_{\on{max}}x$. The previous lemma implies that
\[
\mathbf{1}^\top x = \mathbf{1}^{\top} Ax = \lambda_{\on{max}} \mathbf{1}^\top x.
\]
Since $x$ is positive, $\mathbf{1}^\top x$ is nonzero, and dividing gives $1 = \lambda_{\on{max}}$.
\end{myproof}
In recitation, we will explain how Markov matrices can be interpreted as transition probabilities in diagrams called \emph{Markov chains}. We will also discuss the example
\[
A = \begin{pmatrix}
\frac12 & \frac14 & \frac14 \vspace{1mm} \\
\frac14 & \frac12 & \frac14 \vspace{1mm} \\
\frac14 & \frac14 & \frac12
\end{pmatrix}
\]
from Problem 3 in Section 10.3 on page 480 of Strang's book.
\section{Differential equations}
A path in $\BR^n$ can be thought of as a rule which assigns, to every time $t$, an $n$-vector $\bm{u}(t)$. A path may be the solution to a differential equation
\[
\frac{d}{dt} \, \bm{u}(t) = A\, \bm{u}(t).
\]
This says that, at time $t$, the velocity vector of the path equals the matrix $A$ times the position $\mb{u}(t)$ of the path at that time. It tells you the direction the point must travel, given its current location.
\myhead{Definition} If $A$ is a square matrix, then
\[
e^A := \on{Id} + A + \frac{1}{2} A^2 + \cdots + \frac{1}{n!} A^n + \cdots ,
\]
just like the usual series for the exponential function. For any $A$, it converges absolutely.
If we plug in the matrix $At$, we find
\[
e^{At} = \on{Id} + At + \frac{1}{2} A^2 t^2 + \cdots + \frac{1}{n!} A^n t^n + \cdots .
\]
This is an equality of square matrices whose entries depend on $t$. Differentiating, we find
\e{
\frac{d}{dt}\, e^{At} &= A + A^2 t + \frac{1}{2} A^3\, t^2 + \cdots + \frac{1}{(n-1)!} A^n t^{n-1} + \cdots \\
&= A \left( \on{Id} + At + \frac{1}{2} A^2 t^2 + \cdots + \frac{1}{(n-1)!} A^{n-1} t^{n-1} + \cdots \right) \\
&= A\, e^{At}.
}
If $AB = BA$, then one can show $e^A e^B = e^{A + B}$ with the usual power series manipulations. This implies, for example, that $e^{At_1}e^{At_2} = e^{A(t_1+t_2)}$ and $e^{\Id} e^{A} = e^{\Id + A}$. Note that $e^{\Id} = e\, \Id$.
\myhead{Problem} What is the inverse of $e^{A}$?
\myhead{Problem} Compute $e^{At}$ when $A = \begin{pmatrix}
0 & 1 \\ -1 & 0
\end{pmatrix}$. (See Example 5 in Section 6.3 on page 328 of Strang's book.)
\myhead{Problem} Compute $e^{At}$ when $A = \begin{pmatrix}
1 & 2 \\ 0 & 1
\end{pmatrix}$. (Cf.\ Example 4 in Section 6.3 on page 327 of Strang's book.)
The matrix exponential allows us to solve the differential equation from before. If we take
\[
\bm{u}(t) = e^{At} v
\]
for any fixed $v \in \BR^n$, then
\e{
\frac{d}{dt}\, \bm{u}(t) &= \frac{d}{dt} \, e^{At} v \\
&= A\, e^{At} v \\
&= A\, \bm{u}(t),
}
as desired. Note that $\bm{u}(0) = e^{A0} v = v$, so $v$ is the `starting point' of our solution path.
\myhead{Problem} Convert the one-variable second-order linear differential equation
\[
\frac{d^2}{dt^2} \, y(t) + y(t) = 0
\]
to a two-variable system of first order linear differential equations, and solve it.
(See Example 3 in Section 6.3 on page 323 of Strang's book.)
\myhead{Problem} If $v$ is an eigenvector of $A$ with eigenvalue $\lambda$, show that $v$ is also an eigenvector of $e^{At}$ with eigenvalue $e^{\lambda t}$. Describe the behavior of $e^{\lambda t} v$ as $t \to \infty$, based on where $\lambda$ lies in the complex plane.
\myhead{Problem} If $A$ satisfies $A^\top = -A$, show that $e^{At}$ is orthogonal, and deduce that any solution to
\[
\frac{d}{dt} \, \bm{u}(t) = A\, \bm{u}(t).
\]
must satisfy $\lVert \bm{u}(t) \rVert = \lVert \bm{u}(0) \rVert$ for all $t$.
(See page 328 of Strang's book.)
\end{document} | {
"pile_set_name": "Github"
} |
# Copyright 1999-2020 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
EAPI=7
inherit multilib-build
DESCRIPTION="Meta-ebuild for clang runtime libraries"
HOMEPAGE="https://clang.llvm.org/"
SRC_URI=""
LICENSE="metapackage"
SLOT="$(ver_cut 1-3)"
KEYWORDS=""
IUSE="+compiler-rt libcxx openmp +sanitize"
REQUIRED_USE="sanitize? ( compiler-rt )"
PROPERTIES="live"
RDEPEND="
compiler-rt? (
~sys-libs/compiler-rt-${PV}:${SLOT}
sanitize? ( ~sys-libs/compiler-rt-sanitizers-${PV}:${SLOT} )
)
libcxx? ( >=sys-libs/libcxx-${PV}[${MULTILIB_USEDEP}] )
openmp? ( >=sys-libs/libomp-${PV}[${MULTILIB_USEDEP}] )"
| {
"pile_set_name": "Github"
} |
requirejs.config({
paths: {
'alpha': 'sub/wrong-did-not-multi',
'dep2': 'sub/wrong-did-not-multi'
},
enabled: {
alpha: true
},
packages: ['foo'],
//Made up values just to test nested merging skip logic.
someRegExp: /foo/,
someFunc: function () {},
someArray: ['three', 'four']
});
requirejs(['enabled!alpha', 'enabled!gamma', 'enabled!beta', 'foo', 'bar'], function () {
});
| {
"pile_set_name": "Github"
} |
Windows Registry Editor Version 5.00
; Base16 Default Dark (https://github.com/chriskempson/base16)
; Scheme: Chris Kempson (http://chriskempson.com)
[HKEY_CURRENT_USER\Console]
"ColorTable00"=dword:00181818 ; base00
"ColorTable01"=dword:00c2af7c ; base0D
"ColorTable02"=dword:006cb5a1 ; base0B
"ColorTable03"=dword:00b9c186 ; base0C
"ColorTable04"=dword:004246ab ; base08
"ColorTable05"=dword:00af8bba ; base0E
"ColorTable06"=dword:005696dc ; base09
"ColorTable07"=dword:00d8d8d8 ; base05
"ColorTable08"=dword:00585858 ; base03
"ColorTable09"=dword:00282828 ; base01
"ColorTable10"=dword:00383838 ; base02
"ColorTable11"=dword:00585858 ; base03
"ColorTable12"=dword:00b8b8b8 ; base04
"ColorTable13"=dword:00d8d8d8 ; base05
"ColorTable14"=dword:00e8e8e8 ; base06
"ColorTable15"=dword:00f8f8f8 ; base07 | {
"pile_set_name": "Github"
} |
/*
This file is part of Darling.
Copyright (C) 2017 Lubos Dolezel
Darling is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Darling is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Darling. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Foundation/Foundation.h>
@interface AVStreamSessionInternal : NSObject
@end
| {
"pile_set_name": "Github"
} |
Attribute VB_Name = "Module1"
Sub SelectingRanges_ObjectHierarchy()
'The most explicit way to reference a range of cells.
Application.Workbooks("SelectingRangesBook.xlsm").Worksheets("Sheet1").Range("A1").Select
'Still very explict but can be confusing for sure because we need to keep in mind whether we have a personal macro workbook or not
Application.Workbooks(2).Worksheets(1).Range("B1").Select
'Less Explicit, ThisWorkbook is referring to the workbook that contains our subroutine
Application.ThisWorkbook.Worksheets(1).Range("C1").Select
'Less Explicit, ActiveWorkbook is referring to the workbook that is open and we see.
Application.ActiveWorkbook.Worksheets(1).Range("B1").Select
'We can even be less explicit in our code, but then VBA will fill in the blanks. Which is a good and bad.
'Forget the application
Workbooks("SelectingRangesBook.xlsm").Worksheets("Sheet1").Range("A2").Select '<<< This is how it looks in VBA's eyes Application.Workbooks("SelectingRangesBook.xlsm").Worksheets("Sheet1").Range("B1").Select
'Forget the workbook
Worksheets("Sheet1").Range("A2").Select '<<< This is how it looks in VBA's eyes Application.ActiveWorkbook.Worksheets("Sheet1").Range("B1").Select
'Forget the worksheet
'Range("A2").Select '<<< This is how it looks in VBA's eyes Application.ActiveWorkbook.ActiveWorksheet.Range("A2").Select
'If you use the Select method to select cells, be aware that Select works only on the active worksheet.
End Sub
Sub SelectingWorkbooks()
' The application object has a collection that houses all of our workbooks, its called "WORKBOOKS"
' To access this collection, we call the Application and then the property Workbooks.
' This collection does not contain add-in workbooks (.xla) and workbooks in protected view are not a member of this collection.
' --- "Application.Workbooks"
' If we don't use an object qualifier for this property it's equivalent to using "Application.Workbooks"
' --- "Workbooks" is the same as "Application.Workbooks" we just are dropping the "Application" object.
' SELECTING INDIVIDUAL WORKBOOKS FROM THE WORKBOOK COLLECTIONS
' The Explict way - Using the KEY METHOD
Application.Workbooks("SelectingWorkbooks.xlsx").Activate
Application.Workbooks("SelectingWorkbooks2.xlsx").Activate
' Workbooks("SelectingWorkbooks.xlsx").Activate <<< Also Works
' Workbooks("SelectingWorkbooks2.xlsx").Activate <<< Also Works
' The Less Explict way - Using the INDEX METHOD.
' NOTE ONE: Index is determined by the order in which my workbooks were open.
' NOTE TWO: If you have a PERSONAL.XSLB then this is ALSO a workbook in your collection and it is ALWAYS OPENED FIRST
Application.Workbooks(1).Activate '<<< This is my Personal Macro Workbook and this workbook is ALWAYS OPENED FIRST
Application.Workbooks(2).Activate '<<< This is my workbook that was opened SECOND and it is named "SelectingWorkbooks.xlsx"
Application.Workbooks(3).Activate '<<< This is my workbook that was opened THIRD and it is named "SelectingWorkbooks2.xlsx"
' Workbooks(1).Activate '<<< Also Works
' Workbooks(2).Activate '<<< Also Works
' Workbooks(3).Activate '<<< Also Works
' Using the ActiveWorkbook Method
' NOTE ONE: The ActiveWorkbook is the one that is opened and we can see on our screen.
ActiveWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000
' Using the ThisWorkbook Method
' NOTE ONE: The ThisWorkbook is the one that houses our code.
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = 7000
End Sub
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.android.tools.idea.rendering.multi;
import com.android.sdklib.AndroidTargetHash;
import com.android.sdklib.AndroidVersion;
import com.android.sdklib.BuildToolInfo;
import com.android.sdklib.IAndroidTarget;
import com.android.sdklib.OptionalLibrary;
import com.android.sdklib.SdkVersionInfo;
import java.io.File;
import java.util.List;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* A special {@link IAndroidTarget} which simulates a particular given API level,
* but uses a more recent real platform and layoutlib instead of the original target.
* This allows the layout preview to for example render on versions that are not installed
* on the current system, or to simulate the look of an older render target without the
* big expense of loading and running multiple simultaneous layoutlib instances.
* <p>
* This does have some limitations: the layoutlib code will not actually be the older
* layoutlib, so for example when rendering the old classic Theme, you are getting that
* Theme as implemented in newer versions, not the original. Similarly any code running
* inside the layoutlib.jar will be using a higher version of Build.VERSION.SDK_INT. However,
* in practice (after all, we only run view code) this does not appear to be a big limitation.
*/
public class CompatibilityRenderTarget implements IAndroidTarget {
private final int myApiLevel;
private final IAndroidTarget myDelegate;
private final AndroidVersion myVersion;
private final IAndroidTarget myRealTarget;
private final String myHashString;
public CompatibilityRenderTarget(@NotNull IAndroidTarget delegate, int apiLevel, @Nullable IAndroidTarget realTarget) {
myDelegate = delegate;
myApiLevel = apiLevel;
myRealTarget = realTarget;
myVersion = realTarget != null ? realTarget.getVersion() : new AndroidVersion(apiLevel, null);
// Don't *just* name it say android-15 since that can clash with the REAL key used for android-15
// (if the user has it installed) and in particular for maps like AndroidSdkData#getTargetData
// can end up accidentally using compatibility targets instead of real android platform targets,
// resulting in bugs like b.android.com/213075
myHashString = "compat-" + AndroidTargetHash.getPlatformHashString(myVersion);
}
/**
* Copies an existing {@link CompatibilityRenderTarget} but updates the the render delegate. It will keep the API level and
* the real target.
*/
public static IAndroidTarget copyWithNewDelegate(@NotNull CompatibilityRenderTarget original, @NotNull IAndroidTarget newDelegate) {
return new CompatibilityRenderTarget(newDelegate, original.myApiLevel, original.myRealTarget);
}
/** The {@link IAndroidTarget} we're using for actual rendering */
@NotNull
public IAndroidTarget getRenderTarget() {
return myDelegate;
}
/**
* The simulated {@link IAndroidTarget} if it happens to be installed; we use this
* to pick up better assets for example.
*/
@Nullable
public IAndroidTarget getRealTarget() {
return myRealTarget;
}
@Override
@NotNull
public AndroidVersion getVersion() {
return myVersion;
}
@Override
public String getVersionName() {
return SdkVersionInfo.getAndroidName(myApiLevel);
}
@Override
public String hashString() {
return myHashString;
}
@Override
public int compareTo(@NotNull IAndroidTarget other) {
int delta = myApiLevel - other.getVersion().getApiLevel();
if (delta != 0) {
return delta;
}
return myDelegate.compareTo(other);
}
@Override
public int getRevision() {
return 1;
}
// Resource tricks
@Override
@NotNull
public String getPath(int pathId) {
return myDelegate.getPath(pathId);
}
@Override
@NotNull
public File getFile(int pathId) {
return myDelegate.getFile(pathId);
}
// Remainder: Just delegate
@Override
@NotNull
public String getLocation() {
return myDelegate.getLocation();
}
@Override
public String getVendor() {
return myDelegate.getVendor();
}
@Override
public String getName() {
return myDelegate.getName();
}
@Override
public String getFullName() {
return myDelegate.getFullName();
}
@Override
public String getClasspathName() {
return myDelegate.getClasspathName();
}
@Override
public String getShortClasspathName() {
return myDelegate.getShortClasspathName();
}
@Override
public boolean isPlatform() {
return myDelegate.isPlatform();
}
@Override
public IAndroidTarget getParent() {
return myDelegate.getParent();
}
@Override
public BuildToolInfo getBuildToolInfo() {
return myDelegate.getBuildToolInfo();
}
@Override
@NotNull
public List<String> getBootClasspath() {
return myDelegate.getBootClasspath();
}
@Override
public boolean hasRenderingLibrary() {
return myDelegate.hasRenderingLibrary();
}
@Override
@NotNull
public File[] getSkins() {
return myDelegate.getSkins();
}
@Nullable
@Override
public File getDefaultSkin() {
return myDelegate.getDefaultSkin();
}
@Override
@NotNull
public List<OptionalLibrary> getOptionalLibraries() {
return myDelegate.getOptionalLibraries();
}
@Override
@NotNull
public List<OptionalLibrary> getAdditionalLibraries() {
return myDelegate.getAdditionalLibraries();
}
@Override
public String[] getPlatformLibraries() {
return myDelegate.getPlatformLibraries();
}
@Override
public String getProperty(String name) {
return myDelegate.getProperty(name);
}
@Override
public Map<String, String> getProperties() {
return myDelegate.getProperties();
}
@Override
public boolean canRunOn(IAndroidTarget target) {
return myDelegate.canRunOn(target);
}
}
| {
"pile_set_name": "Github"
} |
//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
#pragma once
// Helper class for file sink
// When failing to open a file, retry several times(5) with small delay between the tries(10 ms)
// Can be set to auto flush on every line
// Throw spdlog_ex exception on errors
#include <spdlog/details/os.h>
#include <spdlog/details/log_msg.h>
#include <chrono>
#include <cstdio>
#include <string>
#include <thread>
#include <cerrno>
namespace spdlog
{
namespace details
{
class file_helper
{
public:
const int open_tries = 5;
const int open_interval = 10;
explicit file_helper() :
_fd(nullptr)
{}
file_helper(const file_helper&) = delete;
file_helper& operator=(const file_helper&) = delete;
~file_helper()
{
close();
}
void open(const filename_t& fname, bool truncate = false)
{
close();
auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab");
_filename = fname;
for (int tries = 0; tries < open_tries; ++tries)
{
if (!os::fopen_s(&_fd, fname, mode))
return;
std::this_thread::sleep_for(std::chrono::milliseconds(open_interval));
}
throw spdlog_ex("Failed opening file " + os::filename_to_str(_filename) + " for writing", errno);
}
void reopen(bool truncate)
{
if (_filename.empty())
throw spdlog_ex("Failed re opening file - was not opened before");
open(_filename, truncate);
}
void flush()
{
std::fflush(_fd);
}
void close()
{
if (_fd)
{
std::fclose(_fd);
_fd = nullptr;
}
}
void write(const log_msg& msg)
{
size_t msg_size = msg.formatted.size();
auto data = msg.formatted.data();
if (std::fwrite(data, 1, msg_size, _fd) != msg_size)
throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno);
}
size_t size()
{
if (!_fd)
throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename));
return os::filesize(_fd);
}
const filename_t& filename() const
{
return _filename;
}
static bool file_exists(const filename_t& name)
{
return os::file_exists(name);
}
private:
FILE* _fd;
filename_t _filename;
};
}
}
| {
"pile_set_name": "Github"
} |
/**
* Merge object b with object a.
*
* var a = { foo: 'bar' }
* , b = { bar: 'baz' };
*
* merge(a, b);
* // => { foo: 'bar', bar: 'baz' }
*
* @param {Object} a
* @param {Object} b
* @return {Object}
* @api public
*/
exports = module.exports = function(a, b){
if (a && b) {
for (var key in b) {
a[key] = b[key];
}
}
return a;
};
| {
"pile_set_name": "Github"
} |
; RUN: llvm-as < %s >%t.bc
; PR21108: Diagnostic handlers get pass remarks, even if they're not enabled.
; Confirm that there are -pass-remarks.
; RUN: llvm-lto -pass-remarks=inline \
; RUN: -exported-symbol _func2 -pass-remarks-analysis=loop-vectorize \
; RUN: -exported-symbol _main -o %t.o %t.bc 2>&1 | \
; RUN: FileCheck %s -allow-empty -check-prefix=REMARKS
; RUN: llvm-nm %t.o | FileCheck %s -check-prefix NM
; RUN: llvm-lto -pass-remarks=inline -use-diagnostic-handler \
; RUN: -exported-symbol _func2 -pass-remarks-analysis=loop-vectorize \
; RUN: -exported-symbol _main -o %t.o %t.bc 2>&1 | \
; RUN: FileCheck %s -allow-empty -check-prefix=REMARKS_DH
; RUN: llvm-nm %t.o | FileCheck %s -check-prefix NM
; Confirm that -pass-remarks are not printed by default.
; RUN: llvm-lto \
; RUN: -exported-symbol _func2 \
; RUN: -exported-symbol _main -o %t.o %t.bc 2>&1 | \
; RUN: FileCheck %s -allow-empty
; RUN: llvm-nm %t.o | FileCheck %s -check-prefix NM
; RUN: llvm-lto -use-diagnostic-handler \
; RUN: -exported-symbol _func2 \
; RUN: -exported-symbol _main -o %t.o %t.bc 2>&1 | \
; RUN: FileCheck %s -allow-empty
; RUN: llvm-nm %t.o | FileCheck %s -check-prefix NM
; Optimization records are collected regardless of the diagnostic handler
; RUN: rm -f %t.yaml
; RUN: llvm-lto -lto-pass-remarks-output=%t.yaml \
; RUN: -exported-symbol _func2 \
; RUN: -exported-symbol _main -o %t.o %t.bc 2>&1 | \
; RUN: FileCheck %s -allow-empty
; RUN: cat %t.yaml | FileCheck %s -check-prefix=YAML
; REMARKS: remark: {{.*}} foo inlined into main
; REMARKS: remark: {{.*}} loop not vectorized: cannot prove it is safe to reorder memory operations
; REMARKS_DH: llvm-lto: remark: {{.*}} foo inlined into main
; REMARKS_DH: llvm-lto: remark: {{.*}} loop not vectorized: cannot prove it is safe to reorder memory operations
; CHECK-NOT: remark:
; CHECK-NOT: llvm-lto:
; NM-NOT: foo
; NM: func2
; NM: main
; YAML: --- !Passed
; YAML-NEXT: Pass: inline
; YAML-NEXT: Name: Inlined
; YAML-NEXT: Function: main
; YAML-NEXT: Args:
; YAML-NEXT: - Callee: foo
; YAML-NEXT: - String: ' inlined into '
; YAML-NEXT: - Caller: main
; YAML-NEXT: - String: ' with '
; YAML-NEXT: - String: '(cost='
; YAML-NEXT: - Cost: '-15000'
; YAML-NEXT: - String: ', threshold='
; YAML-NEXT: - Threshold: '337'
; YAML-NEXT: - String: ')'
; YAML-NEXT: ...
target datalayout = "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-darwin"
declare i32 @bar()
define i32 @foo() {
%a = call i32 @bar()
ret i32 %a
}
define i32 @main() {
%i = call i32 @foo()
ret i32 %i
}
define i32 @func2(i32* %out, i32* %out2, i32* %A, i32* %B, i32* %C, i32* %D, i32* %E, i32* %F) {
entry:
br label %for.body
for.body: ; preds = %for.body, %entry
%i.037 = phi i64 [ 0, %entry ], [ %inc, %for.body ]
%arrayidx = getelementptr inbounds i32, i32* %A, i64 %i.037
%0 = load i32, i32* %arrayidx, align 4
%arrayidx1 = getelementptr inbounds i32, i32* %B, i64 %i.037
%1 = load i32, i32* %arrayidx1, align 4
%add = add nsw i32 %1, %0
%arrayidx2 = getelementptr inbounds i32, i32* %C, i64 %i.037
%2 = load i32, i32* %arrayidx2, align 4
%add3 = add nsw i32 %add, %2
%arrayidx4 = getelementptr inbounds i32, i32* %E, i64 %i.037
%3 = load i32, i32* %arrayidx4, align 4
%add5 = add nsw i32 %add3, %3
%arrayidx6 = getelementptr inbounds i32, i32* %F, i64 %i.037
%4 = load i32, i32* %arrayidx6, align 4
%add7 = add nsw i32 %add5, %4
%arrayidx8 = getelementptr inbounds i32, i32* %out, i64 %i.037
store i32 %add7, i32* %arrayidx8, align 4
%5 = load i32, i32* %arrayidx, align 4
%6 = load i32, i32* %arrayidx1, align 4
%add11 = add nsw i32 %6, %5
%7 = load i32, i32* %arrayidx2, align 4
%add13 = add nsw i32 %add11, %7
%8 = load i32, i32* %arrayidx4, align 4
%add15 = add nsw i32 %add13, %8
%9 = load i32, i32* %arrayidx6, align 4
%add17 = add nsw i32 %add15, %9
%arrayidx18 = getelementptr inbounds i32, i32* %out2, i64 %i.037
store i32 %add17, i32* %arrayidx18, align 4
%inc = add i64 %i.037, 1
%exitcond = icmp eq i64 %inc, 256
br i1 %exitcond, label %for.end, label %for.body
for.end: ; preds = %for.body
ret i32 undef
}
| {
"pile_set_name": "Github"
} |
一个用于显示多种不同类型图片的React组件,包括网络图片、静态资源、临时的本地图片、以及本地磁盘上的图片(如相册)等。详细用法参阅[图片文档](images.html)。
用法样例:
```javascript
renderImages() {
return (
<View>
<Image
style={styles.icon}
source={require('./icon.png')}
/>
<Image
style={styles.logo}
source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}
/>
</View>
);
}
```
### 截图

### 属性
<div class="props">
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="onlayout"></a>onLayout <span class="propType">function</span> <a class="hash-link" href="#onlayout">#</a></h4>
<div>
<p>当元素挂载或者布局改变的时候调用,参数为:<code>{nativeEvent: {layout: {x, y, width, height}}}</code>.</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="onload"></a>onLoad <span class="propType">function</span> <a class="hash-link" href="#onload">#</a></h4>
<div>
<p>加载成功完成时调用此回调函数。</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="onloadend"></a>onLoadEnd <span class="propType">function</span> <a class="hash-link" href="#onloadend">#</a></h4>
<div>
<p>加载结束后,不论成功还是失败,调用此回调函数。</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="onloadstart"></a>onLoadStart <span class="propType">function</span> <a class="hash-link" href="#onloadstart">#</a></h4>
<div>
<p>加载开始时调用。</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="resizemode"></a>resizeMode <span class="propType">enum('cover', 'contain', 'stretch')</span> <a class="hash-link" href="#resizemode">#</a></h4>
<div>
<p>决定当组件尺寸和图片尺寸不成比例的时候如何调整图片的大小。</p>
<ul>
<li><p><code>cover</code>: 在保持图片宽高比的前提下缩放图片,直到宽度和高度都大于等于容器视图的尺寸(如果容器有padding内衬的话,则相应减去)。__译注__:这样图片完全覆盖甚至超出容器,容器中不留任何空白。</p></li>
<li><p><code>contain</code>: 在保持图片宽高比的前提下缩放图片,直到宽度和高度都小于等于容器视图的尺寸(如果容器有padding内衬的话,则相应减去)。__译注__:这样图片完全被包裹在容器中,容器中可能留有空白</p></li>
<li><p><code>stretch</code>: 拉伸图片且不维持宽高比,直到宽高都刚好填满容器。</p></li>
</ul>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="source"></a>source <span class="propType">{uri: string}, number</span> <a class="hash-link" href="#source">#</a></h4>
<div>
<p><code>uri</code>是一个表示图片的资源标识的字符串,它可以是一个http地址或是一个本地文件路径(使用<code>require(相对路径)</code>来引用)。</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="style"></a>style <span class="propType">style</span> <a class="hash-link" href="#style">#</a></h4>
<div class="compactProps">
<div class="prop">
<h6 class="propTitle"><a href="layout-with-flexbox.html">Flexbox...</a></h6>
</div>
<div class="prop">
<h6 class="propTitle"><a href="transforms.html#proptypes">Transforms...</a></h6>
</div>
<div class="prop">
<h6 class="propTitle">resizeMode <span class="propType">Object.keys(ImageResizeMode)</span></h6>
</div>
<div class="prop">
<h6 class="propTitle">backgroundColor <span class="propType">string</span></h6>
</div>
<div class="prop">
<h6 class="propTitle">borderColor <span class="propType">string</span></h6>
</div>
<div class="prop">
<h6 class="propTitle">borderWidth <span class="propType">number</span></h6>
</div>
<div class="prop">
<h6 class="propTitle">borderRadius <span class="propType">number</span></h6>
</div>
<div class="prop">
<h6 class="propTitle">overflow <span class="propType">enum('visible', 'hidden')</span></h6>
</div>
<div class="prop">
<h6 class="propTitle">tintColor <span class="propType">string</span></h6>
</div>
<div class="prop">
<h6 class="propTitle">opacity <span class="propType">number</span></h6>
</div>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="testid"></a>testID <span class="propType">string</span> <a class="hash-link" href="#testid">#</a></h4>
<div>
<p>一个唯一的资源标识符,用来在自动测试脚本中标识这个元素。</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="accessibilitylabel"></a><span class="platform">ios</span>accessibilityLabel <span class="propType">string</span> <a class="hash-link" href="#accessibilitylabel">#</a></h4>
<div>
<p>当用户与图片交互时,读屏器(无障碍功能)会朗读的文字。</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="accessible"></a><span class="platform">ios</span>accessible <span class="propType">bool</span> <a class="hash-link" href="#accessible">#</a></h4>
<div>
<p>当此属性为真的时候,表示这个图片是一个启用了无障碍功能的元素。</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="blurradius"></a><span class="platform">ios</span>blurRadius <span class="propType">number</span> <a class="hash-link" href="#blurradius">#</a>
</h4>
<div>
<p>blurRadius(模糊半径):为图片添加一个指定半径的模糊滤镜。</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="capinsets"></a><span class="platform">ios</span>capInsets <span class="propType">{top: number, left: number, bottom: number, right: number}</span> <a class="hash-link" href="#capinsets">#</a></h4>
<div>
<p>当图片被缩放的时候,capInsets指定的角上的尺寸会被固定而不进行缩放,而中间和边上其他的部分则会被拉伸。这在制作一些可变大小的圆角按钮、阴影、以及其它资源的时候非常有用(译注:这就是常说的九宫格或者.9图。了解更多信息,可以参见<a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets" target="_blank">苹果官方文档</a></p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="defaultsource"></a><span class="platform">ios</span>defaultSource <span class="propType">{uri: string}</span> <a class="hash-link" href="#defaultsource">#</a></h4>
<div>
<p>一个静态图片,当最终的图片正在下载的过程中时显示(loading背景图)。</p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="onerror"></a><span class="platform">ios</span>onError <span class="propType">function</span> <a class="hash-link" href="#onerror">#</a></h4>
<div>
<p>当加载错误的时候调用此回调函数,参数为<code>{nativeEvent: {error}}</code></p>
</div>
</div>
<div class="prop">
<h4 class="propTitle"><a class="anchor" name="onprogress"></a><span class="platform">ios</span>onProgress <span class="propType">function</span> <a class="hash-link" href="#onprogress">#</a></h4>
<div>
<p>在加载过程中不断调用,参数为<code>{nativeEvent: {loaded, total}}</code></p>
</div>
</div>
</div>
### 方法
<div class="props">
<div class="prop"><h4 class="propTitle"><a class="anchor" name="getsize"></a><span class="propType">static </span>getSize<span
class="propType">(uri: string, success: (width: number, height: number) => void, failure: (error: any) => void)</span>
<a class="hash-link" href="#getsize">#</a></h4>
<div><p>在显示图片前获取图片的宽高(以像素为单位)。如果图片地址不正确或下载失败,此方法也会失败。</p>
<p>要获取图片的尺寸,首先需要加载或下载图片(同时会被缓存起来)。这意味着理论上你可以用这个方法来预加载图片,虽然此方法并没有针对这一用法进行优化,而且将来可能会换一些实现方案使得并不需要完整下载图片即可获取尺寸。所以更好的预加载方案是使用下面那个专门的预加载方法。</p></div>
</div>
<div class="prop"><h4 class="propTitle"><a class="anchor" name="prefetch"></a><span class="propType">static </span>prefetch<span
class="propType">(url: string)</span> <a class="hash-link" href="#prefetch">#</a></h4>
<div><p>预加载一个远程图片(将其下载到本地磁盘缓存)。</p></div>
</div>
</div>
### 例子
```javascript
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
ActivityIndicator,
Image,
Platform,
StyleSheet,
Text,
View,
} = ReactNative;
var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
var ImageCapInsetsExample = require('./ImageCapInsetsExample');
const IMAGE_PREFETCH_URL = 'http://facebook.github.io/origami/public/images/blog-hero.jpg?r=1&t=' + Date.now();
var prefetchTask = Image.prefetch(IMAGE_PREFETCH_URL);
var NetworkImageCallbackExample = React.createClass({
getInitialState: function() {
return {
events: [],
startLoadPrefetched: false,
mountTime: new Date(),
};
},
componentWillMount() {
this.setState({mountTime: new Date()});
},
render: function() {
var { mountTime } = this.state;
return (
<View>
<Image
source={this.props.source}
style={[styles.base, {overflow: 'visible'}]}
onLoadStart={() => this._loadEventFired(`✔ onLoadStart (+${new Date() - mountTime}ms)`)}
onLoad={() => this._loadEventFired(`✔ onLoad (+${new Date() - mountTime}ms)`)}
onLoadEnd={() => {
this._loadEventFired(`✔ onLoadEnd (+${new Date() - mountTime}ms)`);
this.setState({startLoadPrefetched: true}, () => {
prefetchTask.then(() => {
this._loadEventFired(`✔ Prefetch OK (+${new Date() - mountTime}ms)`);
}, error => {
this._loadEventFired(`✘ Prefetch failed (+${new Date() - mountTime}ms)`);
});
});
}}
/>
{this.state.startLoadPrefetched ?
<Image
source={this.props.prefetchedSource}
style={[styles.base, {overflow: 'visible'}]}
onLoadStart={() => this._loadEventFired(`✔ (prefetched) onLoadStart (+${new Date() - mountTime}ms)`)}
onLoad={() => this._loadEventFired(`✔ (prefetched) onLoad (+${new Date() - mountTime}ms)`)}
onLoadEnd={() => this._loadEventFired(`✔ (prefetched) onLoadEnd (+${new Date() - mountTime}ms)`)}
/>
: null}
<Text style={{marginTop: 20}}>
{this.state.events.join('\n')}
</Text>
</View>
);
},
_loadEventFired(event) {
this.setState((state) => {
return state.events = [...state.events, event];
});
}
});
var NetworkImageExample = React.createClass({
getInitialState: function() {
return {
error: false,
loading: false,
progress: 0
};
},
render: function() {
var loader = this.state.loading ?
<View style={styles.progress}>
<Text>{this.state.progress}%</Text>
<ActivityIndicator style={{marginLeft:5}} />
</View> : null;
return this.state.error ?
<Text>{this.state.error}</Text> :
<Image
source={this.props.source}
style={[styles.base, {overflow: 'visible'}]}
onLoadStart={(e) => this.setState({loading: true})}
onError={(e) => this.setState({error: e.nativeEvent.error, loading: false})}
onProgress={(e) => this.setState({progress: Math.round(100 * e.nativeEvent.loaded / e.nativeEvent.total)})}
onLoad={() => this.setState({loading: false, error: false})}>
{loader}
</Image>;
}
});
var ImageSizeExample = React.createClass({
getInitialState: function() {
return {
width: 0,
height: 0,
};
},
componentDidMount: function() {
Image.getSize(this.props.source.uri, (width, height) => {
this.setState({width, height});
});
},
render: function() {
return (
<View style={{flexDirection: 'row'}}>
<Image
style={{
width: 60,
height: 60,
backgroundColor: 'transparent',
marginRight: 10,
}}
source={this.props.source} />
<Text>
Actual dimensions:{'\n'}
Width: {this.state.width}, Height: {this.state.height}
</Text>
</View>
);
},
});
var MultipleSourcesExample = React.createClass({
getInitialState: function() {
return {
width: 30,
height: 30,
};
},
render: function() {
return (
<View style={styles.container}>
<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
<Text
style={styles.touchableText}
onPress={this.decreaseImageSize} >
Decrease image size
</Text>
<Text
style={styles.touchableText}
onPress={this.increaseImageSize} >
Increase image size
</Text>
</View>
<Text>Container image size: {this.state.width}x{this.state.height} </Text>
<View
style={[styles.imageContainer, {height: this.state.height, width: this.state.width}]} >
<Image
style={{flex: 1}}
source={[
{uri: 'http://facebook.github.io/react/img/logo_small.png', width: 38, height: 38},
{uri: 'http://facebook.github.io/react/img/logo_small_2x.png', width: 76, height: 76},
{uri: 'http://facebook.github.io/react/img/logo_og.png', width: 400, height: 400}
]}
/>
</View>
</View>
);
},
increaseImageSize: function() {
if (this.state.width >= 100) {
return;
}
this.setState({
width: this.state.width + 10,
height: this.state.height + 10,
});
},
decreaseImageSize: function() {
if (this.state.width <= 10) {
return;
}
this.setState({
width: this.state.width - 10,
height: this.state.height - 10,
});
},
});
exports.displayName = (undefined: ?string);
exports.framework = 'React';
exports.title = '<Image>';
exports.description = 'Base component for displaying different types of images.';
exports.examples = [
{
title: 'Plain Network Image',
description: 'If the `source` prop `uri` property is prefixed with ' +
'"http", then it will be downloaded from the network.',
render: function() {
return (
<Image
source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}
style={styles.base}
/>
);
},
},
{
title: 'Plain Static Image',
description: 'Static assets should be placed in the source code tree, and ' +
'required in the same way as JavaScript modules.',
render: function() {
return (
<View style={styles.horizontal}>
<Image source={require('./uie_thumb_normal.png')} style={styles.icon} />
<Image source={require('./uie_thumb_selected.png')} style={styles.icon} />
<Image source={require('./uie_comment_normal.png')} style={styles.icon} />
<Image source={require('./uie_comment_highlighted.png')} style={styles.icon} />
</View>
);
},
},
{
title: 'Image Loading Events',
render: function() {
return (
<NetworkImageCallbackExample source={{uri: 'http://facebook.github.io/origami/public/images/blog-hero.jpg?r=1&t=' + Date.now()}}
prefetchedSource={{uri: IMAGE_PREFETCH_URL}}/>
);
},
},
{
title: 'Error Handler',
render: function() {
return (
<NetworkImageExample source={{uri: 'http://TYPO_ERROR_facebook.github.io/react/img/logo_og.png'}} />
);
},
platform: 'ios',
},
{
title: 'Image Download Progress',
render: function() {
return (
<NetworkImageExample source={{uri: 'http://facebook.github.io/origami/public/images/blog-hero.jpg?r=1'}}/>
);
},
platform: 'ios',
},
{
title: 'defaultSource',
description: 'Show a placeholder image when a network image is loading',
render: function() {
return (
<Image
defaultSource={require('./bunny.png')}
source={{uri: 'http://facebook.github.io/origami/public/images/birds.jpg'}}
style={styles.base}
/>
);
},
platform: 'ios',
},
{
title: 'Border Color',
render: function() {
return (
<View style={styles.horizontal}>
<Image
source={smallImage}
style={[
styles.base,
styles.background,
{borderWidth: 3, borderColor: '#f099f0'}
]}
/>
</View>
);
},
},
{
title: 'Border Width',
render: function() {
return (
<View style={styles.horizontal}>
<Image
source={smallImage}
style={[
styles.base,
styles.background,
{borderWidth: 5, borderColor: '#f099f0'}
]}
/>
</View>
);
},
},
{
title: 'Border Radius',
render: function() {
return (
<View style={styles.horizontal}>
<Image
style={[styles.base, {borderRadius: 5}]}
source={fullImage}
/>
<Image
style={[styles.base, styles.leftMargin, {borderRadius: 19}]}
source={fullImage}
/>
</View>
);
},
},
{
title: 'Background Color',
render: function() {
return (
<View style={styles.horizontal}>
<Image source={smallImage} style={styles.base} />
<Image
style={[
styles.base,
styles.leftMargin,
{backgroundColor: 'rgba(0, 0, 100, 0.25)'}
]}
source={smallImage}
/>
<Image
style={[styles.base, styles.leftMargin, {backgroundColor: 'red'}]}
source={smallImage}
/>
<Image
style={[styles.base, styles.leftMargin, {backgroundColor: 'black'}]}
source={smallImage}
/>
</View>
);
},
},
{
title: 'Opacity',
render: function() {
return (
<View style={styles.horizontal}>
<Image
style={[styles.base, {opacity: 1}]}
source={fullImage}
/>
<Image
style={[styles.base, styles.leftMargin, {opacity: 0.8}]}
source={fullImage}
/>
<Image
style={[styles.base, styles.leftMargin, {opacity: 0.6}]}
source={fullImage}
/>
<Image
style={[styles.base, styles.leftMargin, {opacity: 0.4}]}
source={fullImage}
/>
<Image
style={[styles.base, styles.leftMargin, {opacity: 0.2}]}
source={fullImage}
/>
<Image
style={[styles.base, styles.leftMargin, {opacity: 0}]}
source={fullImage}
/>
</View>
);
},
},
{
title: 'Nesting',
render: function() {
return (
<Image
style={{width: 60, height: 60, backgroundColor: 'transparent'}}
source={fullImage}>
<Text style={styles.nestedText}>
React
</Text>
</Image>
);
},
},
{
title: 'Tint Color',
description: 'The `tintColor` style prop changes all the non-alpha ' +
'pixels to the tint color.',
render: function() {
return (
<View>
<View style={styles.horizontal}>
<Image
source={require('./uie_thumb_normal.png')}
style={[styles.icon, {borderRadius: 5, tintColor: '#5ac8fa' }]}
/>
<Image
source={require('./uie_thumb_normal.png')}
style={[styles.icon, styles.leftMargin, {borderRadius: 5, tintColor: '#4cd964' }]}
/>
<Image
source={require('./uie_thumb_normal.png')}
style={[styles.icon, styles.leftMargin, {borderRadius: 5, tintColor: '#ff2d55' }]}
/>
<Image
source={require('./uie_thumb_normal.png')}
style={[styles.icon, styles.leftMargin, {borderRadius: 5, tintColor: '#8e8e93' }]}
/>
</View>
<Text style={styles.sectionText}>
It also works with downloaded images:
</Text>
<View style={styles.horizontal}>
<Image
source={smallImage}
style={[styles.base, {borderRadius: 5, tintColor: '#5ac8fa' }]}
/>
<Image
source={smallImage}
style={[styles.base, styles.leftMargin, {borderRadius: 5, tintColor: '#4cd964' }]}
/>
<Image
source={smallImage}
style={[styles.base, styles.leftMargin, {borderRadius: 5, tintColor: '#ff2d55' }]}
/>
<Image
source={smallImage}
style={[styles.base, styles.leftMargin, {borderRadius: 5, tintColor: '#8e8e93' }]}
/>
</View>
</View>
);
},
},
{
title: 'Resize Mode',
description: 'The `resizeMode` style prop controls how the image is ' +
'rendered within the frame.',
render: function() {
return (
<View>
{[smallImage, fullImage].map((image, index) => {
return (
<View key={index}>
<View style={styles.horizontal}>
<View>
<Text style={[styles.resizeModeText]}>
Contain
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.contain}
source={image}
/>
</View>
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>
Cover
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.cover}
source={image}
/>
</View>
</View>
<View style={styles.horizontal}>
<View>
<Text style={[styles.resizeModeText]}>
Stretch
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.stretch}
source={image}
/>
</View>
{ Platform.OS === 'android' ?
<View style={styles.leftMargin}>
<Text style={[styles.resizeModeText]}>
Center
</Text>
<Image
style={styles.resizeMode}
resizeMode={Image.resizeMode.center}
source={image}
/>
</View>
: null }
</View>
</View>
);
})}
</View>
);
},
},
{
title: 'Animated GIF',
render: function() {
return (
<Image
style={styles.gif}
source={{uri: 'http://38.media.tumblr.com/9e9bd08c6e2d10561dd1fb4197df4c4e/tumblr_mfqekpMktw1rn90umo1_500.gif'}}
/>
);
},
platform: 'ios',
},
{
title: 'Base64 image',
render: function() {
return (
<Image
style={styles.base64}
source={{uri: base64Icon, scale: 3}}
/>
);
},
platform: 'ios',
},
{
title: 'Cap Insets',
description:
'When the image is resized, the corners of the size specified ' +
'by capInsets will stay a fixed size, but the center content and ' +
'borders of the image will be stretched. This is useful for creating ' +
'resizable rounded buttons, shadows, and other resizable assets.',
render: function() {
return <ImageCapInsetsExample />;
},
platform: 'ios',
},
{
title: 'Image Size',
render: function() {
return <ImageSizeExample source={fullImage} />;
},
},
{
title: 'MultipleSourcesExample',
description:
'The `source` prop allows passing in an array of uris, so that native to choose which image ' +
'to diplay based on the size of the of the target image',
render: function() {
return <MultipleSourcesExample />;
},
platform: 'android',
},
];
var fullImage = {uri: 'http://facebook.github.io/react/img/logo_og.png'};
var smallImage = {uri: 'http://facebook.github.io/react/img/logo_small_2x.png'};
var styles = StyleSheet.create({
base: {
width: 38,
height: 38,
},
progress: {
flex: 1,
alignItems: 'center',
flexDirection: 'row',
width: 100
},
leftMargin: {
marginLeft: 10,
},
background: {
backgroundColor: '#222222'
},
sectionText: {
marginVertical: 6,
},
nestedText: {
marginLeft: 12,
marginTop: 20,
backgroundColor: 'transparent',
color: 'white'
},
resizeMode: {
width: 90,
height: 60,
borderWidth: 0.5,
borderColor: 'black'
},
resizeModeText: {
fontSize: 11,
marginBottom: 3,
},
icon: {
width: 15,
height: 15,
},
horizontal: {
flexDirection: 'row',
},
gif: {
flex: 1,
height: 200,
},
base64: {
flex: 1,
height: 50,
resizeMode: 'contain',
},
touchableText: {
fontWeight: '500',
color: 'blue',
},
});
``` | {
"pile_set_name": "Github"
} |
// RUN: rm -rf %t
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -x objective-c -verify -fmodules-cache-path=%t -I %S/Inputs %s
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -x objective-c -verify -fmodules-cache-path=%t -I %S/Inputs %s -DALT
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -x objective-c -verify -fmodules-cache-path=%t -I %S/Inputs %s -detailed-preprocessing-record
// RUN: not %clang_cc1 -E -fmodules -fimplicit-module-maps -x objective-c -fmodules-cache-path=%t -I %S/Inputs %s | FileCheck -check-prefix CHECK-PREPROCESSED %s
//
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -x objective-c++ -verify -fmodules-cache-path=%t -I %S/Inputs %s
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -x objective-c++ -verify -fmodules-cache-path=%t -I %S/Inputs %s -DALT
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -x objective-c++ -verify -fmodules-cache-path=%t -I %S/Inputs %s -detailed-preprocessing-record
// RUN: not %clang_cc1 -E -fmodules -fimplicit-module-maps -x objective-c++ -fmodules-cache-path=%t -I %S/Inputs %s | FileCheck -check-prefix CHECK-PREPROCESSED %s
//
// RUN: %clang_cc1 -fmodules -fimplicit-module-maps -DLOCAL_VISIBILITY -fmodules-local-submodule-visibility -x objective-c++ -verify -fmodules-cache-path=%t -I %S/Inputs %s
// FIXME: When we have a syntax for modules in C, use that.
// These notes come from headers in modules, and are bogus.
// FIXME: expected-note@Inputs/macros_left.h:11{{previous definition is here}}
// FIXME: expected-note@Inputs/macros_right.h:12{{previous definition is here}}
// expected-note@Inputs/macros_right.h:12{{expanding this definition of 'LEFT_RIGHT_DIFFERENT'}}
// expected-note@Inputs/macros_right.h:13{{expanding this definition of 'LEFT_RIGHT_DIFFERENT2'}}
// expected-note@Inputs/macros_left.h:14{{other definition of 'LEFT_RIGHT_DIFFERENT'}}
@import macros;
#ifndef INTEGER
# error INTEGER macro should be visible
#endif
#ifdef FLOAT
# error FLOAT macro should not be visible
#endif
#ifdef MODULE
# error MODULE macro should not be visible
#endif
#ifndef INDIRECTLY_IN_MACROS
# error INDIRECTLY_IN_MACROS should be visible
#endif
// CHECK-PREPROCESSED: double d
double d;
DOUBLE *dp = &d;
#__public_macro WIBBLE // expected-error{{no macro named 'WIBBLE'}}
void f() {
// CHECK-PREPROCESSED: int i = INTEGER;
int i = INTEGER; // the value was exported, the macro was not.
i += macros; // expanded from __MODULE__ within the 'macros' module.
}
#ifdef __MODULE__
# error Not building a module!
#endif
#if __building_module(macros)
# error Not building a module
#endif
// None of the modules we depend on have been imported, and therefore
// their macros should not be visible.
#ifdef LEFT
# error LEFT should not be visible
#endif
#ifdef RIGHT
# error RIGHT should not be visible
#endif
#ifdef TOP
# error TOP should not be visible
#endif
#undef INTEGER
#define INTEGER int
// Import left module (which also imports top)
@import macros_left;
INTEGER my_integer = 0;
#ifndef LEFT
# error LEFT should be visible
#endif
#ifdef RIGHT
# error RIGHT should not be visible
#endif
#ifndef TOP
# error TOP should be visible
#endif
#ifdef TOP_LEFT_UNDEF
# error TOP_LEFT_UNDEF should not be defined
#endif
void test1() {
int i;
TOP_RIGHT_REDEF *ip = &i;
}
#define LEFT_RIGHT_DIFFERENT2 double // FIXME: expected-warning{{'LEFT_RIGHT_DIFFERENT2' macro redefined}} \
// expected-note{{other definition of 'LEFT_RIGHT_DIFFERENT2'}}
// Import right module (which also imports top)
@import macros_right;
#undef LEFT_RIGHT_DIFFERENT3
#ifndef LEFT
# error LEFT should be visible
#endif
#ifndef RIGHT
# error RIGHT should be visible
#endif
#ifndef TOP
# error TOP should be visible
#endif
void test2() {
int i;
float f;
double d;
TOP_RIGHT_REDEF *fp = &f; // ok, right's definition overrides top's definition
LEFT_RIGHT_IDENTICAL *ip = &i;
LEFT_RIGHT_DIFFERENT *ip2 = &i; // expected-warning{{ambiguous expansion of macro 'LEFT_RIGHT_DIFFERENT'}}
LEFT_RIGHT_DIFFERENT2 *ip3 = &i; // expected-warning{{ambiguous expansion of macro 'LEFT_RIGHT_DIFFERENT2}}
int LEFT_RIGHT_DIFFERENT3;
}
#define LEFT_RIGHT_DIFFERENT double // FIXME: expected-warning{{'LEFT_RIGHT_DIFFERENT' macro redefined}}
void test3() {
double d;
LEFT_RIGHT_DIFFERENT *dp = &d; // okay
int x = FN_ADD(1,2);
}
#ifndef TOP_RIGHT_UNDEF
# error TOP_RIGHT_UNDEF should still be defined
#endif
@import macros_bottom;
TOP_DEF_RIGHT_UNDEF *TDRUf() { return TDRUp; }
@import macros_right.undef;
int TOP_DEF_RIGHT_UNDEF; // ok, no longer defined
#ifdef LOCAL_VISIBILITY
// TOP_RIGHT_UNDEF should not be undefined, because macros_right.undef does
// not undefine macros_right's macro.
# ifndef TOP_RIGHT_UNDEF
# error TOP_RIGHT_UNDEF should still be defined
# endif
#else
// When macros_right.undef is built and local submodule visibility is not
// enabled, macros_top is visible because the state from building
// macros_right leaks through, so macros_right.undef undefines macros_top's
// macro.
# ifdef TOP_RIGHT_UNDEF
# error TOP_RIGHT_UNDEF should not be defined
# endif
#endif
#ifdef ALT
int tmp = TOP_OTHER_REDEF1;
#endif
@import macros_other;
#ifndef TOP_OTHER_UNDEF1
# error TOP_OTHER_UNDEF1 should still be defined
#endif
#ifndef TOP_OTHER_UNDEF2
# error TOP_OTHER_UNDEF2 should still be defined
#endif
#pragma clang __debug macro TOP_OTHER_REDEF1
#ifndef TOP_OTHER_REDEF1
# error TOP_OTHER_REDEF1 should still be defined
#endif
int n1 = TOP_OTHER_REDEF1; // expected-warning{{ambiguous expansion of macro 'TOP_OTHER_REDEF1'}}
// expected-note@macros_other.h:4 {{expanding this definition}}
// expected-note@macros_top.h:19 {{other definition}}
#ifndef TOP_OTHER_REDEF2
# error TOP_OTHER_REDEF2 should still be defined
#endif
int n2 = TOP_OTHER_REDEF2; // ok
int n3 = TOP_OTHER_DEF_RIGHT_UNDEF; // ok
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_DOM_DISTILLER_CONTENT_BROWSER_DOM_DISTILLER_VIEWER_SOURCE_H_
#define COMPONENTS_DOM_DISTILLER_CONTENT_BROWSER_DOM_DISTILLER_VIEWER_SOURCE_H_
#include <memory>
#include <string>
#include "base/compiler_specific.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_contents.h"
namespace dom_distiller {
class DomDistillerServiceInterface;
class DomDistillerViewerSourceTest;
// Serves HTML and resources for viewing distilled articles.
class DomDistillerViewerSource : public content::URLDataSource {
public:
DomDistillerViewerSource(DomDistillerServiceInterface* dom_distiller_service,
const std::string& scheme);
~DomDistillerViewerSource() override;
class RequestViewerHandle;
// Overridden from content::URLDataSource:
std::string GetSource() override;
void StartDataRequest(
const GURL& url,
const content::WebContents::Getter& wc_getter,
content::URLDataSource::GotDataCallback callback) override;
std::string GetMimeType(const std::string& path) override;
bool ShouldServiceRequest(const GURL& url,
content::BrowserContext* browser_context,
int render_process_id) override;
std::string GetContentSecurityPolicy(
network::mojom::CSPDirectiveName directive) override;
DomDistillerViewerSource(const DomDistillerViewerSource&) = delete;
DomDistillerViewerSource& operator=(const DomDistillerViewerSource&) = delete;
private:
friend class DomDistillerViewerSourceTest;
// The scheme this URLDataSource is hosted under.
std::string scheme_;
// The service which contains all the functionality needed to interact with
// the list of articles.
DomDistillerServiceInterface* dom_distiller_service_;
};
} // namespace dom_distiller
#endif // COMPONENTS_DOM_DISTILLER_CONTENT_BROWSER_DOM_DISTILLER_VIEWER_SOURCE_H_
| {
"pile_set_name": "Github"
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://html.spec.whatwg.org/multipage/#htmloptionscollection
interface HTMLOptionsCollection : HTMLCollection {
// inherits item(), namedItem()
[CEReactions]
attribute unsigned long length; // shadows inherited length
[CEReactions, Throws]
setter void (unsigned long index, HTMLOptionElement? option);
[CEReactions, Throws]
void add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
[CEReactions]
void remove(long index);
attribute long selectedIndex;
};
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2015 Kaprica Security, Inc.
*
* 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.
*
*/
#ifndef MATH_H_
#define MATH_H_
#define NAN __builtin_nan("")
#define PI 3.14159265358979323846264338327950288
static inline double fmin(double a, double b)
{
return a < b ? a : b;
}
static inline double fmax(double a, double b)
{
return a > b ? a : b;
}
#endif
| {
"pile_set_name": "Github"
} |
/*
Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments
Copyright (C) ITsysCOM GmbH
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package v1
import (
"time"
"github.com/cenkalti/rpc2"
"github.com/cgrates/cgrates/sessions"
"github.com/cgrates/cgrates/utils"
)
// Bidirectional JSON methods following
func (ssv1 *SessionSv1) Handlers() map[string]interface{} {
return map[string]interface{}{
utils.SessionSv1GetActiveSessions: ssv1.BiRPCv1GetActiveSessions,
utils.SessionSv1GetActiveSessionsCount: ssv1.BiRPCv1GetActiveSessionsCount,
utils.SessionSv1GetPassiveSessions: ssv1.BiRPCv1GetPassiveSessions,
utils.SessionSv1GetPassiveSessionsCount: ssv1.BiRPCv1GetPassiveSessionsCount,
utils.SessionSv1AuthorizeEvent: ssv1.BiRPCv1AuthorizeEvent,
utils.SessionSv1AuthorizeEventWithDigest: ssv1.BiRPCv1AuthorizeEventWithDigest,
utils.SessionSv1InitiateSession: ssv1.BiRPCv1InitiateSession,
utils.SessionSv1InitiateSessionWithDigest: ssv1.BiRPCv1InitiateSessionWithDigest,
utils.SessionSv1UpdateSession: ssv1.BiRPCv1UpdateSession,
utils.SessionSv1SyncSessions: ssv1.BiRPCv1SyncSessions,
utils.SessionSv1TerminateSession: ssv1.BiRPCv1TerminateSession,
utils.SessionSv1ProcessCDR: ssv1.BiRPCv1ProcessCDR,
utils.SessionSv1ProcessMessage: ssv1.BiRPCv1ProcessMessage,
utils.SessionSv1ProcessEvent: ssv1.BiRPCv1ProcessEvent,
utils.SessionSv1GetCost: ssv1.BiRPCv1GetCost,
utils.SessionSv1ForceDisconnect: ssv1.BiRPCv1ForceDisconnect,
utils.SessionSv1RegisterInternalBiJSONConn: ssv1.BiRPCv1RegisterInternalBiJSONConn,
utils.SessionSv1Ping: ssv1.BiRPCPing,
utils.SessionSv1ReplicateSessions: ssv1.BiRPCv1ReplicateSessions,
utils.SessionSv1SetPassiveSession: ssv1.BiRPCv1SetPassiveSession,
utils.SessionSv1ActivateSessions: ssv1.BiRPCv1ActivateSessions,
utils.SessionSv1DeactivateSessions: ssv1.BiRPCv1DeactivateSessions,
utils.SessionSv1ReAuthorize: ssv1.BiRPCV1ReAuthorize,
utils.SessionSv1DisconnectPeer: ssv1.BiRPCV1DisconnectPeer,
utils.SessionSv1STIRAuthenticate: ssv1.BiRPCV1STIRAuthenticate,
utils.SessionSv1STIRIdentity: ssv1.BiRPCV1STIRIdentity,
utils.SessionSv1Sleep: ssv1.BiRPCV1Sleep, // Sleep method is used to test the concurrent requests mechanism
}
}
func (ssv1 *SessionSv1) BiRPCv1AuthorizeEvent(clnt *rpc2.Client, args *sessions.V1AuthorizeArgs,
rply *sessions.V1AuthorizeReply) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1AuthorizeEvent(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1AuthorizeEventWithDigest(clnt *rpc2.Client, args *sessions.V1AuthorizeArgs,
rply *sessions.V1AuthorizeReplyWithDigest) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1AuthorizeEventWithDigest(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1InitiateSession(clnt *rpc2.Client, args *sessions.V1InitSessionArgs,
rply *sessions.V1InitSessionReply) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1InitiateSession(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1InitiateSessionWithDigest(clnt *rpc2.Client, args *sessions.V1InitSessionArgs,
rply *sessions.V1InitReplyWithDigest) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1InitiateSessionWithDigest(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1UpdateSession(clnt *rpc2.Client, args *sessions.V1UpdateSessionArgs,
rply *sessions.V1UpdateSessionReply) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1UpdateSession(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1SyncSessions(clnt *rpc2.Client, args *utils.TenantWithOpts,
rply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1SyncSessions(clnt, &utils.TenantWithOpts{}, rply)
}
func (ssv1 *SessionSv1) BiRPCv1TerminateSession(clnt *rpc2.Client, args *sessions.V1TerminateSessionArgs,
rply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1TerminateSession(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1ProcessCDR(clnt *rpc2.Client, cgrEv *utils.CGREventWithOpts,
rply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1ProcessCDR(clnt, cgrEv, rply)
}
func (ssv1 *SessionSv1) BiRPCv1ProcessMessage(clnt *rpc2.Client, args *sessions.V1ProcessMessageArgs,
rply *sessions.V1ProcessMessageReply) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1ProcessMessage(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1ProcessEvent(clnt *rpc2.Client, args *sessions.V1ProcessEventArgs,
rply *sessions.V1ProcessEventReply) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1ProcessEvent(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1GetCost(clnt *rpc2.Client, args *sessions.V1ProcessEventArgs,
rply *sessions.V1GetCostReply) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1GetCost(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1GetActiveSessions(clnt *rpc2.Client, args *utils.SessionFilter,
rply *[]*sessions.ExternalSession) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1GetActiveSessions(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1GetActiveSessionsCount(clnt *rpc2.Client, args *utils.SessionFilter,
rply *int) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1GetActiveSessionsCount(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1GetPassiveSessions(clnt *rpc2.Client, args *utils.SessionFilter,
rply *[]*sessions.ExternalSession) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1GetPassiveSessions(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1GetPassiveSessionsCount(clnt *rpc2.Client, args *utils.SessionFilter,
rply *int) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1GetPassiveSessionsCount(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1ForceDisconnect(clnt *rpc2.Client, args *utils.SessionFilter,
rply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1ForceDisconnect(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCv1RegisterInternalBiJSONConn(clnt *rpc2.Client, args string,
rply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1RegisterInternalBiJSONConn(clnt, args, rply)
}
func (ssv1 *SessionSv1) BiRPCPing(clnt *rpc2.Client, ign *utils.CGREventWithOpts,
reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ping(ign, reply)
}
func (ssv1 *SessionSv1) BiRPCv1ReplicateSessions(clnt *rpc2.Client,
args sessions.ArgsReplicateSessions, reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.BiRPCv1ReplicateSessions(clnt, args, reply)
}
func (ssv1 *SessionSv1) BiRPCv1SetPassiveSession(clnt *rpc2.Client,
args *sessions.Session, reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1SetPassiveSession(clnt, args, reply)
}
func (ssv1 *SessionSv1) BiRPCv1ActivateSessions(clnt *rpc2.Client,
args *utils.SessionIDsWithArgsDispatcher, reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1ActivateSessions(clnt, args, reply)
}
func (ssv1 *SessionSv1) BiRPCv1DeactivateSessions(clnt *rpc2.Client,
args *utils.SessionIDsWithArgsDispatcher, reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1DeactivateSessions(clnt, args, reply)
}
// BiRPCV1ReAuthorize sends the RAR for filterd sessions
func (ssv1 *SessionSv1) BiRPCV1ReAuthorize(clnt *rpc2.Client,
args *utils.SessionFilter, reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1ReAuthorize(clnt, args, reply)
}
// BiRPCV1DisconnectPeer sends the DPR for the OriginHost and OriginRealm
func (ssv1 *SessionSv1) BiRPCV1DisconnectPeer(clnt *rpc2.Client,
args *utils.DPRArgs, reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1DisconnectPeer(clnt, args, reply)
}
// BiRPCV1STIRAuthenticate checks the identity using STIR/SHAKEN
func (ssv1 *SessionSv1) BiRPCV1STIRAuthenticate(clnt *rpc2.Client,
args *sessions.V1STIRAuthenticateArgs, reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1STIRAuthenticate(clnt, args, reply)
}
// BiRPCV1STIRIdentity creates the identity for STIR/SHAKEN
func (ssv1 *SessionSv1) BiRPCV1STIRIdentity(clnt *rpc2.Client,
args *sessions.V1STIRIdentityArgs, reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
return ssv1.Ss.BiRPCv1STIRIdentity(nil, args, reply)
}
func (ssv1 *SessionSv1) BiRPCV1Sleep(clnt *rpc2.Client, arg *utils.DurationArgs,
reply *string) (err error) {
if err = utils.ConReqs.Allocate(); err != nil {
return
}
defer utils.ConReqs.Deallocate()
time.Sleep(arg.DurationTime)
*reply = utils.OK
return nil
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/dns/host_resolver_impl.h"
#include <memory>
#include <utility>
#include "base/memory/ptr_util.h"
#if defined(OS_WIN)
#include <Winsock2.h>
#elif defined(OS_POSIX)
#include <netdb.h>
#endif
#include <cmath>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/debug/debugger.h"
#include "base/debug/leak_annotations.h"
#include "base/debug/stack_trace.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/profiler/scoped_tracker.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/threading/worker_pool.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "base/values.h"
#include "net/base/address_family.h"
#include "net/base/address_list.h"
#include "net/base/host_port_pair.h"
#include "net/base/ip_address.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/url_util.h"
#include "net/dns/address_sorter.h"
#include "net/dns/dns_client.h"
#include "net/dns/dns_config_service.h"
#include "net/dns/dns_protocol.h"
#include "net/dns/dns_reloader.h"
#include "net/dns/dns_response.h"
#include "net/dns/dns_transaction.h"
#include "net/dns/dns_util.h"
#include "net/dns/host_resolver_proc.h"
#include "net/log/net_log.h"
#include "net/socket/client_socket_factory.h"
#include "net/udp/datagram_client_socket.h"
#include "url/url_canon_ip.h"
#if defined(OS_WIN)
#include "net/base/winsock_init.h"
#endif
namespace net {
namespace {
// Default delay between calls to the system resolver for the same hostname.
// (Can be overridden by field trial.)
const int64_t kDnsDefaultUnresponsiveDelayMs = 6000;
// Limit the size of hostnames that will be resolved to combat issues in
// some platform's resolvers.
const size_t kMaxHostLength = 4096;
// Default TTL for successful resolutions with ProcTask.
const unsigned kCacheEntryTTLSeconds = 60;
// Default TTL for unsuccessful resolutions with ProcTask.
const unsigned kNegativeCacheEntryTTLSeconds = 0;
// Minimum TTL for successful resolutions with DnsTask.
const unsigned kMinimumTTLSeconds = kCacheEntryTTLSeconds;
// Time between IPv6 probes, i.e. for how long results of each IPv6 probe are
// cached.
const int kIPv6ProbePeriodMs = 1000;
// Google DNS address used for IPv6 probes.
const uint8_t kIPv6ProbeAddress[] =
{ 0x20, 0x01, 0x48, 0x60, 0x48, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x88 };
// We use a separate histogram name for each platform to facilitate the
// display of error codes by their symbolic name (since each platform has
// different mappings).
const char kOSErrorsForGetAddrinfoHistogramName[] =
#if defined(OS_WIN)
"Net.OSErrorsForGetAddrinfo_Win";
#elif defined(OS_MACOSX)
"Net.OSErrorsForGetAddrinfo_Mac";
#elif defined(OS_LINUX)
"Net.OSErrorsForGetAddrinfo_Linux";
#else
"Net.OSErrorsForGetAddrinfo";
#endif
// Gets a list of the likely error codes that getaddrinfo() can return
// (non-exhaustive). These are the error codes that we will track via
// a histogram.
std::vector<int> GetAllGetAddrinfoOSErrors() {
int os_errors[] = {
#if defined(OS_POSIX)
#if !defined(OS_FREEBSD)
#if !defined(OS_ANDROID)
// EAI_ADDRFAMILY has been declared obsolete in Android's and
// FreeBSD's netdb.h.
EAI_ADDRFAMILY,
#endif
// EAI_NODATA has been declared obsolete in FreeBSD's netdb.h.
EAI_NODATA,
#endif
EAI_AGAIN,
EAI_BADFLAGS,
EAI_FAIL,
EAI_FAMILY,
EAI_MEMORY,
EAI_NONAME,
EAI_SERVICE,
EAI_SOCKTYPE,
EAI_SYSTEM,
#elif defined(OS_WIN)
// See: http://msdn.microsoft.com/en-us/library/ms738520(VS.85).aspx
WSA_NOT_ENOUGH_MEMORY,
WSAEAFNOSUPPORT,
WSAEINVAL,
WSAESOCKTNOSUPPORT,
WSAHOST_NOT_FOUND,
WSANO_DATA,
WSANO_RECOVERY,
WSANOTINITIALISED,
WSATRY_AGAIN,
WSATYPE_NOT_FOUND,
// The following are not in doc, but might be to appearing in results :-(.
WSA_INVALID_HANDLE,
#endif
};
// Ensure all errors are positive, as histogram only tracks positive values.
for (size_t i = 0; i < arraysize(os_errors); ++i) {
os_errors[i] = std::abs(os_errors[i]);
}
return base::CustomHistogram::ArrayToCustomRanges(os_errors,
arraysize(os_errors));
}
enum DnsResolveStatus {
RESOLVE_STATUS_DNS_SUCCESS = 0,
RESOLVE_STATUS_PROC_SUCCESS,
RESOLVE_STATUS_FAIL,
RESOLVE_STATUS_SUSPECT_NETBIOS,
RESOLVE_STATUS_MAX
};
// ICANN uses this localhost address to indicate a name collision.
//
// The policy in Chromium is to fail host resolving if it resolves to
// this special address.
//
// Not however that IP literals are exempt from this policy, so it is still
// possible to navigate to http://127.0.53.53/ directly.
//
// For more details: https://www.icann.org/news/announcement-2-2014-08-01-en
const uint8_t kIcanNameCollisionIp[] = {127, 0, 53, 53};
void UmaAsyncDnsResolveStatus(DnsResolveStatus result) {
UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ResolveStatus",
result,
RESOLVE_STATUS_MAX);
}
bool ResemblesNetBIOSName(const std::string& hostname) {
return (hostname.size() < 16) && (hostname.find('.') == std::string::npos);
}
// True if |hostname| ends with either ".local" or ".local.".
bool ResemblesMulticastDNSName(const std::string& hostname) {
DCHECK(!hostname.empty());
const char kSuffix[] = ".local.";
const size_t kSuffixLen = sizeof(kSuffix) - 1;
const size_t kSuffixLenTrimmed = kSuffixLen - 1;
if (hostname[hostname.size() - 1] == '.') {
return hostname.size() > kSuffixLen &&
!hostname.compare(hostname.size() - kSuffixLen, kSuffixLen, kSuffix);
}
return hostname.size() > kSuffixLenTrimmed &&
!hostname.compare(hostname.size() - kSuffixLenTrimmed, kSuffixLenTrimmed,
kSuffix, kSuffixLenTrimmed);
}
// Attempts to connect a UDP socket to |dest|:53.
bool IsGloballyReachable(const IPAddress& dest, const BoundNetLog& net_log) {
// TODO(eroman): Remove ScopedTracker below once crbug.com/455942 is fixed.
tracked_objects::ScopedTracker tracking_profile_1(
FROM_HERE_WITH_EXPLICIT_FUNCTION("455942 IsGloballyReachable"));
std::unique_ptr<DatagramClientSocket> socket(
ClientSocketFactory::GetDefaultFactory()->CreateDatagramClientSocket(
DatagramSocket::DEFAULT_BIND, RandIntCallback(), net_log.net_log(),
net_log.source()));
int rv = socket->Connect(IPEndPoint(dest, 53));
if (rv != OK)
return false;
IPEndPoint endpoint;
rv = socket->GetLocalAddress(&endpoint);
if (rv != OK)
return false;
DCHECK_EQ(ADDRESS_FAMILY_IPV6, endpoint.GetFamily());
const IPAddress& address = endpoint.address();
bool is_link_local =
(address.bytes()[0] == 0xFE) && ((address.bytes()[1] & 0xC0) == 0x80);
if (is_link_local)
return false;
const uint8_t kTeredoPrefix[] = {0x20, 0x01, 0, 0};
if (IPAddressStartsWith(address, kTeredoPrefix))
return false;
return true;
}
// Provide a common macro to simplify code and readability. We must use a
// macro as the underlying HISTOGRAM macro creates static variables.
#define DNS_HISTOGRAM(name, time) UMA_HISTOGRAM_CUSTOM_TIMES(name, time, \
base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromHours(1), 100)
// A macro to simplify code and readability.
#define DNS_HISTOGRAM_BY_PRIORITY(basename, priority, time) \
do { \
switch (priority) { \
case HIGHEST: DNS_HISTOGRAM(basename "_HIGHEST", time); break; \
case MEDIUM: DNS_HISTOGRAM(basename "_MEDIUM", time); break; \
case LOW: DNS_HISTOGRAM(basename "_LOW", time); break; \
case LOWEST: DNS_HISTOGRAM(basename "_LOWEST", time); break; \
case IDLE: DNS_HISTOGRAM(basename "_IDLE", time); break; \
default: NOTREACHED(); break; \
} \
DNS_HISTOGRAM(basename, time); \
} while (0)
// Record time from Request creation until a valid DNS response.
void RecordTotalTime(bool had_dns_config,
bool speculative,
base::TimeDelta duration) {
if (had_dns_config) {
if (speculative) {
DNS_HISTOGRAM("AsyncDNS.TotalTime_speculative", duration);
} else {
DNS_HISTOGRAM("AsyncDNS.TotalTime", duration);
}
} else {
if (speculative) {
DNS_HISTOGRAM("DNS.TotalTime_speculative", duration);
} else {
DNS_HISTOGRAM("DNS.TotalTime", duration);
}
}
}
void RecordTTL(base::TimeDelta ttl) {
UMA_HISTOGRAM_CUSTOM_TIMES("AsyncDNS.TTL", ttl,
base::TimeDelta::FromSeconds(1),
base::TimeDelta::FromDays(1), 100);
}
bool ConfigureAsyncDnsNoFallbackFieldTrial() {
const bool kDefault = false;
// Configure the AsyncDns field trial as follows:
// groups AsyncDnsNoFallbackA and AsyncDnsNoFallbackB: return true,
// groups AsyncDnsA and AsyncDnsB: return false,
// groups SystemDnsA and SystemDnsB: return false,
// otherwise (trial absent): return default.
std::string group_name = base::FieldTrialList::FindFullName("AsyncDns");
if (!group_name.empty()) {
return base::StartsWith(group_name, "AsyncDnsNoFallback",
base::CompareCase::INSENSITIVE_ASCII);
}
return kDefault;
}
//-----------------------------------------------------------------------------
AddressList EnsurePortOnAddressList(const AddressList& list, uint16_t port) {
if (list.empty() || list.front().port() == port)
return list;
return AddressList::CopyWithPort(list, port);
}
// Returns true if |addresses| contains only IPv4 loopback addresses.
bool IsAllIPv4Loopback(const AddressList& addresses) {
for (unsigned i = 0; i < addresses.size(); ++i) {
const IPAddress& address = addresses[i].address();
switch (addresses[i].GetFamily()) {
case ADDRESS_FAMILY_IPV4:
if (address.bytes()[0] != 127)
return false;
break;
case ADDRESS_FAMILY_IPV6:
return false;
default:
NOTREACHED();
return false;
}
}
return true;
}
// Creates NetLog parameters when the resolve failed.
std::unique_ptr<base::Value> NetLogProcTaskFailedCallback(
uint32_t attempt_number,
int net_error,
int os_error,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
if (attempt_number)
dict->SetInteger("attempt_number", attempt_number);
dict->SetInteger("net_error", net_error);
if (os_error) {
dict->SetInteger("os_error", os_error);
#if defined(OS_POSIX)
dict->SetString("os_error_string", gai_strerror(os_error));
#elif defined(OS_WIN)
// Map the error code to a human-readable string.
LPWSTR error_string = nullptr;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
0, // Use the internal message table.
os_error,
0, // Use default language.
(LPWSTR)&error_string,
0, // Buffer size.
0); // Arguments (unused).
dict->SetString("os_error_string", base::WideToUTF8(error_string));
LocalFree(error_string);
#endif
}
return std::move(dict);
}
// Creates NetLog parameters when the DnsTask failed.
std::unique_ptr<base::Value> NetLogDnsTaskFailedCallback(
int net_error,
int dns_error,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetInteger("net_error", net_error);
if (dns_error)
dict->SetInteger("dns_error", dns_error);
return std::move(dict);
};
// Creates NetLog parameters containing the information in a RequestInfo object,
// along with the associated NetLog::Source.
std::unique_ptr<base::Value> NetLogRequestInfoCallback(
const HostResolver::RequestInfo* info,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetString("host", info->host_port_pair().ToString());
dict->SetInteger("address_family",
static_cast<int>(info->address_family()));
dict->SetBoolean("allow_cached_response", info->allow_cached_response());
dict->SetBoolean("is_speculative", info->is_speculative());
return std::move(dict);
}
// Creates NetLog parameters for the creation of a HostResolverImpl::Job.
std::unique_ptr<base::Value> NetLogJobCreationCallback(
const NetLog::Source& source,
const std::string* host,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
source.AddToEventParameters(dict.get());
dict->SetString("host", *host);
return std::move(dict);
}
// Creates NetLog parameters for HOST_RESOLVER_IMPL_JOB_ATTACH/DETACH events.
std::unique_ptr<base::Value> NetLogJobAttachCallback(
const NetLog::Source& source,
RequestPriority priority,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
source.AddToEventParameters(dict.get());
dict->SetString("priority", RequestPriorityToString(priority));
return std::move(dict);
}
// Creates NetLog parameters for the DNS_CONFIG_CHANGED event.
std::unique_ptr<base::Value> NetLogDnsConfigCallback(
const DnsConfig* config,
NetLogCaptureMode /* capture_mode */) {
return config->ToValue();
}
std::unique_ptr<base::Value> NetLogIPv6AvailableCallback(
bool ipv6_available,
bool cached,
NetLogCaptureMode /* capture_mode */) {
std::unique_ptr<base::DictionaryValue> dict(new base::DictionaryValue());
dict->SetBoolean("ipv6_available", ipv6_available);
dict->SetBoolean("cached", cached);
return std::move(dict);
}
// The logging routines are defined here because some requests are resolved
// without a Request object.
// Logs when a request has just been started.
void LogStartRequest(const BoundNetLog& source_net_log,
const HostResolver::RequestInfo& info) {
source_net_log.BeginEvent(
NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST,
base::Bind(&NetLogRequestInfoCallback, &info));
}
// Logs when a request has just completed (before its callback is run).
void LogFinishRequest(const BoundNetLog& source_net_log,
const HostResolver::RequestInfo& info,
int net_error) {
source_net_log.EndEventWithNetErrorCode(
NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST, net_error);
}
// Logs when a request has been cancelled.
void LogCancelRequest(const BoundNetLog& source_net_log,
const HostResolverImpl::RequestInfo& info) {
source_net_log.AddEvent(NetLog::TYPE_CANCELLED);
source_net_log.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_REQUEST);
}
//-----------------------------------------------------------------------------
// Keeps track of the highest priority.
class PriorityTracker {
public:
explicit PriorityTracker(RequestPriority initial_priority)
: highest_priority_(initial_priority), total_count_(0) {
memset(counts_, 0, sizeof(counts_));
}
RequestPriority highest_priority() const {
return highest_priority_;
}
size_t total_count() const {
return total_count_;
}
void Add(RequestPriority req_priority) {
++total_count_;
++counts_[req_priority];
if (highest_priority_ < req_priority)
highest_priority_ = req_priority;
}
void Remove(RequestPriority req_priority) {
DCHECK_GT(total_count_, 0u);
DCHECK_GT(counts_[req_priority], 0u);
--total_count_;
--counts_[req_priority];
size_t i;
for (i = highest_priority_; i > MINIMUM_PRIORITY && !counts_[i]; --i);
highest_priority_ = static_cast<RequestPriority>(i);
// In absence of requests, default to MINIMUM_PRIORITY.
if (total_count_ == 0)
DCHECK_EQ(MINIMUM_PRIORITY, highest_priority_);
}
private:
RequestPriority highest_priority_;
size_t total_count_;
size_t counts_[NUM_PRIORITIES];
};
void MakeNotStale(HostCache::EntryStaleness* stale_info) {
if (!stale_info)
return;
stale_info->expired_by = base::TimeDelta::FromSeconds(-1);
stale_info->network_changes = 0;
stale_info->stale_hits = 0;
}
} // namespace
//-----------------------------------------------------------------------------
bool ResolveLocalHostname(base::StringPiece host,
uint16_t port,
AddressList* address_list) {
address_list->clear();
bool is_local6;
if (!IsLocalHostname(host, &is_local6))
return false;
address_list->push_back(IPEndPoint(IPAddress::IPv6Localhost(), port));
if (!is_local6) {
address_list->push_back(IPEndPoint(IPAddress::IPv4Localhost(), port));
}
return true;
}
const unsigned HostResolverImpl::kMaximumDnsFailures = 16;
// Holds the data for a request that could not be completed synchronously.
// It is owned by a Job. Canceled Requests are only marked as canceled rather
// than removed from the Job's |requests_| list.
class HostResolverImpl::Request {
public:
Request(const BoundNetLog& source_net_log,
const RequestInfo& info,
RequestPriority priority,
const CompletionCallback& callback,
AddressList* addresses)
: source_net_log_(source_net_log),
info_(info),
priority_(priority),
job_(nullptr),
callback_(callback),
addresses_(addresses),
request_time_(base::TimeTicks::Now()) {}
// Mark the request as canceled.
void MarkAsCanceled() {
job_ = nullptr;
addresses_ = nullptr;
callback_.Reset();
}
bool was_canceled() const {
return callback_.is_null();
}
void set_job(Job* job) {
DCHECK(job);
// Identify which job the request is waiting on.
job_ = job;
}
// Prepare final AddressList and call completion callback.
void OnComplete(int error, const AddressList& addr_list) {
DCHECK(!was_canceled());
if (error == OK)
*addresses_ = EnsurePortOnAddressList(addr_list, info_.port());
CompletionCallback callback = callback_;
MarkAsCanceled();
callback.Run(error);
}
Job* job() const {
return job_;
}
// NetLog for the source, passed in HostResolver::Resolve.
const BoundNetLog& source_net_log() {
return source_net_log_;
}
const RequestInfo& info() const {
return info_;
}
RequestPriority priority() const { return priority_; }
void set_priority(RequestPriority priority) { priority_ = priority; }
base::TimeTicks request_time() const { return request_time_; }
private:
const BoundNetLog source_net_log_;
// The request info that started the request.
const RequestInfo info_;
RequestPriority priority_;
// The resolve job that this request is dependent on.
Job* job_;
// The user's callback to invoke when the request completes.
CompletionCallback callback_;
// The address list to save result into.
AddressList* addresses_;
const base::TimeTicks request_time_;
DISALLOW_COPY_AND_ASSIGN(Request);
};
//------------------------------------------------------------------------------
// Calls HostResolverProc using a worker task runner. Performs retries if
// necessary.
//
// Whenever we try to resolve the host, we post a delayed task to check if host
// resolution (OnLookupComplete) is completed or not. If the original attempt
// hasn't completed, then we start another attempt for host resolution. We take
// the results from the first attempt that finishes and ignore the results from
// all other attempts.
//
// TODO(szym): Move to separate source file for testing and mocking.
//
class HostResolverImpl::ProcTask
: public base::RefCountedThreadSafe<HostResolverImpl::ProcTask> {
public:
typedef base::Callback<void(int net_error,
const AddressList& addr_list)> Callback;
ProcTask(const Key& key,
const ProcTaskParams& params,
const Callback& callback,
scoped_refptr<base::TaskRunner> worker_task_runner,
const BoundNetLog& job_net_log)
: key_(key),
params_(params),
callback_(callback),
worker_task_runner_(std::move(worker_task_runner)),
network_task_runner_(base::ThreadTaskRunnerHandle::Get()),
attempt_number_(0),
completed_attempt_number_(0),
completed_attempt_error_(ERR_UNEXPECTED),
had_non_speculative_request_(false),
net_log_(job_net_log) {
if (!params_.resolver_proc.get())
params_.resolver_proc = HostResolverProc::GetDefault();
// If default is unset, use the system proc.
if (!params_.resolver_proc.get())
params_.resolver_proc = new SystemHostResolverProc();
}
void Start() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
StartLookupAttempt();
}
// Cancels this ProcTask. It will be orphaned. Any outstanding resolve
// attempts running on worker thread will continue running. Only once all the
// attempts complete will the final reference to this ProcTask be released.
void Cancel() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (was_canceled() || was_completed())
return;
callback_.Reset();
net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK);
}
void set_had_non_speculative_request() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
had_non_speculative_request_ = true;
}
bool was_canceled() const {
DCHECK(network_task_runner_->BelongsToCurrentThread());
return callback_.is_null();
}
bool was_completed() const {
DCHECK(network_task_runner_->BelongsToCurrentThread());
return completed_attempt_number_ > 0;
}
private:
friend class base::RefCountedThreadSafe<ProcTask>;
~ProcTask() {}
void StartLookupAttempt() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
base::TimeTicks start_time = base::TimeTicks::Now();
++attempt_number_;
// Dispatch the lookup attempt to a worker thread.
if (!worker_task_runner_->PostTask(
FROM_HERE, base::Bind(&ProcTask::DoLookup, this, start_time,
attempt_number_))) {
NOTREACHED();
// Since this method may have been called from Resolve(), can't just call
// OnLookupComplete(). Instead, must wait until Resolve() has returned
// (IO_PENDING).
network_task_runner_->PostTask(
FROM_HERE,
base::Bind(&ProcTask::OnLookupComplete, this, AddressList(),
start_time, attempt_number_, ERR_UNEXPECTED, 0));
return;
}
net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_STARTED,
NetLog::IntCallback("attempt_number", attempt_number_));
// If the results aren't received within a given time, RetryIfNotComplete
// will start a new attempt if none of the outstanding attempts have
// completed yet.
if (attempt_number_ <= params_.max_retry_attempts) {
network_task_runner_->PostDelayedTask(
FROM_HERE, base::Bind(&ProcTask::RetryIfNotComplete, this),
params_.unresponsive_delay);
}
}
// WARNING: In production, this code runs on a worker pool. The shutdown code
// cannot wait for it to finish, so this code must be very careful about using
// other objects (like MessageLoops, Singletons, etc). During shutdown these
// objects may no longer exist. Multiple DoLookups() could be running in
// parallel, so any state inside of |this| must not mutate .
void DoLookup(const base::TimeTicks& start_time,
const uint32_t attempt_number) {
AddressList results;
int os_error = 0;
// Running on a worker task runner.
int error = params_.resolver_proc->Resolve(key_.hostname,
key_.address_family,
key_.host_resolver_flags,
&results,
&os_error);
// Fail the resolution if the result contains 127.0.53.53. See the comment
// block of kIcanNameCollisionIp for details on why.
for (const auto& it : results) {
const IPAddress& cur = it.address();
if (cur.IsIPv4() && IPAddressStartsWith(cur, kIcanNameCollisionIp)) {
error = ERR_ICANN_NAME_COLLISION;
break;
}
}
network_task_runner_->PostTask(
FROM_HERE, base::Bind(&ProcTask::OnLookupComplete, this, results,
start_time, attempt_number, error, os_error));
}
// Makes next attempt if DoLookup() has not finished.
void RetryIfNotComplete() {
DCHECK(network_task_runner_->BelongsToCurrentThread());
if (was_completed() || was_canceled())
return;
params_.unresponsive_delay *= params_.retry_factor;
StartLookupAttempt();
}
// Callback for when DoLookup() completes (runs on task runner thread).
void OnLookupComplete(const AddressList& results,
const base::TimeTicks& start_time,
const uint32_t attempt_number,
int error,
const int os_error) {
TRACE_EVENT0("net", "ProcTask::OnLookupComplete");
DCHECK(network_task_runner_->BelongsToCurrentThread());
// If results are empty, we should return an error.
bool empty_list_on_ok = (error == OK && results.empty());
UMA_HISTOGRAM_BOOLEAN("DNS.EmptyAddressListAndNoError", empty_list_on_ok);
if (empty_list_on_ok)
error = ERR_NAME_NOT_RESOLVED;
bool was_retry_attempt = attempt_number > 1;
// Ideally the following code would be part of host_resolver_proc.cc,
// however it isn't safe to call NetworkChangeNotifier from worker threads.
// So do it here on the IO thread instead.
if (error != OK && NetworkChangeNotifier::IsOffline())
error = ERR_INTERNET_DISCONNECTED;
// If this is the first attempt that is finishing later, then record data
// for the first attempt. Won't contaminate with retry attempt's data.
if (!was_retry_attempt)
RecordPerformanceHistograms(start_time, error, os_error);
RecordAttemptHistograms(start_time, attempt_number, error, os_error);
if (was_canceled())
return;
NetLog::ParametersCallback net_log_callback;
if (error != OK) {
net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
attempt_number,
error,
os_error);
} else {
net_log_callback = NetLog::IntCallback("attempt_number", attempt_number);
}
net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_ATTEMPT_FINISHED,
net_log_callback);
if (was_completed())
return;
// Copy the results from the first worker thread that resolves the host.
results_ = results;
completed_attempt_number_ = attempt_number;
completed_attempt_error_ = error;
if (was_retry_attempt) {
// If retry attempt finishes before 1st attempt, then get stats on how
// much time is saved by having spawned an extra attempt.
retry_attempt_finished_time_ = base::TimeTicks::Now();
}
if (error != OK) {
net_log_callback = base::Bind(&NetLogProcTaskFailedCallback,
0, error, os_error);
} else {
net_log_callback = results_.CreateNetLogCallback();
}
net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_PROC_TASK,
net_log_callback);
callback_.Run(error, results_);
}
void RecordPerformanceHistograms(const base::TimeTicks& start_time,
const int error,
const int os_error) const {
DCHECK(network_task_runner_->BelongsToCurrentThread());
enum Category { // Used in UMA_HISTOGRAM_ENUMERATION.
RESOLVE_SUCCESS,
RESOLVE_FAIL,
RESOLVE_SPECULATIVE_SUCCESS,
RESOLVE_SPECULATIVE_FAIL,
RESOLVE_MAX, // Bounding value.
};
int category = RESOLVE_MAX; // Illegal value for later DCHECK only.
base::TimeDelta duration = base::TimeTicks::Now() - start_time;
if (error == OK) {
if (had_non_speculative_request_) {
category = RESOLVE_SUCCESS;
DNS_HISTOGRAM("DNS.ResolveSuccess", duration);
} else {
category = RESOLVE_SPECULATIVE_SUCCESS;
DNS_HISTOGRAM("DNS.ResolveSpeculativeSuccess", duration);
}
// Log DNS lookups based on |address_family|. This will help us determine
// if IPv4 or IPv4/6 lookups are faster or slower.
switch(key_.address_family) {
case ADDRESS_FAMILY_IPV4:
DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV4", duration);
break;
case ADDRESS_FAMILY_IPV6:
DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_IPV6", duration);
break;
case ADDRESS_FAMILY_UNSPECIFIED:
DNS_HISTOGRAM("DNS.ResolveSuccess_FAMILY_UNSPEC", duration);
break;
}
} else {
if (had_non_speculative_request_) {
category = RESOLVE_FAIL;
DNS_HISTOGRAM("DNS.ResolveFail", duration);
} else {
category = RESOLVE_SPECULATIVE_FAIL;
DNS_HISTOGRAM("DNS.ResolveSpeculativeFail", duration);
}
// Log DNS lookups based on |address_family|. This will help us determine
// if IPv4 or IPv4/6 lookups are faster or slower.
switch(key_.address_family) {
case ADDRESS_FAMILY_IPV4:
DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV4", duration);
break;
case ADDRESS_FAMILY_IPV6:
DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_IPV6", duration);
break;
case ADDRESS_FAMILY_UNSPECIFIED:
DNS_HISTOGRAM("DNS.ResolveFail_FAMILY_UNSPEC", duration);
break;
}
UMA_HISTOGRAM_CUSTOM_ENUMERATION(kOSErrorsForGetAddrinfoHistogramName,
std::abs(os_error),
GetAllGetAddrinfoOSErrors());
}
DCHECK_LT(category, static_cast<int>(RESOLVE_MAX)); // Be sure it was set.
UMA_HISTOGRAM_ENUMERATION("DNS.ResolveCategory", category, RESOLVE_MAX);
}
void RecordAttemptHistograms(const base::TimeTicks& start_time,
const uint32_t attempt_number,
const int error,
const int os_error) const {
DCHECK(network_task_runner_->BelongsToCurrentThread());
bool first_attempt_to_complete =
completed_attempt_number_ == attempt_number;
bool is_first_attempt = (attempt_number == 1);
if (first_attempt_to_complete) {
// If this was first attempt to complete, then record the resolution
// status of the attempt.
if (completed_attempt_error_ == OK) {
UMA_HISTOGRAM_ENUMERATION(
"DNS.AttemptFirstSuccess", attempt_number, 100);
} else {
UMA_HISTOGRAM_ENUMERATION(
"DNS.AttemptFirstFailure", attempt_number, 100);
}
}
if (error == OK)
UMA_HISTOGRAM_ENUMERATION("DNS.AttemptSuccess", attempt_number, 100);
else
UMA_HISTOGRAM_ENUMERATION("DNS.AttemptFailure", attempt_number, 100);
// If first attempt didn't finish before retry attempt, then calculate stats
// on how much time is saved by having spawned an extra attempt.
if (!first_attempt_to_complete && is_first_attempt && !was_canceled()) {
DNS_HISTOGRAM("DNS.AttemptTimeSavedByRetry",
base::TimeTicks::Now() - retry_attempt_finished_time_);
}
if (was_canceled() || !first_attempt_to_complete) {
// Count those attempts which completed after the job was already canceled
// OR after the job was already completed by an earlier attempt (so in
// effect).
UMA_HISTOGRAM_ENUMERATION("DNS.AttemptDiscarded", attempt_number, 100);
// Record if job is canceled.
if (was_canceled())
UMA_HISTOGRAM_ENUMERATION("DNS.AttemptCancelled", attempt_number, 100);
}
base::TimeDelta duration = base::TimeTicks::Now() - start_time;
if (error == OK)
DNS_HISTOGRAM("DNS.AttemptSuccessDuration", duration);
else
DNS_HISTOGRAM("DNS.AttemptFailDuration", duration);
}
// Set on the task runner thread, read on the worker thread.
Key key_;
// Holds an owning reference to the HostResolverProc that we are going to use.
// This may not be the current resolver procedure by the time we call
// ResolveAddrInfo, but that's OK... we'll use it anyways, and the owning
// reference ensures that it remains valid until we are done.
ProcTaskParams params_;
// The listener to the results of this ProcTask.
Callback callback_;
// Task runner for the call to the HostResolverProc.
scoped_refptr<base::TaskRunner> worker_task_runner_;
// Used to post events onto the network thread.
scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_;
// Keeps track of the number of attempts we have made so far to resolve the
// host. Whenever we start an attempt to resolve the host, we increase this
// number.
uint32_t attempt_number_;
// The index of the attempt which finished first (or 0 if the job is still in
// progress).
uint32_t completed_attempt_number_;
// The result (a net error code) from the first attempt to complete.
int completed_attempt_error_;
// The time when retry attempt was finished.
base::TimeTicks retry_attempt_finished_time_;
// True if a non-speculative request was ever attached to this job
// (regardless of whether or not it was later canceled.
// This boolean is used for histogramming the duration of jobs used to
// service non-speculative requests.
bool had_non_speculative_request_;
AddressList results_;
BoundNetLog net_log_;
DISALLOW_COPY_AND_ASSIGN(ProcTask);
};
//-----------------------------------------------------------------------------
// Wraps a call to HaveOnlyLoopbackAddresses to be executed on a
// |worker_task_runner|, as it takes 40-100ms and should not block
// initialization.
class HostResolverImpl::LoopbackProbeJob {
public:
LoopbackProbeJob(const base::WeakPtr<HostResolverImpl>& resolver,
base::TaskRunner* worker_task_runner)
: resolver_(resolver), result_(false) {
DCHECK(resolver.get());
// |worker_task_runner| may posts tasks to the WorkerPool, so need this to
// avoid reporting worker pool leaks in tests. The WorkerPool doesn't have a
// flushing API, so can't do anything about them, other than using another
// task runner.
// http://crbug.com/248513
ANNOTATE_SCOPED_MEMORY_LEAK;
worker_task_runner->PostTaskAndReply(
FROM_HERE,
base::Bind(&LoopbackProbeJob::DoProbe, base::Unretained(this)),
base::Bind(&LoopbackProbeJob::OnProbeComplete, base::Owned(this)));
}
virtual ~LoopbackProbeJob() {}
private:
// Runs on worker thread.
void DoProbe() {
result_ = HaveOnlyLoopbackAddresses();
}
void OnProbeComplete() {
if (!resolver_.get())
return;
resolver_->SetHaveOnlyLoopbackAddresses(result_);
}
// Used/set only on task runner thread.
base::WeakPtr<HostResolverImpl> resolver_;
bool result_;
DISALLOW_COPY_AND_ASSIGN(LoopbackProbeJob);
};
//-----------------------------------------------------------------------------
// Resolves the hostname using DnsTransaction.
// TODO(szym): This could be moved to separate source file as well.
class HostResolverImpl::DnsTask : public base::SupportsWeakPtr<DnsTask> {
public:
class Delegate {
public:
virtual void OnDnsTaskComplete(base::TimeTicks start_time,
int net_error,
const AddressList& addr_list,
base::TimeDelta ttl) = 0;
// Called when the first of two jobs succeeds. If the first completed
// transaction fails, this is not called. Also not called when the DnsTask
// only needs to run one transaction.
virtual void OnFirstDnsTransactionComplete() = 0;
protected:
Delegate() {}
virtual ~Delegate() {}
};
DnsTask(DnsClient* client,
const Key& key,
Delegate* delegate,
const BoundNetLog& job_net_log)
: client_(client),
key_(key),
delegate_(delegate),
net_log_(job_net_log),
num_completed_transactions_(0),
task_start_time_(base::TimeTicks::Now()) {
DCHECK(client);
DCHECK(delegate_);
}
bool needs_two_transactions() const {
return key_.address_family == ADDRESS_FAMILY_UNSPECIFIED;
}
bool needs_another_transaction() const {
return needs_two_transactions() && !transaction_aaaa_;
}
void StartFirstTransaction() {
DCHECK_EQ(0u, num_completed_transactions_);
net_log_.BeginEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK);
if (key_.address_family == ADDRESS_FAMILY_IPV6) {
StartAAAA();
} else {
StartA();
}
}
void StartSecondTransaction() {
DCHECK(needs_two_transactions());
StartAAAA();
}
private:
void StartA() {
DCHECK(!transaction_a_);
DCHECK_NE(ADDRESS_FAMILY_IPV6, key_.address_family);
transaction_a_ = CreateTransaction(ADDRESS_FAMILY_IPV4);
transaction_a_->Start();
}
void StartAAAA() {
DCHECK(!transaction_aaaa_);
DCHECK_NE(ADDRESS_FAMILY_IPV4, key_.address_family);
transaction_aaaa_ = CreateTransaction(ADDRESS_FAMILY_IPV6);
transaction_aaaa_->Start();
}
std::unique_ptr<DnsTransaction> CreateTransaction(AddressFamily family) {
DCHECK_NE(ADDRESS_FAMILY_UNSPECIFIED, family);
return client_->GetTransactionFactory()->CreateTransaction(
key_.hostname,
family == ADDRESS_FAMILY_IPV6 ? dns_protocol::kTypeAAAA :
dns_protocol::kTypeA,
base::Bind(&DnsTask::OnTransactionComplete, base::Unretained(this),
base::TimeTicks::Now()),
net_log_);
}
void OnTransactionComplete(const base::TimeTicks& start_time,
DnsTransaction* transaction,
int net_error,
const DnsResponse* response) {
DCHECK(transaction);
base::TimeDelta duration = base::TimeTicks::Now() - start_time;
if (net_error != OK) {
DNS_HISTOGRAM("AsyncDNS.TransactionFailure", duration);
OnFailure(net_error, DnsResponse::DNS_PARSE_OK);
return;
}
DNS_HISTOGRAM("AsyncDNS.TransactionSuccess", duration);
switch (transaction->GetType()) {
case dns_protocol::kTypeA:
DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_A", duration);
break;
case dns_protocol::kTypeAAAA:
DNS_HISTOGRAM("AsyncDNS.TransactionSuccess_AAAA", duration);
break;
}
AddressList addr_list;
base::TimeDelta ttl;
DnsResponse::Result result = response->ParseToAddressList(&addr_list, &ttl);
UMA_HISTOGRAM_ENUMERATION("AsyncDNS.ParseToAddressList",
result,
DnsResponse::DNS_PARSE_RESULT_MAX);
if (result != DnsResponse::DNS_PARSE_OK) {
// Fail even if the other query succeeds.
OnFailure(ERR_DNS_MALFORMED_RESPONSE, result);
return;
}
++num_completed_transactions_;
if (num_completed_transactions_ == 1) {
ttl_ = ttl;
} else {
ttl_ = std::min(ttl_, ttl);
}
if (transaction->GetType() == dns_protocol::kTypeA) {
DCHECK_EQ(transaction_a_.get(), transaction);
// Place IPv4 addresses after IPv6.
addr_list_.insert(addr_list_.end(), addr_list.begin(), addr_list.end());
} else {
DCHECK_EQ(transaction_aaaa_.get(), transaction);
// Place IPv6 addresses before IPv4.
addr_list_.insert(addr_list_.begin(), addr_list.begin(), addr_list.end());
}
if (needs_two_transactions() && num_completed_transactions_ == 1) {
// No need to repeat the suffix search.
key_.hostname = transaction->GetHostname();
delegate_->OnFirstDnsTransactionComplete();
return;
}
if (addr_list_.empty()) {
// TODO(szym): Don't fallback to ProcTask in this case.
OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
return;
}
// If there are multiple addresses, and at least one is IPv6, need to sort
// them. Note that IPv6 addresses are always put before IPv4 ones, so it's
// sufficient to just check the family of the first address.
if (addr_list_.size() > 1 &&
addr_list_[0].GetFamily() == ADDRESS_FAMILY_IPV6) {
// Sort addresses if needed. Sort could complete synchronously.
client_->GetAddressSorter()->Sort(
addr_list_,
base::Bind(&DnsTask::OnSortComplete,
AsWeakPtr(),
base::TimeTicks::Now()));
} else {
OnSuccess(addr_list_);
}
}
void OnSortComplete(base::TimeTicks start_time,
bool success,
const AddressList& addr_list) {
if (!success) {
DNS_HISTOGRAM("AsyncDNS.SortFailure",
base::TimeTicks::Now() - start_time);
OnFailure(ERR_DNS_SORT_ERROR, DnsResponse::DNS_PARSE_OK);
return;
}
DNS_HISTOGRAM("AsyncDNS.SortSuccess",
base::TimeTicks::Now() - start_time);
// AddressSorter prunes unusable destinations.
if (addr_list.empty()) {
LOG(WARNING) << "Address list empty after RFC3484 sort";
OnFailure(ERR_NAME_NOT_RESOLVED, DnsResponse::DNS_PARSE_OK);
return;
}
OnSuccess(addr_list);
}
void OnFailure(int net_error, DnsResponse::Result result) {
DCHECK_NE(OK, net_error);
net_log_.EndEvent(
NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
base::Bind(&NetLogDnsTaskFailedCallback, net_error, result));
delegate_->OnDnsTaskComplete(task_start_time_, net_error, AddressList(),
base::TimeDelta());
}
void OnSuccess(const AddressList& addr_list) {
net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_DNS_TASK,
addr_list.CreateNetLogCallback());
delegate_->OnDnsTaskComplete(task_start_time_, OK, addr_list, ttl_);
}
DnsClient* client_;
Key key_;
// The listener to the results of this DnsTask.
Delegate* delegate_;
const BoundNetLog net_log_;
std::unique_ptr<DnsTransaction> transaction_a_;
std::unique_ptr<DnsTransaction> transaction_aaaa_;
unsigned num_completed_transactions_;
// These are updated as each transaction completes.
base::TimeDelta ttl_;
// IPv6 addresses must appear first in the list.
AddressList addr_list_;
base::TimeTicks task_start_time_;
DISALLOW_COPY_AND_ASSIGN(DnsTask);
};
//-----------------------------------------------------------------------------
// Aggregates all Requests for the same Key. Dispatched via PriorityDispatch.
class HostResolverImpl::Job : public PrioritizedDispatcher::Job,
public HostResolverImpl::DnsTask::Delegate {
public:
// Creates new job for |key| where |request_net_log| is bound to the
// request that spawned it.
Job(const base::WeakPtr<HostResolverImpl>& resolver,
const Key& key,
RequestPriority priority,
scoped_refptr<base::TaskRunner> worker_task_runner,
const BoundNetLog& source_net_log)
: resolver_(resolver),
key_(key),
priority_tracker_(priority),
worker_task_runner_(std::move(worker_task_runner)),
had_non_speculative_request_(false),
had_dns_config_(false),
num_occupied_job_slots_(0),
dns_task_error_(OK),
creation_time_(base::TimeTicks::Now()),
priority_change_time_(creation_time_),
net_log_(BoundNetLog::Make(source_net_log.net_log(),
NetLog::SOURCE_HOST_RESOLVER_IMPL_JOB)) {
source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CREATE_JOB);
net_log_.BeginEvent(
NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
base::Bind(&NetLogJobCreationCallback,
source_net_log.source(),
&key_.hostname));
}
~Job() override {
if (is_running()) {
// |resolver_| was destroyed with this Job still in flight.
// Clean-up, record in the log, but don't run any callbacks.
if (is_proc_running()) {
proc_task_->Cancel();
proc_task_ = nullptr;
}
// Clean up now for nice NetLog.
KillDnsTask();
net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
ERR_ABORTED);
} else if (is_queued()) {
// |resolver_| was destroyed without running this Job.
// TODO(szym): is there any benefit in having this distinction?
net_log_.AddEvent(NetLog::TYPE_CANCELLED);
net_log_.EndEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB);
}
// else CompleteRequests logged EndEvent.
// Log any remaining Requests as cancelled.
for (const std::unique_ptr<Request>& req : requests_) {
if (req->was_canceled())
continue;
DCHECK_EQ(this, req->job());
LogCancelRequest(req->source_net_log(), req->info());
}
}
// Add this job to the dispatcher. If "at_head" is true, adds at the front
// of the queue.
void Schedule(bool at_head) {
DCHECK(!is_queued());
PrioritizedDispatcher::Handle handle;
if (!at_head) {
handle = resolver_->dispatcher_->Add(this, priority());
} else {
handle = resolver_->dispatcher_->AddAtHead(this, priority());
}
// The dispatcher could have started |this| in the above call to Add, which
// could have called Schedule again. In that case |handle| will be null,
// but |handle_| may have been set by the other nested call to Schedule.
if (!handle.is_null()) {
DCHECK(handle_.is_null());
handle_ = handle;
}
}
void AddRequest(std::unique_ptr<Request> req) {
DCHECK_EQ(key_.hostname, req->info().hostname());
req->set_job(this);
priority_tracker_.Add(req->priority());
req->source_net_log().AddEvent(
NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_ATTACH,
net_log_.source().ToEventParametersCallback());
net_log_.AddEvent(
NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_ATTACH,
base::Bind(&NetLogJobAttachCallback,
req->source_net_log().source(),
priority()));
// TODO(szym): Check if this is still needed.
if (!req->info().is_speculative()) {
had_non_speculative_request_ = true;
if (proc_task_.get())
proc_task_->set_had_non_speculative_request();
}
requests_.push_back(std::move(req));
UpdatePriority();
}
void ChangeRequestPriority(Request* req, RequestPriority priority) {
DCHECK_EQ(key_.hostname, req->info().hostname());
DCHECK(!req->was_canceled());
priority_tracker_.Remove(req->priority());
req->set_priority(priority);
priority_tracker_.Add(req->priority());
UpdatePriority();
}
// Marks |req| as cancelled. If it was the last active Request, also finishes
// this Job, marking it as cancelled, and deletes it.
void CancelRequest(Request* req) {
DCHECK_EQ(key_.hostname, req->info().hostname());
DCHECK(!req->was_canceled());
// Don't remove it from |requests_| just mark it canceled.
req->MarkAsCanceled();
LogCancelRequest(req->source_net_log(), req->info());
priority_tracker_.Remove(req->priority());
net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_REQUEST_DETACH,
base::Bind(&NetLogJobAttachCallback,
req->source_net_log().source(),
priority()));
if (num_active_requests() > 0) {
UpdatePriority();
} else {
// If we were called from a Request's callback within CompleteRequests,
// that Request could not have been cancelled, so num_active_requests()
// could not be 0. Therefore, we are not in CompleteRequests().
CompleteRequestsWithError(OK /* cancelled */);
}
}
// Called from AbortAllInProgressJobs. Completes all requests and destroys
// the job. This currently assumes the abort is due to a network change.
// TODO This should not delete |this|.
void Abort() {
DCHECK(is_running());
CompleteRequestsWithError(ERR_NETWORK_CHANGED);
}
// If DnsTask present, abort it and fall back to ProcTask.
void AbortDnsTask() {
if (dns_task_) {
KillDnsTask();
dns_task_error_ = OK;
StartProcTask();
}
}
// Called by HostResolverImpl when this job is evicted due to queue overflow.
// Completes all requests and destroys the job.
void OnEvicted() {
DCHECK(!is_running());
DCHECK(is_queued());
handle_.Reset();
net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_EVICTED);
// This signals to CompleteRequests that this job never ran.
CompleteRequestsWithError(ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
}
// Attempts to serve the job from HOSTS. Returns true if succeeded and
// this Job was destroyed.
bool ServeFromHosts() {
DCHECK_GT(num_active_requests(), 0u);
AddressList addr_list;
if (resolver_->ServeFromHosts(key(),
requests_.front()->info(),
&addr_list)) {
// This will destroy the Job.
CompleteRequests(
HostCache::Entry(OK, MakeAddressListForRequest(addr_list)),
base::TimeDelta());
return true;
}
return false;
}
const Key& key() const { return key_; }
bool is_queued() const {
return !handle_.is_null();
}
bool is_running() const {
return is_dns_running() || is_proc_running();
}
private:
void KillDnsTask() {
if (dns_task_) {
ReduceToOneJobSlot();
dns_task_.reset();
}
}
// Reduce the number of job slots occupied and queued in the dispatcher
// to one. If the second Job slot is queued in the dispatcher, cancels the
// queued job. Otherwise, the second Job has been started by the
// PrioritizedDispatcher, so signals it is complete.
void ReduceToOneJobSlot() {
DCHECK_GE(num_occupied_job_slots_, 1u);
if (is_queued()) {
resolver_->dispatcher_->Cancel(handle_);
handle_.Reset();
} else if (num_occupied_job_slots_ > 1) {
resolver_->dispatcher_->OnJobFinished();
--num_occupied_job_slots_;
}
DCHECK_EQ(1u, num_occupied_job_slots_);
}
AddressList MakeAddressListForRequest(const AddressList& list) const {
if (requests_.empty())
return list;
return AddressList::CopyWithPort(list, requests_.front()->info().port());
}
void UpdatePriority() {
if (is_queued()) {
if (priority() != static_cast<RequestPriority>(handle_.priority()))
priority_change_time_ = base::TimeTicks::Now();
handle_ = resolver_->dispatcher_->ChangePriority(handle_, priority());
}
}
// PriorityDispatch::Job:
void Start() override {
DCHECK_LE(num_occupied_job_slots_, 1u);
handle_.Reset();
++num_occupied_job_slots_;
if (num_occupied_job_slots_ == 2) {
StartSecondDnsTransaction();
return;
}
DCHECK(!is_running());
net_log_.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB_STARTED);
had_dns_config_ = resolver_->HaveDnsConfig();
base::TimeTicks now = base::TimeTicks::Now();
base::TimeDelta queue_time = now - creation_time_;
base::TimeDelta queue_time_after_change = now - priority_change_time_;
if (had_dns_config_) {
DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTime", priority(),
queue_time);
DNS_HISTOGRAM_BY_PRIORITY("AsyncDNS.JobQueueTimeAfterChange", priority(),
queue_time_after_change);
} else {
DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTime", priority(), queue_time);
DNS_HISTOGRAM_BY_PRIORITY("DNS.JobQueueTimeAfterChange", priority(),
queue_time_after_change);
}
bool system_only =
(key_.host_resolver_flags & HOST_RESOLVER_SYSTEM_ONLY) != 0;
// Caution: Job::Start must not complete synchronously.
if (!system_only && had_dns_config_ &&
!ResemblesMulticastDNSName(key_.hostname)) {
StartDnsTask();
} else {
StartProcTask();
}
}
// TODO(szym): Since DnsTransaction does not consume threads, we can increase
// the limits on |dispatcher_|. But in order to keep the number of WorkerPool
// threads low, we will need to use an "inner" PrioritizedDispatcher with
// tighter limits.
void StartProcTask() {
DCHECK(!is_dns_running());
proc_task_ =
new ProcTask(key_, resolver_->proc_params_,
base::Bind(&Job::OnProcTaskComplete,
base::Unretained(this), base::TimeTicks::Now()),
worker_task_runner_, net_log_);
if (had_non_speculative_request_)
proc_task_->set_had_non_speculative_request();
// Start() could be called from within Resolve(), hence it must NOT directly
// call OnProcTaskComplete, for example, on synchronous failure.
proc_task_->Start();
}
// Called by ProcTask when it completes.
void OnProcTaskComplete(base::TimeTicks start_time,
int net_error,
const AddressList& addr_list) {
DCHECK(is_proc_running());
if (!resolver_->resolved_known_ipv6_hostname_ &&
net_error == OK &&
key_.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
if (key_.hostname == "www.google.com") {
resolver_->resolved_known_ipv6_hostname_ = true;
bool got_ipv6_address = false;
for (size_t i = 0; i < addr_list.size(); ++i) {
if (addr_list[i].GetFamily() == ADDRESS_FAMILY_IPV6) {
got_ipv6_address = true;
break;
}
}
UMA_HISTOGRAM_BOOLEAN("Net.UnspecResolvedIPv6", got_ipv6_address);
}
}
if (dns_task_error_ != OK) {
base::TimeDelta duration = base::TimeTicks::Now() - start_time;
if (net_error == OK) {
DNS_HISTOGRAM("AsyncDNS.FallbackSuccess", duration);
if ((dns_task_error_ == ERR_NAME_NOT_RESOLVED) &&
ResemblesNetBIOSName(key_.hostname)) {
UmaAsyncDnsResolveStatus(RESOLVE_STATUS_SUSPECT_NETBIOS);
} else {
UmaAsyncDnsResolveStatus(RESOLVE_STATUS_PROC_SUCCESS);
}
UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.ResolveError",
std::abs(dns_task_error_));
resolver_->OnDnsTaskResolve(dns_task_error_);
} else {
DNS_HISTOGRAM("AsyncDNS.FallbackFail", duration);
UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
}
}
base::TimeDelta ttl =
base::TimeDelta::FromSeconds(kNegativeCacheEntryTTLSeconds);
if (net_error == OK)
ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds);
// Don't store the |ttl| in cache since it's not obtained from the server.
CompleteRequests(
HostCache::Entry(net_error, MakeAddressListForRequest(addr_list)),
ttl);
}
void StartDnsTask() {
DCHECK(resolver_->HaveDnsConfig());
dns_task_.reset(new DnsTask(resolver_->dns_client_.get(), key_, this,
net_log_));
dns_task_->StartFirstTransaction();
// Schedule a second transaction, if needed.
if (dns_task_->needs_two_transactions())
Schedule(true);
}
void StartSecondDnsTransaction() {
DCHECK(dns_task_->needs_two_transactions());
dns_task_->StartSecondTransaction();
}
// Called if DnsTask fails. It is posted from StartDnsTask, so Job may be
// deleted before this callback. In this case dns_task is deleted as well,
// so we use it as indicator whether Job is still valid.
void OnDnsTaskFailure(const base::WeakPtr<DnsTask>& dns_task,
base::TimeDelta duration,
int net_error) {
DNS_HISTOGRAM("AsyncDNS.ResolveFail", duration);
if (!dns_task)
return;
dns_task_error_ = net_error;
// TODO(szym): Run ServeFromHosts now if nsswitch.conf says so.
// http://crbug.com/117655
// TODO(szym): Some net errors indicate lack of connectivity. Starting
// ProcTask in that case is a waste of time.
if (resolver_->fallback_to_proctask_) {
KillDnsTask();
StartProcTask();
} else {
UmaAsyncDnsResolveStatus(RESOLVE_STATUS_FAIL);
CompleteRequestsWithError(net_error);
}
}
// HostResolverImpl::DnsTask::Delegate implementation:
void OnDnsTaskComplete(base::TimeTicks start_time,
int net_error,
const AddressList& addr_list,
base::TimeDelta ttl) override {
DCHECK(is_dns_running());
base::TimeDelta duration = base::TimeTicks::Now() - start_time;
if (net_error != OK) {
OnDnsTaskFailure(dns_task_->AsWeakPtr(), duration, net_error);
return;
}
DNS_HISTOGRAM("AsyncDNS.ResolveSuccess", duration);
// Log DNS lookups based on |address_family|.
switch(key_.address_family) {
case ADDRESS_FAMILY_IPV4:
DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV4", duration);
break;
case ADDRESS_FAMILY_IPV6:
DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_IPV6", duration);
break;
case ADDRESS_FAMILY_UNSPECIFIED:
DNS_HISTOGRAM("AsyncDNS.ResolveSuccess_FAMILY_UNSPEC", duration);
break;
}
UmaAsyncDnsResolveStatus(RESOLVE_STATUS_DNS_SUCCESS);
RecordTTL(ttl);
resolver_->OnDnsTaskResolve(OK);
base::TimeDelta bounded_ttl =
std::max(ttl, base::TimeDelta::FromSeconds(kMinimumTTLSeconds));
CompleteRequests(
HostCache::Entry(net_error, MakeAddressListForRequest(addr_list), ttl),
bounded_ttl);
}
void OnFirstDnsTransactionComplete() override {
DCHECK(dns_task_->needs_two_transactions());
DCHECK_EQ(dns_task_->needs_another_transaction(), is_queued());
// No longer need to occupy two dispatcher slots.
ReduceToOneJobSlot();
// We already have a job slot at the dispatcher, so if the second
// transaction hasn't started, reuse it now instead of waiting in the queue
// for the second slot.
if (dns_task_->needs_another_transaction())
dns_task_->StartSecondTransaction();
}
// Performs Job's last rites. Completes all Requests. Deletes this.
void CompleteRequests(const HostCache::Entry& entry,
base::TimeDelta ttl) {
CHECK(resolver_.get());
// This job must be removed from resolver's |jobs_| now to make room for a
// new job with the same key in case one of the OnComplete callbacks decides
// to spawn one. Consequently, the job deletes itself when CompleteRequests
// is done.
std::unique_ptr<Job> self_deleter(this);
resolver_->RemoveJob(this);
if (is_running()) {
if (is_proc_running()) {
DCHECK(!is_queued());
proc_task_->Cancel();
proc_task_ = nullptr;
}
KillDnsTask();
// Signal dispatcher that a slot has opened.
resolver_->dispatcher_->OnJobFinished();
} else if (is_queued()) {
resolver_->dispatcher_->Cancel(handle_);
handle_.Reset();
}
if (num_active_requests() == 0) {
net_log_.AddEvent(NetLog::TYPE_CANCELLED);
net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
OK);
return;
}
net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HOST_RESOLVER_IMPL_JOB,
entry.error());
DCHECK(!requests_.empty());
if (entry.error() == OK) {
// Record this histogram here, when we know the system has a valid DNS
// configuration.
UMA_HISTOGRAM_BOOLEAN("AsyncDNS.HaveDnsConfig",
resolver_->received_dns_config_);
}
bool did_complete = (entry.error() != ERR_NETWORK_CHANGED) &&
(entry.error() != ERR_HOST_RESOLVER_QUEUE_TOO_LARGE);
if (did_complete)
resolver_->CacheResult(key_, entry, ttl);
// Complete all of the requests that were attached to the job.
for (const std::unique_ptr<Request>& req : requests_) {
if (req->was_canceled())
continue;
DCHECK_EQ(this, req->job());
// Update the net log and notify registered observers.
LogFinishRequest(req->source_net_log(), req->info(), entry.error());
if (did_complete) {
// Record effective total time from creation to completion.
RecordTotalTime(had_dns_config_, req->info().is_speculative(),
base::TimeTicks::Now() - req->request_time());
}
req->OnComplete(entry.error(), entry.addresses());
// Check if the resolver was destroyed as a result of running the
// callback. If it was, we could continue, but we choose to bail.
if (!resolver_.get())
return;
}
}
// Convenience wrapper for CompleteRequests in case of failure.
void CompleteRequestsWithError(int net_error) {
CompleteRequests(HostCache::Entry(net_error, AddressList()),
base::TimeDelta());
}
RequestPriority priority() const {
return priority_tracker_.highest_priority();
}
// Number of non-canceled requests in |requests_|.
size_t num_active_requests() const {
return priority_tracker_.total_count();
}
bool is_dns_running() const { return !!dns_task_; }
bool is_proc_running() const { return !!proc_task_; }
base::WeakPtr<HostResolverImpl> resolver_;
Key key_;
// Tracks the highest priority across |requests_|.
PriorityTracker priority_tracker_;
// Task runner where the HostResolverProc is invoked.
scoped_refptr<base::TaskRunner> worker_task_runner_;
bool had_non_speculative_request_;
// Distinguishes measurements taken while DnsClient was fully configured.
bool had_dns_config_;
// Number of slots occupied by this Job in resolver's PrioritizedDispatcher.
unsigned num_occupied_job_slots_;
// Result of DnsTask.
int dns_task_error_;
const base::TimeTicks creation_time_;
base::TimeTicks priority_change_time_;
BoundNetLog net_log_;
// Resolves the host using a HostResolverProc.
scoped_refptr<ProcTask> proc_task_;
// Resolves the host using a DnsTransaction.
std::unique_ptr<DnsTask> dns_task_;
// All Requests waiting for the result of this Job. Some can be canceled.
std::vector<std::unique_ptr<Request>> requests_;
// A handle used in |HostResolverImpl::dispatcher_|.
PrioritizedDispatcher::Handle handle_;
};
//-----------------------------------------------------------------------------
HostResolverImpl::ProcTaskParams::ProcTaskParams(
HostResolverProc* resolver_proc,
size_t max_retry_attempts)
: resolver_proc(resolver_proc),
max_retry_attempts(max_retry_attempts),
unresponsive_delay(
base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs)),
retry_factor(2) {
// Maximum of 4 retry attempts for host resolution.
static const size_t kDefaultMaxRetryAttempts = 4u;
if (max_retry_attempts == HostResolver::kDefaultRetryAttempts)
max_retry_attempts = kDefaultMaxRetryAttempts;
}
HostResolverImpl::ProcTaskParams::ProcTaskParams(const ProcTaskParams& other) =
default;
HostResolverImpl::ProcTaskParams::~ProcTaskParams() {}
HostResolverImpl::HostResolverImpl(const Options& options, NetLog* net_log)
: HostResolverImpl(
options,
net_log,
base::WorkerPool::GetTaskRunner(true /* task_is_slow */)) {}
HostResolverImpl::~HostResolverImpl() {
// Prevent the dispatcher from starting new jobs.
dispatcher_->SetLimitsToZero();
// It's now safe for Jobs to call KillDsnTask on destruction, because
// OnJobComplete will not start any new jobs.
STLDeleteValues(&jobs_);
NetworkChangeNotifier::RemoveIPAddressObserver(this);
NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
NetworkChangeNotifier::RemoveDNSObserver(this);
}
void HostResolverImpl::SetMaxQueuedJobs(size_t value) {
DCHECK_EQ(0u, dispatcher_->num_queued_jobs());
DCHECK_GT(value, 0u);
max_queued_jobs_ = value;
}
int HostResolverImpl::Resolve(const RequestInfo& info,
RequestPriority priority,
AddressList* addresses,
const CompletionCallback& callback,
RequestHandle* out_req,
const BoundNetLog& source_net_log) {
DCHECK(addresses);
DCHECK(CalledOnValidThread());
DCHECK_EQ(false, callback.is_null());
// Check that the caller supplied a valid hostname to resolve.
std::string labeled_hostname;
if (!DNSDomainFromDot(info.hostname(), &labeled_hostname))
return ERR_NAME_NOT_RESOLVED;
LogStartRequest(source_net_log, info);
IPAddress ip_address;
IPAddress* ip_address_ptr = nullptr;
if (ip_address.AssignFromIPLiteral(info.hostname()))
ip_address_ptr = &ip_address;
// Build a key that identifies the request in the cache and in the
// outstanding jobs map.
Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
int rv = ResolveHelper(key, info, ip_address_ptr, addresses, false, nullptr,
source_net_log);
if (rv != ERR_DNS_CACHE_MISS) {
LogFinishRequest(source_net_log, info, rv);
RecordTotalTime(HaveDnsConfig(), info.is_speculative(), base::TimeDelta());
return rv;
}
// Next we need to attach our request to a "job". This job is responsible for
// calling "getaddrinfo(hostname)" on a worker thread.
JobMap::iterator jobit = jobs_.find(key);
Job* job;
if (jobit == jobs_.end()) {
job = new Job(weak_ptr_factory_.GetWeakPtr(), key, priority,
worker_task_runner_, source_net_log);
job->Schedule(false);
// Check for queue overflow.
if (dispatcher_->num_queued_jobs() > max_queued_jobs_) {
Job* evicted = static_cast<Job*>(dispatcher_->EvictOldestLowest());
DCHECK(evicted);
evicted->OnEvicted(); // Deletes |evicted|.
if (evicted == job) {
rv = ERR_HOST_RESOLVER_QUEUE_TOO_LARGE;
LogFinishRequest(source_net_log, info, rv);
return rv;
}
}
jobs_.insert(jobit, std::make_pair(key, job));
} else {
job = jobit->second;
}
// Can't complete synchronously. Create and attach request.
std::unique_ptr<Request> req(
new Request(source_net_log, info, priority, callback, addresses));
if (out_req)
*out_req = reinterpret_cast<RequestHandle>(req.get());
job->AddRequest(std::move(req));
// Completion happens during Job::CompleteRequests().
return ERR_IO_PENDING;
}
HostResolverImpl::HostResolverImpl(
const Options& options,
NetLog* net_log,
scoped_refptr<base::TaskRunner> worker_task_runner)
: max_queued_jobs_(0),
proc_params_(NULL, options.max_retry_attempts),
net_log_(net_log),
received_dns_config_(false),
num_dns_failures_(0),
use_local_ipv6_(false),
last_ipv6_probe_result_(true),
resolved_known_ipv6_hostname_(false),
additional_resolver_flags_(0),
fallback_to_proctask_(true),
worker_task_runner_(std::move(worker_task_runner)),
weak_ptr_factory_(this),
probe_weak_ptr_factory_(this) {
if (options.enable_caching)
cache_ = HostCache::CreateDefaultCache();
PrioritizedDispatcher::Limits job_limits = options.GetDispatcherLimits();
dispatcher_.reset(new PrioritizedDispatcher(job_limits));
max_queued_jobs_ = job_limits.total_jobs * 100u;
DCHECK_GE(dispatcher_->num_priorities(), static_cast<size_t>(NUM_PRIORITIES));
#if defined(OS_WIN)
EnsureWinsockInit();
#endif
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
RunLoopbackProbeJob();
#endif
NetworkChangeNotifier::AddIPAddressObserver(this);
NetworkChangeNotifier::AddConnectionTypeObserver(this);
NetworkChangeNotifier::AddDNSObserver(this);
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) && \
!defined(OS_ANDROID)
EnsureDnsReloaderInit();
#endif
OnConnectionTypeChanged(NetworkChangeNotifier::GetConnectionType());
{
DnsConfig dns_config;
NetworkChangeNotifier::GetDnsConfig(&dns_config);
received_dns_config_ = dns_config.IsValid();
// Conservatively assume local IPv6 is needed when DnsConfig is not valid.
use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
}
fallback_to_proctask_ = !ConfigureAsyncDnsNoFallbackFieldTrial();
}
void HostResolverImpl::SetHaveOnlyLoopbackAddresses(bool result) {
if (result) {
additional_resolver_flags_ |= HOST_RESOLVER_LOOPBACK_ONLY;
} else {
additional_resolver_flags_ &= ~HOST_RESOLVER_LOOPBACK_ONLY;
}
}
int HostResolverImpl::ResolveHelper(const Key& key,
const RequestInfo& info,
const IPAddress* ip_address,
AddressList* addresses,
bool allow_stale,
HostCache::EntryStaleness* stale_info,
const BoundNetLog& source_net_log) {
DCHECK(allow_stale == !!stale_info);
// The result of |getaddrinfo| for empty hosts is inconsistent across systems.
// On Windows it gives the default interface's address, whereas on Linux it
// gives an error. We will make it fail on all platforms for consistency.
if (info.hostname().empty() || info.hostname().size() > kMaxHostLength) {
MakeNotStale(stale_info);
return ERR_NAME_NOT_RESOLVED;
}
int net_error = ERR_UNEXPECTED;
if (ResolveAsIP(key, info, ip_address, &net_error, addresses)) {
MakeNotStale(stale_info);
return net_error;
}
if (ServeFromCache(key, info, &net_error, addresses, allow_stale,
stale_info)) {
source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_CACHE_HIT);
// |ServeFromCache()| will set |*stale_info| as needed.
return net_error;
}
// TODO(szym): Do not do this if nsswitch.conf instructs not to.
// http://crbug.com/117655
if (ServeFromHosts(key, info, addresses)) {
source_net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_HOSTS_HIT);
MakeNotStale(stale_info);
return OK;
}
if (ServeLocalhost(key, info, addresses)) {
MakeNotStale(stale_info);
return OK;
}
return ERR_DNS_CACHE_MISS;
}
int HostResolverImpl::ResolveFromCache(const RequestInfo& info,
AddressList* addresses,
const BoundNetLog& source_net_log) {
DCHECK(CalledOnValidThread());
DCHECK(addresses);
// Update the net log and notify registered observers.
LogStartRequest(source_net_log, info);
IPAddress ip_address;
IPAddress* ip_address_ptr = nullptr;
if (ip_address.AssignFromIPLiteral(info.hostname()))
ip_address_ptr = &ip_address;
Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
int rv = ResolveHelper(key, info, ip_address_ptr, addresses, false, nullptr,
source_net_log);
LogFinishRequest(source_net_log, info, rv);
return rv;
}
void HostResolverImpl::ChangeRequestPriority(RequestHandle req_handle,
RequestPriority priority) {
DCHECK(CalledOnValidThread());
Request* req = reinterpret_cast<Request*>(req_handle);
DCHECK(req);
Job* job = req->job();
DCHECK(job);
job->ChangeRequestPriority(req, priority);
}
void HostResolverImpl::CancelRequest(RequestHandle req_handle) {
DCHECK(CalledOnValidThread());
Request* req = reinterpret_cast<Request*>(req_handle);
DCHECK(req);
Job* job = req->job();
DCHECK(job);
job->CancelRequest(req);
}
void HostResolverImpl::SetDnsClientEnabled(bool enabled) {
DCHECK(CalledOnValidThread());
#if defined(ENABLE_BUILT_IN_DNS)
if (enabled && !dns_client_) {
SetDnsClient(DnsClient::CreateClient(net_log_));
} else if (!enabled && dns_client_) {
SetDnsClient(std::unique_ptr<DnsClient>());
}
#endif
}
HostCache* HostResolverImpl::GetHostCache() {
return cache_.get();
}
std::unique_ptr<base::Value> HostResolverImpl::GetDnsConfigAsValue() const {
// Check if async DNS is disabled.
if (!dns_client_.get())
return nullptr;
// Check if async DNS is enabled, but we currently have no configuration
// for it.
const DnsConfig* dns_config = dns_client_->GetConfig();
if (!dns_config)
return base::WrapUnique(new base::DictionaryValue());
return dns_config->ToValue();
}
int HostResolverImpl::ResolveStaleFromCache(
const RequestInfo& info,
AddressList* addresses,
HostCache::EntryStaleness* stale_info,
const BoundNetLog& source_net_log) {
DCHECK(CalledOnValidThread());
DCHECK(addresses);
DCHECK(stale_info);
// Update the net log and notify registered observers.
LogStartRequest(source_net_log, info);
IPAddress ip_address;
IPAddress* ip_address_ptr = nullptr;
if (ip_address.AssignFromIPLiteral(info.hostname()))
ip_address_ptr = &ip_address;
Key key = GetEffectiveKeyForRequest(info, ip_address_ptr, source_net_log);
int rv = ResolveHelper(key, info, ip_address_ptr, addresses, true, stale_info,
source_net_log);
LogFinishRequest(source_net_log, info, rv);
return rv;
}
bool HostResolverImpl::ResolveAsIP(const Key& key,
const RequestInfo& info,
const IPAddress* ip_address,
int* net_error,
AddressList* addresses) {
DCHECK(addresses);
DCHECK(net_error);
if (ip_address == nullptr)
return false;
*net_error = OK;
AddressFamily family = GetAddressFamily(*ip_address);
if (key.address_family != ADDRESS_FAMILY_UNSPECIFIED &&
key.address_family != family) {
// Don't return IPv6 addresses for IPv4 queries, and vice versa.
*net_error = ERR_NAME_NOT_RESOLVED;
} else {
*addresses = AddressList::CreateFromIPAddress(*ip_address, info.port());
if (key.host_resolver_flags & HOST_RESOLVER_CANONNAME)
addresses->SetDefaultCanonicalName();
}
return true;
}
bool HostResolverImpl::ServeFromCache(const Key& key,
const RequestInfo& info,
int* net_error,
AddressList* addresses,
bool allow_stale,
HostCache::EntryStaleness* stale_info) {
DCHECK(addresses);
DCHECK(net_error);
DCHECK(allow_stale == !!stale_info);
if (!info.allow_cached_response() || !cache_.get())
return false;
const HostCache::Entry* cache_entry;
if (allow_stale)
cache_entry = cache_->LookupStale(key, base::TimeTicks::Now(), stale_info);
else
cache_entry = cache_->Lookup(key, base::TimeTicks::Now());
if (!cache_entry)
return false;
*net_error = cache_entry->error();
if (*net_error == OK) {
if (cache_entry->has_ttl())
RecordTTL(cache_entry->ttl());
*addresses = EnsurePortOnAddressList(cache_entry->addresses(), info.port());
}
return true;
}
bool HostResolverImpl::ServeFromHosts(const Key& key,
const RequestInfo& info,
AddressList* addresses) {
DCHECK(addresses);
if (!HaveDnsConfig())
return false;
addresses->clear();
// HOSTS lookups are case-insensitive.
std::string hostname = base::ToLowerASCII(key.hostname);
const DnsHosts& hosts = dns_client_->GetConfig()->hosts;
// If |address_family| is ADDRESS_FAMILY_UNSPECIFIED other implementations
// (glibc and c-ares) return the first matching line. We have more
// flexibility, but lose implicit ordering.
// We prefer IPv6 because "happy eyeballs" will fall back to IPv4 if
// necessary.
if (key.address_family == ADDRESS_FAMILY_IPV6 ||
key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
DnsHosts::const_iterator it = hosts.find(
DnsHostsKey(hostname, ADDRESS_FAMILY_IPV6));
if (it != hosts.end())
addresses->push_back(IPEndPoint(it->second, info.port()));
}
if (key.address_family == ADDRESS_FAMILY_IPV4 ||
key.address_family == ADDRESS_FAMILY_UNSPECIFIED) {
DnsHosts::const_iterator it = hosts.find(
DnsHostsKey(hostname, ADDRESS_FAMILY_IPV4));
if (it != hosts.end())
addresses->push_back(IPEndPoint(it->second, info.port()));
}
// If got only loopback addresses and the family was restricted, resolve
// again, without restrictions. See SystemHostResolverCall for rationale.
if ((key.host_resolver_flags &
HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6) &&
IsAllIPv4Loopback(*addresses)) {
Key new_key(key);
new_key.address_family = ADDRESS_FAMILY_UNSPECIFIED;
new_key.host_resolver_flags &=
~HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
return ServeFromHosts(new_key, info, addresses);
}
return !addresses->empty();
}
bool HostResolverImpl::ServeLocalhost(const Key& key,
const RequestInfo& info,
AddressList* addresses) {
AddressList resolved_addresses;
if (!ResolveLocalHostname(key.hostname, info.port(), &resolved_addresses))
return false;
addresses->clear();
for (const auto& address : resolved_addresses) {
// Include the address if:
// - caller didn't specify an address family, or
// - caller specifically asked for the address family of this address, or
// - this is an IPv6 address and caller specifically asked for IPv4 due
// to lack of detected IPv6 support. (See SystemHostResolverCall for
// rationale).
if (key.address_family == ADDRESS_FAMILY_UNSPECIFIED ||
key.address_family == address.GetFamily() ||
(address.GetFamily() == ADDRESS_FAMILY_IPV6 &&
key.address_family == ADDRESS_FAMILY_IPV4 &&
(key.host_resolver_flags &
HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6))) {
addresses->push_back(address);
}
}
return true;
}
void HostResolverImpl::CacheResult(const Key& key,
const HostCache::Entry& entry,
base::TimeDelta ttl) {
if (cache_.get())
cache_->Set(key, entry, base::TimeTicks::Now(), ttl);
}
void HostResolverImpl::RemoveJob(Job* job) {
DCHECK(job);
JobMap::iterator it = jobs_.find(job->key());
if (it != jobs_.end() && it->second == job)
jobs_.erase(it);
}
HostResolverImpl::Key HostResolverImpl::GetEffectiveKeyForRequest(
const RequestInfo& info,
const IPAddress* ip_address,
const BoundNetLog& net_log) {
HostResolverFlags effective_flags =
info.host_resolver_flags() | additional_resolver_flags_;
AddressFamily effective_address_family = info.address_family();
if (info.address_family() == ADDRESS_FAMILY_UNSPECIFIED) {
if (!use_local_ipv6_ &&
// When resolving IPv4 literals, there's no need to probe for IPv6.
// When resolving IPv6 literals, there's no benefit to artificially
// limiting our resolution based on a probe. Prior logic ensures
// that this query is UNSPECIFIED (see info.address_family()
// check above) so the code requesting the resolution should be amenable
// to receiving a IPv6 resolution.
ip_address == nullptr) {
if (!IsIPv6Reachable(net_log)) {
effective_address_family = ADDRESS_FAMILY_IPV4;
effective_flags |= HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6;
}
}
}
return Key(info.hostname(), effective_address_family, effective_flags);
}
bool HostResolverImpl::IsIPv6Reachable(const BoundNetLog& net_log) {
base::TimeTicks now = base::TimeTicks::Now();
bool cached = true;
if ((now - last_ipv6_probe_time_).InMilliseconds() > kIPv6ProbePeriodMs) {
last_ipv6_probe_result_ =
IsGloballyReachable(IPAddress(kIPv6ProbeAddress), net_log);
last_ipv6_probe_time_ = now;
cached = false;
}
net_log.AddEvent(NetLog::TYPE_HOST_RESOLVER_IMPL_IPV6_REACHABILITY_CHECK,
base::Bind(&NetLogIPv6AvailableCallback,
last_ipv6_probe_result_, cached));
return last_ipv6_probe_result_;
}
void HostResolverImpl::RunLoopbackProbeJob() {
new LoopbackProbeJob(weak_ptr_factory_.GetWeakPtr(),
worker_task_runner_.get());
}
void HostResolverImpl::AbortAllInProgressJobs() {
// In Abort, a Request callback could spawn new Jobs with matching keys, so
// first collect and remove all running jobs from |jobs_|.
std::vector<std::unique_ptr<Job>> jobs_to_abort;
for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ) {
Job* job = it->second;
if (job->is_running()) {
jobs_to_abort.push_back(base::WrapUnique(job));
jobs_.erase(it++);
} else {
DCHECK(job->is_queued());
++it;
}
}
// Pause the dispatcher so it won't start any new dispatcher jobs while
// aborting the old ones. This is needed so that it won't start the second
// DnsTransaction for a job in |jobs_to_abort| if the DnsConfig just became
// invalid.
PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
dispatcher_->SetLimits(
PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
// Life check to bail once |this| is deleted.
base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
// Then Abort them.
for (size_t i = 0; self.get() && i < jobs_to_abort.size(); ++i) {
jobs_to_abort[i]->Abort();
ignore_result(jobs_to_abort[i].release());
}
if (self)
dispatcher_->SetLimits(limits);
}
void HostResolverImpl::AbortDnsTasks() {
// Pause the dispatcher so it won't start any new dispatcher jobs while
// aborting the old ones. This is needed so that it won't start the second
// DnsTransaction for a job if the DnsConfig just changed.
PrioritizedDispatcher::Limits limits = dispatcher_->GetLimits();
dispatcher_->SetLimits(
PrioritizedDispatcher::Limits(limits.reserved_slots.size(), 0));
for (JobMap::iterator it = jobs_.begin(); it != jobs_.end(); ++it)
it->second->AbortDnsTask();
dispatcher_->SetLimits(limits);
}
void HostResolverImpl::TryServingAllJobsFromHosts() {
if (!HaveDnsConfig())
return;
// TODO(szym): Do not do this if nsswitch.conf instructs not to.
// http://crbug.com/117655
// Life check to bail once |this| is deleted.
base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
for (JobMap::iterator it = jobs_.begin(); self.get() && it != jobs_.end();) {
Job* job = it->second;
++it;
// This could remove |job| from |jobs_|, but iterator will remain valid.
job->ServeFromHosts();
}
}
void HostResolverImpl::OnIPAddressChanged() {
resolved_known_ipv6_hostname_ = false;
last_ipv6_probe_time_ = base::TimeTicks();
// Abandon all ProbeJobs.
probe_weak_ptr_factory_.InvalidateWeakPtrs();
if (cache_.get())
cache_->clear();
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
RunLoopbackProbeJob();
#endif
AbortAllInProgressJobs();
// |this| may be deleted inside AbortAllInProgressJobs().
}
void HostResolverImpl::OnConnectionTypeChanged(
NetworkChangeNotifier::ConnectionType type) {
proc_params_.unresponsive_delay =
GetTimeDeltaForConnectionTypeFromFieldTrialOrDefault(
"DnsUnresponsiveDelayMsByConnectionType",
base::TimeDelta::FromMilliseconds(kDnsDefaultUnresponsiveDelayMs),
type);
}
void HostResolverImpl::OnInitialDNSConfigRead() {
UpdateDNSConfig(false);
}
void HostResolverImpl::OnDNSChanged() {
UpdateDNSConfig(true);
}
void HostResolverImpl::UpdateDNSConfig(bool config_changed) {
DnsConfig dns_config;
NetworkChangeNotifier::GetDnsConfig(&dns_config);
if (net_log_) {
net_log_->AddGlobalEntry(
NetLog::TYPE_DNS_CONFIG_CHANGED,
base::Bind(&NetLogDnsConfigCallback, &dns_config));
}
// TODO(szym): Remove once http://crbug.com/137914 is resolved.
received_dns_config_ = dns_config.IsValid();
// Conservatively assume local IPv6 is needed when DnsConfig is not valid.
use_local_ipv6_ = !dns_config.IsValid() || dns_config.use_local_ipv6;
num_dns_failures_ = 0;
// We want a new DnsSession in place, before we Abort running Jobs, so that
// the newly started jobs use the new config.
if (dns_client_.get()) {
dns_client_->SetConfig(dns_config);
if (dns_client_->GetConfig()) {
UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
// If we just switched DnsClients, restart jobs using new resolver.
// TODO(pauljensen): Is this necessary?
config_changed = true;
}
}
if (config_changed) {
// If the DNS server has changed, existing cached info could be wrong so we
// have to drop our internal cache :( Note that OS level DNS caches, such
// as NSCD's cache should be dropped automatically by the OS when
// resolv.conf changes so we don't need to do anything to clear that cache.
if (cache_.get())
cache_->clear();
// Life check to bail once |this| is deleted.
base::WeakPtr<HostResolverImpl> self = weak_ptr_factory_.GetWeakPtr();
// Existing jobs will have been sent to the original server so they need to
// be aborted.
AbortAllInProgressJobs();
// |this| may be deleted inside AbortAllInProgressJobs().
if (self.get())
TryServingAllJobsFromHosts();
}
}
bool HostResolverImpl::HaveDnsConfig() const {
// Use DnsClient only if it's fully configured and there is no override by
// ScopedDefaultHostResolverProc.
// The alternative is to use NetworkChangeNotifier to override DnsConfig,
// but that would introduce construction order requirements for NCN and SDHRP.
return dns_client_ && dns_client_->GetConfig() &&
(proc_params_.resolver_proc || !HostResolverProc::GetDefault());
}
void HostResolverImpl::OnDnsTaskResolve(int net_error) {
DCHECK(dns_client_);
if (net_error == OK) {
num_dns_failures_ = 0;
return;
}
++num_dns_failures_;
if (num_dns_failures_ < kMaximumDnsFailures)
return;
// Disable DnsClient until the next DNS change. Must be done before aborting
// DnsTasks, since doing so may start new jobs.
dns_client_->SetConfig(DnsConfig());
// Switch jobs with active DnsTasks over to using ProcTasks.
AbortDnsTasks();
UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", false);
UMA_HISTOGRAM_SPARSE_SLOWLY("AsyncDNS.DnsClientDisabledReason",
std::abs(net_error));
}
void HostResolverImpl::SetDnsClient(std::unique_ptr<DnsClient> dns_client) {
// DnsClient and config must be updated before aborting DnsTasks, since doing
// so may start new jobs.
dns_client_ = std::move(dns_client);
if (dns_client_ && !dns_client_->GetConfig() &&
num_dns_failures_ < kMaximumDnsFailures) {
DnsConfig dns_config;
NetworkChangeNotifier::GetDnsConfig(&dns_config);
dns_client_->SetConfig(dns_config);
num_dns_failures_ = 0;
if (dns_client_->GetConfig())
UMA_HISTOGRAM_BOOLEAN("AsyncDNS.DnsClientEnabled", true);
}
AbortDnsTasks();
}
} // namespace net
| {
"pile_set_name": "Github"
} |
/*
* pata_amd.c - AMD PATA for new ATA layer
* (C) 2005-2006 Red Hat Inc
*
* Based on pata-sil680. Errata information is taken from data sheets
* and the amd74xx.c driver by Vojtech Pavlik. Nvidia SATA devices are
* claimed by sata-nv.c.
*
* TODO:
* Variable system clock when/if it makes sense
* Power management on ports
*
*
* Documentation publicly available.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_amd"
#define DRV_VERSION "0.4.1"
/**
* timing_setup - shared timing computation and load
* @ap: ATA port being set up
* @adev: drive being configured
* @offset: port offset
* @speed: target speed
* @clock: clock multiplier (number of times 33MHz for this part)
*
* Perform the actual timing set up for Nvidia or AMD PATA devices.
* The actual devices vary so they all call into this helper function
* providing the clock multipler and offset (because AMD and Nvidia put
* the ports at different locations).
*/
static void timing_setup(struct ata_port *ap, struct ata_device *adev, int offset, int speed, int clock)
{
static const unsigned char amd_cyc2udma[] = {
6, 6, 5, 4, 0, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 7
};
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct ata_device *peer = ata_dev_pair(adev);
int dn = ap->port_no * 2 + adev->devno;
struct ata_timing at, apeer;
int T, UT;
const int amd_clock = 33333; /* KHz. */
u8 t;
T = 1000000000 / amd_clock;
UT = T;
if (clock >= 2)
UT = T / 2;
if (ata_timing_compute(adev, speed, &at, T, UT) < 0) {
dev_err(&pdev->dev, "unknown mode %d\n", speed);
return;
}
if (peer) {
/* This may be over conservative */
if (peer->dma_mode) {
ata_timing_compute(peer, peer->dma_mode, &apeer, T, UT);
ata_timing_merge(&apeer, &at, &at, ATA_TIMING_8BIT);
}
ata_timing_compute(peer, peer->pio_mode, &apeer, T, UT);
ata_timing_merge(&apeer, &at, &at, ATA_TIMING_8BIT);
}
if (speed == XFER_UDMA_5 && amd_clock <= 33333) at.udma = 1;
if (speed == XFER_UDMA_6 && amd_clock <= 33333) at.udma = 15;
/*
* Now do the setup work
*/
/* Configure the address set up timing */
pci_read_config_byte(pdev, offset + 0x0C, &t);
t = (t & ~(3 << ((3 - dn) << 1))) | ((clamp_val(at.setup, 1, 4) - 1) << ((3 - dn) << 1));
pci_write_config_byte(pdev, offset + 0x0C , t);
/* Configure the 8bit I/O timing */
pci_write_config_byte(pdev, offset + 0x0E + (1 - (dn >> 1)),
((clamp_val(at.act8b, 1, 16) - 1) << 4) | (clamp_val(at.rec8b, 1, 16) - 1));
/* Drive timing */
pci_write_config_byte(pdev, offset + 0x08 + (3 - dn),
((clamp_val(at.active, 1, 16) - 1) << 4) | (clamp_val(at.recover, 1, 16) - 1));
switch (clock) {
case 1:
t = at.udma ? (0xc0 | (clamp_val(at.udma, 2, 5) - 2)) : 0x03;
break;
case 2:
t = at.udma ? (0xc0 | amd_cyc2udma[clamp_val(at.udma, 2, 10)]) : 0x03;
break;
case 3:
t = at.udma ? (0xc0 | amd_cyc2udma[clamp_val(at.udma, 1, 10)]) : 0x03;
break;
case 4:
t = at.udma ? (0xc0 | amd_cyc2udma[clamp_val(at.udma, 1, 15)]) : 0x03;
break;
default:
return;
}
/* UDMA timing */
if (at.udma)
pci_write_config_byte(pdev, offset + 0x10 + (3 - dn), t);
}
/**
* amd_pre_reset - perform reset handling
* @link: ATA link
* @deadline: deadline jiffies for the operation
*
* Reset sequence checking enable bits to see which ports are
* active.
*/
static int amd_pre_reset(struct ata_link *link, unsigned long deadline)
{
static const struct pci_bits amd_enable_bits[] = {
{ 0x40, 1, 0x02, 0x02 },
{ 0x40, 1, 0x01, 0x01 }
};
struct ata_port *ap = link->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
if (!pci_test_config_bits(pdev, &amd_enable_bits[ap->port_no]))
return -ENOENT;
return ata_sff_prereset(link, deadline);
}
/**
* amd_cable_detect - report cable type
* @ap: port
*
* AMD controller/BIOS setups record the cable type in word 0x42
*/
static int amd_cable_detect(struct ata_port *ap)
{
static const u32 bitmask[2] = {0x03, 0x0C};
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
u8 ata66;
pci_read_config_byte(pdev, 0x42, &ata66);
if (ata66 & bitmask[ap->port_no])
return ATA_CBL_PATA80;
return ATA_CBL_PATA40;
}
/**
* amd_fifo_setup - set the PIO FIFO for ATA/ATAPI
* @ap: ATA interface
* @adev: ATA device
*
* Set the PCI fifo for this device according to the devices present
* on the bus at this point in time. We need to turn the post write buffer
* off for ATAPI devices as we may need to issue a word sized write to the
* device as the final I/O
*/
static void amd_fifo_setup(struct ata_port *ap)
{
struct ata_device *adev;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
static const u8 fifobit[2] = { 0xC0, 0x30};
u8 fifo = fifobit[ap->port_no];
u8 r;
ata_for_each_dev(adev, &ap->link, ENABLED) {
if (adev->class == ATA_DEV_ATAPI)
fifo = 0;
}
if (pdev->device == PCI_DEVICE_ID_AMD_VIPER_7411) /* FIFO is broken */
fifo = 0;
/* On the later chips the read prefetch bits become no-op bits */
pci_read_config_byte(pdev, 0x41, &r);
r &= ~fifobit[ap->port_no];
r |= fifo;
pci_write_config_byte(pdev, 0x41, r);
}
/**
* amd33_set_piomode - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*
* Program the AMD registers for PIO mode.
*/
static void amd33_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
amd_fifo_setup(ap);
timing_setup(ap, adev, 0x40, adev->pio_mode, 1);
}
static void amd66_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
amd_fifo_setup(ap);
timing_setup(ap, adev, 0x40, adev->pio_mode, 2);
}
static void amd100_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
amd_fifo_setup(ap);
timing_setup(ap, adev, 0x40, adev->pio_mode, 3);
}
static void amd133_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
amd_fifo_setup(ap);
timing_setup(ap, adev, 0x40, adev->pio_mode, 4);
}
/**
* amd33_set_dmamode - set initial DMA mode data
* @ap: ATA interface
* @adev: ATA device
*
* Program the MWDMA/UDMA modes for the AMD and Nvidia
* chipset.
*/
static void amd33_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
timing_setup(ap, adev, 0x40, adev->dma_mode, 1);
}
static void amd66_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
timing_setup(ap, adev, 0x40, adev->dma_mode, 2);
}
static void amd100_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
timing_setup(ap, adev, 0x40, adev->dma_mode, 3);
}
static void amd133_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
timing_setup(ap, adev, 0x40, adev->dma_mode, 4);
}
/* Both host-side and drive-side detection results are worthless on NV
* PATAs. Ignore them and just follow what BIOS configured. Both the
* current configuration in PCI config reg and ACPI GTM result are
* cached during driver attach and are consulted to select transfer
* mode.
*/
static unsigned long nv_mode_filter(struct ata_device *dev,
unsigned long xfer_mask)
{
static const unsigned int udma_mask_map[] =
{ ATA_UDMA2, ATA_UDMA1, ATA_UDMA0, 0,
ATA_UDMA3, ATA_UDMA4, ATA_UDMA5, ATA_UDMA6 };
struct ata_port *ap = dev->link->ap;
char acpi_str[32] = "";
u32 saved_udma, udma;
const struct ata_acpi_gtm *gtm;
unsigned long bios_limit = 0, acpi_limit = 0, limit;
/* find out what BIOS configured */
udma = saved_udma = (unsigned long)ap->host->private_data;
if (ap->port_no == 0)
udma >>= 16;
if (dev->devno == 0)
udma >>= 8;
if ((udma & 0xc0) == 0xc0)
bios_limit = ata_pack_xfermask(0, 0, udma_mask_map[udma & 0x7]);
/* consult ACPI GTM too */
gtm = ata_acpi_init_gtm(ap);
if (gtm) {
acpi_limit = ata_acpi_gtm_xfermask(dev, gtm);
snprintf(acpi_str, sizeof(acpi_str), " (%u:%u:0x%x)",
gtm->drive[0].dma, gtm->drive[1].dma, gtm->flags);
}
/* be optimistic, EH can take care of things if something goes wrong */
limit = bios_limit | acpi_limit;
/* If PIO or DMA isn't configured at all, don't limit. Let EH
* handle it.
*/
if (!(limit & ATA_MASK_PIO))
limit |= ATA_MASK_PIO;
if (!(limit & (ATA_MASK_MWDMA | ATA_MASK_UDMA)))
limit |= ATA_MASK_MWDMA | ATA_MASK_UDMA;
/* PIO4, MWDMA2, UDMA2 should always be supported regardless of
cable detection result */
limit |= ata_pack_xfermask(ATA_PIO4, ATA_MWDMA2, ATA_UDMA2);
ata_port_dbg(ap, "nv_mode_filter: 0x%lx&0x%lx->0x%lx, "
"BIOS=0x%lx (0x%x) ACPI=0x%lx%s\n",
xfer_mask, limit, xfer_mask & limit, bios_limit,
saved_udma, acpi_limit, acpi_str);
return xfer_mask & limit;
}
/**
* nv_probe_init - cable detection
* @lin: ATA link
*
* Perform cable detection. The BIOS stores this in PCI config
* space for us.
*/
static int nv_pre_reset(struct ata_link *link, unsigned long deadline)
{
static const struct pci_bits nv_enable_bits[] = {
{ 0x50, 1, 0x02, 0x02 },
{ 0x50, 1, 0x01, 0x01 }
};
struct ata_port *ap = link->ap;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
if (!pci_test_config_bits(pdev, &nv_enable_bits[ap->port_no]))
return -ENOENT;
return ata_sff_prereset(link, deadline);
}
/**
* nv100_set_piomode - set initial PIO mode data
* @ap: ATA interface
* @adev: ATA device
*
* Program the AMD registers for PIO mode.
*/
static void nv100_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
timing_setup(ap, adev, 0x50, adev->pio_mode, 3);
}
static void nv133_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
timing_setup(ap, adev, 0x50, adev->pio_mode, 4);
}
/**
* nv100_set_dmamode - set initial DMA mode data
* @ap: ATA interface
* @adev: ATA device
*
* Program the MWDMA/UDMA modes for the AMD and Nvidia
* chipset.
*/
static void nv100_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
timing_setup(ap, adev, 0x50, adev->dma_mode, 3);
}
static void nv133_set_dmamode(struct ata_port *ap, struct ata_device *adev)
{
timing_setup(ap, adev, 0x50, adev->dma_mode, 4);
}
static void nv_host_stop(struct ata_host *host)
{
u32 udma = (unsigned long)host->private_data;
/* restore PCI config register 0x60 */
pci_write_config_dword(to_pci_dev(host->dev), 0x60, udma);
}
static struct scsi_host_template amd_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static const struct ata_port_operations amd_base_port_ops = {
.inherits = &ata_bmdma32_port_ops,
.prereset = amd_pre_reset,
};
static struct ata_port_operations amd33_port_ops = {
.inherits = &amd_base_port_ops,
.cable_detect = ata_cable_40wire,
.set_piomode = amd33_set_piomode,
.set_dmamode = amd33_set_dmamode,
};
static struct ata_port_operations amd66_port_ops = {
.inherits = &amd_base_port_ops,
.cable_detect = ata_cable_unknown,
.set_piomode = amd66_set_piomode,
.set_dmamode = amd66_set_dmamode,
};
static struct ata_port_operations amd100_port_ops = {
.inherits = &amd_base_port_ops,
.cable_detect = ata_cable_unknown,
.set_piomode = amd100_set_piomode,
.set_dmamode = amd100_set_dmamode,
};
static struct ata_port_operations amd133_port_ops = {
.inherits = &amd_base_port_ops,
.cable_detect = amd_cable_detect,
.set_piomode = amd133_set_piomode,
.set_dmamode = amd133_set_dmamode,
};
static const struct ata_port_operations nv_base_port_ops = {
.inherits = &ata_bmdma_port_ops,
.cable_detect = ata_cable_ignore,
.mode_filter = nv_mode_filter,
.prereset = nv_pre_reset,
.host_stop = nv_host_stop,
};
static struct ata_port_operations nv100_port_ops = {
.inherits = &nv_base_port_ops,
.set_piomode = nv100_set_piomode,
.set_dmamode = nv100_set_dmamode,
};
static struct ata_port_operations nv133_port_ops = {
.inherits = &nv_base_port_ops,
.set_piomode = nv133_set_piomode,
.set_dmamode = nv133_set_dmamode,
};
static void amd_clear_fifo(struct pci_dev *pdev)
{
u8 fifo;
/* Disable the FIFO, the FIFO logic will re-enable it as
appropriate */
pci_read_config_byte(pdev, 0x41, &fifo);
fifo &= 0x0F;
pci_write_config_byte(pdev, 0x41, fifo);
}
static int amd_init_one(struct pci_dev *pdev, const struct pci_device_id *id)
{
static const struct ata_port_info info[10] = {
{ /* 0: AMD 7401 - no swdma */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA2,
.port_ops = &amd33_port_ops
},
{ /* 1: Early AMD7409 - no swdma */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA4,
.port_ops = &amd66_port_ops
},
{ /* 2: AMD 7409 */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA4,
.port_ops = &amd66_port_ops
},
{ /* 3: AMD 7411 */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &amd100_port_ops
},
{ /* 4: AMD 7441 */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &amd100_port_ops
},
{ /* 5: AMD 8111 - no swdma */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &amd133_port_ops
},
{ /* 6: AMD 8111 UDMA 100 (Serenade) - no swdma */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &amd133_port_ops
},
{ /* 7: Nvidia Nforce */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &nv100_port_ops
},
{ /* 8: Nvidia Nforce2 and later - no swdma */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &nv133_port_ops
},
{ /* 9: AMD CS5536 (Geode companion) */
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
.port_ops = &amd100_port_ops
}
};
const struct ata_port_info *ppi[] = { NULL, NULL };
int type = id->driver_data;
void *hpriv = NULL;
u8 fifo;
int rc;
ata_print_version_once(&pdev->dev, DRV_VERSION);
rc = pcim_enable_device(pdev);
if (rc)
return rc;
pci_read_config_byte(pdev, 0x41, &fifo);
/* Check for AMD7409 without swdma errata and if found adjust type */
if (type == 1 && pdev->revision > 0x7)
type = 2;
/* Serenade ? */
if (type == 5 && pdev->subsystem_vendor == PCI_VENDOR_ID_AMD &&
pdev->subsystem_device == PCI_DEVICE_ID_AMD_SERENADE)
type = 6; /* UDMA 100 only */
/*
* Okay, type is determined now. Apply type-specific workarounds.
*/
ppi[0] = &info[type];
if (type < 3)
ata_pci_bmdma_clear_simplex(pdev);
if (pdev->vendor == PCI_VENDOR_ID_AMD)
amd_clear_fifo(pdev);
/* Cable detection on Nvidia chips doesn't work too well,
* cache BIOS programmed UDMA mode.
*/
if (type == 7 || type == 8) {
u32 udma;
pci_read_config_dword(pdev, 0x60, &udma);
hpriv = (void *)(unsigned long)udma;
}
/* And fire it up */
return ata_pci_bmdma_init_one(pdev, ppi, &amd_sht, hpriv, 0);
}
#ifdef CONFIG_PM_SLEEP
static int amd_reinit_one(struct pci_dev *pdev)
{
struct ata_host *host = pci_get_drvdata(pdev);
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
if (pdev->vendor == PCI_VENDOR_ID_AMD) {
amd_clear_fifo(pdev);
if (pdev->device == PCI_DEVICE_ID_AMD_VIPER_7409 ||
pdev->device == PCI_DEVICE_ID_AMD_COBRA_7401)
ata_pci_bmdma_clear_simplex(pdev);
}
ata_host_resume(host);
return 0;
}
#endif
static const struct pci_device_id amd[] = {
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_COBRA_7401), 0 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_VIPER_7409), 1 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_VIPER_7411), 3 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_OPUS_7441), 4 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_8111_IDE), 5 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_IDE), 7 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE2_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE2S_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE3_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE3S_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_CK804_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP04_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP51_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP55_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP61_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP65_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP67_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP73_IDE), 8 },
{ PCI_VDEVICE(NVIDIA, PCI_DEVICE_ID_NVIDIA_NFORCE_MCP77_IDE), 8 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_CS5536_IDE), 9 },
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_CS5536_DEV_IDE), 9 },
{ },
};
static struct pci_driver amd_pci_driver = {
.name = DRV_NAME,
.id_table = amd,
.probe = amd_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM_SLEEP
.suspend = ata_pci_device_suspend,
.resume = amd_reinit_one,
#endif
};
module_pci_driver(amd_pci_driver);
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for AMD and Nvidia PATA IDE");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, amd);
MODULE_VERSION(DRV_VERSION);
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2016 Thomas Pornin <[email protected]>
*
* 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.
*/
#ifndef BR_BEARSSL_HMAC_H__
#define BR_BEARSSL_HMAC_H__
#include <stddef.h>
#include <stdint.h>
#include "t_bearssl_hash.h"
#ifdef __cplusplus
extern "C" {
#endif
/** \file bearssl_hmac.h
*
* # HMAC
*
* HMAC is initialized with a key and an underlying hash function; it
* then fills a "key context". That context contains the processed
* key.
*
* With the key context, a HMAC context can be initialized to process
* the input bytes and obtain the MAC output. The key context is not
* modified during that process, and can be reused.
*
* IMPORTANT: HMAC shall be used only with functions that have the
* following properties:
*
* - hash output size does not exceed 64 bytes;
* - hash internal state size does not exceed 64 bytes;
* - internal block length is a power of 2 between 16 and 256 bytes.
*/
/**
* \brief HMAC key context.
*
* The HMAC key context is initialised with a hash function implementation
* and a secret key. Contents are opaque (callers should not access them
* directly). The caller is responsible for allocating the context where
* appropriate. Context initialisation and usage incurs no dynamic
* allocation, so there is no release function.
*/
typedef struct {
#ifndef BR_DOXYGEN_IGNORE
const br_hash_class *dig_vtable;
unsigned char ksi[64], kso[64];
#endif
} br_hmac_key_context;
/**
* \brief HMAC key context initialisation.
*
* Initialise the key context with the provided key, using the hash function
* identified by `digest_vtable`. This supports arbitrary key lengths.
*
* \param kc HMAC key context to initialise.
* \param digest_vtable pointer to the hash function implementation vtable.
* \param key pointer to the HMAC secret key.
* \param key_len HMAC secret key length (in bytes).
*/
void br_hmac_key_init(br_hmac_key_context *kc,
const br_hash_class *digest_vtable, const void *key, size_t key_len);
/*
* \brief Get the underlying hash function.
*
* This function returns a pointer to the implementation vtable of the
* hash function used for this HMAC key context.
*
* \param kc HMAC key context.
* \return the hash function implementation.
*/
static inline const br_hash_class *br_hmac_key_get_digest(
const br_hmac_key_context *kc)
{
return kc->dig_vtable;
}
/**
* \brief HMAC computation context.
*
* The HMAC computation context maintains the state for a single HMAC
* computation. It is modified as input bytes are injected. The context
* is caller-allocated and has no release function since it does not
* dynamically allocate external resources. Its contents are opaque.
*/
typedef struct {
#ifndef BR_DOXYGEN_IGNORE
br_hash_compat_context dig;
unsigned char kso[64];
size_t out_len;
#endif
} br_hmac_context;
/**
* \brief HMAC computation initialisation.
*
* Initialise a HMAC context with a key context. The key context is
* unmodified. Relevant data from the key context is immediately copied;
* the key context can thus be independently reused, modified or released
* without impacting this HMAC computation.
*
* An explicit output length can be specified; the actual output length
* will be the minimum of that value and the natural HMAC output length.
* If `out_len` is 0, then the natural HMAC output length is selected. The
* "natural output length" is the output length of the underlying hash
* function.
*
* \param ctx HMAC context to initialise.
* \param kc HMAC key context (already initialised with the key).
* \param out_len HMAC output length (0 to select "natural length").
*/
void br_hmac_init(br_hmac_context *ctx,
const br_hmac_key_context *kc, size_t out_len);
/**
* \brief Get the HMAC output size.
*
* The HMAC output size is the number of bytes that will actually be
* produced with `br_hmac_out()` with the provided context. This function
* MUST NOT be called on a non-initialised HMAC computation context.
* The returned value is the minimum of the HMAC natural length (output
* size of the underlying hash function) and the `out_len` parameter which
* was used with the last `br_hmac_init()` call on that context (if the
* initialisation `out_len` parameter was 0, then this function will
* return the HMAC natural length).
*
* \param ctx the (already initialised) HMAC computation context.
* \return the HMAC actual output size.
*/
static inline size_t
br_hmac_size(br_hmac_context *ctx)
{
return ctx->out_len;
}
/*
* \brief Get the underlying hash function.
*
* This function returns a pointer to the implementation vtable of the
* hash function used for this HMAC context.
*
* \param hc HMAC context.
* \return the hash function implementation.
*/
static inline const br_hash_class *br_hmac_get_digest(
const br_hmac_context *hc)
{
return hc->dig.vtable;
}
/**
* \brief Inject some bytes in HMAC.
*
* The provided `len` bytes are injected as extra input in the HMAC
* computation incarnated by the `ctx` HMAC context. It is acceptable
* that `len` is zero, in which case `data` is ignored (and may be
* `NULL`) and this function does nothing.
*/
void br_hmac_update(br_hmac_context *ctx, const void *data, size_t len);
/**
* \brief Compute the HMAC output.
*
* The destination buffer MUST be large enough to accommodate the result;
* its length is at most the "natural length" of HMAC (i.e. the output
* length of the underlying hash function). The context is NOT modified;
* further bytes may be processed. Thus, "partial HMAC" values can be
* efficiently obtained.
*
* Returned value is the output length (in bytes).
*
* \param ctx HMAC computation context.
* \param out destination buffer for the HMAC output.
* \return the produced value length (in bytes).
*/
size_t br_hmac_out(const br_hmac_context *ctx, void *out);
/**
* \brief Constant-time HMAC computation.
*
* This function compute the HMAC output in constant time. Some extra
* input bytes are processed, then the output is computed. The extra
* input consists in the `len` bytes pointed to by `data`. The `len`
* parameter must lie between `min_len` and `max_len` (inclusive);
* `max_len` bytes are actually read from `data`. Computing time (and
* memory access pattern) will not depend upon the data byte contents or
* the value of `len`.
*
* The output is written in the `out` buffer, that MUST be large enough
* to receive it.
*
* The difference `max_len - min_len` MUST be less than 2<sup>30</sup>
* (i.e. about one gigabyte).
*
* This function computes the output properly only if the underlying
* hash function uses MD padding (i.e. MD5, SHA-1, SHA-224, SHA-256,
* SHA-384 or SHA-512).
*
* The provided context is NOT modified.
*
* \param ctx the (already initialised) HMAC computation context.
* \param data the extra input bytes.
* \param len the extra input length (in bytes).
* \param min_len minimum extra input length (in bytes).
* \param max_len maximum extra input length (in bytes).
* \param out destination buffer for the HMAC output.
* \return the produced value length (in bytes).
*/
size_t br_hmac_outCT(const br_hmac_context *ctx,
const void *data, size_t len, size_t min_len, size_t max_len,
void *out);
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/favicon.ico">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
<title>ColReorder example - jQuery UI styling</title>
<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="../../Plugins/integration/jqueryui/dataTables.jqueryui.css">
<link rel="stylesheet" type="text/css" href="../css/dataTables.colReorder.css">
<link rel="stylesheet" type="text/css" href="../../../examples/resources/syntax/shCore.css">
<link rel="stylesheet" type="text/css" href="../../../examples/resources/demo.css">
<style type="text/css" class="init">
</style>
<script type="text/javascript" language="javascript" src="../../../media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="../../../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" src="../../Plugins/integration/jqueryui/dataTables.jqueryui.js"></script>
<script type="text/javascript" language="javascript" src="../js/dataTables.colReorder.js"></script>
<script type="text/javascript" language="javascript" src="../../../examples/resources/syntax/shCore.js"></script>
<script type="text/javascript" language="javascript" src="../../../examples/resources/demo.js"></script>
<script type="text/javascript" language="javascript" class="init">
$(document).ready(function() {
var table = $('#example').dataTable();
new $.fn.dataTable.ColReorder( table );
} );
</script>
</head>
<body class="dt-example">
<div class="container">
<section>
<h1>ColReorder example <span>jQuery UI styling</span></h1>
<div class="info">
<p>This example shows how the jQuery UI ThemeRoller option in DataTables can be used with ColReorder.</p>
<p>The important thing to note here is that it is easier to use <code>new $.fn.dataTable.ColReorder()</code> to add ColReorder to the table rather than <a href=
"//datatables.net/reference/option/dom"><code class="option" title="DataTables initialisation option">dom<span>DT</span></code></a> as the jQuery UI integration
uses a complex expression for <a href="//datatables.net/reference/option/dom"><code class="option" title=
"DataTables initialisation option">dom<span>DT</span></code></a>.</p>
</div>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>Junior Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$86,000</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>Senior Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
<td>2012/03/29</td>
<td>$433,060</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>33</td>
<td>2008/11/28</td>
<td>$162,700</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
<td>61</td>
<td>2012/12/02</td>
<td>$372,000</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
<td>59</td>
<td>2012/08/06</td>
<td>$137,500</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
<td>55</td>
<td>2010/10/14</td>
<td>$327,900</td>
</tr>
<tr>
<td>Colleen Hurst</td>
<td>Javascript Developer</td>
<td>San Francisco</td>
<td>39</td>
<td>2009/09/15</td>
<td>$205,500</td>
</tr>
<tr>
<td>Sonya Frost</td>
<td>Software Engineer</td>
<td>Edinburgh</td>
<td>23</td>
<td>2008/12/13</td>
<td>$103,600</td>
</tr>
<tr>
<td>Jena Gaines</td>
<td>Office Manager</td>
<td>London</td>
<td>30</td>
<td>2008/12/19</td>
<td>$90,560</td>
</tr>
<tr>
<td>Quinn Flynn</td>
<td>Support Lead</td>
<td>Edinburgh</td>
<td>22</td>
<td>2013/03/03</td>
<td>$342,000</td>
</tr>
<tr>
<td>Charde Marshall</td>
<td>Regional Director</td>
<td>San Francisco</td>
<td>36</td>
<td>2008/10/16</td>
<td>$470,600</td>
</tr>
<tr>
<td>Haley Kennedy</td>
<td>Senior Marketing Designer</td>
<td>London</td>
<td>43</td>
<td>2012/12/18</td>
<td>$313,500</td>
</tr>
<tr>
<td>Tatyana Fitzpatrick</td>
<td>Regional Director</td>
<td>London</td>
<td>19</td>
<td>2010/03/17</td>
<td>$385,750</td>
</tr>
<tr>
<td>Michael Silva</td>
<td>Marketing Designer</td>
<td>London</td>
<td>66</td>
<td>2012/11/27</td>
<td>$198,500</td>
</tr>
<tr>
<td>Paul Byrd</td>
<td>Chief Financial Officer (CFO)</td>
<td>New York</td>
<td>64</td>
<td>2010/06/09</td>
<td>$725,000</td>
</tr>
<tr>
<td>Gloria Little</td>
<td>Systems Administrator</td>
<td>New York</td>
<td>59</td>
<td>2009/04/10</td>
<td>$237,500</td>
</tr>
<tr>
<td>Bradley Greer</td>
<td>Software Engineer</td>
<td>London</td>
<td>41</td>
<td>2012/10/13</td>
<td>$132,000</td>
</tr>
<tr>
<td>Dai Rios</td>
<td>Personnel Lead</td>
<td>Edinburgh</td>
<td>35</td>
<td>2012/09/26</td>
<td>$217,500</td>
</tr>
<tr>
<td>Jenette Caldwell</td>
<td>Development Lead</td>
<td>New York</td>
<td>30</td>
<td>2011/09/03</td>
<td>$345,000</td>
</tr>
<tr>
<td>Yuri Berry</td>
<td>Chief Marketing Officer (CMO)</td>
<td>New York</td>
<td>40</td>
<td>2009/06/25</td>
<td>$675,000</td>
</tr>
<tr>
<td>Caesar Vance</td>
<td>Pre-Sales Support</td>
<td>New York</td>
<td>21</td>
<td>2011/12/12</td>
<td>$106,450</td>
</tr>
<tr>
<td>Doris Wilder</td>
<td>Sales Assistant</td>
<td>Sidney</td>
<td>23</td>
<td>2010/09/20</td>
<td>$85,600</td>
</tr>
<tr>
<td>Angelica Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009/10/09</td>
<td>$1,200,000</td>
</tr>
<tr>
<td>Gavin Joyce</td>
<td>Developer</td>
<td>Edinburgh</td>
<td>42</td>
<td>2010/12/22</td>
<td>$92,575</td>
</tr>
<tr>
<td>Jennifer Chang</td>
<td>Regional Director</td>
<td>Singapore</td>
<td>28</td>
<td>2010/11/14</td>
<td>$357,650</td>
</tr>
<tr>
<td>Brenden Wagner</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>28</td>
<td>2011/06/07</td>
<td>$206,850</td>
</tr>
<tr>
<td>Fiona Green</td>
<td>Chief Operating Officer (COO)</td>
<td>San Francisco</td>
<td>48</td>
<td>2010/03/11</td>
<td>$850,000</td>
</tr>
<tr>
<td>Shou Itou</td>
<td>Regional Marketing</td>
<td>Tokyo</td>
<td>20</td>
<td>2011/08/14</td>
<td>$163,000</td>
</tr>
<tr>
<td>Michelle House</td>
<td>Integration Specialist</td>
<td>Sidney</td>
<td>37</td>
<td>2011/06/02</td>
<td>$95,400</td>
</tr>
<tr>
<td>Suki Burks</td>
<td>Developer</td>
<td>London</td>
<td>53</td>
<td>2009/10/22</td>
<td>$114,500</td>
</tr>
<tr>
<td>Prescott Bartlett</td>
<td>Technical Author</td>
<td>London</td>
<td>27</td>
<td>2011/05/07</td>
<td>$145,000</td>
</tr>
<tr>
<td>Gavin Cortez</td>
<td>Team Leader</td>
<td>San Francisco</td>
<td>22</td>
<td>2008/10/26</td>
<td>$235,500</td>
</tr>
<tr>
<td>Martena Mccray</td>
<td>Post-Sales support</td>
<td>Edinburgh</td>
<td>46</td>
<td>2011/03/09</td>
<td>$324,050</td>
</tr>
<tr>
<td>Unity Butler</td>
<td>Marketing Designer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/12/09</td>
<td>$85,675</td>
</tr>
<tr>
<td>Howard Hatfield</td>
<td>Office Manager</td>
<td>San Francisco</td>
<td>51</td>
<td>2008/12/16</td>
<td>$164,500</td>
</tr>
<tr>
<td>Hope Fuentes</td>
<td>Secretary</td>
<td>San Francisco</td>
<td>41</td>
<td>2010/02/12</td>
<td>$109,850</td>
</tr>
<tr>
<td>Vivian Harrell</td>
<td>Financial Controller</td>
<td>San Francisco</td>
<td>62</td>
<td>2009/02/14</td>
<td>$452,500</td>
</tr>
<tr>
<td>Timothy Mooney</td>
<td>Office Manager</td>
<td>London</td>
<td>37</td>
<td>2008/12/11</td>
<td>$136,200</td>
</tr>
<tr>
<td>Jackson Bradshaw</td>
<td>Director</td>
<td>New York</td>
<td>65</td>
<td>2008/09/26</td>
<td>$645,750</td>
</tr>
<tr>
<td>Olivia Liang</td>
<td>Support Engineer</td>
<td>Singapore</td>
<td>64</td>
<td>2011/02/03</td>
<td>$234,500</td>
</tr>
<tr>
<td>Bruno Nash</td>
<td>Software Engineer</td>
<td>London</td>
<td>38</td>
<td>2011/05/03</td>
<td>$163,500</td>
</tr>
<tr>
<td>Sakura Yamamoto</td>
<td>Support Engineer</td>
<td>Tokyo</td>
<td>37</td>
<td>2009/08/19</td>
<td>$139,575</td>
</tr>
<tr>
<td>Thor Walton</td>
<td>Developer</td>
<td>New York</td>
<td>61</td>
<td>2013/08/11</td>
<td>$98,540</td>
</tr>
<tr>
<td>Finn Camacho</td>
<td>Support Engineer</td>
<td>San Francisco</td>
<td>47</td>
<td>2009/07/07</td>
<td>$87,500</td>
</tr>
<tr>
<td>Serge Baldwin</td>
<td>Data Coordinator</td>
<td>Singapore</td>
<td>64</td>
<td>2012/04/09</td>
<td>$138,575</td>
</tr>
<tr>
<td>Zenaida Frank</td>
<td>Software Engineer</td>
<td>New York</td>
<td>63</td>
<td>2010/01/04</td>
<td>$125,250</td>
</tr>
<tr>
<td>Zorita Serrano</td>
<td>Software Engineer</td>
<td>San Francisco</td>
<td>56</td>
<td>2012/06/01</td>
<td>$115,000</td>
</tr>
<tr>
<td>Jennifer Acosta</td>
<td>Junior Javascript Developer</td>
<td>Edinburgh</td>
<td>43</td>
<td>2013/02/01</td>
<td>$75,650</td>
</tr>
<tr>
<td>Cara Stevens</td>
<td>Sales Assistant</td>
<td>New York</td>
<td>46</td>
<td>2011/12/06</td>
<td>$145,600</td>
</tr>
<tr>
<td>Hermione Butler</td>
<td>Regional Director</td>
<td>London</td>
<td>47</td>
<td>2011/03/21</td>
<td>$356,250</td>
</tr>
<tr>
<td>Lael Greer</td>
<td>Systems Administrator</td>
<td>London</td>
<td>21</td>
<td>2009/02/27</td>
<td>$103,500</td>
</tr>
<tr>
<td>Jonas Alexander</td>
<td>Developer</td>
<td>San Francisco</td>
<td>30</td>
<td>2010/07/14</td>
<td>$86,500</td>
</tr>
<tr>
<td>Shad Decker</td>
<td>Regional Director</td>
<td>Edinburgh</td>
<td>51</td>
<td>2008/11/13</td>
<td>$183,000</td>
</tr>
<tr>
<td>Michael Bruce</td>
<td>Javascript Developer</td>
<td>Singapore</td>
<td>29</td>
<td>2011/06/27</td>
<td>$183,000</td>
</tr>
<tr>
<td>Donna Snider</td>
<td>Customer Support</td>
<td>New York</td>
<td>27</td>
<td>2011/01/25</td>
<td>$112,000</td>
</tr>
</tbody>
</table>
<ul class="tabs">
<li class="active">Javascript</li>
<li>HTML</li>
<li>CSS</li>
<li>Ajax</li>
<li>Server-side script</li>
</ul>
<div class="tabs">
<div class="js">
<p>The Javascript shown below is used to initialise the table shown in this example:</p><code class="multiline language-js">$(document).ready(function() {
var table = $('#example').dataTable();
new $.fn.dataTable.ColReorder( table );
} );</code>
<p>In addition to the above code, the following Javascript library files are loaded for use in this example:</p>
<ul>
<li><a href="../../../media/js/jquery.js">../../../media/js/jquery.js</a></li>
<li><a href="../../../media/js/jquery.dataTables.js">../../../media/js/jquery.dataTables.js</a></li>
<li><a href="../../Plugins/integration/jqueryui/dataTables.jqueryui.js">../../Plugins/integration/jqueryui/dataTables.jqueryui.js</a></li>
<li><a href="../js/dataTables.colReorder.js">../js/dataTables.colReorder.js</a></li>
</ul>
</div>
<div class="table">
<p>The HTML shown below is the raw HTML table element, before it has been enhanced by DataTables:</p>
</div>
<div class="css">
<div>
<p>This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The
additional CSS used is shown below:</p><code class="multiline language-css"></code>
</div>
<p>The following CSS library files are loaded for use in this example to provide the styling of the table:</p>
<ul>
<li><a href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css</a></li>
<li><a href="../../Plugins/integration/jqueryui/dataTables.jqueryui.css">../../Plugins/integration/jqueryui/dataTables.jqueryui.css</a></li>
<li><a href="../css/dataTables.colReorder.css">../css/dataTables.colReorder.css</a></li>
</ul>
</div>
<div class="ajax">
<p>This table loads data by Ajax. The latest data that has been loaded is shown below. This data will update automatically as any additional data is
loaded.</p>
</div>
<div class="php">
<p>The script used to perform the server-side processing for this table is shown below. Please note that this is just an example script using PHP. Server-side
processing scripts can be written in any language, using <a href="//datatables.net/manual/server-side">the protocol described in the DataTables
documentation</a>.</p>
</div>
</div>
</section>
</div>
<section>
<div class="footer">
<div class="gradient"></div>
<div class="liner">
<h2>Other examples</h2>
<div class="toc">
<div class="toc-group">
<h3><a href="./index.html">Examples</a></h3>
<ul class="toc active">
<li><a href="./simple.html">Basic initialisation</a></li>
<li><a href="./new_init.html">Initialisation using `new`</a></li>
<li><a href="./alt_insert.html">Alternative insert styling</a></li>
<li><a href="./realtime.html">Realtime updating</a></li>
<li><a href="./state_save.html">State saving</a></li>
<li><a href="./scrolling.html">Scrolling table</a></li>
<li><a href="./predefined.html">Predefined column ordering</a></li>
<li><a href="./reset.html">Reset ordering API</a></li>
<li><a href="./colvis.html">ColVis integration</a></li>
<li><a href="./fixedcolumns.html">FixedColumns integration</a></li>
<li><a href="./fixedheader.html">FixedHeader integration</a></li>
<li class="active"><a href="./jqueryui.html">jQuery UI styling</a></li>
<li><a href="./col_filter.html">Individual column filtering</a></li>
<li><a href="./server_side.html">Server-side processing</a></li>
</ul>
</div>
</div>
<div class="epilogue">
<p>Please refer to the <a href="http://www.datatables.net">DataTables documentation</a> for full information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and <a href="http://www.datatables.net/plug-ins">plug-ins</a>
which extend the capabilities of DataTables.</p>
<p class="copyright">DataTables designed and created by <a href="http://www.sprymedia.co.uk">SpryMedia Ltd</a> © 2007-2015<br>
DataTables is licensed under the <a href="http://www.datatables.net/mit">MIT license</a>.</p>
</div>
</div>
</div>
</section>
</body>
</html> | {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 53c7d9340a3685c408bc1cb0fdaf953f
timeCreated: 1474751352
licenseType: Pro
TrueTypeFontImporter:
serializedVersion: 4
fontSize: 16
forceTextureCase: -2
characterSpacing: 0
characterPadding: 1
includeFontData: 1
fontNames:
- Roboto
fallbackFontReferences:
- {fileID: 12800000, guid: 0092f7798b6beb94c80979279fa3c9f9, type: 3}
- {fileID: 12800000, guid: 06d08cbcfa41d1e49bbeedbe1bb43076, type: 3}
customCharacters:
fontRenderingMode: 0
ascentCalculationMode: 1
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018 gxw <[email protected]>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "vp3dsp_mips.h"
#include "libavutil/mips/generic_macros_msa.h"
#include "libavutil/intreadwrite.h"
#include "libavcodec/rnd_avg.h"
static void idct_msa(uint8_t *dst, int stride, int16_t *input, int type)
{
v8i16 r0, r1, r2, r3, r4, r5, r6, r7, sign;
v4i32 r0_r, r0_l, r1_r, r1_l, r2_r, r2_l, r3_r, r3_l,
r4_r, r4_l, r5_r, r5_l, r6_r, r6_l, r7_r, r7_l;
v4i32 A, B, C, D, Ad, Bd, Cd, Dd, E, F, G, H;
v4i32 Ed, Gd, Add, Bdd, Fd, Hd;
v16u8 sign_l;
v16i8 d0, d1, d2, d3, d4, d5, d6, d7;
v4i32 c0, c1, c2, c3, c4, c5, c6, c7;
v4i32 f0, f1, f2, f3, f4, f5, f6, f7;
v4i32 sign_t;
v16i8 zero = {0};
v16i8 mask = {0, 4, 8, 12, 16, 20, 24, 28, 0, 0, 0, 0, 0, 0, 0, 0};
v4i32 cnst64277w = {64277, 64277, 64277, 64277};
v4i32 cnst60547w = {60547, 60547, 60547, 60547};
v4i32 cnst54491w = {54491, 54491, 54491, 54491};
v4i32 cnst46341w = {46341, 46341, 46341, 46341};
v4i32 cnst36410w = {36410, 36410, 36410, 36410};
v4i32 cnst25080w = {25080, 25080, 25080, 25080};
v4i32 cnst12785w = {12785, 12785, 12785, 12785};
v4i32 cnst8w = {8, 8, 8, 8};
v4i32 cnst2048w = {2048, 2048, 2048, 2048};
v4i32 cnst128w = {128, 128, 128, 128};
/* Extended input data */
LD_SH8(input, 8, r0, r1, r2, r3, r4, r5, r6, r7);
sign = __msa_clti_s_h(r0, 0);
r0_r = (v4i32) __msa_ilvr_h(sign, r0);
r0_l = (v4i32) __msa_ilvl_h(sign, r0);
sign = __msa_clti_s_h(r1, 0);
r1_r = (v4i32) __msa_ilvr_h(sign, r1);
r1_l = (v4i32) __msa_ilvl_h(sign, r1);
sign = __msa_clti_s_h(r2, 0);
r2_r = (v4i32) __msa_ilvr_h(sign, r2);
r2_l = (v4i32) __msa_ilvl_h(sign, r2);
sign = __msa_clti_s_h(r3, 0);
r3_r = (v4i32) __msa_ilvr_h(sign, r3);
r3_l = (v4i32) __msa_ilvl_h(sign, r3);
sign = __msa_clti_s_h(r4, 0);
r4_r = (v4i32) __msa_ilvr_h(sign, r4);
r4_l = (v4i32) __msa_ilvl_h(sign, r4);
sign = __msa_clti_s_h(r5, 0);
r5_r = (v4i32) __msa_ilvr_h(sign, r5);
r5_l = (v4i32) __msa_ilvl_h(sign, r5);
sign = __msa_clti_s_h(r6, 0);
r6_r = (v4i32) __msa_ilvr_h(sign, r6);
r6_l = (v4i32) __msa_ilvl_h(sign, r6);
sign = __msa_clti_s_h(r7, 0);
r7_r = (v4i32) __msa_ilvr_h(sign, r7);
r7_l = (v4i32) __msa_ilvl_h(sign, r7);
/* Right part */
A = ((r1_r * cnst64277w) >> 16) + ((r7_r * cnst12785w) >> 16);
B = ((r1_r * cnst12785w) >> 16) - ((r7_r * cnst64277w) >> 16);
C = ((r3_r * cnst54491w) >> 16) + ((r5_r * cnst36410w) >> 16);
D = ((r5_r * cnst54491w) >> 16) - ((r3_r * cnst36410w) >> 16);
Ad = ((A - C) * cnst46341w) >> 16;
Bd = ((B - D) * cnst46341w) >> 16;
Cd = A + C;
Dd = B + D;
E = ((r0_r + r4_r) * cnst46341w) >> 16;
F = ((r0_r - r4_r) * cnst46341w) >> 16;
G = ((r2_r * cnst60547w) >> 16) + ((r6_r * cnst25080w) >> 16);
H = ((r2_r * cnst25080w) >> 16) - ((r6_r * cnst60547w) >> 16);
Ed = E - G;
Gd = E + G;
Add = F + Ad;
Bdd = Bd - H;
Fd = F - Ad;
Hd = Bd + H;
r0_r = Gd + Cd;
r7_r = Gd - Cd;
r1_r = Add + Hd;
r2_r = Add - Hd;
r3_r = Ed + Dd;
r4_r = Ed - Dd;
r5_r = Fd + Bdd;
r6_r = Fd - Bdd;
/* Left part */
A = ((r1_l * cnst64277w) >> 16) + ((r7_l * cnst12785w) >> 16);
B = ((r1_l * cnst12785w) >> 16) - ((r7_l * cnst64277w) >> 16);
C = ((r3_l * cnst54491w) >> 16) + ((r5_l * cnst36410w) >> 16);
D = ((r5_l * cnst54491w) >> 16) - ((r3_l * cnst36410w) >> 16);
Ad = ((A - C) * cnst46341w) >> 16;
Bd = ((B - D) * cnst46341w) >> 16;
Cd = A + C;
Dd = B + D;
E = ((r0_l + r4_l) * cnst46341w) >> 16;
F = ((r0_l - r4_l) * cnst46341w) >> 16;
G = ((r2_l * cnst60547w) >> 16) + ((r6_l * cnst25080w) >> 16);
H = ((r2_l * cnst25080w) >> 16) - ((r6_l * cnst60547w) >> 16);
Ed = E - G;
Gd = E + G;
Add = F + Ad;
Bdd = Bd - H;
Fd = F - Ad;
Hd = Bd + H;
r0_l = Gd + Cd;
r7_l = Gd - Cd;
r1_l = Add + Hd;
r2_l = Add - Hd;
r3_l = Ed + Dd;
r4_l = Ed - Dd;
r5_l = Fd + Bdd;
r6_l = Fd - Bdd;
/* Row 0 to 3 */
TRANSPOSE4x4_SW_SW(r0_r, r1_r, r2_r, r3_r,
r0_r, r1_r, r2_r, r3_r);
TRANSPOSE4x4_SW_SW(r0_l, r1_l, r2_l, r3_l,
r0_l, r1_l, r2_l, r3_l);
A = ((r1_r * cnst64277w) >> 16) + ((r3_l * cnst12785w) >> 16);
B = ((r1_r * cnst12785w) >> 16) - ((r3_l * cnst64277w) >> 16);
C = ((r3_r * cnst54491w) >> 16) + ((r1_l * cnst36410w) >> 16);
D = ((r1_l * cnst54491w) >> 16) - ((r3_r * cnst36410w) >> 16);
Ad = ((A - C) * cnst46341w) >> 16;
Bd = ((B - D) * cnst46341w) >> 16;
Cd = A + C;
Dd = B + D;
E = ((r0_r + r0_l) * cnst46341w) >> 16;
E += cnst8w;
F = ((r0_r - r0_l) * cnst46341w) >> 16;
F += cnst8w;
if (type == 1) { // HACK
E += cnst2048w;
F += cnst2048w;
}
G = ((r2_r * cnst60547w) >> 16) + ((r2_l * cnst25080w) >> 16);
H = ((r2_r * cnst25080w) >> 16) - ((r2_l * cnst60547w) >> 16);
Ed = E - G;
Gd = E + G;
Add = F + Ad;
Bdd = Bd - H;
Fd = F - Ad;
Hd = Bd + H;
A = (Gd + Cd) >> 4;
B = (Gd - Cd) >> 4;
C = (Add + Hd) >> 4;
D = (Add - Hd) >> 4;
E = (Ed + Dd) >> 4;
F = (Ed - Dd) >> 4;
G = (Fd + Bdd) >> 4;
H = (Fd - Bdd) >> 4;
if (type != 1) {
LD_SB8(dst, stride, d0, d1, d2, d3, d4, d5, d6, d7);
ILVR_B4_SW(zero, d0, zero, d1, zero, d2, zero, d3,
f0, f1, f2, f3);
ILVR_B4_SW(zero, d4, zero, d5, zero, d6, zero, d7,
f4, f5, f6, f7);
ILVR_H4_SW(zero, f0, zero, f1, zero, f2, zero, f3,
c0, c1, c2, c3);
ILVR_H4_SW(zero, f4, zero, f5, zero, f6, zero, f7,
c4, c5, c6, c7);
A += c0;
B += c7;
C += c1;
D += c2;
E += c3;
F += c4;
G += c5;
H += c6;
}
CLIP_SW8_0_255(A, B, C, D, E, F, G, H);
sign_l = __msa_or_v((v16u8)r1_r, (v16u8)r2_r);
sign_l = __msa_or_v(sign_l, (v16u8)r3_r);
sign_l = __msa_or_v(sign_l, (v16u8)r0_l);
sign_l = __msa_or_v(sign_l, (v16u8)r1_l);
sign_l = __msa_or_v(sign_l, (v16u8)r2_l);
sign_l = __msa_or_v(sign_l, (v16u8)r3_l);
sign_t = __msa_ceqi_w((v4i32)sign_l, 0);
Add = ((r0_r * cnst46341w) + (8 << 16)) >> 20;
if (type == 1) {
Bdd = Add + cnst128w;
CLIP_SW_0_255(Bdd);
Ad = Bdd;
Bd = Bdd;
Cd = Bdd;
Dd = Bdd;
Ed = Bdd;
Fd = Bdd;
Gd = Bdd;
Hd = Bdd;
} else {
Ad = Add + c0;
Bd = Add + c1;
Cd = Add + c2;
Dd = Add + c3;
Ed = Add + c4;
Fd = Add + c5;
Gd = Add + c6;
Hd = Add + c7;
CLIP_SW8_0_255(Ad, Bd, Cd, Dd, Ed, Fd, Gd, Hd);
}
Ad = (v4i32)__msa_and_v((v16u8)Ad, (v16u8)sign_t);
Bd = (v4i32)__msa_and_v((v16u8)Bd, (v16u8)sign_t);
Cd = (v4i32)__msa_and_v((v16u8)Cd, (v16u8)sign_t);
Dd = (v4i32)__msa_and_v((v16u8)Dd, (v16u8)sign_t);
Ed = (v4i32)__msa_and_v((v16u8)Ed, (v16u8)sign_t);
Fd = (v4i32)__msa_and_v((v16u8)Fd, (v16u8)sign_t);
Gd = (v4i32)__msa_and_v((v16u8)Gd, (v16u8)sign_t);
Hd = (v4i32)__msa_and_v((v16u8)Hd, (v16u8)sign_t);
sign_t = __msa_ceqi_w(sign_t, 0);
A = (v4i32)__msa_and_v((v16u8)A, (v16u8)sign_t);
B = (v4i32)__msa_and_v((v16u8)B, (v16u8)sign_t);
C = (v4i32)__msa_and_v((v16u8)C, (v16u8)sign_t);
D = (v4i32)__msa_and_v((v16u8)D, (v16u8)sign_t);
E = (v4i32)__msa_and_v((v16u8)E, (v16u8)sign_t);
F = (v4i32)__msa_and_v((v16u8)F, (v16u8)sign_t);
G = (v4i32)__msa_and_v((v16u8)G, (v16u8)sign_t);
H = (v4i32)__msa_and_v((v16u8)H, (v16u8)sign_t);
r0_r = Ad + A;
r1_r = Bd + C;
r2_r = Cd + D;
r3_r = Dd + E;
r0_l = Ed + F;
r1_l = Fd + G;
r2_l = Gd + H;
r3_l = Hd + B;
/* Row 4 to 7 */
TRANSPOSE4x4_SW_SW(r4_r, r5_r, r6_r, r7_r,
r4_r, r5_r, r6_r, r7_r);
TRANSPOSE4x4_SW_SW(r4_l, r5_l, r6_l, r7_l,
r4_l, r5_l, r6_l, r7_l);
A = ((r5_r * cnst64277w) >> 16) + ((r7_l * cnst12785w) >> 16);
B = ((r5_r * cnst12785w) >> 16) - ((r7_l * cnst64277w) >> 16);
C = ((r7_r * cnst54491w) >> 16) + ((r5_l * cnst36410w) >> 16);
D = ((r5_l * cnst54491w) >> 16) - ((r7_r * cnst36410w) >> 16);
Ad = ((A - C) * cnst46341w) >> 16;
Bd = ((B - D) * cnst46341w) >> 16;
Cd = A + C;
Dd = B + D;
E = ((r4_r + r4_l) * cnst46341w) >> 16;
E += cnst8w;
F = ((r4_r - r4_l) * cnst46341w) >> 16;
F += cnst8w;
if (type == 1) { // HACK
E += cnst2048w;
F += cnst2048w;
}
G = ((r6_r * cnst60547w) >> 16) + ((r6_l * cnst25080w) >> 16);
H = ((r6_r * cnst25080w) >> 16) - ((r6_l * cnst60547w) >> 16);
Ed = E - G;
Gd = E + G;
Add = F + Ad;
Bdd = Bd - H;
Fd = F - Ad;
Hd = Bd + H;
A = (Gd + Cd) >> 4;
B = (Gd - Cd) >> 4;
C = (Add + Hd) >> 4;
D = (Add - Hd) >> 4;
E = (Ed + Dd) >> 4;
F = (Ed - Dd) >> 4;
G = (Fd + Bdd) >> 4;
H = (Fd - Bdd) >> 4;
if (type != 1) {
ILVL_H4_SW(zero, f0, zero, f1, zero, f2, zero, f3,
c0, c1, c2, c3);
ILVL_H4_SW(zero, f4, zero, f5, zero, f6, zero, f7,
c4, c5, c6, c7);
A += c0;
B += c7;
C += c1;
D += c2;
E += c3;
F += c4;
G += c5;
H += c6;
}
CLIP_SW8_0_255(A, B, C, D, E, F, G, H);
sign_l = __msa_or_v((v16u8)r5_r, (v16u8)r6_r);
sign_l = __msa_or_v(sign_l, (v16u8)r7_r);
sign_l = __msa_or_v(sign_l, (v16u8)r4_l);
sign_l = __msa_or_v(sign_l, (v16u8)r5_l);
sign_l = __msa_or_v(sign_l, (v16u8)r6_l);
sign_l = __msa_or_v(sign_l, (v16u8)r7_l);
sign_t = __msa_ceqi_w((v4i32)sign_l, 0);
Add = ((r4_r * cnst46341w) + (8 << 16)) >> 20;
if (type == 1) {
Bdd = Add + cnst128w;
CLIP_SW_0_255(Bdd);
Ad = Bdd;
Bd = Bdd;
Cd = Bdd;
Dd = Bdd;
Ed = Bdd;
Fd = Bdd;
Gd = Bdd;
Hd = Bdd;
} else {
Ad = Add + c0;
Bd = Add + c1;
Cd = Add + c2;
Dd = Add + c3;
Ed = Add + c4;
Fd = Add + c5;
Gd = Add + c6;
Hd = Add + c7;
CLIP_SW8_0_255(Ad, Bd, Cd, Dd, Ed, Fd, Gd, Hd);
}
Ad = (v4i32)__msa_and_v((v16u8)Ad, (v16u8)sign_t);
Bd = (v4i32)__msa_and_v((v16u8)Bd, (v16u8)sign_t);
Cd = (v4i32)__msa_and_v((v16u8)Cd, (v16u8)sign_t);
Dd = (v4i32)__msa_and_v((v16u8)Dd, (v16u8)sign_t);
Ed = (v4i32)__msa_and_v((v16u8)Ed, (v16u8)sign_t);
Fd = (v4i32)__msa_and_v((v16u8)Fd, (v16u8)sign_t);
Gd = (v4i32)__msa_and_v((v16u8)Gd, (v16u8)sign_t);
Hd = (v4i32)__msa_and_v((v16u8)Hd, (v16u8)sign_t);
sign_t = __msa_ceqi_w(sign_t, 0);
A = (v4i32)__msa_and_v((v16u8)A, (v16u8)sign_t);
B = (v4i32)__msa_and_v((v16u8)B, (v16u8)sign_t);
C = (v4i32)__msa_and_v((v16u8)C, (v16u8)sign_t);
D = (v4i32)__msa_and_v((v16u8)D, (v16u8)sign_t);
E = (v4i32)__msa_and_v((v16u8)E, (v16u8)sign_t);
F = (v4i32)__msa_and_v((v16u8)F, (v16u8)sign_t);
G = (v4i32)__msa_and_v((v16u8)G, (v16u8)sign_t);
H = (v4i32)__msa_and_v((v16u8)H, (v16u8)sign_t);
r4_r = Ad + A;
r5_r = Bd + C;
r6_r = Cd + D;
r7_r = Dd + E;
r4_l = Ed + F;
r5_l = Fd + G;
r6_l = Gd + H;
r7_l = Hd + B;
VSHF_B2_SB(r0_r, r4_r, r1_r, r5_r, mask, mask, d0, d1);
VSHF_B2_SB(r2_r, r6_r, r3_r, r7_r, mask, mask, d2, d3);
VSHF_B2_SB(r0_l, r4_l, r1_l, r5_l, mask, mask, d4, d5);
VSHF_B2_SB(r2_l, r6_l, r3_l, r7_l, mask, mask, d6, d7);
/* Final sequence of operations over-write original dst */
ST_D1(d0, 0, dst);
ST_D1(d1, 0, dst + stride);
ST_D1(d2, 0, dst + 2 * stride);
ST_D1(d3, 0, dst + 3 * stride);
ST_D1(d4, 0, dst + 4 * stride);
ST_D1(d5, 0, dst + 5 * stride);
ST_D1(d6, 0, dst + 6 * stride);
ST_D1(d7, 0, dst + 7 * stride);
}
void ff_vp3_idct_put_msa(uint8_t *dest, ptrdiff_t line_size, int16_t *block)
{
idct_msa(dest, line_size, block, 1);
memset(block, 0, sizeof(*block) * 64);
}
void ff_vp3_idct_add_msa(uint8_t *dest, ptrdiff_t line_size, int16_t *block)
{
idct_msa(dest, line_size, block, 2);
memset(block, 0, sizeof(*block) * 64);
}
void ff_vp3_idct_dc_add_msa(uint8_t *dest, ptrdiff_t line_size, int16_t *block)
{
int i = (block[0] + 15) >> 5;
v4i32 dc = {i, i, i, i};
v16i8 d0, d1, d2, d3, d4, d5, d6, d7;
v4i32 c0, c1, c2, c3, c4, c5, c6, c7;
v4i32 e0, e1, e2, e3, e4, e5, e6, e7;
v4i32 r0, r1, r2, r3, r4, r5, r6, r7;
v16i8 mask = {0, 4, 8, 12, 16, 20, 24, 28, 0, 0, 0, 0, 0, 0, 0, 0};
v16i8 zero = {0};
LD_SB8(dest, line_size, d0, d1, d2, d3, d4, d5, d6, d7);
ILVR_B4_SW(zero, d0, zero, d1, zero, d2, zero, d3,
c0, c1, c2, c3);
ILVR_B4_SW(zero, d4, zero, d5, zero, d6, zero, d7,
c4, c5, c6, c7);
/* Right part */
ILVR_H4_SW(zero, c0, zero, c1, zero, c2, zero, c3,
e0, e1, e2, e3);
ILVR_H4_SW(zero, c4, zero, c5, zero, c6, zero, c7,
e4, e5, e6, e7);
e0 += dc;
e1 += dc;
e2 += dc;
e3 += dc;
e4 += dc;
e5 += dc;
e6 += dc;
e7 += dc;
CLIP_SW8_0_255(e0, e1, e2, e3, e4, e5, e6, e7);
/* Left part */
ILVL_H4_SW(zero, c0, zero, c1, zero, c2, zero, c3,
r0, r1, r2, r3);
ILVL_H4_SW(zero, c4, zero, c5, zero, c6, zero, c7,
r4, r5, r6, r7);
r0 += dc;
r1 += dc;
r2 += dc;
r3 += dc;
r4 += dc;
r5 += dc;
r6 += dc;
r7 += dc;
CLIP_SW8_0_255(r0, r1, r2, r3, r4, r5, r6, r7);
VSHF_B2_SB(e0, r0, e1, r1, mask, mask, d0, d1);
VSHF_B2_SB(e2, r2, e3, r3, mask, mask, d2, d3);
VSHF_B2_SB(e4, r4, e5, r5, mask, mask, d4, d5);
VSHF_B2_SB(e6, r6, e7, r7, mask, mask, d6, d7);
/* Final sequence of operations over-write original dst */
ST_D1(d0, 0, dest);
ST_D1(d1, 0, dest + line_size);
ST_D1(d2, 0, dest + 2 * line_size);
ST_D1(d3, 0, dest + 3 * line_size);
ST_D1(d4, 0, dest + 4 * line_size);
ST_D1(d5, 0, dest + 5 * line_size);
ST_D1(d6, 0, dest + 6 * line_size);
ST_D1(d7, 0, dest + 7 * line_size);
block[0] = 0;
}
void ff_vp3_v_loop_filter_msa(uint8_t *first_pixel, ptrdiff_t stride,
int *bounding_values)
{
int nstride = -stride;
v4i32 e0, e1, f0, f1, g0, g1;
v16i8 zero = {0};
v16i8 d0, d1, d2, d3;
v8i16 c0, c1, c2, c3;
v8i16 r0;
v8i16 cnst3h = {3, 3, 3, 3, 3, 3, 3, 3},
cnst4h = {4, 4, 4, 4, 4, 4, 4, 4};
v16i8 mask = {0, 4, 8, 12, 16, 20, 24, 28, 0, 0, 0, 0, 0, 0, 0, 0};
int16_t temp_16[8];
int temp_32[8];
LD_SB4(first_pixel + nstride * 2, stride, d0, d1, d2, d3);
ILVR_B4_SH(zero, d0, zero, d1, zero, d2, zero, d3,
c0, c1, c2, c3);
r0 = (c0 - c3) + (c2 - c1) * cnst3h;
r0 += cnst4h;
r0 = r0 >> 3;
/* Get filter_value from bounding_values one by one */
ST_SH(r0, temp_16);
for (int i = 0; i < 8; i++)
temp_32[i] = bounding_values[temp_16[i]];
LD_SW2(temp_32, 4, e0, e1);
ILVR_H2_SW(zero, c1, zero, c2, f0, g0);
ILVL_H2_SW(zero, c1, zero, c2, f1, g1);
f0 += e0;
f1 += e1;
g0 -= e0;
g1 -= e1;
CLIP_SW4_0_255(f0, f1, g0, g1);
VSHF_B2_SB(f0, f1, g0, g1, mask, mask, d1, d2);
/* Final move to first_pixel */
ST_D1(d1, 0, first_pixel + nstride);
ST_D1(d2, 0, first_pixel);
}
void ff_vp3_h_loop_filter_msa(uint8_t *first_pixel, ptrdiff_t stride,
int *bounding_values)
{
v16i8 d0, d1, d2, d3, d4, d5, d6, d7;
v8i16 c0, c1, c2, c3, c4, c5, c6, c7;
v8i16 r0;
v4i32 e0, e1, f0, f1, g0, g1;
v16i8 zero = {0};
v8i16 cnst3h = {3, 3, 3, 3, 3, 3, 3, 3},
cnst4h = {4, 4, 4, 4, 4, 4, 4, 4};
v16i8 mask = {0, 16, 4, 20, 8, 24, 12, 28, 0, 0, 0, 0, 0, 0, 0, 0};
int16_t temp_16[8];
int temp_32[8];
LD_SB8(first_pixel - 2, stride, d0, d1, d2, d3, d4, d5, d6, d7);
ILVR_B4_SH(zero, d0, zero, d1, zero, d2, zero, d3,
c0, c1, c2, c3);
ILVR_B4_SH(zero, d4, zero, d5, zero, d6, zero, d7,
c4, c5, c6, c7);
TRANSPOSE8x8_SH_SH(c0, c1, c2, c3, c4, c5, c6, c7,
c0, c1, c2, c3, c4, c5, c6, c7);
r0 = (c0 - c3) + (c2 - c1) * cnst3h;
r0 += cnst4h;
r0 = r0 >> 3;
/* Get filter_value from bounding_values one by one */
ST_SH(r0, temp_16);
for (int i = 0; i < 8; i++)
temp_32[i] = bounding_values[temp_16[i]];
LD_SW2(temp_32, 4, e0, e1);
ILVR_H2_SW(zero, c1, zero, c2, f0, g0);
ILVL_H2_SW(zero, c1, zero, c2, f1, g1);
f0 += e0;
f1 += e1;
g0 -= e0;
g1 -= e1;
CLIP_SW4_0_255(f0, f1, g0, g1);
VSHF_B2_SB(f0, g0, f1, g1, mask, mask, d1, d2);
/* Final move to first_pixel */
ST_H4(d1, 0, 1, 2, 3, first_pixel - 1, stride);
ST_H4(d2, 0, 1, 2, 3, first_pixel - 1 + 4 * stride, stride);
}
void ff_put_no_rnd_pixels_l2_msa(uint8_t *dst, const uint8_t *src1,
const uint8_t *src2, ptrdiff_t stride, int h)
{
if (h == 8) {
v16i8 d0, d1, d2, d3, d4, d5, d6, d7;
v16i8 c0, c1, c2, c3;
v4i32 a0, a1, a2, a3, b0, b1, b2, b3;
v4i32 e0, e1, e2;
v4i32 f0, f1, f2;
v4u32 t0, t1, t2, t3;
v16i8 mask = {0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23};
int32_t value = 0xfefefefe;
v4i32 fmask = {value, value, value, value};
LD_SB8(src1, stride, d0, d1, d2, d3, d4, d5, d6, d7);
VSHF_B2_SB(d0, d1, d2, d3, mask, mask, c0, c1);
VSHF_B2_SB(d4, d5, d6, d7, mask, mask, c2, c3);
a0 = (v4i32) __msa_pckev_d((v2i64)c1, (v2i64)c0);
a2 = (v4i32) __msa_pckod_d((v2i64)c1, (v2i64)c0);
a1 = (v4i32) __msa_pckev_d((v2i64)c3, (v2i64)c2);
a3 = (v4i32) __msa_pckod_d((v2i64)c3, (v2i64)c2);
LD_SB8(src2, stride, d0, d1, d2, d3, d4, d5, d6, d7);
VSHF_B2_SB(d0, d1, d2, d3, mask, mask, c0, c1);
VSHF_B2_SB(d4, d5, d6, d7, mask, mask, c2, c3);
b0 = (v4i32) __msa_pckev_d((v2i64)c1, (v2i64)c0);
b2 = (v4i32) __msa_pckod_d((v2i64)c1, (v2i64)c0);
b1 = (v4i32) __msa_pckev_d((v2i64)c3, (v2i64)c2);
b3 = (v4i32) __msa_pckod_d((v2i64)c3, (v2i64)c2);
e0 = (v4i32) __msa_xor_v((v16u8)a0, (v16u8)b0);
e0 = (v4i32) __msa_and_v((v16u8)e0, (v16u8)fmask);
t0 = ((v4u32)e0) >> 1;
e2 = (v4i32) __msa_and_v((v16u8)a0, (v16u8)b0);
t0 = t0 + (v4u32)e2;
e1 = (v4i32) __msa_xor_v((v16u8)a1, (v16u8)b1);
e1 = (v4i32) __msa_and_v((v16u8)e1, (v16u8)fmask);
t1 = ((v4u32)e1) >> 1;
e2 = (v4i32) __msa_and_v((v16u8)a1, (v16u8)b1);
t1 = t1 + (v4u32)e2;
f0 = (v4i32) __msa_xor_v((v16u8)a2, (v16u8)b2);
f0 = (v4i32) __msa_and_v((v16u8)f0, (v16u8)fmask);
t2 = ((v4u32)f0) >> 1;
f2 = (v4i32) __msa_and_v((v16u8)a2, (v16u8)b2);
t2 = t2 + (v4u32)f2;
f1 = (v4i32) __msa_xor_v((v16u8)a3, (v16u8)b3);
f1 = (v4i32) __msa_and_v((v16u8)f1, (v16u8)fmask);
t3 = ((v4u32)f1) >> 1;
f2 = (v4i32) __msa_and_v((v16u8)a3, (v16u8)b3);
t3 = t3 + (v4u32)f2;
ST_W8(t0, t1, 0, 1, 2, 3, 0, 1, 2, 3, dst, stride);
ST_W8(t2, t3, 0, 1, 2, 3, 0, 1, 2, 3, dst + 4, stride);
} else {
int i;
for (i = 0; i < h; i++) {
uint32_t a, b;
a = AV_RN32(&src1[i * stride]);
b = AV_RN32(&src2[i * stride]);
AV_WN32A(&dst[i * stride], no_rnd_avg32(a, b));
a = AV_RN32(&src1[i * stride + 4]);
b = AV_RN32(&src2[i * stride + 4]);
AV_WN32A(&dst[i * stride + 4], no_rnd_avg32(a, b));
}
}
}
| {
"pile_set_name": "Github"
} |
var qstack_8c =
[
[ "qstack", "qstack_8c.html#ad59200fd9723a575e042365b916e150b", null ],
[ "qstack_setsize", "qstack_8c.html#a243157bbd832b1a29da906cdf1e067d1", null ],
[ "qstack_push", "qstack_8c.html#af6bd78d22c5ac2a5dbcc4102416a1682", null ],
[ "qstack_pushstr", "qstack_8c.html#a3c626c12f0f8ad9b1899c4d6e9fa78a6", null ],
[ "qstack_pushint", "qstack_8c.html#a227a2c394e088afee835b79aa1e81a90", null ],
[ "qstack_pop", "qstack_8c.html#a79ecf0838fc92a6fde5e43fcac757426", null ],
[ "qstack_popstr", "qstack_8c.html#a5a4924e9e1201c9049d0baa68d4c1da7", null ],
[ "qstack_popint", "qstack_8c.html#a355b4b772da518e3e63702e61df44886", null ],
[ "qstack_popat", "qstack_8c.html#a20cfe4a51fa37348293d199b22530b04", null ],
[ "qstack_get", "qstack_8c.html#aae38a11a6be7fbea79f3ca51c65a4aee", null ],
[ "qstack_getstr", "qstack_8c.html#a6e2940f626e655f803cb78c452780c1a", null ],
[ "qstack_getint", "qstack_8c.html#af37f84c47e9cd48b3f070fa96777029e", null ],
[ "qstack_getat", "qstack_8c.html#a513b235ab408d98c6324fbef841e3e1a", null ],
[ "qstack_size", "qstack_8c.html#a3eac4be39a2ae68c7290735b034fc66c", null ],
[ "qstack_clear", "qstack_8c.html#a1ca1db3402919fe147e32a16ee56a051", null ],
[ "qstack_debug", "qstack_8c.html#af40fcb35c362981495c37aa7963ff50d", null ],
[ "qstack_free", "qstack_8c.html#a2a091ec90ef14302cb29ea07c1ce84b2", null ]
]; | {
"pile_set_name": "Github"
} |
/**
* 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.
*/
package org.apache.activemq.plugin;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Plugin which allows to force every incoming message to be PERSISTENT or
* NON-PERSISTENT.
*
* Useful, if you have set the broker usage policy to process ONLY persistent or
* ONLY non-persistent messages.
*
* @org.apache.xbean.XBean element="forcePersistencyModeBrokerPlugin"
*/
public class ForcePersistencyModeBrokerPlugin implements BrokerPlugin {
private static Logger LOG = LoggerFactory.getLogger(ForcePersistencyModeBrokerPlugin.class);
private boolean persistenceFlag = false;
/**
* Constructor
*/
public ForcePersistencyModeBrokerPlugin() {}
/**
* @param broker
*
* @return the Broker
*
* @throws Exception
*
* @see org.apache.activemq.broker.BrokerPlugin#installPlugin(org.apache.activemq.broker.Broker)
*/
@Override
public Broker installPlugin(Broker broker) throws Exception {
ForcePersistencyModeBroker pB = new ForcePersistencyModeBroker(broker);
pB.setPersistenceFlag(isPersistenceForced());
LOG.info("Installing ForcePersistencyModeBroker plugin: persistency enforced={}", pB.isPersistent());
return pB;
}
/**
* Sets the persistence mode.
*
* @param persistenceFlag
*/
public void setPersistenceFlag(final boolean persistenceFlag) {
this.persistenceFlag = persistenceFlag;
}
/**
* @return the mode the (activated) plugin will set the message delivery
* mode
*/
public final boolean isPersistenceForced() {
return persistenceFlag;
}
}
| {
"pile_set_name": "Github"
} |
### 消息:北京承诺采购更多农产品 推动美国取消关税
------------------------
#### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) | [手把手翻墙教程](https://github.com/gfw-breaker/guides/wiki) | [禁闻聚合安卓版](https://github.com/gfw-breaker/bn-android) | [网门安卓版](https://github.com/oGate2/oGate) | [神州正道安卓版](https://github.com/SzzdOgate/update)
<div class="zhidingtu">
<div class="ar-wrap-3x2">
<img alt="图为川普与习近平6月在大阪G20会议上会面(AP)" class="ar-wrap-inside-fill" src="http://img.soundofhope.org/2019/11/4ae139f4-fbf0-11e9-acf9-cafedce87d15-image-hires-231205-600x400.jpg"/>
</div>
<div class="caption">
图为川普与习近平6月在大阪G20会议上会面(AP)
</div>
</div>
<hr/>
#### [翻墙必看视频(文昭、江峰、法轮功、八九六四、香港反送中...)](https://github.com/gfw-breaker/banned-news/blob/master/pages/links.md)
<div class="content">
<p>
<span class="content-info-date">
【希望之声2019年11月4日】
</span>
<span class="content-info-type">
(本台记者凌杉综合编译)
</span>
三名了解内部讨论的人士表示,北京当局目前以加速购买农产品为代价,敦促川普(特朗普)政府取消原定于12月中旬生效的关税,并促进中美贸易协议第一阶段的签署。
</p>
<div class="widget ad-300x250 ad-ecf">
<!-- ZW30 Post Embed 300x250 1 -->
<ins class="adsbygoogle" data-ad-client="ca-pub-1519518652909441" data-ad-slot="9768754376" style="display:inline-block;width:300px;height:250px">
</ins>
</div>
<p>
美媒《Politico》的消息人士说,北京正在试图采取一切办法让美国取消对中贸易关税,力度堪比篮球赛上的“全场盯人”。作为交换条件,北京同意在两年内购买价值高达500亿美元的美国农产品,并履行承诺开放其金融服务业并加强知识产权保护。在此之前,北京当局仅同意在首年购买200亿美金价值的农产品。
</p>
<p>
消息来源称,目前的假设是,中美两国达成第一阶段协议将消除原定12月15日,对约1600亿美元的中国商品开征的15%关税,本批关税包括笔记本电脑和智能手机在内的一系列主要消费品。
</p>
<p>
对于撤销12月关税的消息,美方当局目前尚未做出公开回应。美国商务部长罗斯近期表示,他预计12月的关税可能会因中美达成第一部分协议而取消。
</p>
<p>
知情者透露,北京方面还敦促美国取消9月1日对价值约1,120亿美元的中国商品征收的15%关税,但美方并未做出任何相关决定。此外,中方还非常希望取消对价值2500亿美元的中国商品加征25%的关税,或至少削减一半,尽管目前这预计无法写入交易(指美国不会同意)。
</p>
<p>
川普政府目前公开同意暂停10月15日将2500亿美金关税提高到30%的计划。
</p>
<p>
关于如何确保中方履行贸易协议,知情者说,美方官员目前正在考虑的主要执行机制是如果中方违规,可以重新开征所有关税。
</p>
<p>
对于执行协议,白宫贸易顾问彼得·纳瓦罗在近期的采访中也提到,美方可以在北京不遵守协议的情况下增加关税,这些内容应该写入协议的执行机制。
</p>
<p>
中美两国目前仍然处于停火期,并在朝着签署第一阶段贸易协议努力。中美双方此前的预期是在11月中旬的智利APEC峰会上签署协议,不过,智利不久前因为大规模的民主抗议而取消了该会议,白宫方面表示,美方将很快公布新的地点。
</p>
<div>
</div>
<p>
美国总统川普上周日(11月3日)说,中美签署协议的地点选址有进展,“首先,我想达成这笔协议。我的意思是,选一个地点对为来说将非常容易。但首先,我们将看看是否能达成交易。如果我们达成交易,那么开会的地点将非常容易。这将是在美国的某个地方”。
</p>
<p>
白宫一位高级官员称,目前中美两国仍在就强制技术转让和知识产权保护的问题谈判,在其他方面,两国协议基本完成。相关的协议预计将涵盖货币、金融等一些领域的内容,同时涵盖北京采购农产品的协议。
</p>
<p>
川普表示,初步协议将涵盖两国之间60%的问题。谈判的第二阶段将解决更多的结构性问题,例如国企补贴等问题,这些不会涵盖在第一部分协议中。
</p>
<div class="content-info-btm">
<p class="content-info-zerenbianji">
<span class="content-info-title">
责任编辑:
</span>
<span class="content-info-content">
宋月
</span>
</p>
</div>
</div>
<hr/>
手机上长按并复制下列链接或二维码分享本文章:<br/>
https://github.com/gfw-breaker/banned-news/blob/master/pages/soh_rdzz/n3310716.md <br/>
<a href='https://github.com/gfw-breaker/banned-news/blob/master/pages/soh_rdzz/n3310716.md'><img src='https://github.com/gfw-breaker/banned-news/blob/master/pages/soh_rdzz/n3310716.md.png'/></a> <br/>
原文地址(需翻墙访问):http://www.soundofhope.org/gb/2019/11/04/n3310716.html
------------------------
#### [首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) | [一键翻墙软件](https://github.com/gfw-breaker/nogfw/blob/master/README.md) | [《九评共产党》](https://github.com/gfw-breaker/9ping.md/blob/master/README.md#九评之一评共产党是什么) | [《解体党文化》](https://github.com/gfw-breaker/jtdwh.md/blob/master/README.md) | [《共产主义的终极目的》](https://github.com/gfw-breaker/gczydzjmd.md/blob/master/README.md)
<img src='http://gfw-breaker.win/banned-news/pages/soh_rdzz/n3310716.md' width='0px' height='0px'/> | {
"pile_set_name": "Github"
} |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FILE_UTILS_H_
#define FILE_UTILS_H_
#include <dirent.h>
#include <sys/types.h>
#include <unistd.h>
#include <functional>
#include <map>
#include <memory>
#include "logging.h"
namespace file_utils {
// RAII classes for auto-releasing fd/dirs.
template <typename RESOURCE_TYPE, int (*CLOSE_FN)(RESOURCE_TYPE)>
struct ScopedResource {
explicit ScopedResource(RESOURCE_TYPE r) : r_(r) { CHECK(r); }
~ScopedResource() { CLOSE_FN(r_); }
RESOURCE_TYPE r_;
};
using ScopedFD = ScopedResource<int, close>;
using ScopedDir = ScopedResource<DIR*, closedir>;
// Invokes predicate(pid) for each folder in |proc_path|/[0-9]+ which has
// a numeric name (typically pids and tids).
void ForEachPidInProcPath(const char* proc_path,
std::function<void(int)> predicate);
// Reads the contents of |path| fully into |buf| up to |length| chars.
// |buf| is guaranteed to be null terminated.
ssize_t ReadFile(const char* path, char* buf, size_t length);
// Reads a single-line file, stripping out any \0, \r, \n and replacing
// non-printable charcters with '?'. |buf| is guaranteed to be null terminated.
bool ReadFileTrimmed(const char* path, char* buf, size_t length);
// Convenience wrappers for /proc/|pid|/|proc_file| paths.
ssize_t ReadProcFile(int pid, const char* proc_file, char* buf, size_t length);
bool ReadProcFileTrimmed(int pid,
const char* proc_file,
char* buf,
size_t length);
// Takes a C string buffer and chunks it into lines without creating any
// copies. It modifies the original buffer, by replacing \n with \0.
class LineReader {
public:
LineReader(char* buf, size_t size);
~LineReader();
const char* NextLine();
private:
char* ptr_;
char* end_;
};
} // namespace file_utils
#endif // FILE_UTILS_H_
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!-- Metadata Standard tab, gmd:MD_Metadata/gmd:metadataStandardName and
gmd:MD_Metadata/gmd:metadataStandardVersion (Service) -->
<h:div xmlns:g="http://www.esri.com/geoportal/gxe"
xmlns:h="http://www.esri.com/geoportal/gxe/html"
h:tag="div" g:label="$i18n.catalog.iso19139.MD_Metadata.section.metadata.standard">
<g:element g:targetName="gmd:metadataStandardName" g:minOccurs="1" g:maxOccurs="1"
g:label="$i18n.catalog.iso19139.MD_Metadata.metadataStandardName"
g:preferOpen="true" g:extends="$base/schema/gco/basicTypes/CharacterString_PropertyType.xml">
<g:body>
<g:element g:value="INSPIRE Metadata Implementing Rules">
<!--<g:body><g:input g:extends="$base/core/ui/InputText.xml" h:readonly="readonly"/></g:body>-->
</g:element>
</g:body>
</g:element>
<g:element g:targetName="gmd:metadataStandardVersion" g:minOccurs="1" g:maxOccurs="1"
g:label="$i18n.catalog.iso19139.MD_Metadata.metadataStandardVersion"
g:preferOpen="true" g:extends="$base/schema/gco/basicTypes/CharacterString_PropertyType.xml">
<g:body>
<g:element g:value="Technical Guidelines based on EN ISO 19115 and EN ISO 19119 (Version 1.2)">
<!--<g:body><g:input g:extends="$base/core/ui/InputText.xml" h:readonly="readonly"/></g:body>-->
</g:element>
</g:body>
</g:element>
</h:div>
| {
"pile_set_name": "Github"
} |
(function() {
var o1 = {
m1: function(){ return {}; },
m2: function(){ return {}; },
m3: function(){ return {}; },
m4: function(){ return {}; }
};
o1.m1(); // analyzed precisely
o1.m2(); // analyzed precisely
unknown(o1.m2);
var o = unknown? o1: {};
o.m3(); // not analyzed precisely: `o1` is not the only receiver.
var m4 = o.m4;
m4(); // (not a method call)
var o2 = {};
o2.m = function() { return {}; };
// not analyzed precisely: `m` may be in the prototype since `m`
// is not in the initializer, and we do not attempt to reason flow
// sensitively beyond that at the moment
o2.m();
});
(function(){
function f1(){return {};}
var v1 = {m: f1}.m(); // analyzed precisely
v1 === true;
function f2(){return {};}
var o2 = {m: f2};
var v2 = o2.m(); // analyzed precisely
v2 === true;
function f3(){return {};}
var v3 = ({m: f3}).m(); // analyzed precisely
v3 === true;
function f4(){return {};}
var { o4 } = {m: f4};
// not analyzed precisely: o4 is from a destructuring assignment
// (and it is even `undefined` in this case)
var v4 = o4.m();
v4 === true;
});
(function(){
(function(o = {m: () => 42}){
var v1 = o.m(); // not analyzed precisely: `o` may be `unknown`
})(unknown);
function f(o = {m: () => 42}){
var v2 = o.m(); // not analyzed precisely: `o` may be `unknown`
};
f(unknown);
(function(o = {m: () => 42}){
var v3 = o.m(); // not analyzed precisely: `o.m` may be `unknown`
})({m: unknown});
(function(o = {m: () => 42}){
// not analyzed precisely: we only support unique receivers at
// the moment
var v4 = o.m();
})({m: () => true});
});
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env php
<?php
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any our classes "manually". Feels great to relax.
|
*/
require __DIR__.'/bootstrap/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running. We will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);
| {
"pile_set_name": "Github"
} |
import process from 'process'
import { signals } from 'signal-exit'
import { gracefulExit } from './graceful_exit.js'
// Make sure the server stops when graceful exits are possible
// Also send related events
// We cannot handle `process.exit()` since graceful exit is async
export const setupGracefulExit = function ({
protocolAdapters,
dbAdapters,
stopProcessErrors,
config,
}) {
const exitFunc = gracefulExit.bind(undefined, {
protocolAdapters,
dbAdapters,
stopProcessErrors,
config,
})
const exitSignals = getExitSignals()
exitSignals.forEach((exitSignal) => {
process.on(exitSignal, exitFunc)
})
return { exitFunc }
}
// Add `SIGUSR2` for Nodemon
const getExitSignals = function () {
const exitSignals = signals()
return exitSignals.includes('SIGUSR2')
? exitSignals
: [...exitSignals, 'SIGUSR2']
}
| {
"pile_set_name": "Github"
} |
/** Copyright 2019 Mek Global Limited. */
package org.knowm.xchange.kucoin.service;
import java.io.IOException;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.knowm.xchange.kucoin.dto.response.KucoinResponse;
import org.knowm.xchange.kucoin.dto.response.TradeHistoryResponse;
/** Based on code by chenshiwei on 2019/1/22. */
@Path("/api/v1/market")
@Produces(MediaType.APPLICATION_JSON)
public interface HistoryAPI {
/**
* List the latest trades for a symbol.
*
* @param symbol The symbol whose trades should be fetched.
* @return The trades for the symbol.
*/
@GET
@Path("/histories")
KucoinResponse<List<TradeHistoryResponse>> getTradeHistories(@QueryParam("symbol") String symbol)
throws IOException;
}
| {
"pile_set_name": "Github"
} |
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.util;
import java.util.List;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.olap.util.filter.IResultRow;
import org.eclipse.birt.data.engine.script.ScriptConstants;
import org.mozilla.javascript.Scriptable;
/**
*
*/
public class DimensionJSObjectPopulator implements IJSObjectPopulator
{
//
private DummyJSLevels dimObj;
private Scriptable scope;
private String dimensionName;
private List levelNames;
/**
*
* @param scope
* @param dimensionName
* @param levelNames
*/
public DimensionJSObjectPopulator( Scriptable scope, String dimensionName,
List levelNames )
{
this.scope = scope;
this.dimensionName = dimensionName;
this.levelNames = levelNames;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.olap.util.IJSObjectPopulator#doInit()
*/
public void doInit( ) throws DataException
{
this.dimObj = new DummyJSLevels( dimensionName );
DummyJSDimensionObject dimObj = new DummyJSDimensionObject( this.dimObj,
levelNames );
scope.put( ScriptConstants.DIMENSION_SCRIPTABLE,
scope,
new DummyJSDimensionAccessor( dimensionName, dimObj ) );
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.olap.util.IJSObjectPopulator#setData(java.lang.Object)
*/
public void setData( Object resultRow )
{
assert resultRow instanceof IResultRow;
dimObj.setResultRow( ( IResultRow ) resultRow );
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.olap.util.IJSObjectPopulator#cleanUp()
*/
public void cleanUp( )
{
this.scope.delete( ScriptConstants.DIMENSION_SCRIPTABLE );
this.scope.setParentScope( null );
}
}
| {
"pile_set_name": "Github"
} |
/* @flow */
import config from '../config'
import { warn } from './debug'
import { inBrowser, inWeex } from './env'
import { isPromise } from 'shared/util'
import { pushTarget, popTarget } from '../observer/dep'
export function handleError (err: Error, vm: any, info: string) {
// Deactivate deps tracking while processing error handler to avoid possible infinite rendering.
// See: https://github.com/vuejs/vuex/issues/1505
pushTarget()
try {
if (vm) {
let cur = vm
while ((cur = cur.$parent)) {
const hooks = cur.$options.errorCaptured
if (hooks) {
for (let i = 0; i < hooks.length; i++) {
try {
const capture = hooks[i].call(cur, err, vm, info) === false
if (capture) return
} catch (e) {
globalHandleError(e, cur, 'errorCaptured hook')
}
}
}
}
}
globalHandleError(err, vm, info)
} finally {
popTarget()
}
}
export function invokeWithErrorHandling (
handler: Function,
context: any,
args: null | any[],
vm: any,
info: string
) {
let res
try {
res = args ? handler.apply(context, args) : handler.call(context)
if (res && !res._isVue && isPromise(res) && !res._handled) {
res.catch(e => handleError(e, vm, info + ` (Promise/async)`))
// issue #9511
// avoid catch triggering multiple times when nested calls
res._handled = true
}
} catch (e) {
handleError(e, vm, info)
}
return res
}
function globalHandleError (err, vm, info) {
if (config.errorHandler) {
try {
return config.errorHandler.call(null, err, vm, info)
} catch (e) {
// if the user intentionally throws the original error in the handler,
// do not log it twice
if (e !== err) {
logError(e, null, 'config.errorHandler')
}
}
}
logError(err, vm, info)
}
function logError (err, vm, info) {
if (process.env.NODE_ENV !== 'production') {
warn(`Error in ${info}: "${err.toString()}"`, vm)
}
/* istanbul ignore else */
if ((inBrowser || inWeex) && typeof console !== 'undefined') {
console.error(err)
} else {
throw err
}
}
| {
"pile_set_name": "Github"
} |
package types
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
// ServiceUpdateResponse service update response
// swagger:model ServiceUpdateResponse
type ServiceUpdateResponse struct {
// Optional warning messages
Warnings []string `json:"Warnings"`
}
| {
"pile_set_name": "Github"
} |
/**
@page build_and_install Build and install gf
@tableofcontents
In this document, you will learn how to build and install gf so that you are ready for your first project with gf. It is assumed you already have a compiler installed (gcc or clang for Linux; MSVC included in Visual Studio for Windows).
gf needs a conformant C++14 compiler. The minimum version of supported compilers are given in the following table.
| Compiler | Version | Reference |
|----------|:-------:|---------------------------------------------------------------------------------------------------------|
| GCC | 5 | [C++14 Support in GCC](https://gcc.gnu.org/projects/cxx-status.html#cxx14) |
| Clang | 3.4 | [C++14 implementation status](http://clang.llvm.org/cxx_status.html#cxx14) |
| MSVC | VS 2017 | [Visual C++ Language Conformance](https://docs.microsoft.com/en-us/cpp/visual-cpp-language-conformance) |
@section dependencies Dependencies
gf needs some external libraries and tools that you must install before compiling gf. Here are some information about these libraries, especially the required minimum version.
Libraries:
| Name | Version | License |
|-----------------------------------------------------------------------------------------|:-------:|:-----------:|
| [SDL2](https://www.libsdl.org/) | 2.0.2 | zlib/libpng |
| [Boost Filesystem](http://www.boost.org/doc/libs/release/libs/filesystem/) | 1.55 | Boost |
| [Boost String Algorithms](http://www.boost.org/doc/libs/release/libs/algorithm/string/) | 1.55 | Boost |
| [Boost Heap](http://www.boost.org/doc/libs/release/libs/heap/) | 1.55 | Boost |
| [Freetype](http://freetype.org/) | 2.5.2 | Freetype |
| [zlib](https://zlib.net/) | 1.2.8 | zlib/libpng |
Tools:
| Name | Version |
|-----------------------------|:-------:|
| [CMake](https://cmake.org/) | 3.0.2 |
@section getting_started_with_linux Getting started with Linux
This section assumes you have a working compiler, either [gcc](https://gcc.gnu.org/) or [clang](https://clang.llvm.org/), and [git](https://git-scm.com/).
@subsection dependencies_for_linux Dependencies for Linux
The recommanded way for handling dependencies on Linux is to use your favorite distribution's package manager. Here are the packages needed to build gf for various widespread distributions.
For Debian/Ubuntu:
~~~{.sh}
apt-get install libsdl2-dev libboost-filesystem-dev libboost-dev libfreetype6-dev zlib1g-dev cmake
~~~
For Archlinux:
~~~{.sh}
pacman -S sdl2 boost freetype2 zlib cmake
~~~
For Fedora/Red Hat/CentOS:
~~~{.sh}
dnf install SDL2-devel boost-devel freetype-devel zlib-devel cmake
~~~
@subsection build_and_install_for_linux Build and install
First, build:
~~~{.sh}
git clone https://github.com/GamedevFramework/gf.git
cd gf
git submodule update --init
mkdir build
cd build
cmake ../ -DGF_BUILD_GAMES=ON -DGF_BUILD_TOOLS=ON
make
~~~
Then install:
~~~{.sh}
make install # may require root permissions
~~~
@section getting_started_with_windows Getting started with Windows
This section assumes you are using at least [Visual Studio Community 2017](https://www.visualstudio.com/vs/community/). You also need [git for Windows](https://git-for-windows.github.io/) and [CMake 3.8 or newer](https://cmake.org/download/). Finally, the working directory where everything will be installed is set to `C:\Local\`. You can choose whatever directory you want.
@subsection dependencies_for_windows Dependencies for Windows
For Windows, [vcpkg](https://github.com/Microsoft/vcpkg) can handle the dependencies.
First, you have to install vcpkg from its git repository. From a command line, in the working directory:
~~~{.bat}
C:\Local> git clone https://github.com/Microsoft/vcpkg.git
C:\Local> cd vcpkg
~~~
Then, you have to follow the instructions from the vcpkg documentation. Normally, during the installation process, it will detect the installed CMake.
~~~{.bat}
C:\Local\vcpkg> .\bootstrap-vcpkg.bat
C:\Local\vcpkg> .\vcpkg integrate install
~~~
Then, you can install the dependencies:
~~~{.bat}
C:\Local\vcpkg> .\vcpkg install sdl2:x64-windows freetype:x64-windows zlib:x64-windows boost-algorithm:x64-windows boost-filesystem:x64-windows boost-heap:x64-windows boost-container:x64-windows
~~~
@subsection build_and_install_for_windows Build and install
Back in the working directory, you can prepare the build of gf. Everything will be installed in the vcpkg hierarchy.
~~~{.bat}
C:\Local> git clone https://github.com/GamedevFramework/gf.git
C:\Local> cd gf
C:\Local\gf> git submodule update --init
C:\Local\gf> mkdir build
C:\Local\gf> cd build
C:\Local\gf\build> cmake ../ -DCMAKE_TOOLCHAIN_FILE=C:\Local\vcpkg\scripts\buildsystems\vcpkg.cmake -DCMAKE_INSTALL_PREFIX=C:\Local\vcpkg\installed\x64-windows -DGF_BUILD_GAMES=ON -DGF_BUILD_TOOLS=ON
~~~
Finally, open Visual Studio. Then, open the gf solution located at `C:\Local\gf\build\GF.sln`. Then, choose "Release" and build the solution (F7). Finally, build the "INSTALL" project. gf is installed as well as its tools and games.
*/
| {
"pile_set_name": "Github"
} |
package railo.runtime.tag;
import java.io.IOException;
import javax.xml.parsers.FactoryConfigurationError;
import railo.runtime.converter.ConverterException;
import railo.runtime.converter.JSConverter;
import railo.runtime.converter.WDDXConverter;
import railo.runtime.exp.ApplicationException;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.ext.tag.TagImpl;
import railo.runtime.op.Caster;
/**
* Serializes and de-serializes CFML data structures to the XML-based WDDX format.
* Generates JavaScript statements to instantiate JavaScript objects equivalent to the contents of a
* WDDX packet or some CFML data structures.
*
*
*
**/
public final class Wddx extends TagImpl {
/** The value to be processed. */
private Object input;
/** Specifies the action taken by the cfwddx tag. */
private String action;
/** The name of the variable to hold the output of the operation. This attribute is required for
** action = 'WDDX2CFML'. For all other actions, if this attribute is not provided, the result of the
** WDDX processing is outputted in the HTML stream. */
private String output;
private boolean validate;
/** The name of the top-level JavaScript object created by the deserialization process. The object
** created is an instance of the WddxRecordset object, explained in WddxRecordset Object. */
private String toplevelvariable;
/** Indicates whether to output time-zone information when serializing CFML to WDDX. If time-zone
** information is taken into account, the hour-minute offset, as represented in the ISO8601 format, is
** calculated in the date-time output. If time-zone information is not taken into account, the local
** time is output. The default is Yes. */
private boolean usetimezoneinfo;
private boolean xmlConform;
@Override
public void release() {
super.release();
input=null;
action=null;
output=null;
validate=false;
toplevelvariable=null;
usetimezoneinfo=false;
xmlConform=false;
}
/** set the value input
* The value to be processed.
* @param input value to set
**/
public void setInput(Object input) {
this.input=input;
}
/** set the value action
* Specifies the action taken by the cfwddx tag.
* @param action value to set
**/
public void setAction(String action) {
this.action=action.toLowerCase();
}
/** set the value output
* The name of the variable to hold the output of the operation. This attribute is required for
* action = 'WDDX2CFML'. For all other actions, if this attribute is not provided, the result of the
* WDDX processing is outputted in the HTML stream.
* @param output value to set
**/
public void setOutput(String output) {
this.output=output;
}
/** set the value validate
*
* @param validate value to set
**/
public void setValidate(boolean validate) {
this.validate=validate;
}
/** set the value toplevelvariable
* The name of the top-level JavaScript object created by the deserialization process. The object
* created is an instance of the WddxRecordset object, explained in WddxRecordset Object.
* @param toplevelvariable value to set
**/
public void setToplevelvariable(String toplevelvariable) {
this.toplevelvariable=toplevelvariable;
}
/** set the value usetimezoneinfo
* Indicates whether to output time-zone information when serializing CFML to WDDX. If time-zone
* information is taken into account, the hour-minute offset, as represented in the ISO8601 format, is
* calculated in the date-time output. If time-zone information is not taken into account, the local
* time is output. The default is Yes.
* @param usetimezoneinfo value to set
**/
public void setUsetimezoneinfo(boolean usetimezoneinfo) {
this.usetimezoneinfo=usetimezoneinfo;
}
/**
* sets if generated code is xml or wddx conform
* @param xmlConform
*/
public void setXmlconform(boolean xmlConform) {
this.xmlConform=xmlConform;
}
@Override
public int doStartTag() throws PageException {
try {
doIt();
} catch (Exception e) {
throw Caster.toPageException(e);
}
return SKIP_BODY;
}
private void doIt() throws ExpressionException, PageException, ConverterException, IOException, FactoryConfigurationError {
// cfml > wddx
if(action.equals("cfml2wddx")) {
if(output!=null) pageContext.setVariable(output,cfml2wddx(input));
else pageContext.forceWrite(cfml2wddx(input));
}
// wddx > cfml
else if(action.equals("wddx2cfml")) {
if(output==null) throw new ApplicationException("at tag cfwddx the attribute output is required if you set action==wddx2cfml");
pageContext.setVariable(output,wddx2cfml(Caster.toString(input)));
}
// cfml > js
else if(action.equals("cfml2js")) {
if(output!=null) pageContext.setVariable(output,cfml2js(input));
else pageContext.forceWrite(cfml2js(input));
}
// wddx > js
else if(action.equals("wddx2js")) {
if(output!=null) pageContext.setVariable(output,wddx2js(Caster.toString(input)));
else pageContext.forceWrite(wddx2js(Caster.toString(input)));
}
else throw new ExpressionException("invalid attribute action for tag cfwddx, attributes are [cfml2wddx, wddx2cfml,cfml2js, wddx2js].");
}
private String cfml2wddx(Object input) throws ConverterException {
WDDXConverter converter =new WDDXConverter(pageContext.getTimeZone(),xmlConform,true);
if(!usetimezoneinfo)converter.setTimeZone(null);
return converter.serialize(input);
}
private Object wddx2cfml(String input) throws ConverterException, IOException, FactoryConfigurationError {
WDDXConverter converter =new WDDXConverter(pageContext.getTimeZone(),xmlConform,true);
converter.setTimeZone(pageContext.getTimeZone());
return converter.deserialize(input,validate);
}
private String cfml2js(Object input) throws ConverterException {
if(toplevelvariable==null)missingTopLevelVariable();
JSConverter converter =new JSConverter();
return converter.serialize(input,toplevelvariable);
}
private String wddx2js(String input) throws ConverterException, IOException, FactoryConfigurationError {
if(toplevelvariable==null)missingTopLevelVariable();
JSConverter converter =new JSConverter();
return converter.serialize(wddx2cfml(input),toplevelvariable);
}
private ApplicationException missingTopLevelVariable() {
return new ApplicationException("at tag cfwddx the attribute topLevelVariable is required if you set action equal wddx2js or cfml2js");
}
@Override
public int doEndTag() {
return EVAL_PAGE;
}
} | {
"pile_set_name": "Github"
} |
// 104 easy 二叉树的最大深度
// 给定一个二叉树,找出其最大深度。
// 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
//
// 说明: 叶子节点是指没有子节点的节点。
//
// 示例:
// 给定二叉树 [3,9,20,null,null,15,7],
//
// 3
// / \
// 9 20
// / \
// 15 7
// 返回它的最大深度 3 。
//
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
if (root === null){
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};
| {
"pile_set_name": "Github"
} |
object dmodURI: TdmodURI
OldCreateOrder = False
Left = 282
Top = 184
Height = 167
Width = 213
object URI: TBXBubble
Category = 'Misc'
Description = 'URI'
OnTest = URITest
Left = 32
Top = 24
end
end
| {
"pile_set_name": "Github"
} |
/*
html5doctor.com Reset Stylesheet
v1.6.1
Last Updated: 2010-09-17
Author: Richard Clark - http://richclarkdesign.com
Twitter: @rich_clark
*/
html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
margin:0;
padding:0;
border:0;
outline:0;
font-size:100%;
vertical-align:baseline;
background:transparent;
}
body {
line-height:1;
}
article,aside,details,figcaption,figure,
footer,header,hgroup,menu,nav,section {
display:block;
}
nav ul {
list-style:none;
}
blockquote, q {
quotes:none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content:'';
content:none;
}
a {
margin:0;
padding:0;
font-size:100%;
vertical-align:baseline;
background:transparent;
}
/* change colours to suit your needs */
ins {
background-color:#ff9;
color:#000;
text-decoration:none;
}
/* change colours to suit your needs */
mark {
background-color:#ff9;
color:#000;
font-style:italic;
font-weight:bold;
}
del {
text-decoration: line-through;
}
abbr[title], dfn[title] {
border-bottom:1px dotted;
cursor:help;
}
table {
border-collapse:collapse;
border-spacing:0;
}
/* change border colour to suit your needs */
hr {
display:block;
height:1px;
border:0;
border-top:1px solid #cccccc;
margin:1em 0;
padding:0;
}
input, select {
vertical-align:middle;
} | {
"pile_set_name": "Github"
} |
# redux-persist-transform-encrypt
[](https://www.npmjs.com/package/redux-persist-transform-encrypt)
[](https://travis-ci.org/maxdeviant/redux-persist-transform-encrypt)
Encrypt your Redux store.
## Usage
### Synchronous
```js
import { persistReducer } from 'redux-persist'
import createEncryptor from 'redux-persist-transform-encrypt'
const encryptor = createEncryptor({
secretKey: 'my-super-secret-key',
onError: function(error) {
// Handle the error.
}
})
const reducer = persistReducer(
{
transforms: [encryptor]
},
baseReducer
)
```
### Asynchronous
**Note:** Asynchronous support is still a work in progress.
```js
import { persistReducer } from 'redux-persist'
import createAsyncEncryptor from 'redux-persist-transform-encrypt/async'
const asyncEncryptor = createAsyncEncryptor({
secretKey: 'my-super-secret-key'
})
const reducer = persistReducer(
{
transforms: [asyncEncryptor]
},
baseReducer
)
```
### Custom Error Handling
The `onError` property given to the `createEncryptor` options is an optional
function that receives an `Error` object as its only parameter. This allows
custom error handling from the parent application.
| {
"pile_set_name": "Github"
} |
function Get-InstallTasks([HashTable]$pp) {
$parameters = @{
"DesktopIcon" = @{ Task = "!desktopicon"; Output = "Enabling Desktop Icon" }
"QuickLaunchIcon" = @{ Task = "!quicklaunchicon"; Output = "Enabling Quick Launch Icon" }
"DisableFileAssoc" = @{ Task = "fileassoc"; Output = "Disabling File Association" }
}
$tasks = @()
foreach ($param in $parameters.Keys) {
if ($pp[$param]) {
if ($parameters[$param].Task.StartsWith('!')) {
$parameters[$param].Task = $parameters[$param].Task.TrimStart('!')
} else {
$parameters[$param].Task = '!' + $parameters[$param].Task
}
Write-Host $parameters[$param].Output
}
$tasks += @($parameters[$param].Task)
}
' /TASKS="{0}"' -f ($tasks -join ',')
}
| {
"pile_set_name": "Github"
} |
osgi(1) asadmin Utility Subcommands osgi(1)
NAME
osgi - delegates the command line to the Apache Felix Gogo remote shell
for the execution of OSGi shell commands
SYNOPSIS
osgi [--help]
[--session session]
[--session-id session-id]
[--instance instance]
[command_line]
DESCRIPTION
The osgi subcommand delegates the command line to the Apache Felix Gogo
remote shell for the execution of OSGi shell commands. Commands are
executed by the remote shell and results are returned by the asadmin
utility. The remote shell is provided with GlassFish Server and used to
administer and inspect the OSGi runtime.
Multiple command-line sessions can be created. Use the --session and
--session-id options to run commands in a specific command-line
session. If no session is specified, a new session is created to run
commands and closed when execution completes.
A related subcommand is the osgi-shell subcommand, which enables you to
run multiple commands from a file or run commands interactively. For
more information about the osgi-shell subcommand, see the osgi-shell(1)
help page.
This subcommand is supported in remote mode only.
OPTIONS
--help, -?
Displays the help text for the osgi subcommand.
--session
Performs command-line session operations. Valid values are:
new
Creates a new session and returns a session ID.
stop
Stops the session with the specified session ID.
list
Lists all active sessions.
execute
Runs a command in the session with the specified session ID.
--session-id
Specifies the session ID for command-line session operations.
--instance
Specifies the server instance to which the command is being
delegated.
The default is the domain administration server (DAS). The DAS must
be running to run a command on another instance.
OPERANDS
command_line
The complete command-line syntax as provided for commands in the
Apache Felix Gogo remote shell.
EXAMPLES
Example 1, Listing Apache Felix Gogo Remote Shell Commands
This example lists the Apache Felix Gogo remote shell commands that
can be used with the osgi subcommand.
Some lines of output are omitted from this example for readability.
asadmin> osgi help
felix:bundlelevel
felix:cd
felix:frameworklevel
felix:headers
felix:help
felix:inspect
felix:install
felix:lb
felix:log
felix:ls
felix:refresh
felix:resolve
...
gogo:cat
gogo:each
gogo:echo
gogo:format
gogo:getopt
gogo:gosh
gogo:grep
...
Command osgi executed successfully.
Example 2, Running a Remote Shell Command
This example runs the Felix Remote Shell Command lb without any
arguments to list all installed OSGi bundles.
Some lines of output are omitted from this example for readability.
asadmin> osgi lb
START LEVEL 2
ID|State |Level|Name
0|Active | 0|System Bundle
1|Active | 1|Metro Web Services API OSGi Bundle
2|Active | 1|javax.annotation API
3|Active | 1|jaxb-api
...
Command osgi executed successfully.
Example 3, Running Commands That Create and Target a Specific
Command-Line Session
This example runs commands that create and target a specific
command-line session.
Some lines of output are omitted from this example for readability.
asadmin> osgi --session new
9537e570-0def-4f2e-9c19-bc8f51a8082f
...
asadmin> osgi --session list
9537e570-0def-4f2e-9c19-bc8f51a8082f
...
asadmin> osgi --session execute --session-id 9537e570-0def-4f2e-9c19-bc8f51a8082f lb
START LEVEL 2
ID|State |Level|Name
0|Active | 0|System Bundle
1|Active | 1|Metro Web Services API OSGi Bundle
2|Active | 1|javax.annotation API
3|Active | 1|jaxb-api
...
asadmin> osgi --session stop --session-id 9537e570-0def-4f2e-9c19-bc8f51a8082f
Command osgi executed successfully.
EXIT STATUS
0
subcommand executed successfully
1
error in executing the subcommand
SEE ALSO
osgi-shell(1)
asadmin(1M)
Java EE 8 06 Feb 2013 osgi(1)
| {
"pile_set_name": "Github"
} |
var browserify = require('../');
var vm = require('vm');
var test = require('tap').test;
test('byte order marker', function (t) {
t.plan(2);
var b = browserify(__dirname + '/bom/hello.js');
b.bundle(function (err, src) {
if (err) t.fail(err);
var c = {
console: { log: function (msg) {
t.equal(msg, 'hello');
} }
};
vm.runInNewContext(src, c);
t.notOk(/\ufeff/.test(src.toString('utf8')));
});
});
| {
"pile_set_name": "Github"
} |
// XXX this can probably be replaced with gentle-fs.mkdir everywhere it's used
const chownr = require('chownr')
const inflight = require('inflight')
const log = require('npmlog')
const mkdirp = require('mkdirp')
const inferOwner = require('infer-owner')
// retain ownership of the parent dir
// this matches behavior in cacache to infer the cache ownership
// based on the ownership of the cache folder or it is parent.
module.exports = function correctMkdir (path, cb) {
cb = inflight('correctMkdir: ' + path, cb)
if (!cb) {
return log.verbose('correctMkdir', path, 'correctMkdir already in flight; waiting')
} else {
log.verbose('correctMkdir', path, 'correctMkdir not in flight; initializing')
}
if (!process.getuid) {
log.verbose('makeCacheDir', 'UID & GID are irrelevant on', process.platform)
return mkdirp(path, (er, made) => cb(er, { uid: 0, gid: 0 }))
}
inferOwner(path).then(owner => {
mkdirp(path, (er, made) => {
if (er) {
log.error('correctMkdir', 'failed to make directory %s', path)
return cb(er)
}
chownr(made || path, owner.uid, owner.gid, (er) => cb(er, owner))
})
}, er => {
log.error('correctMkdir', 'failed to infer path ownership %s', path)
return cb(er)
})
}
| {
"pile_set_name": "Github"
} |
<!--
Description: entry title relative to document URI
Expect: bozo and entries[0]['title'] == u'<div><a href="http://127.0.0.1:8097/relative/uri">click here</a></div>'
-->
<feed version="0.3" xmlns="http://purl.org/atom/ns#">
<entry>
<title type="text/html" mode="base64">
PGRpdj48YSBocmVmPSIvcmVsYXRpdmUvdXJpIj5jbGljayBoZXJlPC9hPjwvZGl2Pg==
</title>
</entry>
</feed | {
"pile_set_name": "Github"
} |
Scope: []
Kind: Module
FrameDescriptor: Empty
CellVars: Empty
FreeVars: Empty
Scope: gen
Kind: Generator
FrameDescriptor: [x, <return_val>]
CellVars: Empty
FreeVars: Empty
| {
"pile_set_name": "Github"
} |
//1152x864 text scheme file
// Pie menu for marines
SchemeName = "PieMenuScheme"
FontName = "Arial"
FontSize = 16
FgColor = "255 170 0 255"
BgColor = "0 0 0 141"
FgColorArmed = "255 255 255 255"
BgColorArmed = "255 170 0 67"
// Minimap, radar
SchemeName = "HierarchyScheme"
FontName = "Helvetica"
FontSize = 10
FgColor = "255 170 0 255"
BgColor = "40 40 40 128"
FgColorArmed = "255 255 255 255"
BgColorArmed = "255 170 0 0"
// Particle editing
SchemeName = "PSEScheme"
FontName = "Arial"
FontSize = 34
FgColor = "240 179 17 255"
BgColor = "50 50 50 141"
// Overwatch
SchemeName = "OverwatchScheme"
FontName = "Arial"
FontSize = 34
FgColor = "240 179 17 255"
BgColor = "50 50 50 141"
// Action buttons in lower right
SchemeName = "ActionButtonScheme"
FontName = "Arial"
FontSize = 21
FgColor = "172 244 255 255"
BgColor = "0 0 0 0"
// Upper left resources, reinforcements
SchemeName = "CommanderStatusScheme"
FontName = "Arial"
FontSize = 21
FgColor = "172 244 255 255"
BgColor = "0 0 0 0"
// Upper left resources, reinforcements
SchemeName = "MarineStatusScheme"
FontName = "Arial"
FontSize = 21
FgColor = "0 153 255 255"
BgColor = "0 0 0 0"
// Scoreboard title
SchemeName = "Scoreboard Title Text"
FontName = "Arial"
FontSize = 21
FgColor = "243 252 10 255"
BgColor = "0 0 0 0"
// Scoreboard text (ignores color, uses hard-coded team color instead)
SchemeName = "Scoreboard Small Text"
FontName = "Arial"
FontSize = 16
FgColor = "255 170 0 255"
BgColor = "0 0 0 141"
FgColorArmed = "255 255 255 255"
BgColorArmed = "255 170 0 67"
// Tiny text (used for number of players)
SchemeName = "Scoreboard Tiny Text"
FontName = "Arial"
FontSize = 10
FgColor = "255 170 0 255"
BgColor = "0 0 0 141"
FgColorArmed = "255 255 255 255"
BgColorArmed = "255 170 0 67"
// Research area, pop-up text for action buttons
//SchemeName = "MiddleHelpScheme"
//FontName = "Helvetica"
//FontSize = 14
//FgColor = "172 244 255 255"
//BgColor = "0 0 0 0"
// Make the logout button obvious
//SchemeName = "LogoutButtonScheme"
//FontName = "Arial"
//FontSize = 34
//FgColor = "255 255 255 255"
//BgColor = "0 0 0 0"
| {
"pile_set_name": "Github"
} |
module.exports = (api) => {
api.describe({
id: 'mie_id',
key: 'mie',
enableBy: api.EnableBy.config,
});
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/schemas/model/DescribeSchemaResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Schemas::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DescribeSchemaResult::DescribeSchemaResult()
{
}
DescribeSchemaResult::DescribeSchemaResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
DescribeSchemaResult& DescribeSchemaResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("Content"))
{
m_content = jsonValue.GetString("Content");
}
if(jsonValue.ValueExists("Description"))
{
m_description = jsonValue.GetString("Description");
}
if(jsonValue.ValueExists("LastModified"))
{
m_lastModified = jsonValue.GetString("LastModified");
}
if(jsonValue.ValueExists("SchemaArn"))
{
m_schemaArn = jsonValue.GetString("SchemaArn");
}
if(jsonValue.ValueExists("SchemaName"))
{
m_schemaName = jsonValue.GetString("SchemaName");
}
if(jsonValue.ValueExists("SchemaVersion"))
{
m_schemaVersion = jsonValue.GetString("SchemaVersion");
}
if(jsonValue.ValueExists("tags"))
{
Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects();
for(auto& tagsItem : tagsJsonMap)
{
m_tags[tagsItem.first] = tagsItem.second.AsString();
}
}
if(jsonValue.ValueExists("Type"))
{
m_type = jsonValue.GetString("Type");
}
if(jsonValue.ValueExists("VersionCreatedDate"))
{
m_versionCreatedDate = jsonValue.GetString("VersionCreatedDate");
}
return *this;
}
| {
"pile_set_name": "Github"
} |
To enable further customization of OpenNMT, it is possible to easily modify the default behaviour of some modules, to add some options or even to disable some others. This is done with `hooks`.
Hooks are defined by a lua file (let us call it `myhook.lua`) containing the extension code and that is dynamically loaded by passing the option `-hook_file myhook` in the different tools.
These hook files should return a table defining some functions corresponding to *hook entry points* in the code. These functions are replacing or introducing some code in the standard flow. These functions can also decide based on the actual request, to not change the standard flow, in which case, they have to return a `nil` value.
## Example
For instance, let us consider the following hook file:
```
local unicode = require('tools.utils.unicode')
local function mytokenization(_, line)
local tokens = {}
for _, c, _ in unicode.utf8_iter(line) do
table.insert(tokens, c)
end
return tokens
end
return {
tokenize = mytokenization
}
```
save it in `myhook.lua` and let us try a standard tokenization:
```
$ echo "c'est épatant" | th tools/tokenize.lua -hook_file myhook
c ' e s t _ é p a t a n t
Tokenization completed in 0.001 seconds - 1 sentences
```
the tokenization function has taken over the normal tokenization.
Let us do that more cleanly, first - document this as a new option, we just need to declare the new option in the hook file:
```
local myopt =
{
{
'-mode', 'conservative',
[[Define how aggressive should the tokenization be. `aggressive` only keeps sequences
of letters/numbers, `conservative` allows a mix of alphanumeric as in: "2,000", "E65",
"soft-landing", etc. `space` is doing space tokenization. `char` is doing character tokenization]],
{
enum = {'space', 'conservative', 'aggressive', 'char'}
}
}
}
```
and define a hook to the `declareOpts` function:
```
local function declareOptsFn(cmd)
cmd:setCmdLineOptions(myopt, 'Tokenizer')
end
return {
tokenize = mytokenization,
declareOpts = declareOptsFn
}
```
checking the help now shows the updated option:
```
th tools/tokenize.lua -hook_file myhook -h:
[...]
-mode <string> (accepted: space, conservative, aggressive, char; default: conservative)
Define how aggressive should the tokenization be. `aggressive`
only keeps sequences of letters/numbers, `conservative` allows
a mix of alphanumeric as in: "2,000", "E65", "soft-landing",
etc. `space` is doing space tokenization. `char` is doing character
tokenization
[...]
```
we just need to redefine only this new mode in the tokenization function, for that, we now check the variable `opt`:
```
local function mytokenization(opt, line)
-- fancy tokenization, it has to return a table of tokens (possibly with features)
if opt.mode == "char" then
local tokens = {}
for v, c, _ in unicode.utf8_iter(line) do
if unicode.isSeparator(v) then
table.insert(tokens, '_')
else
table.insert(tokens, c)
end
end
return tokens
end
end
```
which gives the regular behavior by default:
```
$ echo "c'est épatant" | th tools/tokenize.lua -hook_file myhook
gives the expected c ' est épatant
```
and the updated behavior with the hook and the option set:
```
$ echo "c'est épatant" | th tools/tokenize.lua -hook_file myhook -mode char
gives the new: c ' e s t _ é p a t a n t
```
## Sample Hooks
Several hooks are available in `hooks` directory - see description [here](http://github.com/OpenNMT/OpenNMT/hooks/README.md).
## Testing hooks
You can run unit tests with hook by adding `-hook_file myhook` as a first parameter of test.lua:
```
th test/test.lua -hook_file myhook
```
It is a good practice to run the complete set of tests with your hooks to check for possible side-effects.
To add specific tests for your hook, you have to define a hook on `hookName` returning the name of the hook, and use this value to add dynamically additional tests. Look at `test/auto/TokenizerTest.lua` for an example:
```
function tokenizerTest.hooks()
local hookName = _G.hookManager:call("hookName")
if hookName == "chartok" then
local opt = cmd:parse({'-mode', 'char'})
testTok(opt, "49th meeting Social and human rights questions [14 (g)]",
"4 9 t h ▁ m e e t i n g ▁ S o c i a l ▁ a n d ▁ h u m a n ▁ r i g h t s ▁ q u e s t i o n s ▁ [ 1 4 ▁ ( g ) ]")
elseif hookName == "sentencepiece" then
local opt = cmd:parse({'-mode','none', '-sentencepiece' ,'hooks/lua-sentencepiece/test/sample.model'})
testTok(opt, "une impulsion Berry-Siniora pourraient changer quoi",
"▁un e ▁imp ul s ion ▁B erry - S i nior a ▁po ur ra i ent ▁change r ▁ quoi")
end
end
```
## Predefined hook entry point
Special entry points:
* `declareOpts`: this hook is in charge of modifying the actual option for the current script - for instance, it is possible to add, remove or modify some options. A hook does not necessarily require new options - you can defined a hook that operates by default to replace internal features by a more efficient implementation. To avoid confusion, make sure in these cases that all the options are supported and the result is the same.
* `hookName`: special hook, allowing the code to know about the name of the current hook. `function hookName() return NAME end` - can be used in automatic tests
Normal entry points:
* `tokenize`: replace or extend internal tokenization - prototype is: `function mytokenization(opt, line, bpe)` that has to return a table of tokens (and possible features). See [hooks/chartokenization.lua](http://github.com/OpenNMT/OpenNMT/hooks/chartokenization.lua) for an example.
* `detokenize`: replace or extend internal detokenization - prototype is: `function mytokenization(line, opt)` that has to return a detokenized string. See [hooks/chartokenization.lua](http://github.com/OpenNMT/OpenNMT/hooks/chartokenization.lua) for an example.
* `post_tokenize`: performs a transformation of the tokens list just after tokenization. Typically interesting to add features. See [[hooks/chartokenization.lua](http://github.com/OpenNMT/OpenNMT/hooks/treetagger-tag.lua) for an example.
* `mpreprocess`: on the fly normalization on source and target strings during preprocessing. `function mpreprocessFn(opt, line)` that returns normalized line. Note that the options associated to the source or target options are dynamically changed for the call.
* `bpreprocess`: performs a bilingual normalization of the source and target sentences during preprocessing. `function bpreprocessFn(opt, sentences)`. `sentences` is a `{srcs,tgts}` where `srcs` and `tgts` are respectively list of source and target sentences. Sentences are sent by batch of 10000.
| {
"pile_set_name": "Github"
} |
version https://git-lfs.github.com/spec/v1
oid sha256:828900a8005ad2da27ee2fd150c1f494ff0e8e1cecc4e0eabf271f4dc1f1261b
size 3427
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2009 the original author or authors.
*
* 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 org.gradle.api.internal.tasks.compile;
import org.apache.tools.ant.taskdefs.optional.depend.Depend;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.BuildException;
public class AntDepend extends Depend {
private Path src;
public Path createSrc() {
if (src == null) {
src = new Path(getProject());
}
return src.createPath();
}
@Override
public void execute() throws BuildException {
setSrcdir(src);
super.execute();
}
}
| {
"pile_set_name": "Github"
} |
package com.terrafolio.gradle.plugins.jenkins.tasks
import com.terrafolio.gradle.plugins.jenkins.dsl.JenkinsConfigurable
import com.terrafolio.gradle.plugins.jenkins.service.BuildDirService
class DumpJenkinsItemsTask extends AbstractDumpJenkinsItemsTask {
def prettyPrint = true
def prettyPrintPreserveWhitespace = false;
public DumpJenkinsItemsTask() {
super();
needsCredentials = false
description = "Dumps item configurations from the local model to files."
}
@Override
public void writeXmlConfigurations(JenkinsConfigurable item, BuildDirService buildDirService, String itemType) {
eachServer(item) { server, service ->
def file = new File(buildDirService.makeAndGetDir("${server.name}/${itemType}"), "${item.name}.xml")
if (prettyPrint) {
file.withWriter { fileWriter ->
def node = new XmlParser().parseText(item.getServerSpecificXml(server));
def nodePrinter = new XmlNodePrinter(new PrintWriter(fileWriter))
nodePrinter.preserveWhitespace = prettyPrintPreserveWhitespace;
nodePrinter.print(node)
}
} else {
def xml = item.getServerSpecificXml(server)
file.write(xml)
}
}
}
}
| {
"pile_set_name": "Github"
} |
/* http://jmblog.github.com/color-themes-for-google-code-highlightjs */
.tomorrow-comment, pre .comment, pre .title {
color: #8e908c;
}
.tomorrow-red, pre .variable, pre .attribute, pre .tag, pre .regexp, pre .ruby .constant, pre .xml .tag .title, pre .xml .pi, pre .xml .doctype, pre .html .doctype, pre .css .id, pre .css .class, pre .css .pseudo {
color: #c82829;
}
.tomorrow-orange, pre .number, pre .preprocessor, pre .built_in, pre .literal, pre .params, pre .constant {
color: #f5871f;
}
.tomorrow-yellow, pre .class, pre .ruby .class .title, pre .css .rules .attribute {
color: #eab700;
}
.tomorrow-green, pre .string, pre .value, pre .inheritance, pre .header, pre .ruby .symbol, pre .xml .cdata {
color: #718c00;
}
.tomorrow-aqua, pre .css .hexcolor {
color: #3e999f;
}
.tomorrow-blue, pre .function, pre .python .decorator, pre .python .title, pre .ruby .function .title, pre .ruby .title .keyword, pre .perl .sub, pre .javascript .title, pre .coffeescript .title {
color: #4271ae;
}
.tomorrow-purple, pre .keyword, pre .javascript .function {
color: #8959a8;
}
pre code {
display: block;
background: white;
color: #4d4d4c;
padding: 0.5em;
}
pre .coffeescript .javascript,
pre .javascript .xml,
pre .tex .formula,
pre .xml .javascript,
pre .xml .vbscript,
pre .xml .css,
pre .xml .cdata {
opacity: 0.5;
}
| {
"pile_set_name": "Github"
} |
#!/sbin/openrc-run
# Copyright 1999-2011 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
PIDFILE="/var/run/bugzilla/${SVCNAME}.pid"
JOBQUEUE_USER=${JOBQUEUE_USER:-root}
JOBQUEUE_GROUP=${JOBQUEUE_GROUP:-root}
checkconfig() {
[[ -z "${JOBQUEUE_USER}" || -z "$(getent passwd ${JOBQUEUE_USER})" ]] && { eerror "JOBQUEUE_USER not set or doesn't exist"; return 1; }
[[ -z "${JOBQUEUE_GROUP}" || -z "$(getent group ${JOBQUEUE_GROUP})" ]] && { eerror "JOBQUEUE_GROUP not set or doesn't exist"; return 1; }
[[ -z "${JOBQUEUE_PATH}" && ! -x "${JOBQUEUE_PATH}" ]] && { eerror "JOBQUEUE_PATH not set or not executable"; return 1; }
return 0
}
start() {
ebegin "Starting ${SVCNAME}"
checkconfig || return 1
piddir="${PIDFILE%/*}"
if [ ! -d "${piddir}" ]; then
checkpath -q -d -o $JOBQUEUE_USER:$JOBQUEUE_GROUP -m 0770 "${piddir}" || {
eend 1
return 1
}
fi
start-stop-daemon --start --pidfile $PIDFILE --user $JOBQUEUE_USER --group $JOBQUEUE_GROUP \
--exec $JOBQUEUE_PATH -- -p $PIDFILE -n $SVCNAME start 1>/dev/null
eend $?
}
stop() {
ebegin "Stopping ${SVCNAME}"
checkconfig || return 1
start-stop-daemon --pidfile $PIDFILE --stop --exec $JOBQUEUE_PATH -- -p $PIDFILE -n $SVCNAME stop
eend $?
}
| {
"pile_set_name": "Github"
} |
{
"name": "libdvdread",
"full_name": "libdvdread",
"oldname": null,
"aliases": [
],
"versioned_formulae": [
],
"desc": "C library for reading DVD-video images",
"license": "GPL-2.0",
"homepage": "https://www.videolan.org/developers/libdvdnav.html",
"versions": {
"stable": "6.1.1",
"head": "HEAD",
"bottle": true
},
"urls": {
"stable": {
"url": "https://download.videolan.org/pub/videolan/libdvdread/6.1.1/libdvdread-6.1.1.tar.bz2",
"tag": null,
"revision": null
}
},
"revision": 0,
"version_scheme": 0,
"bottle": {
"stable": {
"rebuild": 0,
"cellar": ":any",
"prefix": "/home/linuxbrew/.linuxbrew",
"root_url": "https://linuxbrew.bintray.com/bottles",
"files": {
"catalina": {
"url": "https://linuxbrew.bintray.com/bottles/libdvdread-6.1.1.catalina.bottle.tar.gz",
"sha256": "83bebe58015f6f34973afa003934f183e7ac9202f5e579cfd12536f9ceac1719"
},
"mojave": {
"url": "https://linuxbrew.bintray.com/bottles/libdvdread-6.1.1.mojave.bottle.tar.gz",
"sha256": "7405838fee2b93209c2bd0834db89c2a2334a94f7d368feb87599da1b08062f6"
},
"high_sierra": {
"url": "https://linuxbrew.bintray.com/bottles/libdvdread-6.1.1.high_sierra.bottle.tar.gz",
"sha256": "c881a8c1c872d922f45bf8a692b9d79b5f6ade1a2f4a48d470d05491bc017436"
},
"x86_64_linux": {
"url": "https://linuxbrew.bintray.com/bottles/libdvdread-6.1.1.x86_64_linux.bottle.tar.gz",
"sha256": "0c5f9b444bdf360b956450b1f5cfa5e1a700abfb084fc7a472846774495c1fec"
}
}
}
},
"keg_only": false,
"bottle_disabled": false,
"options": [
],
"build_dependencies": [
],
"dependencies": [
"libdvdcss"
],
"recommended_dependencies": [
],
"optional_dependencies": [
],
"uses_from_macos": [
],
"requirements": [
],
"conflicts_with": [
],
"caveats": null,
"installed": [
],
"linked_keg": null,
"pinned": false,
"outdated": false,
"deprecated": false,
"disabled": false
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright (C) 2007 Rob Buis <[email protected]>
* Copyright (C) 2007 Nikolas Zimmermann <[email protected]>
* Copyright (C) 2007 Eric Seidel <[email protected]>
* Copyright (C) 2009 Google, Inc. All rights reserved.
* Copyright (C) Research In Motion Limited 2010. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_LAYOUT_SUPPORT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_LAYOUT_SUPPORT_H_
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/style/svg_computed_style_defs.h"
#include "third_party/blink/renderer/platform/graphics/dash_array.h"
#include "third_party/blink/renderer/platform/transforms/affine_transform.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
namespace blink {
class AffineTransform;
class FloatPoint;
class FloatRect;
class LayoutGeometryMap;
class LayoutBoxModelObject;
class LayoutObject;
class ComputedStyle;
class SVGLengthContext;
class StrokeData;
class TransformState;
class CORE_EXPORT SVGLayoutSupport {
STATIC_ONLY(SVGLayoutSupport);
public:
// Shares child layouting code between
// LayoutSVGRoot/LayoutSVG(Hidden)Container
static void LayoutChildren(LayoutObject*,
bool force_layout,
bool screen_scaling_factor_changed,
bool layout_size_changed);
// Layout resources used by this node.
static void LayoutResourcesIfNeeded(const LayoutObject&);
// Helper function determining whether overflow is hidden.
static bool IsOverflowHidden(const LayoutObject&);
static bool IsOverflowHidden(const ComputedStyle&);
// Adjusts the visualRect in combination with filter, clipper and masker
// in local coordinates.
static void AdjustVisualRectWithResources(
const LayoutObject&,
const FloatRect& object_bounding_box,
FloatRect&);
// Determine if the LayoutObject references a filter resource object.
static bool HasFilterResource(const LayoutObject&);
// Determine whether the passed location intersects a clip path referenced by
// the passed LayoutObject.
// |reference_box| is used to resolve 'objectBoundingBox' units/percentages,
// and can differ from the reference box of the passed LayoutObject.
static bool IntersectsClipPath(const LayoutObject&,
const FloatRect& reference_box,
const HitTestLocation&);
// Shared child hit-testing code between LayoutSVGRoot/LayoutSVGContainer.
static bool HitTestChildren(LayoutObject* last_child,
HitTestResult&,
const HitTestLocation&,
const PhysicalOffset& accumulated_offset,
HitTestAction);
static void ComputeContainerBoundingBoxes(const LayoutObject* container,
FloatRect& object_bounding_box,
bool& object_bounding_box_valid,
FloatRect& stroke_bounding_box,
FloatRect& local_visual_rect);
// Important functions used by nearly all SVG layoutObjects centralizing
// coordinate transformations / visual rect calculations
static FloatRect LocalVisualRect(const LayoutObject&);
static PhysicalRect VisualRectInAncestorSpace(
const LayoutObject&,
const LayoutBoxModelObject& ancestor,
VisualRectFlags = kDefaultVisualRectFlags);
static PhysicalRect TransformVisualRect(const LayoutObject&,
const AffineTransform&,
const FloatRect&);
static bool MapToVisualRectInAncestorSpace(
const LayoutObject&,
const LayoutBoxModelObject* ancestor,
const FloatRect& local_visual_rect,
PhysicalRect& result_rect,
VisualRectFlags = kDefaultVisualRectFlags);
static void MapLocalToAncestor(const LayoutObject*,
const LayoutBoxModelObject* ancestor,
TransformState&,
MapCoordinatesFlags);
static void MapAncestorToLocal(const LayoutObject&,
const LayoutBoxModelObject* ancestor,
TransformState&,
MapCoordinatesFlags);
static const LayoutObject* PushMappingToContainer(
const LayoutObject*,
const LayoutBoxModelObject* ancestor_to_stop_at,
LayoutGeometryMap&);
// Shared between SVG layoutObjects and resources.
static void ApplyStrokeStyleToStrokeData(StrokeData&,
const ComputedStyle&,
const LayoutObject&,
float dash_scale_factor);
static DashArray ResolveSVGDashArray(const SVGDashArray&,
const ComputedStyle&,
const SVGLengthContext&);
// Determines if any ancestor has adjusted the scale factor.
static bool ScreenScaleFactorChanged(const LayoutObject*);
// Determines if any ancestor's layout size has changed.
static bool LayoutSizeOfNearestViewportChanged(const LayoutObject*);
// Helper method for determining if a LayoutObject marked as text (isText()==
// true) can/will be laid out as part of a <text>.
static bool IsLayoutableTextNode(const LayoutObject*);
// Determines whether a svg node should isolate or not based on ComputedStyle.
static bool WillIsolateBlendingDescendantsForStyle(const ComputedStyle&);
static bool WillIsolateBlendingDescendantsForObject(const LayoutObject*);
template <typename LayoutObjectType>
static bool ComputeHasNonIsolatedBlendingDescendants(const LayoutObjectType*);
static bool IsIsolationRequired(const LayoutObject*);
static AffineTransform DeprecatedCalculateTransformToLayer(
const LayoutObject*);
static float CalculateScreenFontSizeScalingFactor(const LayoutObject*);
static LayoutObject* FindClosestLayoutSVGText(const LayoutObject*,
const FloatPoint&);
private:
static void UpdateObjectBoundingBox(FloatRect& object_bounding_box,
bool& object_bounding_box_valid,
LayoutObject* other,
FloatRect other_bounding_box);
};
class SubtreeContentTransformScope {
STACK_ALLOCATED();
public:
SubtreeContentTransformScope(const AffineTransform&);
~SubtreeContentTransformScope();
static AffineTransform CurrentContentTransformation() {
return AffineTransform(current_content_transformation_);
}
private:
static AffineTransform::Transform current_content_transformation_;
AffineTransform saved_content_transformation_;
};
template <typename LayoutObjectType>
bool SVGLayoutSupport::ComputeHasNonIsolatedBlendingDescendants(
const LayoutObjectType* object) {
for (LayoutObject* child = object->FirstChild(); child;
child = child->NextSibling()) {
if (child->IsBlendingAllowed() && child->StyleRef().HasBlendMode())
return true;
if (child->HasNonIsolatedBlendingDescendants() &&
!WillIsolateBlendingDescendantsForObject(child))
return true;
}
return false;
}
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_SVG_SVG_LAYOUT_SUPPORT_H_
| {
"pile_set_name": "Github"
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
namespace Tests.ViewModel
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using EmployeeTracker.Common;
using EmployeeTracker.Fakes;
using EmployeeTracker.Model;
using EmployeeTracker.ViewModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Tests;
/// <summary>
/// Unit tests for EmployeeWorkspaceViewModel
/// </summary>
[TestClass]
public class EmployeeWorkspaceViewModelTests
{
/// <summary>
/// Verify creation of a workspace with no data
/// </summary>
[TestMethod]
public void InitializeWithEmptyData()
{
using (FakeEmployeeContext ctx = new FakeEmployeeContext())
{
UnitOfWork unit = new UnitOfWork(ctx);
ObservableCollection<DepartmentViewModel> departments = new ObservableCollection<DepartmentViewModel>();
ObservableCollection<EmployeeViewModel> employees = new ObservableCollection<EmployeeViewModel>();
EmployeeWorkspaceViewModel vm = new EmployeeWorkspaceViewModel(employees, departments, unit);
Assert.AreSame(employees, vm.AllEmployees, "ViewModel should expose the same instance of the collection so that changes outside the ViewModel are reflected.");
Assert.IsNull(vm.CurrentEmployee, "Current employee should not be set if there are no department.");
Assert.IsNotNull(vm.AddEmployeeCommand, "AddEmployeeCommand should be initialized");
Assert.IsNotNull(vm.DeleteEmployeeCommand, "DeleteEmployeeCommand should be initialized");
}
}
/// <summary>
/// Verify creation of a workspace with data
/// </summary>
[TestMethod]
public void InitializeWithData()
{
Employee e1 = new Employee();
Employee e2 = new Employee();
Department d1 = new Department();
Department d2 = new Department();
using (FakeEmployeeContext ctx = new FakeEmployeeContext(new Employee[] { e1, e2 }, new Department[] { d1, d2 }))
{
UnitOfWork unit = new UnitOfWork(ctx);
ObservableCollection<DepartmentViewModel> departments = new ObservableCollection<DepartmentViewModel>(ctx.Departments.Select(d => new DepartmentViewModel(d)));
ObservableCollection<EmployeeViewModel> employees = new ObservableCollection<EmployeeViewModel>();
foreach (var e in ctx.Employees)
{
employees.Add(new EmployeeViewModel(e, employees, departments, unit));
}
EmployeeWorkspaceViewModel vm = new EmployeeWorkspaceViewModel(employees, departments, unit);
Assert.IsNotNull(vm.CurrentEmployee, "Current employee should be set if there are departments.");
Assert.AreSame(employees, vm.AllEmployees, "ViewModel should expose the same instance of the Employee collection so that changes outside the ViewModel are reflected.");
Assert.AreSame(employees, vm.AllEmployees[0].ManagerLookup, "ViewModel should expose the same instance of the Employee collection to children so that changes outside the ViewModel are reflected.");
Assert.AreSame(departments, vm.AllEmployees[0].DepartmentLookup, "ViewModel should expose the same instance of the Department collection to children so that changes outside the ViewModel are reflected.");
}
}
/// <summary>
/// Verify NullArgumentExceptions are thrown where null is invalid
/// </summary>
[TestMethod]
public void NullArgumentChecks()
{
using (FakeEmployeeContext ctx = new FakeEmployeeContext())
{
UnitOfWork unit = new UnitOfWork(ctx);
Utilities.CheckNullArgumentException(() => { new EmployeeWorkspaceViewModel(null, new ObservableCollection<DepartmentViewModel>(), unit); }, "employees", "ctor");
Utilities.CheckNullArgumentException(() => { new EmployeeWorkspaceViewModel(new ObservableCollection<EmployeeViewModel>(), null, unit); }, "departmentLookup", "ctor");
Utilities.CheckNullArgumentException(() => { new EmployeeWorkspaceViewModel(new ObservableCollection<EmployeeViewModel>(), new ObservableCollection<DepartmentViewModel>(), null); }, "unitOfWork", "ctor");
}
}
/// <summary>
/// Verify current employee getter and setter
/// </summary>
[TestMethod]
public void CurrentEmployee()
{
using (FakeEmployeeContext ctx = BuildContextWithData())
{
EmployeeWorkspaceViewModel vm = BuildViewModel(ctx);
string lastProperty;
vm.PropertyChanged += (sender, e) => { lastProperty = e.PropertyName; };
lastProperty = null;
vm.CurrentEmployee = null;
Assert.IsNull(vm.CurrentEmployee, "CurrentEmployee should have been nulled.");
Assert.AreEqual("CurrentEmployee", lastProperty, "CurrentEmployee should have raised a PropertyChanged when set to null.");
lastProperty = null;
var employee = vm.AllEmployees.First();
vm.CurrentEmployee = employee;
Assert.AreSame(employee, vm.CurrentEmployee, "CurrentEmployee has not been set to specified value.");
Assert.AreEqual("CurrentEmployee", lastProperty, "CurrentEmployee should have raised a PropertyChanged when set to a value.");
}
}
/// <summary>
/// Verify additions to employee collection are reflected
/// </summary>
[TestMethod]
public void ExternalAddToEmployeeCollection()
{
using (FakeEmployeeContext ctx = BuildContextWithData())
{
UnitOfWork unit = new UnitOfWork(ctx);
EmployeeWorkspaceViewModel vm = BuildViewModel(ctx, unit);
EmployeeViewModel currentEmployee = vm.CurrentEmployee;
EmployeeViewModel newEmployee = new EmployeeViewModel(new Employee(), vm.AllEmployees, new ObservableCollection<DepartmentViewModel>(), unit);
vm.AllEmployees.Add(newEmployee);
Assert.IsTrue(vm.AllEmployees.Contains(newEmployee), "New employee should have been added to AllEmployees.");
Assert.AreSame(currentEmployee, vm.CurrentEmployee, "CurrentEmployee should not have changed.");
Assert.IsFalse(ctx.IsObjectTracked(newEmployee.Model), "ViewModel is not responsible for adding employees created externally.");
}
}
/// <summary>
/// Verify removals from employee collection are reflected
/// When current employee is remains in collection
/// </summary>
[TestMethod]
public void ExternalRemoveFromEmployeeCollection()
{
using (FakeEmployeeContext ctx = BuildContextWithData())
{
UnitOfWork unit = new UnitOfWork(ctx);
EmployeeWorkspaceViewModel vm = BuildViewModel(ctx, unit);
EmployeeViewModel current = vm.AllEmployees.First();
EmployeeViewModel toDelete = vm.AllEmployees.Skip(1).First();
vm.CurrentEmployee = current;
vm.AllEmployees.Remove(toDelete);
Assert.IsFalse(vm.AllEmployees.Contains(toDelete), "Employee should have been removed from AllDepartments.");
Assert.AreSame(current, vm.CurrentEmployee, "CurrentEmployee should not have changed.");
Assert.IsTrue(ctx.IsObjectTracked(toDelete.Model), "ViewModel is not responsible for deleting employees removed externally.");
}
}
/// <summary>
/// Verify removals from employee collection are reflected
/// When current employee is removed
/// </summary>
[TestMethod]
public void ExternalRemoveSelectedEmployeeFromCollection()
{
using (FakeEmployeeContext ctx = BuildContextWithData())
{
UnitOfWork unit = new UnitOfWork(ctx);
EmployeeWorkspaceViewModel vm = BuildViewModel(ctx, unit);
EmployeeViewModel current = vm.CurrentEmployee;
string lastProperty = null;
vm.PropertyChanged += (sender, e) => { lastProperty = e.PropertyName; };
vm.AllEmployees.Remove(current);
Assert.IsFalse(vm.AllEmployees.Contains(current), "Employee should have been removed from AllEmployees.");
Assert.IsNull(vm.CurrentEmployee, "CurrentEmployee should have been nulled as it was removed from the collection.");
Assert.AreEqual("CurrentEmployee", lastProperty, "CurrentEmployee should have raised a PropertyChanged.");
Assert.IsTrue(ctx.IsObjectTracked(current.Model), "ViewModel is not responsible for deleting employees removed externally.");
}
}
/// <summary>
/// Verify department delete command is only available when an employee is selected
/// </summary>
[TestMethod]
public void DeleteCommandOnlyAvailableWhenEmployeeSelected()
{
using (FakeEmployeeContext ctx = BuildContextWithData())
{
EmployeeWorkspaceViewModel vm = BuildViewModel(ctx);
vm.CurrentEmployee = null;
Assert.IsFalse(vm.DeleteEmployeeCommand.CanExecute(null), "Delete command should be disabled when no employee is selected.");
vm.CurrentEmployee = vm.AllEmployees.First();
Assert.IsTrue(vm.DeleteEmployeeCommand.CanExecute(null), "Delete command should be enabled when employee is selected.");
}
}
/// <summary>
/// Verify employee can be deleted
/// </summary>
[TestMethod]
public void DeleteEmployee()
{
using (FakeEmployeeContext ctx = BuildContextWithData())
{
EmployeeWorkspaceViewModel vm = BuildViewModel(ctx);
EmployeeViewModel toDelete = vm.CurrentEmployee;
int originalCount = vm.AllEmployees.Count;
string lastProperty = null;
vm.PropertyChanged += (sender, e) => { lastProperty = e.PropertyName; };
vm.DeleteEmployeeCommand.Execute(null);
Assert.AreEqual(originalCount - 1, vm.AllEmployees.Count, "One employee should have been removed from the AllEmployees property.");
Assert.IsFalse(vm.AllEmployees.Contains(toDelete), "The selected employee should have been removed.");
Assert.IsFalse(ctx.IsObjectTracked(toDelete.Model), "The selected employee has not been removed from the context.");
Assert.IsNull(vm.CurrentEmployee, "No employee should be selected after deletion.");
Assert.AreEqual("CurrentEmployee", lastProperty, "CurrentEmployee should have raised a PropertyChanged.");
}
}
/// <summary>
/// Verify a new employee can be added when another employee is selected
/// </summary>
[TestMethod]
public void AddWhenEmployeeSelected()
{
using (FakeEmployeeContext ctx = BuildContextWithData())
{
EmployeeWorkspaceViewModel vm = BuildViewModel(ctx);
vm.CurrentEmployee = vm.AllEmployees.First();
TestAddEmployee(ctx, vm);
}
}
/// <summary>
/// Verify a new employee can be added when no employee is selected
/// </summary>
[TestMethod]
public void AddWhenEmployeeNotSelected()
{
using (FakeEmployeeContext ctx = BuildContextWithData())
{
EmployeeWorkspaceViewModel vm = BuildViewModel(ctx);
vm.CurrentEmployee = null;
TestAddEmployee(ctx, vm);
}
}
/// <summary>
/// Verifies addition of employee to workspace and unit of work
/// </summary>
/// <param name="unitOfWork">Context employee should get added to</param>
/// <param name="vm">Workspace to add employee to</param>
private static void TestAddEmployee(FakeEmployeeContext ctx, EmployeeWorkspaceViewModel vm)
{
List<EmployeeViewModel> originalEmployees = vm.AllEmployees.ToList();
string lastProperty = null;
vm.PropertyChanged += (sender, e) => { lastProperty = e.PropertyName; };
Assert.IsTrue(vm.AddEmployeeCommand.CanExecute(null), "Add command should always be enabled.");
vm.AddEmployeeCommand.Execute(null);
Assert.AreEqual(originalEmployees.Count + 1, vm.AllEmployees.Count, "One new employee should have been added to the AllEmployees property.");
Assert.IsFalse(originalEmployees.Contains(vm.CurrentEmployee), "The new employee should be selected.");
Assert.IsNotNull(vm.CurrentEmployee, "The new employee should be selected.");
Assert.AreEqual("CurrentEmployee", lastProperty, "CurrentEmployee should have raised a PropertyChanged.");
Assert.IsTrue(ctx.IsObjectTracked(vm.CurrentEmployee.Model), "The new employee has not been added to the context.");
}
/// <summary>
/// Creates a fake context with seed data
/// </summary>
/// <returns>The fake context</returns>
private static FakeEmployeeContext BuildContextWithData()
{
Employee e1 = new Employee();
Employee e2 = new Employee();
Department d1 = new Department();
Department d2 = new Department();
return new FakeEmployeeContext(new Employee[] { e1, e2 }, new Department[] { d1, d2 });
}
/// <summary>
/// Creates a ViewModel based on a fake context
/// </summary>
/// <param name="ctx">Context to base view model on</param>
/// <returns>The new ViewModel</returns>
private static EmployeeWorkspaceViewModel BuildViewModel(FakeEmployeeContext ctx)
{
return BuildViewModel(ctx, new UnitOfWork(ctx));
}
/// <summary>
/// Creates a ViewModel based on a fake context using an existing unit of work
/// </summary>
/// <param name="ctx">Context to base view model on</param>
/// <param name="unit">Current unit of work</param>
/// <returns>The new ViewModel</returns>
private static EmployeeWorkspaceViewModel BuildViewModel(FakeEmployeeContext ctx, UnitOfWork unit)
{
ObservableCollection<DepartmentViewModel> departments = new ObservableCollection<DepartmentViewModel>(ctx.Departments.Select(d => new DepartmentViewModel(d)));
ObservableCollection<EmployeeViewModel> employees = new ObservableCollection<EmployeeViewModel>();
foreach (var e in ctx.Employees)
{
employees.Add(new EmployeeViewModel(e, employees, departments, unit));
}
return new EmployeeWorkspaceViewModel(employees, departments, unit);
}
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="JsDoc Toolkit"/>
<title>Camera - Hilo API Document</title>
<style>
iframe{
border:1px solid #333;
}
</style>
<link href="../../bootstrap3.0.3/css/bootstrap.min.css" rel="stylesheet">
<link href="../../bootstrap3.0.3/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="../../css/prettify.min.css" rel="stylesheet">
<link href="../../css/api.min.css" rel="stylesheet">
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<span>Hilo</span><span></span>
</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="//hiloteam.github.io/index.html">首页</a></li>
<li><a href="//github.com/hiloteam/Hilo" target="_blank">源码下载</a></li>
<li class="active"><a href="../index.html">API文档</a></li>
<li><a href="//hiloteam.github.io/tutorial/index.html">教程文档</a></li>
<li><a href="//hiloteam.github.io/examples/index.html">作品演示</a></li>
</u>
</div>
</div>
</div>
<div class="container main">
<div class="col-md-3">
<div class="bs-sidebar well">
<!-- <div class="hilo-header">类列表</div> -->
<ul class="nav bs-sidenav">
<li class="nav-pkg">core<span></span></li>
<li class="nav-class"><a href="../symbols/Class.html">Class</a></li>
<li class="nav-class"><a href="../symbols/Hilo.html">Hilo</a></li>
<li class="nav-pkg">event<span></span></li>
<li class="nav-class"><a href="../symbols/EventMixin.html">EventMixin</a></li>
<li class="nav-pkg">game<span></span></li>
<li class="nav-class"><a href="../symbols/Camera.html">Camera</a></li>
<li class="nav-class"><a href="../symbols/Camera3d.html">Camera3d</a></li>
<li class="nav-class"><a href="../symbols/ParticleSystem.html">ParticleSystem</a></li>
<li class="nav-pkg">geom<span></span></li>
<li class="nav-class"><a href="../symbols/Matrix.html">Matrix</a></li>
<li class="nav-pkg">loader<span></span></li>
<li class="nav-class"><a href="../symbols/LoadQueue.html">LoadQueue</a></li>
<li class="nav-pkg">media<span></span></li>
<li class="nav-class"><a href="../symbols/HTMLAudio.html">HTMLAudio</a></li>
<li class="nav-class"><a href="../symbols/WebAudio.html">WebAudio</a></li>
<li class="nav-class"><a href="../symbols/WebSound.html">WebSound</a></li>
<li class="nav-pkg">renderer<span></span></li>
<li class="nav-class"><a href="../symbols/CanvasRenderer.html">CanvasRenderer</a></li>
<li class="nav-class"><a href="../symbols/DOMRenderer.html">DOMRenderer</a></li>
<li class="nav-class"><a href="../symbols/Renderer.html">Renderer</a></li>
<li class="nav-class"><a href="../symbols/WebGLRenderer.html">WebGLRenderer</a></li>
<li class="nav-pkg">tween<span></span></li>
<li class="nav-class"><a href="../symbols/Ease.html">Ease</a></li>
<li class="nav-class"><a href="../symbols/Tween.html">Tween</a></li>
<li class="nav-pkg">util<span></span></li>
<li class="nav-class"><a href="../symbols/TextureAtlas.html">TextureAtlas</a></li>
<li class="nav-class"><a href="../symbols/Ticker.html">Ticker</a></li>
<li class="nav-class"><a href="../symbols/browser.html">browser</a></li>
<li class="nav-class"><a href="../symbols/drag.html">drag</a></li>
<li class="nav-class"><a href="../symbols/util.html">util</a></li>
<li class="nav-pkg">view<span></span></li>
<li class="nav-class"><a href="../symbols/Bitmap.html">Bitmap</a></li>
<li class="nav-class"><a href="../symbols/BitmapText.html">BitmapText</a></li>
<li class="nav-class"><a href="../symbols/Button.html">Button</a></li>
<li class="nav-class"><a href="../symbols/CacheMixin.html">CacheMixin</a></li>
<li class="nav-class"><a href="../symbols/Container.html">Container</a></li>
<li class="nav-class"><a href="../symbols/DOMElement.html">DOMElement</a></li>
<li class="nav-class"><a href="../symbols/Drawable.html">Drawable</a></li>
<li class="nav-class"><a href="../symbols/Graphics.html">Graphics</a></li>
<li class="nav-class"><a href="../symbols/Sprite.html">Sprite</a></li>
<li class="nav-class"><a href="../symbols/Stage.html">Stage</a></li>
<li class="nav-class"><a href="../symbols/Text.html">Text</a></li>
<li class="nav-class"><a href="../symbols/View.html">View</a></li>
</ul>
</div>
</div>
<div class="col-md-9">
<!-- ============================== class title ============================ -->
<h1 style="margin-top:0;">
Camera
</h1><hr style="margin-top:10px;" />
<!-- ============================== class summary ========================== -->
<p class="description">
<span style="display:block;margin:0 0 2px 0;">
<b style="margin-right:10px;">Module</b> hilo/game/Camera
</span>
<span style="display:block;margin:0 0 2px 0;">
<b style="margin-right:10px;">Requires</b>
<span><a href="../symbols/Class.html">hilo/core/Class</a></span>, <span><a href="../symbols/util.html">hilo/util/util</a></span>
</span>
<span style="display:block;margin:0 0 2px 0;">
<b style="margin-right:10px;">Source</b>
<a href="../symbols/src/docs_api-en_code_game_Camera.js.html">Camera.js</a>
</span>
<br>
Camera.
</p>
<!-- ============================== properties summary ===================== -->
<div style="margin:30px 0 5px 0;">
<h3 style="display:inline;margin-right:10px;">Properties</h3>
</div>
<table class="table table-striped table-bordered table-condensed table-symbol" cellspacing="0">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Property </th>
<th scope="col">Defined</th>
</tr>
</thead>
<tbody>
<tr >
<td>
</td>
<td class="fixedFont">
<div>
<!-- -->
<b><a href="../symbols/Camera.html#bounds">bounds</a></b>:Array
</div>
<div class="description">
The rect area where camera is allowed to move [x, y, width, height].
</div>
</td>
<td>
Camera
</td>
</tr>
<tr >
<td>
</td>
<td class="fixedFont">
<div>
<!-- -->
<b><a href="../symbols/Camera.html#deadzone">deadzone</a></b>:Array
</div>
<div class="description">
The rect area where camera isn't allowed to move[ x, y, width, height].
</div>
</td>
<td>
Camera
</td>
</tr>
<tr >
<td>
</td>
<td class="fixedFont">
<div>
<!-- -->
<b><a href="../symbols/Camera.html#height">height</a></b>:Number
</div>
<div class="description">
The height of the camera.
</div>
</td>
<td>
Camera
</td>
</tr>
<tr >
<td>
</td>
<td class="fixedFont">
<div>
<!-- -->
<b><a href="../symbols/Camera.html#scroll">scroll</a></b>:Object
</div>
<div class="description">
The scrolling value of the camera {x:0, y:0}.
</div>
</td>
<td>
Camera
</td>
</tr>
<tr >
<td>
</td>
<td class="fixedFont">
<div>
<!-- -->
<b><a href="../symbols/Camera.html#target">target</a></b>:View
</div>
<div class="description">
The target that the camera follow.
</div>
</td>
<td>
Camera
</td>
</tr>
<tr >
<td>
</td>
<td class="fixedFont">
<div>
<!-- -->
<b><a href="../symbols/Camera.html#width">width</a></b>:Number
</div>
<div class="description">
The width of the camera.
</div>
</td>
<td>
Camera
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function toggleProperties(){
var alink = $('#propToggleIcon');
if(alink.hasClass('glyphicon-circle-arrow-right')){
alink.removeClass('glyphicon-circle-arrow-right');
alink.addClass('glyphicon-circle-arrow-down');
$('#propToggleTip').html('Hide Inherited Properties');
$('.inheritProp').show();
}else{
alink.removeClass('glyphicon-circle-arrow-down');
alink.addClass('glyphicon-circle-arrow-right');
$('#propToggleTip').html('Show Inherited Properties');
$('.inheritProp').hide();
}
}
</script>
<!-- ============================== methods summary ======================== -->
<div style="margin:30px 0 5px; 0">
<h3 style="display:inline;margin-right:10px;">Methods</h3>
</div>
<table class="table table-striped table-bordered table-condensed table-symbol" cellspacing="0">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Method</th>
<th scope="col">Defined</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>
<div class="fixedFont">
<b><a href="#constructor">Camera</a></b>(properties:Object)
</div>
<div class="description">Constructor</div>
</td>
<td>Camera</td>
</tr>
<tr >
<td>
</td>
<td class="fixedFont">
<div><b><a href="../symbols/Camera.html#follow">follow</a></b>(target:Object, deadzone:Array)
</div>
<div class="description">
Follow the target.
</div>
</td>
<td>
Camera
</td>
</tr>
<tr >
<td>
</td>
<td class="fixedFont">
<div><b><a href="../symbols/Camera.html#tick">tick</a></b>(deltaTime:Number)
</div>
<div class="description">
update.
</div>
</td>
<td>
Camera
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function toggleMethods(){
var alink = $('#methodToggleIcon');
if(alink.hasClass('glyphicon-circle-arrow-right')){
alink.removeClass('glyphicon-circle-arrow-right');
alink.addClass('glyphicon-circle-arrow-down');
$('#methodToggleTip').html('Hide Inherited Methods');
$('.inheritMethod').show();
}else{
alink.removeClass('glyphicon-circle-arrow-down');
alink.addClass('glyphicon-circle-arrow-right');
$('#methodToggleTip').html('Show Inherited Methods');
$('.inheritMethod').hide();
}
}
</script>
<!-- ============================== field details ========================== -->
<br/>
<div class="">
<h3 style="margin-bottom:15px;">Property Detail</h3>
</div>
<a class="anchor" name="bounds"> </a>
<div class="member-box">
<div class="member-header">
<b>bounds</b><span class="light">:Array</span>
</div>
<div class="description">
The rect area where camera is allowed to move [x, y, width, height].
</div>
</div>
<a class="anchor" name="deadzone"> </a>
<div class="member-box">
<div class="member-header">
<b>deadzone</b><span class="light">:Array</span>
</div>
<div class="description">
The rect area where camera isn't allowed to move[ x, y, width, height].
</div>
</div>
<a class="anchor" name="height"> </a>
<div class="member-box">
<div class="member-header">
<b>height</b><span class="light">:Number</span>
</div>
<div class="description">
The height of the camera.
</div>
</div>
<a class="anchor" name="scroll"> </a>
<div class="member-box">
<div class="member-header">
<b>scroll</b><span class="light">:Object</span>
</div>
<div class="description">
The scrolling value of the camera {x:0, y:0}.
</div>
</div>
<a class="anchor" name="target"> </a>
<div class="member-box">
<div class="member-header">
<b>target</b><span class="light">:<a href="../symbols/View.html">View</a></span>
</div>
<div class="description">
The target that the camera follow.
</div>
</div>
<a class="anchor" name="width"> </a>
<div class="member-box">
<div class="member-header">
<b>width</b><span class="light">:Number</span>
</div>
<div class="description">
The width of the camera.
</div>
</div>
<!-- ============================== constructor details ==================== -->
<br/>
<div class="details">
<a class="anchor" name="constructor"> </a>
<div class="">
<h3 style="margin-bottom:15px;">Constructor</h3>
</div>
<div class="member-box">
<div class="member-header">
<b>Camera</b>(properties:Object)
</div>
<dl class="detailList">
<dt class="heading"><span class="label">parameters</span></dt>
<dt style="margin-left:20px;font-weight:normal;">
<b>properties</b>:<span>Object</span>
— The properties to create a view object, contains all writeable props of this class
</dt>
</dl>
</div>
</div>
<!-- ============================== method details ========================= -->
<br/>
<div class=""><h3 style="margin-bottom:15px;">Method Detail</h3></div>
<a class="anchor" name="follow"> </a>
<div class="member-box">
<div class="member-header">
<b>follow</b>(target:Object, deadzone:Array)
</div>
<div class="description">Follow the target.</div>
<dl class="detailList">
<dt class="heading"><span class="label">parameters</span></dt>
<dt style="margin-left:20px;font-weight:normal;">
<b>target</b>:<span>Object</span>
— The target that the camera follow. It must has x and y properties.
</dt>
<dt style="margin-left:20px;font-weight:normal;">
<b>deadzone</b>:<span>Array</span>
— The rect area where camera isn't allowed to move[ x, y, width, height].
</dt>
</dl>
</div>
<a class="anchor" name="tick"> </a>
<div class="member-box">
<div class="member-header">
<b>tick</b>(deltaTime:Number)
</div>
<div class="description">update.</div>
<dl class="detailList">
<dt class="heading"><span class="label">parameters</span></dt>
<dt style="margin-left:20px;font-weight:normal;">
<b>deltaTime</b>:<span>Number</span>
—
</dt>
</dl>
</div>
</div>
</div>
<footer class="col-md-12">
<hr>
<p>© Hilo 2016</p>
</footer>
<script src="../../js/jquery.min.js"></script>
<script src="../../bootstrap3.0.3/js/bootstrap.min.js"></script>
<script src="../../js/prettify.min.js"></script>
<script type="text/javascript">
//make code pretty
$('pre').addClass('prettyprint linenums fixedFont');
window.prettyPrint && prettyPrint();
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
Copyright 2018 The Kubernetes Authors.
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 transformers
import (
"fmt"
"log"
"strings"
)
type mutateFunc func(interface{}) (interface{}, error)
func mutateField(
m map[string]interface{},
pathToField []string,
createIfNotPresent bool,
fns ...mutateFunc) error {
if len(pathToField) == 0 {
return nil
}
_, found := m[pathToField[0]]
if !found {
if !createIfNotPresent {
return nil
}
m[pathToField[0]] = map[string]interface{}{}
}
if len(pathToField) == 1 {
var err error
for _, fn := range fns {
m[pathToField[0]], err = fn(m[pathToField[0]])
if err != nil {
return err
}
}
return nil
}
v := m[pathToField[0]]
newPathToField := pathToField[1:]
switch typedV := v.(type) {
case nil:
log.Printf(
"nil value at `%s` ignored in mutation attempt",
strings.Join(pathToField, "."))
return nil
case map[string]interface{}:
return mutateField(typedV, newPathToField, createIfNotPresent, fns...)
case []interface{}:
for i := range typedV {
item := typedV[i]
typedItem, ok := item.(map[string]interface{})
if !ok {
return fmt.Errorf("%#v is expected to be %T", item, typedItem)
}
err := mutateField(typedItem, newPathToField, createIfNotPresent, fns...)
if err != nil {
return err
}
}
return nil
default:
return fmt.Errorf("%#v is not expected to be a primitive type", typedV)
}
}
| {
"pile_set_name": "Github"
} |
// license:BSD-3-Clause
// copyright-holders:Angelo Salese, David Haywood
/*******************************************************************************************
Best League (c) 1993
A Big Striker Italian bootleg (made by Playmark?) running on a different hardware.
driver by David Haywood & Angelo Salese
Changes 29/03/2005 - Pierpaolo Prazzoli
- Fixed tilemaps and sprites offset
- Fixed visible area
- Fixed dip-switches
- Added oki banking
- Added sprites wraparound
- Added sprites color masking
Dip Locations added according to Service Mode
*******************************************************************************************/
#include "emu.h"
#include "cpu/m68000/m68000.h"
#include "sound/okim6295.h"
#include "emupal.h"
#include "screen.h"
#include "speaker.h"
#include "tilemap.h"
class bestleag_state : public driver_device
{
public:
bestleag_state(const machine_config &mconfig, device_type type, const char *tag) :
driver_device(mconfig, type, tag),
m_maincpu(*this, "maincpu"),
m_oki(*this, "oki"),
m_gfxdecode(*this, "gfxdecode"),
m_palette(*this, "palette"),
m_bgram(*this, "bgram"),
m_fgram(*this, "fgram"),
m_txram(*this, "txram"),
m_vregs(*this, "vregs"),
m_spriteram(*this, "spriteram")
{ }
required_device<cpu_device> m_maincpu;
required_device<okim6295_device> m_oki;
required_device<gfxdecode_device> m_gfxdecode;
required_device<palette_device> m_palette;
required_shared_ptr<uint16_t> m_bgram;
required_shared_ptr<uint16_t> m_fgram;
required_shared_ptr<uint16_t> m_txram;
required_shared_ptr<uint16_t> m_vregs;
required_shared_ptr<uint16_t> m_spriteram;
tilemap_t *m_tx_tilemap;
tilemap_t *m_bg_tilemap;
tilemap_t *m_fg_tilemap;
void txram_w(offs_t offset, uint16_t data);
void bgram_w(offs_t offset, uint16_t data);
void fgram_w(offs_t offset, uint16_t data);
void oki_bank_w(uint16_t data);
TILE_GET_INFO_MEMBER(get_tx_tile_info);
TILE_GET_INFO_MEMBER(get_bg_tile_info);
TILE_GET_INFO_MEMBER(get_fg_tile_info);
TILEMAP_MAPPER_MEMBER(bsb_bg_scan);
virtual void video_start() override;
uint32_t screen_update_bestleag(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
uint32_t screen_update_bestleaw(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
void draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect);
void bestleag(machine_config &config);
void bestleaw(machine_config &config);
void bestleag_map(address_map &map);
};
/* Video Handling */
TILE_GET_INFO_MEMBER(bestleag_state::get_tx_tile_info)
{
int code = m_txram[tile_index];
tileinfo.set(0,
(code & 0x0fff)|0x8000,
(code & 0xf000) >> 12,
0);
}
TILE_GET_INFO_MEMBER(bestleag_state::get_bg_tile_info)
{
int code = m_bgram[tile_index];
tileinfo.set(1,
(code & 0x0fff),
(code & 0xf000) >> 12,
0);
}
TILE_GET_INFO_MEMBER(bestleag_state::get_fg_tile_info)
{
int code = m_fgram[tile_index];
tileinfo.set(1,
(code & 0x0fff)|0x1000,
((code & 0xf000) >> 12)|0x10,
0);
}
TILEMAP_MAPPER_MEMBER(bestleag_state::bsb_bg_scan)
{
int offset;
offset = ((col&0xf)*16) + (row&0xf);
offset += (col >> 4) * 0x100;
offset += (row >> 4) * 0x800;
return offset;
}
void bestleag_state::video_start()
{
m_tx_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(bestleag_state::get_tx_tile_info)), TILEMAP_SCAN_COLS, 8, 8, 256, 32);
m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(bestleag_state::get_bg_tile_info)), tilemap_mapper_delegate(*this, FUNC(bestleag_state::bsb_bg_scan)), 16, 16, 128, 64);
m_fg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(bestleag_state::get_fg_tile_info)), tilemap_mapper_delegate(*this, FUNC(bestleag_state::bsb_bg_scan)), 16, 16, 128, 64);
m_tx_tilemap->set_transparent_pen(15);
m_fg_tilemap->set_transparent_pen(15);
}
/*
Note: sprite chip is different than the other Big Striker sets and they
include several similiarities with other Playmark games (including
the sprite end code and the data being offset (i.e. spriteram starting from 0x16/2))
*/
void bestleag_state::draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect)
{
uint16_t *spriteram16 = m_spriteram;
/*
Sprites are the same to sslam, but using 16x16 sprites instead of 8x8
*/
int offs;
for (offs = 0x16/2;offs < m_spriteram.bytes()/2;offs += 4)
{
int code = spriteram16[offs+3] & 0xfff;
int color = (spriteram16[offs+2] & 0xf000) >> 12;
int sx = (spriteram16[offs+2] & 0x1ff) - 20;
int sy = (0xff - (spriteram16[offs+0] & 0xff)) - 15;
int flipx = (spriteram16[offs+0] & 0x4000) >> 14;
/* Sprite list end code */
if(spriteram16[offs+0] & 0x2000)
return;
/* it can change sprites color mask like the original set */
if(m_vregs[0x00/2] & 0x1000)
color &= 7;
m_gfxdecode->gfx(2)->transpen(bitmap,cliprect,
code,
color,
flipx, 0,
flipx ? (sx+16) : (sx),sy,15);
m_gfxdecode->gfx(2)->transpen(bitmap,cliprect,
code+1,
color,
flipx, 0,
flipx ? (sx) : (sx+16),sy,15);
/* wraparound x */
m_gfxdecode->gfx(2)->transpen(bitmap,cliprect,
code,
color,
flipx, 0,
flipx ? (sx+16 - 512) : (sx - 512),sy,15);
m_gfxdecode->gfx(2)->transpen(bitmap,cliprect,
code+1,
color,
flipx, 0,
flipx ? (sx - 512) : (sx+16 - 512),sy,15);
}
}
uint32_t bestleag_state::screen_update_bestleag(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
m_bg_tilemap->set_scrollx(0,(m_vregs[0x00/2] & 0xfff) + (m_vregs[0x08/2] & 0x7) - 3);
m_bg_tilemap->set_scrolly(0,m_vregs[0x02/2]);
m_tx_tilemap->set_scrollx(0,m_vregs[0x04/2]);
m_tx_tilemap->set_scrolly(0,m_vregs[0x06/2]);
m_fg_tilemap->set_scrollx(0,m_vregs[0x08/2] & 0xfff8);
m_fg_tilemap->set_scrolly(0,m_vregs[0x0a/2]);
m_bg_tilemap->draw(screen, bitmap, cliprect, 0,0);
m_fg_tilemap->draw(screen, bitmap, cliprect, 0,0);
draw_sprites(bitmap,cliprect);
m_tx_tilemap->draw(screen, bitmap, cliprect, 0,0);
return 0;
}
uint32_t bestleag_state::screen_update_bestleaw(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
m_bg_tilemap->set_scrollx(0,m_vregs[0x08/2]);
m_bg_tilemap->set_scrolly(0,m_vregs[0x0a/2]);
m_tx_tilemap->set_scrollx(0,m_vregs[0x00/2]);
m_tx_tilemap->set_scrolly(0,m_vregs[0x02/2]);
m_fg_tilemap->set_scrollx(0,m_vregs[0x04/2]);
m_fg_tilemap->set_scrolly(0,m_vregs[0x06/2]);
m_bg_tilemap->draw(screen, bitmap, cliprect, 0,0);
m_fg_tilemap->draw(screen, bitmap, cliprect, 0,0);
draw_sprites(bitmap,cliprect);
m_tx_tilemap->draw(screen, bitmap, cliprect, 0,0);
return 0;
}
void bestleag_state::txram_w(offs_t offset, uint16_t data)
{
m_txram[offset] = data;
m_tx_tilemap->mark_tile_dirty(offset);
}
void bestleag_state::bgram_w(offs_t offset, uint16_t data)
{
m_bgram[offset] = data;
m_bg_tilemap->mark_tile_dirty(offset);
}
void bestleag_state::fgram_w(offs_t offset, uint16_t data)
{
m_fgram[offset] = data;
m_fg_tilemap->mark_tile_dirty(offset);
}
void bestleag_state::oki_bank_w(uint16_t data)
{
m_oki->set_rom_bank((data - 1) & 3);
}
/* Memory Map */
void bestleag_state::bestleag_map(address_map &map)
{
map(0x000000, 0x03ffff).rom();
map(0x0d2000, 0x0d3fff).noprw(); // left over from the original game (only read / written in memory test)
map(0x0e0000, 0x0e3fff).ram().w(FUNC(bestleag_state::bgram_w)).share("bgram");
map(0x0e8000, 0x0ebfff).ram().w(FUNC(bestleag_state::fgram_w)).share("fgram");
map(0x0f0000, 0x0f3fff).ram().w(FUNC(bestleag_state::txram_w)).share("txram");
map(0x0f8000, 0x0f800b).ram().share("vregs");
map(0x100000, 0x100fff).ram().w(m_palette, FUNC(palette_device::write16)).share("palette");
map(0x200000, 0x200fff).ram().share("spriteram");
map(0x300010, 0x300011).portr("SYSTEM");
map(0x300012, 0x300013).portr("P1");
map(0x300014, 0x300015).portr("P2");
map(0x300016, 0x300017).portr("DSWA");
map(0x300018, 0x300019).portr("DSWB");
map(0x30001c, 0x30001d).w(FUNC(bestleag_state::oki_bank_w));
map(0x30001f, 0x30001f).rw(m_oki, FUNC(okim6295_device::read), FUNC(okim6295_device::write));
map(0x304000, 0x304001).nopw();
map(0xfe0000, 0xffffff).ram();
}
#define BESTLEAG_PLAYER_INPUT( player ) \
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(player) PORT_8WAY \
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(player) PORT_8WAY \
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(player) PORT_8WAY \
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(player) PORT_8WAY \
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(player) \
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(player) \
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(player) \
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
static INPUT_PORTS_START( bestleag )
PORT_START("SYSTEM")
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN2 )
PORT_START("P1")
BESTLEAG_PLAYER_INPUT( 1 )
PORT_START("P2")
BESTLEAG_PLAYER_INPUT( 2 )
PORT_START("DSWA")
PORT_DIPNAME( 0x0f, 0x0f, DEF_STR( Coin_A ) ) PORT_DIPLOCATION("SW.A:1,2,3,4")
PORT_DIPSETTING( 0x07, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x09, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x0f, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x06, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0x0e, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x0d, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0x0b, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) )
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) // also set "Coin B" to "Free Play"
/* 0x01 to 0x05 gives 2C_3C */
PORT_DIPNAME( 0xf0, 0xf0, DEF_STR( Coin_B ) ) PORT_DIPLOCATION("SW.A:5,6,7,8")
PORT_DIPSETTING( 0x70, DEF_STR( 4C_1C ) )
PORT_DIPSETTING( 0x80, DEF_STR( 3C_1C ) )
PORT_DIPSETTING( 0x90, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0xf0, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x60, DEF_STR( 2C_3C ) )
PORT_DIPSETTING( 0xe0, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0xd0, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0xc0, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0xb0, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0xa0, DEF_STR( 1C_6C ) )
PORT_DIPSETTING( 0x00, DEF_STR( Free_Play ) ) // also set "Coin A" to "Free Play"
/* 0x10 to 0x50 gives 2C_3C */
PORT_START("DSWB")
PORT_DIPNAME( 0x01, 0x01, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("SW.B:1") // Doesn't work ?
PORT_DIPSETTING( 0x01, DEF_STR( Off ) )
PORT_DIPSETTING( 0x00, DEF_STR( On ) )
PORT_DIPNAME( 0x06, 0x06, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SW.B:2,3")
PORT_DIPSETTING( 0x02, DEF_STR( Easy ) )
PORT_DIPSETTING( 0x06, DEF_STR( Normal ) )
PORT_DIPSETTING( 0x04, DEF_STR( Hard ) )
PORT_DIPSETTING( 0x00, DEF_STR( Hardest ) )
PORT_DIPNAME( 0x18, 0x18, "Timer Speed" ) PORT_DIPLOCATION("SW.B:4,5")
PORT_DIPSETTING( 0x08, "Slow" ) // 65
PORT_DIPSETTING( 0x18, DEF_STR( Normal ) ) // 50
PORT_DIPSETTING( 0x10, "Fast" ) // 35
PORT_DIPSETTING( 0x00, "Fastest" ) // 25
PORT_DIPNAME( 0x20, 0x20, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW.B:6")
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x20, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x40, "2 Players Game" ) PORT_DIPLOCATION("SW.B:7")
PORT_DIPSETTING( 0x40, "1 Credit" )
PORT_DIPSETTING( 0x00, "2 Credits" )
PORT_SERVICE_DIPLOC( 0x80, IP_ACTIVE_LOW, "SW.B:8")
INPUT_PORTS_END
/* GFX Decode */
static const gfx_layout bestleag_charlayout =
{
8,8,
RGN_FRAC(1,4),
4,
{ RGN_FRAC(3,4), RGN_FRAC(2,4), RGN_FRAC(1,4), RGN_FRAC(0,4) },
{ 0, 1, 2, 3, 4, 5, 6, 7 },
{ 0*8, 2*8, 4*8, 6*8,1*8,3*8,5*8,7*8},
8*8
};
static const gfx_layout bestleag_char16layout =
{
16,16,
RGN_FRAC(1,4),
4,
{ RGN_FRAC(3,4), RGN_FRAC(2,4), RGN_FRAC(1,4), RGN_FRAC(0,4) },
{ 0,1,2, 3, 4, 5, 6, 7,
128+0,128+1,128+2,128+3,128+4,128+5,128+6,128+7 },
{ 0*8,1*8,2*8,3*8,4*8,5*8,6*8,7*8,8*8,9*8,10*8,11*8,12*8,13*8,14*8,15*8 },
16*16
};
static GFXDECODE_START( gfx_bestleag )
GFXDECODE_ENTRY( "gfx1", 0, bestleag_charlayout, 0x200, 16 )
GFXDECODE_ENTRY( "gfx1", 0, bestleag_char16layout, 0x000, 32 )
GFXDECODE_ENTRY( "gfx2", 0, bestleag_char16layout, 0x300, 16 )
GFXDECODE_END
void bestleag_state::bestleag(machine_config &config)
{
M68000(config, m_maincpu, 12000000);
m_maincpu->set_addrmap(AS_PROGRAM, &bestleag_state::bestleag_map);
m_maincpu->set_vblank_int("screen", FUNC(bestleag_state::irq6_line_hold));
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER));
screen.set_refresh_hz(60);
screen.set_vblank_time(ATTOSECONDS_IN_USEC(0));
screen.set_size(32*8, 32*8);
screen.set_visarea(0*8, 32*8-1, 2*8, 30*8-1);
screen.set_screen_update(FUNC(bestleag_state::screen_update_bestleag));
screen.set_palette(m_palette);
GFXDECODE(config, m_gfxdecode, m_palette, gfx_bestleag);
PALETTE(config, m_palette).set_format(palette_device::RRRRGGGGBBBBRGBx, 0x800);
SPEAKER(config, "lspeaker").front_left();
SPEAKER(config, "rspeaker").front_right();
OKIM6295(config, m_oki, 1000000, okim6295_device::PIN7_HIGH); /* Hand-tuned */
m_oki->add_route(ALL_OUTPUTS, "lspeaker", 1.00);
m_oki->add_route(ALL_OUTPUTS, "rspeaker", 1.00);
}
void bestleag_state::bestleaw(machine_config &config)
{
bestleag(config);
subdevice<screen_device>("screen")->set_screen_update(FUNC(bestleag_state::screen_update_bestleaw));
}
/* Rom Loading */
ROM_START( bestleag )
ROM_REGION( 0x40000, "maincpu", 0 ) /* 68000 Code */
ROM_LOAD16_BYTE( "2.bin", 0x00000, 0x20000, CRC(d2be3431) SHA1(37815c80b9fbc246fcdaa202d40fb40b10f55b45) ) // sldh
ROM_LOAD16_BYTE( "3.bin", 0x00001, 0x20000, CRC(f29c613a) SHA1(c66fa53f38bfa77ce1b894db74f94ce573c62412) ) // sldh
ROM_REGION( 0x200000, "gfx1", 0 ) /* 16x16x4 BG and 8x8x4 FG Tiles */
ROM_LOAD( "4.bin", 0x000000, 0x80000, CRC(47f7c9bc) SHA1(f0e5ef971f3bd6972316c248175436055cb5789d) ) // sldh
ROM_LOAD( "5.bin", 0x080000, 0x80000, CRC(6a6f499d) SHA1(cacdccc64d09fa7289221cdea4654e6c2d811647) ) // sldh
ROM_LOAD( "6.bin", 0x100000, 0x80000, CRC(0c3d2609) SHA1(6e1f1c5b010ef0dfa3f7b4ff9a832e758fbb97d5) ) // sldh
ROM_LOAD( "7.bin", 0x180000, 0x80000, CRC(dcece871) SHA1(7db919ab7f51748b77b3bd35228bbf71b951349f) ) // sldh
ROM_REGION( 0x080000, "gfx2", 0 ) /* 16x16x4 Sprites */
ROM_LOAD( "27_27c010.u86", 0x000000, 0x20000, CRC(a463422a) SHA1(a3b6efd1c57b0a3b0ce4ce734a9a9b79540c4136) )
ROM_LOAD( "28_27c010.u85", 0x020000, 0x20000, CRC(ebec74ed) SHA1(9a1620f4ca163470f5e567f650663ae368bdd3c1) )
ROM_LOAD( "29_27c010.u84", 0x040000, 0x20000, CRC(7ea4e22d) SHA1(3c7f05dfd1c5889bfcbc14d08026e2a484870216) )
ROM_LOAD( "30_27c010.u83", 0x060000, 0x20000, CRC(283d9ba6) SHA1(6054853f76907a4a0f89ad5aa02dde9d3d4ff196) )
ROM_REGION( 0x80000, "oki_rom", 0 ) /* Samples */
ROM_LOAD( "20_27c040.u16", 0x00000, 0x80000, CRC(e152138e) SHA1(9d41b61b98414e1d5804b5a9edf4acb4c5f31615) )
ROM_REGION( 0xc0000, "oki", 0 )
ROM_COPY( "oki_rom", 0x000000, 0x000000, 0x020000)
ROM_COPY( "oki_rom", 0x020000, 0x020000, 0x020000)
ROM_COPY( "oki_rom", 0x000000, 0x040000, 0x020000)
ROM_COPY( "oki_rom", 0x040000, 0x060000, 0x020000)
ROM_COPY( "oki_rom", 0x000000, 0x080000, 0x020000)
ROM_COPY( "oki_rom", 0x060000, 0x0a0000, 0x020000)
ROM_END
ROM_START( bestleaw )
ROM_REGION( 0x40000, "maincpu", 0 ) /* 68000 Code */
ROM_LOAD16_BYTE( "21_27c101.u67", 0x00000, 0x20000, CRC(ab5abd37) SHA1(822a4ab77041ea4d62d9f8df6197c4afe2558f21) )
ROM_LOAD16_BYTE( "22_27c010.u66", 0x00001, 0x20000, CRC(4abc0580) SHA1(c834ad0710d1ecd3babb446df4b3b4e5d0b23cbd) )
ROM_REGION( 0x200000, "gfx1", 0 ) /* 16x16x4 BG and 8x8x4 FG Tiles */
ROM_LOAD( "23_27c040.u36", 0x000000, 0x80000, CRC(dcd53a97) SHA1(ed22c51a3501bbe164d8ec4b19f1f67e28e10427) )
ROM_LOAD( "24_27c040.u42", 0x080000, 0x80000, CRC(2984c1a0) SHA1(ddab53cc6e9debb7f1fb7dae8196ff6df31cbedc) )
ROM_LOAD( "25_27c040.u38", 0x100000, 0x80000, CRC(8bb5d73a) SHA1(bc93825aab08340ef182cde56323bf30ea6c5edf) )
ROM_LOAD( "26_27c4001.u45", 0x180000, 0x80000, CRC(a82c905d) SHA1(b1c1098ad79eb66943bc362246983427d0263b6e) )
ROM_REGION( 0x080000, "gfx2", 0 ) /* 16x16x4 Sprites */
ROM_LOAD( "27_27c010.u86", 0x000000, 0x20000, CRC(a463422a) SHA1(a3b6efd1c57b0a3b0ce4ce734a9a9b79540c4136) )
ROM_LOAD( "28_27c010.u85", 0x020000, 0x20000, CRC(ebec74ed) SHA1(9a1620f4ca163470f5e567f650663ae368bdd3c1) )
ROM_LOAD( "29_27c010.u84", 0x040000, 0x20000, CRC(7ea4e22d) SHA1(3c7f05dfd1c5889bfcbc14d08026e2a484870216) )
ROM_LOAD( "30_27c010.u83", 0x060000, 0x20000, CRC(283d9ba6) SHA1(6054853f76907a4a0f89ad5aa02dde9d3d4ff196) )
ROM_REGION( 0x80000, "oki_rom", 0 ) /* Samples */
ROM_LOAD( "20_27c040.u16", 0x00000, 0x80000, CRC(e152138e) SHA1(9d41b61b98414e1d5804b5a9edf4acb4c5f31615) )
ROM_REGION( 0xc0000, "oki", 0 )
ROM_COPY( "oki_rom", 0x000000, 0x000000, 0x020000)
ROM_COPY( "oki_rom", 0x020000, 0x020000, 0x020000)
ROM_COPY( "oki_rom", 0x000000, 0x040000, 0x020000)
ROM_COPY( "oki_rom", 0x040000, 0x060000, 0x020000)
ROM_COPY( "oki_rom", 0x000000, 0x080000, 0x020000)
ROM_COPY( "oki_rom", 0x060000, 0x0a0000, 0x020000)
ROM_REGION( 0x2000, "plds", 0 )
ROM_LOAD( "85c060.bin", 0x0000, 0x032f, CRC(537100ac) SHA1(3d5e9013e3cba660671f02e78c233c866dad2e53) )
ROM_LOAD( "gal16v8-25hb1.u182", 0x0200, 0x0117, NO_DUMP ) /* Protected */
ROM_LOAD( "gal16v8-25hb1.u183", 0x0400, 0x0117, NO_DUMP ) /* Protected */
ROM_LOAD( "gal16v8-25hb1.u58", 0x0800, 0x0117, NO_DUMP ) /* Protected */
ROM_LOAD( "palce20v8h-15pc-4.u38", 0x1000, 0x0157, NO_DUMP ) /* Protected */
ROM_END
/* GAME drivers */
GAME( 1993, bestleag, bigstrik, bestleag, bestleag, bestleag_state, empty_init, ROT0, "bootleg", "Best League (bootleg of Big Striker, Italian Serie A)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
GAME( 1993, bestleaw, bigstrik, bestleaw, bestleag, bestleag_state, empty_init, ROT0, "bootleg", "Best League (bootleg of Big Striker, World Cup)", MACHINE_NO_COCKTAIL | MACHINE_SUPPORTS_SAVE )
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: cf4029a4f513c46318ecfb4b85fec4c0
timeCreated: 1540578242
licenseType: Free
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 100100000
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
<!-- XML EXCHANGE TABLE MODEL DECLARATION MODULE -->
<!-- This set of declarations defines the XML version of the Exchange
Table Model as of the date shown in the Formal Public Identifier
(FPI) for this entity.
This set of declarations may be referred to using a public external
entity declaration and reference as shown in the following three
lines:
<!ENTITY % calstblx
PUBLIC "-//OASIS//DTD XML Exchange Table Model 19990315//EN">
%calstblx;
If various parameter entities used within this set of declarations
are to be given non-default values, the appropriate declarations
should be given before calling in this package (i.e., before the
"%calstblx;" reference).
-->
<!-- The motivation for this XML version of the Exchange Table Model
is simply to create an XML version of the SGML Exchange Table
Model. By design, no effort has been made to "improve" the model.
This XML version incorporates the logical bare minimum changes
necessary to make the Exchange Table Model a valid XML DTD.
It has been modified slightly for use in the combined HTML/CALS models
supported by DocBook V4.3 and later.
-->
<!-- The XML version of the Exchange Table Model differs from
the SGML version in the following ways:
The following parameter entities have been removed:
- tbl.table.excep, tbl.hdft.excep, tbl.row.excep, tbl.entry.excep
There are no exceptions in XML. The following normative statement
is made in lieu of exceptions: the exchange table model explicitly
forbids a table from occurring within another table. If the
content model of an entry includes a table element, then this
cannot be enforced by the DTD, but it is a deviation from the
exchange table model to include a table within a table.
- tbl.hdft.name, tbl.hdft.mdl, tbl.hdft.excep, tbl.hdft.att
The motivation for these elements was to change the table
header/footer elements. Since XML does not allow element declarations
to contain name groups, and the exchange table model does not
allow a table to contain footers, the continued presence of these
attributes seems unnecessary.
The following parameter entity has been added:
- tbl.thead.att
This entity parameterizes the attributes on thead. It replaces
the tbl.hdft.att parameter entity.
Other miscellaneous changes:
- Tag ommission indicators have been removed
- Comments have been removed from declarations
- NUMBER attributes have been changed to NMTOKEN
- NUTOKEN attributes have been to changed to NMTOKEN
- Removed the grouping characters around the content model
parameter entry for the 'entry' element. This is necessary
so that an entry can contain #PCDATA and be defined as an
optional, repeatable OR group beginning with #PCDATA.
-->
<!-- This entity includes a set of element and attribute declarations
that partially defines the Exchange table model. However, the model
is not well-defined without the accompanying natural language
description of the semantics (meanings) of these various elements,
attributes, and attribute values. The semantic writeup, also available
from SGML Open, should be used in conjunction with this entity.
-->
<!-- In order to use the Exchange table model, various parameter entity
declarations are required. A brief description is as follows:
ENTITY NAME WHERE USED WHAT IT IS
%yesorno In ATTLIST of: An attribute declared value
almost all elements for a "boolean" attribute
%paracon In content model of: The "text" (logical content)
<entry> of the model group for <entry>
%titles In content model of: The "title" part of the model
table element group for the table element
%tbl.table.name In declaration of: The name of the "table"
table element element
%tbl.table-titles.mdl In content model of: The model group for the title
table elements part of the content model for
table element
%tbl.table.mdl In content model of: The model group for the content
table elements model for table element,
often (and by default) defined
in terms of %tbl.table-titles.mdl
and tgroup
%tbl.table.att In ATTLIST of: Additional attributes on the
table element table element
%bodyatt In ATTLIST of: Additional attributes on the
table element table element (for backward
compatibility with the SGML
model)
%tbl.tgroup.mdl In content model of: The model group for the content
<tgroup> model for <tgroup>
%tbl.tgroup.att In ATTLIST of: Additional attributes on the
<tgroup> <tgroup> element
%tbl.thead.att In ATTLIST of: Additional attributes on the
<thead> <thead> element
%tbl.tbody.att In ATTLIST of: Additional attributes on the
<tbody> <tbody> element
%tbl.colspec.att In ATTLIST of: Additional attributes on the
<colspec> <colspec> element
%tbl.row.mdl In content model of: The model group for the content
<row> model for <row>
%tbl.row.att In ATTLIST of: Additional attributes on the
<row> <row> element
%tbl.entry.mdl In content model of: The model group for the content
<entry> model for <entry>
%tbl.entry.att In ATTLIST of: Additional attributes on the
<entry> <entry> element
This set of declarations will use the default definitions shown below
for any of these parameter entities that are not declared before this
set of declarations is referenced.
-->
<!-- These definitions are not directly related to the table model, but are
used in the default CALS table model and may be defined elsewhere (and
prior to the inclusion of this table module) in the referencing DTD. -->
<!ENTITY % yesorno 'NMTOKEN'> <!-- no if zero(s), yes if any other value -->
<!ENTITY % titles 'title?'>
<!ENTITY % pcd "#PCDATA">
<!ENTITY % paracon '%pcd;'> <!-- default for use in entry content -->
<!--
The parameter entities as defined below change and simplify the CALS table
model as published (as part of the Example DTD) in MIL-HDBK-28001. The
resulting simplified DTD has support from the SGML Open vendors and is
therefore more interoperable among different systems.
These following declarations provide the Exchange default definitions
for these entities. However, these entities can be redefined (by giving
the appropriate parameter entity declaration(s) prior to the reference
to this Table Model declaration set entity) to fit the needs of the
current application.
Note, however, that changes may have significant effect on the ability to
interchange table information. These changes may manifest themselves
in useability, presentation, and possible structure information degradation.
-->
<!ENTITY % tbl.table.name "table">
<!ENTITY % tbl.table-titles.mdl "%titles;,">
<!ENTITY % tbl.table-main.mdl "tgroup+">
<!ENTITY % tbl.table.mdl "%tbl.table-titles.mdl; %tbl.table-main.mdl;">
<!ENTITY % tbl.table.att "
pgwide %yesorno; #IMPLIED ">
<!ENTITY % bodyatt "">
<!ENTITY % tbl.tgroup.mdl "colspec*,thead?,tbody">
<!ENTITY % tbl.tgroup.att "">
<!ENTITY % tbl.thead.att "">
<!ENTITY % tbl.tbody.att "">
<!ENTITY % tbl.colspec.att "">
<!ENTITY % tbl.row.mdl "entry+">
<!ENTITY % tbl.row.att "">
<!ENTITY % tbl.entry.mdl "(%paracon;)*">
<!ENTITY % tbl.entry.att "">
<!ENTITY % tbl.frame.attval "top|bottom|topbot|all|sides|none">
<!ENTITY % tbl.tbody.mdl "row+">
<!-- ===== Element and attribute declarations follow. ===== -->
<!--
Default declarations previously defined in this entity and
referenced below include:
ENTITY % tbl.table.name "table"
ENTITY % tbl.table-titles.mdl "%titles;,"
ENTITY % tbl.table.mdl "%tbl.table-titles; tgroup+"
ENTITY % tbl.table.att "
pgwide %yesorno; #IMPLIED "
-->
<!--doc:???-->
<!ELEMENT %tbl.table.name; (%tbl.table.mdl;)>
<!ATTLIST %tbl.table.name;
frame (%tbl.frame.attval;) #IMPLIED
colsep %yesorno; #IMPLIED
rowsep %yesorno; #IMPLIED
%tbl.table.att;
%bodyatt;
>
<!--
Default declarations previously defined in this entity and
referenced below include:
ENTITY % tbl.tgroup.mdl "colspec*,thead?,tbody"
ENTITY % tbl.tgroup.att ""
-->
<!--doc:A wrapper for the main content of a table, or part of a table.-->
<!ELEMENT tgroup (%tbl.tgroup.mdl;) >
<!ATTLIST tgroup
cols NMTOKEN #REQUIRED
colsep %yesorno; #IMPLIED
rowsep %yesorno; #IMPLIED
align (left|right|center|justify|char) #IMPLIED
%tbl.tgroup.att;
>
<!--
Default declarations previously defined in this entity and
referenced below include:
ENTITY % tbl.colspec.att ""
-->
<!--doc:Specifications for a column in a table.-->
<!ELEMENT colspec EMPTY >
<!ATTLIST colspec
colnum NMTOKEN #IMPLIED
colname NMTOKEN #IMPLIED
colwidth CDATA #IMPLIED
colsep %yesorno; #IMPLIED
rowsep %yesorno; #IMPLIED
align (left|right|center|justify|char) #IMPLIED
char CDATA #IMPLIED
charoff NMTOKEN #IMPLIED
%tbl.colspec.att;
>
<!--
Default declarations previously defined in this entity and
referenced below include:
ENTITY % tbl.thead.att ""
-->
<!--doc:A table header consisting of one or more rows.-->
<!ELEMENT thead (row+)>
<!ATTLIST thead
valign (top|middle|bottom) #IMPLIED
%tbl.thead.att;
>
<!--
Default declarations previously defined in this entity and
referenced below include:
ENTITY % tbl.tbody.att ""
-->
<!--doc:A wrapper for the rows of a table or informal table.-->
<!ELEMENT tbody (%tbl.tbody.mdl;)>
<!ATTLIST tbody
valign (top|middle|bottom) #IMPLIED
%tbl.tbody.att;
>
<!--
Default declarations previously defined in this entity and
referenced below include:
ENTITY % tbl.row.mdl "entry+"
ENTITY % tbl.row.att ""
-->
<!--doc:A row in a table.-->
<!ELEMENT row (%tbl.row.mdl;)>
<!ATTLIST row
rowsep %yesorno; #IMPLIED
valign (top|middle|bottom) #IMPLIED
%tbl.row.att;
>
<!--
Default declarations previously defined in this entity and
referenced below include:
ENTITY % paracon "#PCDATA"
ENTITY % tbl.entry.mdl "(%paracon;)*"
ENTITY % tbl.entry.att ""
-->
<!--doc:A cell in a table.-->
<!ELEMENT entry (%tbl.entry.mdl;)*>
<!ATTLIST entry
colname NMTOKEN #IMPLIED
namest NMTOKEN #IMPLIED
nameend NMTOKEN #IMPLIED
morerows NMTOKEN #IMPLIED
colsep %yesorno; #IMPLIED
rowsep %yesorno; #IMPLIED
align (left|right|center|justify|char) #IMPLIED
char CDATA #IMPLIED
charoff NMTOKEN #IMPLIED
valign (top|middle|bottom) #IMPLIED
%tbl.entry.att;
>
| {
"pile_set_name": "Github"
} |
{
"static_ExecuteCallThatAskForeGasThenTrabsactionHas_d1g0v0_Istanbul" : {
"_info" : {
"comment" : "",
"filling-rpc-server" : "Geth-1.9.6-unstable-63b18027-20190920",
"filling-tool-version" : "retesteth-0.0.1+commit.0ae18aef.Linux.g++",
"lllcversion" : "Version: 0.5.12-develop.2019.9.13+commit.2d601a4f.Linux.g++",
"source" : "src/GeneralStateTestsFiller/stStaticCall/static_ExecuteCallThatAskForeGasThenTrabsactionHasFiller.json",
"sourceHash" : "475b0ab4012d67ba79ff0ff6aa83db0b2e2c6a4dbf42df2f47515070e84f7e35"
},
"genesisBlockHeader" : {
"bloom" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"difficulty" : "0x20000",
"extraData" : "0x00",
"gasLimit" : "0x989680",
"gasUsed" : "0x0",
"hash" : "0xa24ec945cd7aab21fc763f59975e791cebbaa85c5e73d9c6465a43472f06cdbd",
"mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce" : "0x0000000000000000",
"number" : "0x0",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"receiptTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot" : "0xa4eac9ca82ed97c43576a98c564a6f0fd6ee31c7d6c35acf70df2c7889ece3b2",
"timestamp" : "0x0",
"transactionsTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"pre" : {
"0x1000000000000000000000000000000000000001" : {
"balance" : "0x0186a0",
"code" : "0x600160015200",
"nonce" : "0x00",
"storage" : {
}
},
"0x2000000000000000000000000000000000000001" : {
"balance" : "0x0186a0",
"code" : "0x5b61c3506080511015601c5760013b506001608051016080526000565b00",
"nonce" : "0x00",
"storage" : {
}
},
"0x3000000000000000000000000000000000000001" : {
"balance" : "0x0186a0",
"code" : "0x600160015500",
"nonce" : "0x00",
"storage" : {
}
},
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x0186a0",
"code" : "0x",
"nonce" : "0x00",
"storage" : {
}
},
"0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x00",
"code" : "0x6000600060006000600035620927c0fa60015500",
"nonce" : "0x00",
"storage" : {
}
}
},
"postState" : {
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"code" : "0x",
"nonce" : "0x01",
"balance" : "0x00",
"storage" : {
}
},
"0x1000000000000000000000000000000000000001" : {
"code" : "0x600160015200",
"nonce" : "0x00",
"balance" : "0x0186a0",
"storage" : {
}
},
"0x3000000000000000000000000000000000000001" : {
"code" : "0x600160015500",
"nonce" : "0x00",
"balance" : "0x0186a0",
"storage" : {
}
},
"0x2000000000000000000000000000000000000001" : {
"code" : "0x5b61c3506080511015601c5760013b506001608051016080526000565b00",
"nonce" : "0x00",
"balance" : "0x0186a0",
"storage" : {
}
},
"0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" : {
"code" : "0x",
"nonce" : "0x00",
"balance" : "0x1bc16d674ec986a0",
"storage" : {
}
},
"0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"code" : "0x6000600060006000600035620927c0fa60015500",
"nonce" : "0x00",
"balance" : "0x00",
"storage" : {
}
}
},
"network" : "Istanbul",
"sealEngine" : "NoProof",
"lastblockhash" : "0x1e2ecb25d1fd673d42c1530e421646dd5b46ee1246f82dde1f2fff5042c7846a",
"genesisRLP" : "0xf901f8f901f3a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa0a4eac9ca82ed97c43576a98c564a6f0fd6ee31c7d6c35acf70df2c7889ece3b2a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083989680808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0",
"blocks" : [
{
"rlp" : "0xf90280f901f8a0a24ec945cd7aab21fc763f59975e791cebbaa85c5e73d9c6465a43472f06cdbda01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa0d3243a44929fa04b250903e275edd8ec03b132eb9cf9d44e0f02af296ec96005a090457849e6d55702554ad7bea287d6cecdf065d57ba49808bbf7fcddc809dd7ca0777f1c1c378807634128348e4f0eeca6a0e7f516ea411690ca04266323f671a4b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000018398bca4830186a08203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f882f8808001830186a094b94f5374fce5edbc8e2a8697c15331677e6ebf0b80a000000000000000000000000020000000000000000000000000000000000000011ca026abe17dd0003b6e9a26e9c457ccf1553af623d87e2e85adad1b730522c18a91a04fd51ef1b46ffeafd83e621102443bfb55867bf3da499f7c703f5bf99592e0c5c0",
"blockHeader" : {
"bloom" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"difficulty" : "0x20000",
"extraData" : "0x00",
"gasLimit" : "0x98bca4",
"gasUsed" : "0x186a0",
"hash" : "0x1e2ecb25d1fd673d42c1530e421646dd5b46ee1246f82dde1f2fff5042c7846a",
"mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce" : "0x0000000000000000",
"number" : "0x1",
"parentHash" : "0xa24ec945cd7aab21fc763f59975e791cebbaa85c5e73d9c6465a43472f06cdbd",
"receiptTrie" : "0x777f1c1c378807634128348e4f0eeca6a0e7f516ea411690ca04266323f671a4",
"stateRoot" : "0xd3243a44929fa04b250903e275edd8ec03b132eb9cf9d44e0f02af296ec96005",
"timestamp" : "0x3e8",
"transactionsTrie" : "0x90457849e6d55702554ad7bea287d6cecdf065d57ba49808bbf7fcddc809dd7c",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"transactions" : [
{
"data" : "0x0000000000000000000000002000000000000000000000000000000000000001",
"gasLimit" : "0x0186a0",
"gasPrice" : "0x01",
"nonce" : "0x00",
"to" : "0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "0x00",
"v" : "0x1c",
"r" : "0x26abe17dd0003b6e9a26e9c457ccf1553af623d87e2e85adad1b730522c18a91",
"s" : "0x4fd51ef1b46ffeafd83e621102443bfb55867bf3da499f7c703f5bf99592e0c5"
}
]
}
]
},
"static_ExecuteCallThatAskForeGasThenTrabsactionHas_d2g0v0_Istanbul" : {
"_info" : {
"comment" : "",
"filling-rpc-server" : "Geth-1.9.6-unstable-63b18027-20190920",
"filling-tool-version" : "retesteth-0.0.1+commit.0ae18aef.Linux.g++",
"lllcversion" : "Version: 0.5.12-develop.2019.9.13+commit.2d601a4f.Linux.g++",
"source" : "src/GeneralStateTestsFiller/stStaticCall/static_ExecuteCallThatAskForeGasThenTrabsactionHasFiller.json",
"sourceHash" : "475b0ab4012d67ba79ff0ff6aa83db0b2e2c6a4dbf42df2f47515070e84f7e35"
},
"genesisBlockHeader" : {
"bloom" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"difficulty" : "0x20000",
"extraData" : "0x00",
"gasLimit" : "0x989680",
"gasUsed" : "0x0",
"hash" : "0xa24ec945cd7aab21fc763f59975e791cebbaa85c5e73d9c6465a43472f06cdbd",
"mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce" : "0x0000000000000000",
"number" : "0x0",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"receiptTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot" : "0xa4eac9ca82ed97c43576a98c564a6f0fd6ee31c7d6c35acf70df2c7889ece3b2",
"timestamp" : "0x0",
"transactionsTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"pre" : {
"0x1000000000000000000000000000000000000001" : {
"balance" : "0x0186a0",
"code" : "0x600160015200",
"nonce" : "0x00",
"storage" : {
}
},
"0x2000000000000000000000000000000000000001" : {
"balance" : "0x0186a0",
"code" : "0x5b61c3506080511015601c5760013b506001608051016080526000565b00",
"nonce" : "0x00",
"storage" : {
}
},
"0x3000000000000000000000000000000000000001" : {
"balance" : "0x0186a0",
"code" : "0x600160015500",
"nonce" : "0x00",
"storage" : {
}
},
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x0186a0",
"code" : "0x",
"nonce" : "0x00",
"storage" : {
}
},
"0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x00",
"code" : "0x6000600060006000600035620927c0fa60015500",
"nonce" : "0x00",
"storage" : {
}
}
},
"postState" : {
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"code" : "0x",
"nonce" : "0x01",
"balance" : "0x00",
"storage" : {
}
},
"0x1000000000000000000000000000000000000001" : {
"code" : "0x600160015200",
"nonce" : "0x00",
"balance" : "0x0186a0",
"storage" : {
}
},
"0x3000000000000000000000000000000000000001" : {
"code" : "0x600160015500",
"nonce" : "0x00",
"balance" : "0x0186a0",
"storage" : {
}
},
"0x2000000000000000000000000000000000000001" : {
"code" : "0x5b61c3506080511015601c5760013b506001608051016080526000565b00",
"nonce" : "0x00",
"balance" : "0x0186a0",
"storage" : {
}
},
"0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" : {
"code" : "0x",
"nonce" : "0x00",
"balance" : "0x1bc16d674ec986a0",
"storage" : {
}
},
"0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"code" : "0x6000600060006000600035620927c0fa60015500",
"nonce" : "0x00",
"balance" : "0x00",
"storage" : {
}
}
},
"network" : "Istanbul",
"sealEngine" : "NoProof",
"lastblockhash" : "0xd67567980ceaf5f8da53a14a50ef56a64406bc0d097101ca7c3f4c68bc543e68",
"genesisRLP" : "0xf901f8f901f3a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa0a4eac9ca82ed97c43576a98c564a6f0fd6ee31c7d6c35acf70df2c7889ece3b2a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083989680808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0",
"blocks" : [
{
"rlp" : "0xf90280f901f8a0a24ec945cd7aab21fc763f59975e791cebbaa85c5e73d9c6465a43472f06cdbda01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa0d3243a44929fa04b250903e275edd8ec03b132eb9cf9d44e0f02af296ec96005a0480d8fc02b661270d1c5af10cc38f0f7fead1203538774871a7762574ee8014ca0777f1c1c378807634128348e4f0eeca6a0e7f516ea411690ca04266323f671a4b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000018398bca4830186a08203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f882f8808001830186a094b94f5374fce5edbc8e2a8697c15331677e6ebf0b80a000000000000000000000000030000000000000000000000000000000000000011ba00b979a3eba9db3e6bc375a823ec923a7d8d81b54912ccc5ab939dd4696e8c131a071edc4e5a8ca9b4ef806678db93773c4dc6b0db5cb826289e2bc354953c09a7fc0",
"blockHeader" : {
"bloom" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"difficulty" : "0x20000",
"extraData" : "0x00",
"gasLimit" : "0x98bca4",
"gasUsed" : "0x186a0",
"hash" : "0xd67567980ceaf5f8da53a14a50ef56a64406bc0d097101ca7c3f4c68bc543e68",
"mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce" : "0x0000000000000000",
"number" : "0x1",
"parentHash" : "0xa24ec945cd7aab21fc763f59975e791cebbaa85c5e73d9c6465a43472f06cdbd",
"receiptTrie" : "0x777f1c1c378807634128348e4f0eeca6a0e7f516ea411690ca04266323f671a4",
"stateRoot" : "0xd3243a44929fa04b250903e275edd8ec03b132eb9cf9d44e0f02af296ec96005",
"timestamp" : "0x3e8",
"transactionsTrie" : "0x480d8fc02b661270d1c5af10cc38f0f7fead1203538774871a7762574ee8014c",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"transactions" : [
{
"data" : "0x0000000000000000000000003000000000000000000000000000000000000001",
"gasLimit" : "0x0186a0",
"gasPrice" : "0x01",
"nonce" : "0x00",
"to" : "0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "0x00",
"v" : "0x1b",
"r" : "0x0b979a3eba9db3e6bc375a823ec923a7d8d81b54912ccc5ab939dd4696e8c131",
"s" : "0x71edc4e5a8ca9b4ef806678db93773c4dc6b0db5cb826289e2bc354953c09a7f"
}
]
}
]
},
"static_ExecuteCallThatAskForeGasThenTrabsactionHas_d0g0v0_Istanbul" : {
"_info" : {
"comment" : "",
"filling-rpc-server" : "Geth-1.9.6-unstable-63b18027-20190920",
"filling-tool-version" : "retesteth-0.0.1+commit.0ae18aef.Linux.g++",
"lllcversion" : "Version: 0.5.12-develop.2019.9.13+commit.2d601a4f.Linux.g++",
"source" : "src/GeneralStateTestsFiller/stStaticCall/static_ExecuteCallThatAskForeGasThenTrabsactionHasFiller.json",
"sourceHash" : "475b0ab4012d67ba79ff0ff6aa83db0b2e2c6a4dbf42df2f47515070e84f7e35"
},
"genesisBlockHeader" : {
"bloom" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"difficulty" : "0x20000",
"extraData" : "0x00",
"gasLimit" : "0x989680",
"gasUsed" : "0x0",
"hash" : "0xa24ec945cd7aab21fc763f59975e791cebbaa85c5e73d9c6465a43472f06cdbd",
"mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce" : "0x0000000000000000",
"number" : "0x0",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"receiptTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot" : "0xa4eac9ca82ed97c43576a98c564a6f0fd6ee31c7d6c35acf70df2c7889ece3b2",
"timestamp" : "0x0",
"transactionsTrie" : "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"pre" : {
"0x1000000000000000000000000000000000000001" : {
"balance" : "0x0186a0",
"code" : "0x600160015200",
"nonce" : "0x00",
"storage" : {
}
},
"0x2000000000000000000000000000000000000001" : {
"balance" : "0x0186a0",
"code" : "0x5b61c3506080511015601c5760013b506001608051016080526000565b00",
"nonce" : "0x00",
"storage" : {
}
},
"0x3000000000000000000000000000000000000001" : {
"balance" : "0x0186a0",
"code" : "0x600160015500",
"nonce" : "0x00",
"storage" : {
}
},
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x0186a0",
"code" : "0x",
"nonce" : "0x00",
"storage" : {
}
},
"0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x00",
"code" : "0x6000600060006000600035620927c0fa60015500",
"nonce" : "0x00",
"storage" : {
}
}
},
"postState" : {
"0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"code" : "0x",
"nonce" : "0x01",
"balance" : "0xe2fd",
"storage" : {
}
},
"0x1000000000000000000000000000000000000001" : {
"code" : "0x600160015200",
"nonce" : "0x00",
"balance" : "0x0186a0",
"storage" : {
}
},
"0x3000000000000000000000000000000000000001" : {
"code" : "0x600160015500",
"nonce" : "0x00",
"balance" : "0x0186a0",
"storage" : {
}
},
"0x2000000000000000000000000000000000000001" : {
"code" : "0x5b61c3506080511015601c5760013b506001608051016080526000565b00",
"nonce" : "0x00",
"balance" : "0x0186a0",
"storage" : {
}
},
"0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" : {
"code" : "0x",
"nonce" : "0x00",
"balance" : "0x1bc16d674ec8a3a3",
"storage" : {
}
},
"0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"code" : "0x6000600060006000600035620927c0fa60015500",
"nonce" : "0x00",
"balance" : "0x00",
"storage" : {
"0x01" : "0x01"
}
}
},
"network" : "Istanbul",
"sealEngine" : "NoProof",
"lastblockhash" : "0xaaac1f0d2ec15e842d334ab023496fc3f93ff253ec2f13c744447bf53815759e",
"genesisRLP" : "0xf901f8f901f3a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa0a4eac9ca82ed97c43576a98c564a6f0fd6ee31c7d6c35acf70df2c7889ece3b2a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000830200008083989680808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0",
"blocks" : [
{
"rlp" : "0xf9027ff901f7a0a24ec945cd7aab21fc763f59975e791cebbaa85c5e73d9c6465a43472f06cdbda01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa0d9b315dc575cd334cbdfbde4045561536393a3372aa2a84d86b12501221e5808a040f4acede2431c34d4e75f40b1287e81bd0775ea04f0eb6e503c852b115e51a5a098cc8f9e7ba5ade68635cfffa07de2254f72364530be8d65c7dcdc8bf8bce676b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000018398bca482a3a38203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f882f8808001830186a094b94f5374fce5edbc8e2a8697c15331677e6ebf0b80a000000000000000000000000010000000000000000000000000000000000000011ca057d3ba4141ee46e4493e903aea5a8669d26265671e15c8369052a9e2633596e2a0526175ee3c34982de8dbe982e1f925e747dc64ecbb3412f739cffffede09b961c0",
"blockHeader" : {
"bloom" : "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"difficulty" : "0x20000",
"extraData" : "0x00",
"gasLimit" : "0x98bca4",
"gasUsed" : "0xa3a3",
"hash" : "0xaaac1f0d2ec15e842d334ab023496fc3f93ff253ec2f13c744447bf53815759e",
"mixHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce" : "0x0000000000000000",
"number" : "0x1",
"parentHash" : "0xa24ec945cd7aab21fc763f59975e791cebbaa85c5e73d9c6465a43472f06cdbd",
"receiptTrie" : "0x98cc8f9e7ba5ade68635cfffa07de2254f72364530be8d65c7dcdc8bf8bce676",
"stateRoot" : "0xd9b315dc575cd334cbdfbde4045561536393a3372aa2a84d86b12501221e5808",
"timestamp" : "0x3e8",
"transactionsTrie" : "0x40f4acede2431c34d4e75f40b1287e81bd0775ea04f0eb6e503c852b115e51a5",
"uncleHash" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"transactions" : [
{
"data" : "0x0000000000000000000000001000000000000000000000000000000000000001",
"gasLimit" : "0x0186a0",
"gasPrice" : "0x01",
"nonce" : "0x00",
"to" : "0xb94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "0x00",
"v" : "0x1c",
"r" : "0x57d3ba4141ee46e4493e903aea5a8669d26265671e15c8369052a9e2633596e2",
"s" : "0x526175ee3c34982de8dbe982e1f925e747dc64ecbb3412f739cffffede09b961"
}
]
}
]
}
} | {
"pile_set_name": "Github"
} |
# [684. 冗余连接](https://leetcode-cn.com/problems/redundant-connection)
[English Version](/solution/0600-0699/0684.Redundant%20Connection/README_EN.md)
## 题目描述
<!-- 这里写题目描述 -->
<p>在本问题中, 树指的是一个连通且无环的<strong>无向</strong>图。</p>
<p>输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。</p>
<p>结果图是一个以<code>边</code>组成的二维数组。每一个<code>边</code>的元素是一对<code>[u, v]</code> ,满足 <code>u < v</code>,表示连接顶点<code>u</code> 和<code>v</code>的<strong>无向</strong>图的边。</p>
<p>返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 <code>[u, v]</code> 应满足相同的格式 <code>u < v</code>。</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> [[1,2], [1,3], [2,3]]
<strong>输出:</strong> [2,3]
<strong>解释:</strong> 给定的无向图为:
1
/ \
2 - 3
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> [[1,2], [2,3], [3,4], [1,4], [1,5]]
<strong>输出:</strong> [1,4]
<strong>解释:</strong> 给定的无向图为:
5 - 1 - 2
| |
4 - 3
</pre>
<p><strong>注意:</strong></p>
<ul>
<li>输入的二维数组大小在 3 到 1000。</li>
<li>二维数组中的整数在1到N之间,其中N是输入数组的大小。</li>
</ul>
<p><strong>更新(2017-09-26):</strong><br>
我们已经重新检查了问题描述及测试用例,明确图是<em><strong>无向 </strong></em>图。对于有向图详见<strong><a href="https://leetcodechina.com/problems/redundant-connection-ii/description/">冗余连接II</a>。</strong>对于造成任何不便,我们深感歉意。</p>
## 解法
<!-- 这里可写通用的实现逻辑 -->
<!-- tabs:start -->
### **Python3**
<!-- 这里可写当前语言的特殊实现逻辑 -->
```python
```
### **Java**
<!-- 这里可写当前语言的特殊实现逻辑 -->
```java
```
### **...**
```
```
<!-- tabs:end --> | {
"pile_set_name": "Github"
} |
let list = [
{ id: 1, title: '一级' },
{ id: 2, title: '二级' },
{ id: 3, title: '三级', disabled: true },
{ id: 10, title: '一级-0', parent: '1' },
{ id: 11, title: '一级-1', parent: '1' },
{ id: 12, title: '一级-2', parent: '1' },
{ id: 13, title: '一级-3', parent: '1' },
{ id: 14, title: '一级-4', parent: '1' },
{ id: 101, title: '一级-0-1', parent: '10' },
{ id: 102, title: '一级-0-2', parent: '10' },
{ id: 103, title: '一级-0-3', parent: '10' },
{ id: 20, title: '二级-0', parent: '2' },
{ id: 21, title: '二级-1', parent: '2' },
{ id: 22, title: '二级-2', parent: '2' },
{ id: 23, title: '二级-3', parent: '2' },
{ id: 24, title: '二级-4', parent: '2' },
{ id: 30, title: '三级-0', parent: '3' },
{ id: 31, title: '三级-1', parent: '3' },
{ id: 32, title: '三级-2', parent: '3' },
{ id: 33, title: '三级-3', parent: '3' }
];
export default function () {
return {
simple: {
title: '测试',
keyName: 'id',
parentName: 'parent',
titleName: 'title',
dataMode: 'list',
datas() {
return list;
}
}
};
};
| {
"pile_set_name": "Github"
} |
:020000040800F2
:10000000C8080020310200080D1E00080F1E00085D
:10001000111E0008131E0008151E00080000000035
:10002000000000000000000000000000171E000893
:10003000191E0008000000001B1E00081F1E0008FB
:100040004B0200084B0200084B0200084B0200085C
:100050004B0200084B0200084B0200084B0200084C
:100060004B0200084B0200084B0200084B0200083C
:100070004B0200084B0200084B0200084B0200082C
:100080004B0200084B0200084B0200084B0200081C
:100090004B0200084B0200084B0200084B0200080C
:1000A0004B0200084B0200084B0200084B020008FC
:1000B0004B0200084B0200084B0200084B020008EC
:1000C0004B0200084B0200084B0200084B020008DC
:1000D0004B0200084B0200084B0200084B020008CC
:1000E0004B0200084B0200084B0200084B020008BC
:1000F0004B0200084B0200084B0200084B020008AC
:100100004B0200084B0200084B0200084B0200089B
:100110004B0200084B0200084B0200084B0200088B
:100120004B0200084B0200084B0200084B0200087B
:100130004B0200084B0200084B0200084B0200086B
:100140004B0200084B0200084B0200084B0200085B
:100150004B0200084B0200084B0200084B0200084B
:100160004B0200084B0200084B0200084B0200083B
:100170004B0200084B0200084B0200084B0200082B
:100180004B0200084B02000800F002F800F040F8B3
:100190000AA090E8000C82448344AAF10107DA45E2
:1001A00001D100F035F8AFF2090EBAE80F0013F0F4
:1001B000010F18BFFB1A43F0010318472424000065
:1001C00044240000103A24BF78C878C1FAD85207F6
:1001D00024BF30C830C144BF04680C6070470000C1
:1001E0000023002400250026103A28BF78C1FBD840
:1001F000520728BF30C148BF0B6070471FB502F0DF
:1002000027F89DE8030001F045FF1FBD10B510BDA4
:1002100001F09CFF1146FFF7F1FF01F0B5FD01F081
:10022000BAFF03B4FFF7F2FF03BC01F0EBFF0000DD
:100230000948804709480047FEE7FEE7FEE7FEE77A
:10024000FEE7FEE7FEE7FEE7FEE7FEE704480549B6
:10025000054A064B70470000CB1E000889010008C4
:10026000C8020020C8080020C8040020C8040020DC
:10027000F848016841F001010160F64A00210832A6
:1002800011600268F44B1A400260031DF34A1A60C1
:10029000F04BF34A84331A60F04A103A1B1D1A607F
:1002A000026822F480220260EA480C300160181DC6
:1002B00001607047E7490022891C0A700870704786
:1002C00002460020510901290CD002290CD0E14935
:1002D0007431096802F01F02012393400B4200D0E1
:1002E00001207047DB49F4E7DA497031F1E718B5CE
:1002F00000204FF4A04400903120FFF7E1FF009967
:10030000491C0091A14201D00028F5D03120FFF70F
:10031000D7FF002800D0012018BDCE4A116821F077
:10032000F80141EAC00010607047CE49086070478C
:10033000C849002270310A700A70012802D00428CE
:1003400001D1052008707047C7490860704741EA2D
:1003500082115A0810B5C54B029C03EB02421143AF
:10036000014341EA0460BB49091D086010BDBD4955
:1003700008667047800140EA0170B6498431086020
:100380007047B84988667047800140EA0160B1490A
:1003900040EA0270883108607047B24908677047C8
:1003A000B049C8647047AB4B08331A68084322F061
:1003B000EC62104318607047A64B08331A68084374
:1003C00022F07842104318607047A24A0832116840
:1003D00021F003010143116070479E480830006816
:1003E00000F00C0070479B4A0832116821F0F001C0
:1003F000014311607047974A0832116821F4E051B7
:10040000014311607047934A0832116821F460413A
:1004100041EAC0001060704770B58E4B0833196810
:10042000934C11F00C0104D0924E042903D00829FA
:1004300003D004601BE0066019E0864A121D1168B3
:10044000C1F38055116801F03F0115B1B6FBF1F120
:1004500001E0B4FBF1F114681268C4F3881461433D
:10046000C2F30142521C5200B1FBF2F10160196863
:100470000F2202EA1111804A545C0168E140416098
:100480001C68072505EA9424145D21FA04F48460AD
:100490001B6805EA5333D25CD140C16070BDC0F324
:1004A0000121032908D16B4B08331968734A21F4E1
:1004B000F81102400A431A60664970310A68C0F3B5
:1004C0000B0002430A60704767494439086070476F
:1004D00065494039086070476249C1F85C0170475E
:1004E0005C4A8C32116821F440110143116070475D
:1004F000584A8C32116821F4400101431160704761
:10050000544A8C321168401E21F01F0101431160D2
:100510007047504A8C3211686FF0FF0321F4F85194
:1005200003EB00200843106070474A4A8C32116880
:1005300021F440310143116070475149C1F8E00195
:100540007047444A30320029116801D0014300E06D
:100550008143116070473F4A34320029116801D04D
:10056000014300E08143116070473A4A3832002964
:10057000116801D0014300E0814311607047354AA2
:1005800040320029116801D0014300E0814311602D
:100590007047304A44320029116801D0014300E01D
:1005A0008143116070472B4A10320029116801D035
:1005B000014300E0814311607047264A143200294C
:1005C000116801D0014300E0814311607047214A66
:1005D00018320029116801D0014300E08143116005
:1005E00070471C4A20320029116801D0014300E005
:1005F000814311607047174A24320029116801D0E5
:10060000014300E0814311607047124A50320029D3
:10061000116801D0014300E08143116070470D4A29
:1006200054320029116801D0014300E08143116078
:100630007047084A58320029116801D0014300E090
:10064000814311607047034A60320029116819D054
:10065000014318E000380240FFFFF6EA10300024A2
:100660000030002000004742800E47420000FFFF9C
:100670000024F40040787D0100000020FFFCFF0F03
:1006800000104742814311607047194A00291168E0
:1006900001D0014300E081431160704714490C31DF
:1006A0000128086803D020F008000860704740F077
:1006B0000800FAE70E4A573A0029117801D00143A1
:1006C00000E081431170704709481030016841F023
:1006D0008071016070470146054A0020583A12684F
:1006E0000A4200D00120704701495639087070470E
:1006F00064380240774910B5884206D10121084686
:10070000FFF751FF002101205BE07349884206D1C9
:1007100001210220FFF747FF0021022051E06F492D
:10072000884206D101210420FFF73DFF002104206B
:1007300047E06B49884206D101210820FFF733FFCB
:10074000002108203DE06749884206D101211020A0
:10075000FFF729FF0021102033E06349884206D1CA
:1007600001212020FFF71FFF0021202029E05F4901
:10077000884206D101214020FFF715FF00214020CB
:100780001FE05B49884206D101218020FFF70BFF63
:100790000021802015E05749884202D101218415AB
:1007A0000AE05549884202D10121441504E0534929
:1007B00088420AD1012104152046FFF7F4FE0021EA
:1007C0002046BDE81040FFF7EEBE10BDF0B5002298
:1007D00001274FF0030C0B6807FA02F52B40AB42E0
:1007E0002CD1066853000CFA03F4A64306600E7978
:1007F000D0F800E09E4046EA0E0606600E79012E13
:1008000001D0022E12D18668A64386604E79D0F8B8
:1008100008E09E4046EA0E0686604668AE434660A3
:1008200045688E799640B6B235434560C568A543A4
:10083000C560CC799C40C3681C43C460521C102A1C
:10084000C9D3F0BD4FF6FF71016000210171417104
:100850008171C171704708B541F480320092C26164
:10086000C1610099C161C169C069009008BD0246BB
:10087000002012690A4200D001207047006980B24E
:1008800070470246002052690A4200D0012070479A
:10089000406980B2704701837047418370470AB155
:1008A00001837047418370474161704742694A4004
:1008B000426170474B07DB0E9A40C90810B500EB48
:1008C0008100016A0F249C40A1430162016A114327
:1008D000016210BD00000240000402400008024016
:1008E000000C0240001002400014024000180240B8
:1008F000001C024000200240002402400028024068
:10090000C14910B5884202D10121841424E0BF49B5
:10091000884202D10121041404E0BD4988420AD171
:100920000121C4132046FFF75CFE2046BDE81040BD
:100930000021FFF756BEB749884202D10121441475
:100940000AE0B549884202D101210C0504E0B3490F
:1009500088420AD101214C052046FFF74CFE204673
:10096000BDE810400021FFF746BE10BD30B502883B
:100970004C8802F441530A88CD8822438C882C434A
:1009800022430C8922434C8922438C892243CC89FF
:1009900022431A430280828B22F400628283098AF6
:1009A000018230BDF0B502220023858B01244FF275
:1009B0004006354085830284868B8D68022D3DD0AC
:1009C0008A8802B10224964A13681B0203D5136871
:1009D00023F400031360924A7C3213681268C3F355
:1009E00088138F4FC2F302723F1F3D683F6805F0C6
:1009F0003F057F0201D58B4F00E08B4FB7FBF5F52C
:100A00005D43B5FBF2F2CB88B3F5007F2BD06301D9
:100A1000B2FBF3F202EB82028B685200B2FBF3F2FC
:100A2000521D92B20A23B2FBF3F202F00103D21A72
:100A30004FF6FF74C2F34F0204EA0323941EFE2C08
:100A400001D302220023CC881A43144304840A8869
:100A50004B881A438B8889890B431A43324342F4EB
:100A600000618183F0BD120AD4E70021018041803A
:100A70008180C180018141818181C1810721018201
:100A800070470021018041808180C1800222826004
:100A9000818170470029018802D041F0400101E0C6
:100AA00021F04001018070470029818B02D041F480
:100AB000806101E021F4806181837047028822F423
:100AC0000062028002880A4302807047B1F5804FBD
:100AD000018803D021F480410180704741F48041B6
:100AE000FAE7A1F57E420188FF3A02D041F4807115
:100AF00001E021F48071018070470029818802D0D3
:100B000041F0040101E021F00401818070470029D7
:100B1000818802D041F0100101E021F010018180B4
:100B2000704730B5828B00234FF24004224082830D
:100B300002220284848B0A884FF48075B2F5007F0C
:100B400000D002B92B464A888D8889892A431943E7
:100B50000A43224342F40061818330BD808970479B
:100B6000818170470029018802D041F4005101E0E1
:100B700021F4005101807047018841F480510180C7
:100B80007047012901D0008B7047808A7047008A26
:100B90007047002A828801D00A4300E08A4382809D
:100BA0007047090901238B40002A828899B201D03D
:100BB0000A4300E08A43828070470246002012897F
:100BC0000A4200D001207047C9430181704730B507
:100BD00001F00F030125024605FA03F40020A3B239
:100BE000090905FA01F49188A4B2128921401A4238
:100BF00002D0002900D0012030BD01F00F020121F8
:100C00009140C943018170470030014000380040E5
:100C1000003C0040003401400050014000540140BD
:100C20000838024040787D010024F40070B55A482D
:100C30004168491C4160816811B18168491E816029
:100C4000AFF300800024554E18E006EB8405686879
:100C500090B1017B81B1826872B1521E8260696875
:100C60000AD14869096988476868016881606868CD
:100C7000416809B900210173641CE4B23078A042D4
:100C8000E3D870BD464801684FF47A70B1FBF0F0CC
:100C9000401EB0F1807F12D24FF0E0225061414BF4
:100CA000F02083F8140D00209061072010613E4869
:100CB000B1FBF0F13848C160012101707047FEE7D7
:100CC00035480078002805D04FF0E020016941F058
:100CD0000201016170474FF0E020016921F002013B
:100CE000016170472DE9F0472C4C0546DDF8209056
:100CF00020781E4617468846052802D30020BDE806
:100D0000F087182001F050F90028F8D00560C0E9FC
:100D100001850773C0E90469217804EB810148600B
:100D20002178491C2170EAE71C4B30B400211A7865
:100D300006E003EB81046468844203D0491CC9B215
:100D40008A42F6D88A4218D003EB81004068EFF35C
:100D5000108472B605E003EB8102491C9568C9B2A4
:100D600055601A78521E8A42F5DC1978491E1970AE
:100D700004B962B630BC01F046B930BC70470021FE
:100D800001737047012101737047016881607047EA
:100D90004160704701607047100000203C00002057
:100DA000280000200FE000E0C0C62D007CB5012126
:100DB0000420FFF7C6FB00208DF806008DF8070021
:100DC00003208DF805000120C403FA4E8DF80400BD
:100DD000694630460094FFF7F9FC611000916946BE
:100DE0003046FFF7F3FCA510694630460095FFF743
:100DF000EDFC21463046FFF74EFD29463046FFF711
:100E00004AFD0021EC4800F0A4FC7CBD70B5E94E21
:100E100004464FF4005529463046FFF73EFDE64AAA
:100E2000108840060DD510898007FCD01089000677
:100E3000F9D4948110898007FCD010890006F9D478
:100E4000908929463046BDE87040FFF724BDD94A55
:100E5000012808D002280BD1800300290146104642
:100E600004D0FFF718BD4FF48040F6E7FFF715BD3B
:100E7000704708B500210091814201D2491CFAE770
:100E800008BD10B50C4618B1012805D1012100E0BC
:100E900000210120FFF7DBFF2046BDE81040B5E749
:100EA0002DE9F041C54F0024E000B97808308842B0
:100EB00022D3F878B0EBC40F22D344F040010020D5
:100EC000FFF7DFFF387840F080010020FFF7D9FFFF
:100ED000C4EBC4003D7800EB4006DFF8E48208E094
:100EE00005EB8601012018F80110FFF7CAFF6D1C01
:100EF000EDB278788542F3D9641CE4B2062CD3D3E2
:100F000053203870002078702F21B970F870BDE838
:100F1000F08130B5A94C2578A84200D220706078C5
:100F2000824200D96270A078814200D2A170E0783C
:100F3000834200D9E37030BDA04A107151717047EF
:100F400010B580210020FFF79CFF4021BDE8104034
:100F5000002096E710B5FFF7F3FF0020984A0146FE
:100F60004FF4FC731154401C9842FBD300210846F7
:100F7000FFF7E2FF00212F2353220846FFF7C9FFA6
:100F8000BDE810408CE710B50446FFF70FFF0021C5
:100F90000220FFF75CFF42F21070FFF76AFF0121A9
:100FA0000220FFF754FF21210020FFF76AFF1421E0
:100FB0000020FFF766FF7F2C00D97F2444F08001DA
:100FC0000020FFF75EFF20210020FFF75AFF0C21D1
:100FD0000020FFF756FFFFF7B3FF0C210020FFF7BB
:100FE00050FFBDE81040B5E710B5044621210020B0
:100FF000FFF747FF7F2C00D97F2444F080010020B9
:10100000FFF73FFF2021BDE81040002039E730B452
:1010100054281BD2302919D2140001F007034FF0D5
:10102000010202FA03F24FEAD103C3EBC303644D9A
:1010300003EB430300EB8303EC5C01D0144300E0BB
:101040009443EC5430BC0B46024662E730BC704718
:10105000012801D00D2100E00C21002011E72DE92D
:10106000F74F92460746012A17D006204FF0080C8A
:10107000DFF8488198F804100144542907D998F8FA
:101080000520624488F80520002288F80420002604
:1010900007EB4709A0F1010B37E004204FF0060CE5
:1010A000E6E7202F08D3BAF1010F07D0454901EB3D
:1010B0004900304410F8C05C3DB109E0424909EBF9
:1010C0000100304410F8605CF6E70FB1202F1AD110
:1010D000002411E00198012825FA04F01ED098F8A8
:1010E000051040F300022144C9B298F80400521CD4
:1010F000FFF78DFF641CE4B26445EBD398F804104D
:10110000491C88F80410761CF6B25E45C9DB98F8D5
:101110000410491C88F80410BDE8FE8F98F80510EB
:1011200000F001022144C9B298F80400E0E770B56C
:1011300015460E46044604E02A463146641CFFF775
:101140008EFF20780028F7D170BD2DE9F04394463A
:10115000DDF81C901F460C460546604501D9AC469B
:101160001546BC4201D90F461C46BCEB0500A7EB57
:10117000040609D09EB1B0423CDDC0EB46077100C9
:10118000404201EB400832E04A4621462846FFF73C
:101190003EFF641CE4B2A742F6D2BDE8F0834A46A3
:1011A00021462846FFF733FF6D1CEDB2AC45F6D261
:1011B000F3E7000000080240003800402000002053
:1011C000540000205A220008A02400084A46214664
:1011D0002846FFF71CFF6D1CEDB2002F04DD641CD8
:1011E000E4B208EB070001E007EB460007B26545F3
:1011F000ECD11BE0C6EB400C7100404201EB400813
:1012000012E04A4621462846FFF701FF641CE4B27B
:10121000BCF1000F04DD6D1CEDB208EB0C0001E029
:101220000CEB46000FFA80FCBC42EAD14A4621464C
:101230002846BDE8F043EAE62DE9F8411D46079C43
:1012400016460F4680460B460094FFF77EFF424647
:101250002B46394610460094FFF777FF32462B465F
:10126000394610460094FFF770FF2B463246194668
:1012700040460094FFF769FFBDE8F8812DE9F84189
:101280001D4617460C468046079E08E023463A4610
:10129000194640460096FFF758FF641CE4B2AC4282
:1012A000F4D3E9E72DE9FF4F844650001446C0F11E
:1012B000000881B00F460819C2F10106C1B24FF013
:1012C000010900256046049AFFF7A1FE381BC1B250
:1012D0006046049AFFF79BFE0CEB0400C0B239464F
:1012E000049AFFF794FEACEB0400C0B23946049AAE
:1012F00059E0002E08DB08F102000FFA80F8641EA6
:1013000006EB080024B206B209F102000FFA80F9D8
:101310006D1C06EB09002DB206B20CEB050007EBC5
:10132000040A00900AF0FF01C0B2049AFFF76FFEB2
:10133000ACEB050B0AF0FF010BF0FF00049AFFF77E
:1013400066FE0098A7EB040A0AF0FF01C0B2049AF7
:10135000FFF75DFE0AF0FF010BF0FF00049AFFF7B4
:1013600056FE0CEB040007EB050A00900AF0FF01A3
:10137000C0B2049AFFF74BFEACEB040B0AF0FF017E
:101380000BF0FF00049AFFF742FE0098A7EB050A56
:101390000AF0FF01C0B2049AFFF739FE0AF0FF011C
:1013A0000BF0FF00049AFFF732FEA542A1DB05B067
:1013B000BDE8F08F2DE9FE4F804650001446C0F185
:1013C000000A0F460819C2F10106C1B299464FF052
:1013D000010B00251A464046FFF719FE381BC1B223
:1013E0004A464046FFF713FE08EB04000190C0B2E6
:1013F0004A463946FFF70BFEA8EB040C0CF0FF0041
:101400004A463946FFF703FE01983B46C2B2CDF883
:1014100000900CF0FF00194643E0002E08DB0AF1B3
:1014200002000FFA80FA641E06EB0A0024B206B22C
:101430000BF102000FFA80FB6D1C06EB0B002DB2C6
:1014400006B208EB0500C2B20290A8EB0500CDE998
:1014500000903919CBB2C9B2C0B2FFF776FE01983D
:10146000391BC2B20298CBB2CDF80090C9B2C0B25B
:10147000FFF76BFEA8EB04017819CAB20291C3B260
:10148000C1B208EB0400CDE90090C0B2FFF75DFEE9
:101490000299781BCAB2C3B2C1B20198CDF80090CC
:1014A000C0B2FFF752FEA542B7DB35E670471CB568
:1014B00030B1032803D10521FE48FFF7F7FF1CBD1B
:1014C00005210320CDE9000100231A464FF4E04135
:1014D000F94800F06CFB1CBD7CB50525F74E0324D4
:1014E00040B101280CD0032803D10521F448FFF7AF
:1014F000DDFF7CBD00231A464FF4607130460CE0DE
:1015000000231A464FF400613046CDE9004500F053
:101510004EFB0023EB481A46C021CDE9004500F000
:1015200046FB7CBD1CB50522E74C032140B10128D8
:101530000CD0032803D10521E448FFF7B7FF1CBDF9
:10154000CDE9001200231A46642105E0CDE900121E
:1015500000231A464FF4E041204600F028FB1CBD52
:101560001CB50622032140B101280DD0032803D168
:101570000621D748FFF79AFF1CBDCDE900120023D2
:101580001A463821D34806E0CDE9001200231A4656
:101590004FF4E051D04800F00AFB1CBD7CB5052596
:1015A000CC4E032450B1012816D002281AD00328AB
:1015B00003D10521C948FFF779FF7CBD00231A46F6
:1015C0004FF480613046CDE9004500F0F0FA002389
:1015D0001A460C21C04809E000231A464FF4604126
:1015E000304603E00023BE481A460D21CDE90045F0
:1015F00000F0DDFA7CBD1CB50522032140B10128B5
:101600000DD0032803D10521B648FFF74FFF1CBDBD
:10161000CDE9001200231A46E021B34805E0CDE9E8
:10162000001200231A463821AA4800F0C0FA1CBD57
:101630002DE9FF4F85B00446DDE912BA99461646FA
:101640006846FFF712FAA748A84F0025844208D140
:10165000386840F4805038600698FFF7CCFFADF84A
:1016600004509E48DFF884828442A8F104080AD11D
:10167000D8F8001041F48041C8F800100698FFF730
:101680008DFFADF80450924884420AD1D8F800107A
:1016900041F40041C8F800100698FFF761FFADF86B
:1016A00004508A48844208D1386840F400503860B9
:1016B0000698FFF737FFADF804508148844208D1FF
:1016C000386840F4801038600698FFF705FFADF8E1
:1016D00004507848844208D1386840F400103860DB
:1016E0000698FFF7E4FEADF80450ADF80C90ADF8A5
:1016F00000504FF40070ADF80EA0ADF802B0ADF898
:101700000A0046B10121012E08D00220022E08D085
:10171000032E0BD00EE0ADF8065004E0ADF80650F5
:1017200006E0ADF80600ADF8085003E0ADF806009D
:10173000ADF80810208820F040002080694620463F
:10174000FFF714F9208840F04000208009B0BDE880
:10175000F08F2DE9FC410446624800250F464FF406
:101760008276844205D1CDE9006520230022FFF76F
:101770005FFF5A48844206D1CDE90065202300224C
:101780003946FFF755FF5248844206D1CDE900653E
:10179000202300223946FFF74BFF4C48844206D1F4
:1017A000CDE90065202300223946FFF741FF444878
:1017B000844206D1CDE90065202300223946FFF797
:1017C00037FF3C48844206D1CDE900652023002242
:1017D0003946FFF72DFFBDE8FC812DE9FC410446A9
:1017E00040480025174688464FF48276844204D14B
:1017F000CDE900652023FFF71BFF3848844206D15E
:10180000CDE9006520233A464146FFF711FF3048F5
:10181000844206D1CDE9006520233A464146FFF7D0
:1018200007FF2A48844206D1CDE9006520233A46C5
:101830004146FFF7FDFE2248844206D1CDE900650E
:1018400020233A464146FFF7F3FE1A488442C2D1AC
:10185000CDE9006520233A464146FFF7E9FEBAE7A5
:101860002DE9FC470446DDE90A651E481F469046FF
:101870008946844205D1CDE9006513463A46FFF713
:10188000D7FE1648844206D1CDE9006543463A4664
:101890004946FFF7CDFE0E48844206D1CDE90065EA
:1018A00043463A464946FFF7C3FE0848844225D1DD
:1018B00043461DE00054014000180240001402405D
:1018C00000500140001C0240001002400034014062
:1018D000003C004000040240000802400038004084
:1018E0000020024000300140000002404438024025
:1018F000CDE900653A464946FFF79AFE77488442AB
:1019000006D1CDE9006543463A464946FFF790FEC9
:101910007348844206D1CDE9006543463A464946BC
:10192000FFF786FEBDE8FC877FB50D00044620D09A
:101930006846FEF771FD6B48844208D06A488442CD
:1019400005D06648844202D06548844201D103999B
:1019500000E0029900200124421C04FA02F3B1FBCA
:10196000F3F3AB4202D8C00004B070BDD0B2082877
:10197000F2D33820F8E702880388C2F3C02223F0AC
:10198000400303800129018808D021F4006101800F
:10199000018841F0400101801046704741F4006128
:1019A000F5E730B50488640614D50489A407FCD093
:1019B00004892406F9D400240AE00D5D8581058997
:1019C000AD07FCD005892D06F9D485891555641C11
:1019D0009C42F2D330BD10B503885B0613D5038952
:1019E0009B07FCD003891B06F9D4002309E0CC5CDB
:1019F00084810489A407FCD004892406F9D484894D
:101A00005B1C9342F3D310BD30B50488640613D534
:101A10000489A407FCD004892406F9D4002409E031
:101A200082810589AD07FCD005892D06F9D4858909
:101A30000D55641C9C42F3D330BD30B50488640658
:101A400016D50489A407FCD004892406F9D40024FF
:101A50000CE031F8145085810589AD07FCD005896B
:101A60002D06F9D4858922F81450641C9C42F0D3C9
:101A700030BD10B503885B0614D503899B07FCD0E5
:101A800003891B06F9D400230AE031F8134084814E
:101A90000489A407FCD004892406F9D484895B1C3A
:101AA0009342F2D310BD30B50488640614D504897E
:101AB000A407FCD004892406F9D400240AE082811A
:101AC0000589AD07FCD005892D06F9D4858921F853
:101AD0001450641C9C42F2D330BD00000050014001
:101AE000005401400030014000340140A349084443
:101AF000C0F38F2070472DE9F04F9A46DDE909B811
:101B000089460346FFF7F2FFC5B200204FF0030EEF
:101B10000121814011EA090F28D0994E36F815406D
:101B20000C4326F81540DF6844000EFA04F6B7436C
:101B30000BFA04FC47EA0C07DF601F6802FA04FC9A
:101B4000B74347EA0C071F60012A01D0022A0DD1D2
:101B50005F6889B28F430AFA00F189B20F435F6070
:101B6000996808FA04F4B14321439960401CC0B25B
:101B70001028CDD3BDE8F08F00B5FFF7B7FF0121E6
:101B80008140804802681143016000BDFCB51646E3
:101B9000DDE907C50C00074608D0FFF7EDFFCDE9EA
:101BA00000C5324621463846FFF7A5FFFCBD2DE9AA
:101BB000FC4F9946DDE90BB792460D00064622D050
:101BC000FFF7DAFF002201214FF00F0C01FA02F0BB
:101BD00028420DD0D00806EB8003186A5407E40EA3
:101BE0000CFA04F820EA080007FA04F4204318620B
:101BF000521C102AEAD3CDE9009B53460222294603
:101C00003046FFF778FFBDE8FC8FF0B50E4605467D
:101C1000FFF76CFF00225A49C4B24FF0010C0327B2
:101C20000CFA02F333420CD028684FEA420E07FA4E
:101C30000EFE40EA0E00286031F81400984321F8A7
:101C40001400521CD2B2102AEAD3F0BDF0B5002223
:101C50000125032605FA02F30B4205D0046857005C
:101C600006FA07F39C430460521CD2B2102AF1D347
:101C7000F0BDF0B500220127032607FA02F33C4627
:101C80000B4208D00568530006FA03FC25EA0C0550
:101C90009C4025430560521CD2B2102AEDD3F0BD02
:101CA000F0B500220125032605FA02F30B4205D008
:101CB0000468570006FA07F31C430460521CD2B2B2
:101CC000102AF1D3F0BDF0B500220126032402272B
:101CD00006FA02F30B4209D00568530004FA03FC2C
:101CE00025EA0C0507FA03F31D430560521CD2B226
:101CF000102AEDD3F0BDF0B500230127032507FA24
:101D000003F40C4209D0C6685C0005FA04FC26EA1C
:101D10000C0602FA04F42643C6605B1CDBB2102BEF
:101D2000EDD3F0BD41F48032C261C161C261C169CD
:101D3000C0697047002102E0491C89B240080128AF
:101D4000FAD80846704700B5FFF7D0FE0121814060
:101D50000C4802688A43026000BD00B5FFF7C6FE6A
:101D6000074931F8100000BD00B5FFF7BFFE044978
:101D700031F81000C04380B200BD00000000FEBF7B
:101D80004C0200203038024000F09FF84020FFF75E
:101D9000FAF803210E20FFF7CFF80022012110A04E
:101DA000FFF7C5F90D210F20FFF7C6F8002201212A
:101DB0000EA0FFF7BCF91A211E20FFF7BDF8002284
:101DC00001210DA0FFF7B3F92A212D20FFF7B4F868
:101DD000012211460AA0FFF7AAF9FFF761F8FEE712
:101DE00053544D33324634787800000044697363AD
:101DF0006F766572790000003230313400000000E7
:101E00006D616A65726C652E657500007047FEE74E
:101E1000FEE7FEE7FEE7704770477047704710B572
:101E2000FEF704FF10BD00000CB5002254490092DB
:101E30000192086840F4803008604FF4A0430868BD
:101E400000F4003001900098401C0090019810B9F7
:101E500000989842F3D10868800334D5012001909E
:101E600047484030026842F08052026045480268AC
:101E700042F4404202604248083002680260026850
:101E800042F400420260026842F4A0520260031F62
:101E90003D4A1A600A6842F080720A600A6892013C
:101EA000FCD53A4940F205720A60016821F003014D
:101EB0000160016841F0020101600168C1F3810124
:101EC0000229FAD10CBD01920CBD314810B5016850
:101ED00041F4700101602A48016841F0010101608C
:101EE000274A00210832116002682A4B1A4002601A
:101EF000031D294A1A60026822F4802202602048E9
:101F00000C300160FFF790FF21494FF000608039ED
:101F1000086010BD70B51A4D083528681F4B204960
:101F200010F00C0004D01F4E042803D0082803D062
:101F30000B601BE00E6019E0114A121D1068C0F31F
:101F40008054106800F03F0014B1B6FBF0F001E0DF
:101F5000B3FBF0F013681268C3F388135843C2F35D
:101F60000142521C5200B0FBF2F0086028680C4A93
:101F7000C0F30310121D105C0A68C2400A6070BDF5
:101F8000003802400070004008544007003C024006
:101F900088ED00E0FFFFF6FE103000240024F4007E
:101FA0002800002040787D0170B5064600F056F804
:101FB000056806F10B0020F00704B4429CBF002026
:101FC00070BD2B466A68BAB11068A04210D304F104
:101FD000080188423CBF5068586007D35168101907
:101FE00041601168091B016058601460101D70BDCC
:101FF00013465268002AE7D12146284600F036F8F9
:102000000028DED170BD70B50446051F00F026F82B
:102010000068002C14BF446870BD002C18BFAC428F
:102020003CBF20466468F8D301680A18AA4218BF6A
:10203000456003D12A6805461144016028684119AA
:10204000A1421CBF6C6070BD616869602168084472
:10205000286070BD704770477047000000487047A7
:102060006C020020704770477047704738B50446CF
:102070000A4600206946AFF30080002808BF38BD3B
:1020800002460099204600F03FF8012038BD0120AB
:1020900000F054B8F8B5AFF30080054600200C46B8
:1020A000102000BF0646A819A0420DD93246694645
:1020B0000020AFF30080070008BF00F03FF8009851
:1020C000A04218BF0546C419FFF7C8FF05600746C0
:1020D000F01D20F007004619284600F00AF8B44227
:1020E00008BFF8BDA21B31463868BDE8F84000F0D3
:1020F0000BB800210160C0E9011070471020704743
:102100000048704764020020034640688C4600285F
:1021100018BF88423CBF03464068F8D3186818448B
:10212000884207D00CF1030020F00700001D411A7F
:10213000521A0146081D0A60FFF765BF10B500F08E
:1021400039F8BDE8104000F02FB870477546FFF72A
:10215000D7FFAE4605006946534620F00700854686
:1021600018B020B5FEF772F8BDE820404FF0000629
:102170004FF000074FF000084FF0000B21F007016F
:10218000AC46ACE8C009ACE8C009ACE8C009ACE8B2
:10219000C0098D46704710B50446AFF30080204655
:1021A000BDE81040FEF73DB8002801D000F02AB885
:1021B0007047000010B5012805D0002103A000F0F1
:1021C00027F8012010BD09A1F8E700005349475244
:1021D000544D454D3A204F7574206F6620686561F7
:1021E00070206D656D6F7279000000003A204865BF
:1021F0006170206D656D6F727920636F727275709A
:102200007465640001491820ABBEFEE72600020099
:1022100070B505460C460A2000E06D1C00F011F870
:1022200035B128780028F8D102E0641C00F009F8E4
:1022300014B120780028F8D1BDE870400A20AFF32F
:10224000008008B569468DF800000320ABBE08BDCC
:102250004FF04070E1EE100A7047000000000000EF
:1022600000002F000000000700070000147F147F0B
:102270001400242A7F2A1200323408162600364918
:1022800055225000000503000000001C2241000000
:102290000041221C000014083E08140008083E08F3
:1022A00008000000503000001010101010000060F6
:1022B000600000002010080402003E5149453E0025
:1022C00000427F4000004261514946002141454B98
:1022D00031001814127F10002745454539003C4A4B
:1022E0004949300001710905030036494949360062
:1022F000064949291E000036360000000056360007
:1023000000000814224100001414141414000041A9
:1023100022140800020151090600324959513E00B9
:102320007E1111117E007F49494936003E414141ED
:1023300022007F4141221C007F49494941007F0919
:10234000090901003E4149497A007F0808087F00D9
:1023500000417F4100002040413F01007F081422DE
:1023600041007F40404040007F020C027F007F041C
:1023700008107F003E4141413E007F0909090600E7
:102380003E4151215E007F091929460046494949CD
:10239000310001017F0101003F4040403F001F200C
:1023A00040201F003F4038403F0063140814630082
:1023B000070870080700615149454300007F41410B
:1023C0000000552A552A55000041417F00000402B3
:1023D00001020400404040404000000102040000AF
:1023E0002054545478007F484444380038444444CE
:1023F0002000384444487F00385454541800087E64
:10240000090102000C5252523E007F080404780079
:1024100000447D4000002040443D00007F102844DF
:10242000000000417F4000007C04180478007C0814
:10243000040478003844444438007C141414080020
:10244000081414187C007C080404080048545454F0
:102450002000043F444020003C4040207C001C20E1
:1024600040201C003C4030403C00442810284400E0
:102470000C5050503C004464544C4400007F3E1CBF
:102480000800081C3E7F0000087C7E7C0800103E8F
:102490007E3E10003E3E3E3E3E00007F3E1C080059
:1024A0000000000017000300031F0A1F0A1F050990
:1024B00004120F171C000300000E11110E0005027C
:1024C00005040E04100800040404001000080402AF
:1024D0001F111F121F101D151711151F07041F179D
:1024E000151D1F151D01011F1F151F17151F000AA0
:1024F00000100A00040A110A0A0A110A040115034D
:102500000E15161E051E1F150A0E11111F110E1F86
:1025100015151F05050E151D1F041F111F1108108D
:102520000F1F041B1F10101F061F1F0E1F0E110E62
:102530001F05020E111E1F0D16121509011F010F96
:10254000100F0718071F0C1F1B041B031C03191572
:10255000131F110002040800111F020102101010C5
:102560000102001A161C1F120C0C12120C121F0C66
:102570001A16041E0506150F1F021C001D00101060
:102580000D1F0C12111F101E0E1E1E021C0C120C11
:102590001E0A04040A1E1C0202141E0A021F120E46
:1025A000101E0E100E1E1C1E120C1202141E1A1EDD
:1025B00016041B11001F00111B040406021F1F1F1D
:1025C000000000000000000000000000000000000B
:1025D00000000000000000000000000000000000FB
:1025E00000260008000000203C000000C401000894
:1025F0003C2600083C0000208C080000E001000898
:102600000000000001020304010203040607080998
:1026100000000000000000000000000000000000BA
:102620000000000000000000007A030A0000000023
:0C26300000000000010203040607080976
:040000050800018965
:00000001FF
| {
"pile_set_name": "Github"
} |
import csharp
from IntLiteral l
select l
| {
"pile_set_name": "Github"
} |
CREATE TABLE rhnXccdfBenchmark
(
id NUMBER NOT NULL
CONSTRAINT rhn_xccdf_benchmark_id_pk PRIMARY KEY
USING INDEX TABLESPACE [[64k_tbs]],
identifier VARCHAR2(120) NOT NULL,
version VARCHAR2(80) NOT NULL
)
ENABLE ROW MOVEMENT
;
CREATE UNIQUE INDEX rhn_xccdf_benchmark_iv_uq
ON rhnXccdfBenchmark (identifier, version)
TABLESPACE [[64k_tbs]]
NOLOGGING;
CREATE SEQUENCE rhn_xccdf_benchmark_id_seq;
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Templating\Helper;
use Symfony\Component\Templating\Helper\Helper;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* RouterHelper manages links between pages in a template context.
*
* @author Fabien Potencier <[email protected]>
*/
class RouterHelper extends Helper
{
protected $generator;
/**
* Constructor.
*
* @param UrlGeneratorInterface $router A Router instance
*/
public function __construct(UrlGeneratorInterface $router)
{
$this->generator = $router;
}
/**
* Generates a URL from the given parameters.
*
* @param string $name The name of the route
* @param mixed $parameters An array of parameters
* @param Boolean $absolute Whether to generate an absolute URL
*
* @return string The generated URL
*/
public function generate($name, $parameters = array(), $absolute = false)
{
return $this->generator->generate($name, $parameters, $absolute);
}
/**
* Returns the canonical name of this helper.
*
* @return string The canonical name
*/
public function getName()
{
return 'router';
}
}
| {
"pile_set_name": "Github"
} |
{
"Marketplace": {
"ActivateLicenseKey": "有効化",
"ActionActivatePlugin": "プラグインを有効にする",
"ActionActivateTheme": "テーマを有効にする",
"ActionInstall": "インストール",
"AddToCart": "カートに追加",
"AllowedUploadFormats": "このページから ZIP 形式のプラグインやテーマをアップロードをすることができます",
"Authors": "著者",
"Browse": "ブラウズ",
"LatestMarketplaceUpdates": "マーケットプレイスの最新情報",
"BackToMarketplace": "マーケットプレイスへ戻る",
"BrowseMarketplace": "ブラウズ・マーケットプレイス",
"ByXDevelopers": "%s の開発者",
"CannotInstall": "インストールできません",
"CannotUpdate": "更新できません",
"ClickToCompletePurchase": "クリックすると購入が完了します。",
"CurrentNumPiwikUsers": "Matomo には現在 %1$s 人の登録ユーザーがいます。",
"ConfirmRemoveLicense": "ライセンスキーを削除してもよろしいですか?購入したプラグインのアップデートは今後受信しません。",
"Developer": "デベロッパー",
"DevelopersLearnHowToDevelopPlugins": "デベロッパー:%1$s テーマやプラグイン %2$s を開発することで Matomo を拡張、カスタマイズする方法を学びます。",
"NoticeRemoveMarketplaceFromReportingMenu": "%1$sホワイトラベル%2$sプラグインをインストールすると、レポートメニューからマーケットプレイスを削除できます。",
"Marketplace": "マーケットプレイス",
"PaidPlugins": "プレミアム機能",
"FeaturedPlugin": "注目のプラグイン",
"InstallingNewPluginViaMarketplaceOrUpload": "マーケットプレイスから自動的に %1$s をインストールするか、または%3$s%4$sを.zip形式でアップロード%2$sすることができます。",
"InstallingPlugin": "%s のインストール",
"InstallPurchasedPlugins": "購入したプラグインをインストールする",
"LastCommitTime": "( 最終更新 %s )",
"LastUpdated": "最終更新日",
"License": "ライセンス",
"LicenseKey": "ライセンスキー",
"LicenseKeyActivatedSuccess": "ライセンスキーが正常に有効化されました!",
"LicenseKeyDeletedSuccess": "ライセンスキーが正常に削除されました。",
"Exceeded": "超過",
"LicenseMissing": "ライセンスが不足しています",
"LicenseMissingDeactivatedDescription": "ライセンスなしで使用しているため次のプラグインが無効化されました: %1$s %2$sこの問題を解決するには、ライセンスキーを更新するか、%3$s今すぐサブスクリプションを取得%4$s するか、プラグインを無効にします。",
"PluginLicenseMissingDescription": "このプラグインのライセンスがないため、このプラグインをダウンロードすることはできません。この問題を解決するには、ライセンスキーを更新するか、サブスクリプションを取得するか、プラグインをアンインストールしてください。",
"LicenseExceeded": "ライセンス超過",
"LicenseExceededDescription": "次のプラグインのライセンスは、ライセンスの許可ユーザー数が超過すると無効になります:%1$s %2$sこれらのプラグインのアップデートをダウンロードすることはできません。 この問題を解決するには、一部のユーザーを削除するか、サブスクリプションを%3$s今すぐアップグレードしてください。%4$s",
"PluginLicenseExceededDescription": "このプラグインはダウンロードできません。 このプラグインのライセンスは、ライセンスの許可ユーザーの数を超えており、無効です。 この問題を解決するには、一部のユーザーを削除するか、サブスクリプションをアップグレードしてください。",
"LicenseExpired": "ライセンスの有効期限切れです",
"LicenseExpiredDescription": "以下のプラグインのライセンスは有効期限が切れています:%1$s %2$sこれらのプラグインのアップデートは今後受信しません。 この問題を解決するには、%3$s今すぐサブスクリプションを更新%4$sするか、使用しなくなったプラグインを無効にしてください。",
"LicenseRenewsNextPaymentDate": "次の支払日に更新",
"UpgradeSubscription": "アップグレードサブスクリプション",
"ViewSubscriptionsSummary": "%1$sプラグインのサブスクリプションを表示します。%2$s",
"ViewSubscriptions": "サブスクリプションを表示する",
"ExceptionLinceseKeyIsExpired": "このライセンスキーは期限切れです。",
"ExceptionLinceseKeyIsNotValid": "このライセンスキーは無効です。",
"LicenseKeyIsValidShort": "ライセンスキーは有効です!",
"RemoveLicenseKey": "ライセンスキーを削除",
"InstallAllPurchasedPlugins": "購入したすべてのプラグインを一度にインストールする",
"InstallAllPurchasedPluginsAction": "購入した %d プラグインをインストールして有効にする",
"InstallThesePlugins": "これにより、次のプラグインがインストールされ、有効になります:",
"AllPaidPluginsInstalledAndActivated": "有料のプラグインはすべて正常にインストールされ、有効化されました。",
"OnlySomePaidPluginsInstalledAndActivated": "一部の有料プラグインは正常にインストールされませんでした。",
"NewVersion": "新しいバージョン",
"NotAllowedToBrowseMarketplacePlugins": "Matomo プラットフォームのカスタマイズまたは拡張のために、インストール可能なプラグインのリストを閲覧することができます。もしこれらのいづれかのインストールが必要な場合は、管理者にお問い合わせください。",
"NotAllowedToBrowseMarketplaceThemes": "Matomo プラットフォームの外観をカスタマイズするのにインストール可能な Matomo テーマのリストをご確認ください。これらのいづれかをインストールしたい場合は、管理者にお問い合わせください。",
"NoPluginsFound": "プラグインは見つかりませんでした",
"NoThemesFound": "テーマは見つかりませんでした",
"NoSubscriptionsFound": "サブスクリプションが見つかりませんでした",
"NumDownloadsLatestVersion": "最新バージョン:%s のダウンロード",
"OverviewPluginSubscriptions": "プラグインサブスクリプションの概要",
"OverviewPluginSubscriptionsMissingLicense": "ライセンスキーが設定されていません。プラグインサブスクリプションを購入した場合は、%1$sマーケットプレイス%2$sに行き、ライセンスキーを入力します。",
"OverviewPluginSubscriptionsAllDetails": "すべての詳細を表示したり、サブスクリプションを変更するには、アカウントにログインします。",
"OverviewPluginSubscriptionsMissingInfo": "サブスクリプションが不足している可能性があります。たとえば、支払いがまだ完了していない場合などです。そのような場合は、数時間後にもう一度試してみるか、Matomo チームに連絡してください。",
"NoValidSubscriptionNoUpdates": "サブスクリプションが期限切れになると、このプラグインのアップデートは今後受信されなくなります。",
"PluginSubscriptionsList": "これは、ライセンスキーに関連付けられたサブスクリプションのリストです。",
"PaidPluginsNoLicenseKeyIntro": "%1$sプレミアム有料プラグイン%2$sを購入した場合は、以下の受信ライセンスキーを挿入してください。",
"PaidPluginsWithLicenseKeyIntro": "有効なライセンスキーが設定されています。 セキュリティ上の理由から、ここではライセンスキーを表示しません。 ライセンスキーを紛失した場合は、Matomo チームに連絡してください。",
"PaidPluginsNoLicenseKeyIntroNoSuperUserAccess": "マーケットプレースで%1$sプレミアム有料プラグイン%2$sを購入した場合、ライセンスキーを追加するにはスーパーユーザーのアクセス権を持つユーザーにお尋ねください。",
"PluginDescription": "プラグインとテーマを Marketplace 経由でダウンロードして Matomo の機能を拡張します。",
"PluginKeywords": "キーワード",
"PluginUpdateAvailable": "あなたは現在、バージョン %1$s を使用しています。新しいバージョン %2$s が利用可能です。",
"PluginVersionInfo": "%2$s からの %1$s",
"PluginWebsite": "プラグインのウェブサイト",
"PriceExclTax": "%1$s %2$s 税別",
"PriceFromPerPeriod": "%1$s \/ %2$s から",
"Reviews": "レビュー",
"ShownPriceIsExclTax": "表示価格は税別です。",
"Screenshots": "スクリーンショット",
"SortByNewest": "最新",
"SortByAlpha": "アルファベット順",
"SortByLastUpdated": "最終更新",
"SortByPopular": "人気",
"StepDownloadingPluginFromMarketplace": "マーケットプレイスからプラグインをダウンロード",
"StepDownloadingThemeFromMarketplace": "マーケットプレイスからテーマをダウンロード",
"StepUnzippingPlugin": "プラグインを解凍",
"StepUnzippingTheme": "テーマを解凍",
"StepThemeSuccessfullyInstalled": "テーマ %1$s %2$s のインストールに成功しました。",
"StepPluginSuccessfullyInstalled": "プラグイン %1$s %2$s のインストールに成功しました。",
"StepPluginSuccessfullyUpdated": "プラグイン %1$s %2$s のアップデートに成功しました。",
"StepReplaceExistingPlugin": "既存のプラグインを置き換える",
"StepReplaceExistingTheme": "既存のテーマを置き換える",
"StepThemeSuccessfullyUpdated": "テーマ %1$s %2$s のアップデートに成功しました。",
"SubscriptionType": "タイプ",
"SubscriptionStartDate": "開始日",
"SubscriptionEndDate": "終了日",
"SubscriptionNextPaymentDate": "次の支払日",
"SubscriptionInvalid": "このサブスクリプションは無効または期限切れです",
"SubscriptionExpiresSoon": "このサブスクリプションはまもなく終了します",
"Support": "サポート",
"TeaserExtendPiwikByUpload": "ZIP ファイルをアップロードして Matomo を拡張",
"LicenseExceededPossibleCause": "ライセンスが超過しています。この Matomo インストールには、サブスクリプションの承認よりも多くのユーザーがいる可能性があります。",
"Updated": "更新済",
"UpdatingPlugin": "%1$s を更新しています",
"UploadZipFile": "ZIP ファイルをアップロード",
"PluginUploadDisabled": "設定ファイルでプラグインのアップロードが無効になっています。 この機能を有効にするには、設定を更新するか、管理者に連絡してください。",
"LicenseKeyExpiresSoon": "まもなくライセンスキーが期限切れになりますので、%1$sに連絡してください。",
"LicenseKeyIsExpired": "ライセンスキーの有効期限が切れていますので、%1$sに連絡してください。",
"MultiServerEnvironmentWarning": "Matomo を複数のサーバーで使用しているため、プラグインを直接インストールまたは更新することはできません。 プラグインは1つのサーバーにのみインストールされます。 代わりに、プラグインをダウンロードして手動ですべてのサーバーにデプロイしてください。",
"AutoUpdateDisabledWarning": "設定で自動アップデートが無効になっているため、プラグインを直接インストールまたはアップデートすることはできません。自動更新を有効にするには、%2$sに%1$sを設定します。",
"ViewRepositoryChangelog": "変更内容を表示"
}
} | {
"pile_set_name": "Github"
} |
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/UTILS-reinterpolate.R
\name{reinterpolate}
\alias{reinterpolate}
\title{Wrapper for simple linear reinterpolation}
\usage{
reinterpolate(x, new.length, multivariate = FALSE)
}
\arguments{
\item{x}{Data to reinterpolate. Either a vector, a matrix/data.frame where each row is to be
reinterpolated, or a list of vectors/matrices.}
\item{new.length}{Desired length of the output series.}
\item{multivariate}{Is \code{x} a multivariate time series? It will be detected automatically if a
list is provided in \code{x}.}
}
\value{
Reinterpolated time series
}
\description{
This function is just a wrapper for the native function \code{\link[stats:approx]{stats::approx()}} to do simple linear
reinterpolation. It also supports matrices, data frames, and lists of time series.
}
\details{
Multivariate series must have time spanning the rows and variables spanning the columns.
}
\examples{
data(uciCT)
# list of univariate series
series <- reinterpolate(CharTraj, 205L)
# list of multivariate series
series <- reinterpolate(CharTrajMV, 205L)
# single multivariate series
series <- reinterpolate(CharTrajMV[[1L]], 205L, TRUE)
}
| {
"pile_set_name": "Github"
} |
# Piler
[](http://travis-ci.org/epeli/piler)
Feature highlights
* Minify and concatenate JS and CSS for fast page loads
* Tag rendering
* Namespaces
* Transparent preprocessor
* Push CSS changes to the browser using Socket.IO
* Easy code sharing with server
### **[Need feedback for upcoming version 0.6.0](https://github.com/epeli/piler/issues/61)**
## Awesome Asset Manager for Node.js
*Piler* allows you to manage all your JavaScript and CSS assets cleanly and
directly from code. It will concatenate and minify them in production and it
takes care of rendering the tags. The idea is to make your pages load as
quickly as possible.
So why create a yet another asset manager? Because Node.js is special. In
Node.js a JavaScript asset isn't just a pile of bits that are sent to the
browser. It's code. It's code that can be also used in the server and I think
that it's the job of asset managers to help with it. So in *Piler* you can take
code directly from your Javascript objects, not just from JavaScript files.
Copying things from Rails is just not enough. This is just a one reason why
*Piler* was created.
Server-side code:
```javascript
clientjs.addOb({BROWSER_GLOBAL: {
aFunction: function() {
console.log("Hello I'm in the browser also. Here I have", window, "and other friends");
}
}});
```
You can also tell *Piler* to directly execute some function in the browser:
```javascript
clientjs.addExec(function() {
BROWSER_GLOBAL.aFunction();
alert("Hello" + window.navigator.appVersion);
});
```
Currently *Piler* works only with [Express], but other frameworks are planned
as well.
*Piler* is written following principles in mind:
* Creating best possible production setup for assets should be as easy as
including script/link to a page.
* Namespaces. You don't want to serve huge blob of admin view code for all
anonymous users.
* Support any JS- or CSS-files. No need to create special structure for your
assets. Just include your jQueries or whatever.
* Preprocessor languages are first class citizens. Eg. Just change the file
extension to .coffee to use CoffeeScript. That's it. No need to worry about
compiled files.
* Use heavy caching. Browser caches are killed automatically using the hash
sum of the assets.
* Awesome development mode. Build-in support for pushing CSS changes to
browsr using Socket.IO.
**Full example Express 2.x**
```javascript
var createServer = require("express").createServer;
var piler = require("piler");
var app = createServer();
var clientjs = piler.createJSManager();
var clientcss = piler.createCSSManager();
app.configure(function() {
clientjs.bind(app);
clientcss.bind(app);
clientcss.addFile(__dirname + "/style.css");
clientjs.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");
clientjs.addFile(__dirname + "/client/hello.js");
});
app.configure("development", function() {
clientjs.liveUpdate(clientcss);
});
clientjs.addOb({ VERSION: "1.0.0" });
clientjs.addExec(function() {
alert("Hello browser" + window.navigator.appVersion);
});
app.get("/", function(req, res){
res.render("index.jade", {
layout: false,
js: clientjs.renderTags(),
css: clientcss.renderTags()
});
});
app.listen(8080);
```
**Full example Express 3.x**
```javascript
var express = require('express'),
http = require('http'),
piler = require("piler"),
app = express();
var clientjs = piler.createJSManager();
var clientcss = piler.createCSSManager();
var srv = require('http').createServer(app);
app.configure(function(){
clientjs.bind(app,srv);
clientcss.bind(app,srv);
clientcss.addFile(__dirname + "/style.css");
clientjs.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");
clientjs.addFile(__dirname + "/client/hello.js");
});
app.configure("development", function() {
clientjs.liveUpdate(clientcss);
});
clientjs.addOb({ VERSION: "1.0.0" });
clientjs.addExec(function() {
alert("Hello browser" + window.navigator.appVersion);
});
app.get("/", function(req, res){
res.render("index.jade", {
layout: false,
js: clientjs.renderTags(),
css: clientcss.renderTags()
});
});
srv.listen(8080);
```
index.jade:
```jade
!!! 5
html
head
!{css}
!{js}
body
h1 Hello Piler
```
## Namespaces
The example above uses just a one pile. The global pile.
If you for example want to add big editor files only for administration pages
you can create a pile for it:
```javascript
clientjs.addFile("admin", __dirname + "/editor.js");
clientjs.addFile("admin", __dirname + "/editor.extension.js");
```
This will add file editor.js and editor.extension.js to a admin pile. Now you
can add that to your admin pages by using giving it as parameter for
*renderTags*.
```javascript
js.renderTags("admin");
```
This will render script-tags for the global pile and the admin-pile.
*js.renderTags* and *css.renderTags* can take variable amount of arguments.
Use *js.renderTags("pile1", "pile2", ....)* to render multiple namespaces
Piling works just the same with css.
## Sharing code with the server
Ok, that's pretty much what every asset manager does, but with *Piler* you can
share code directly from your server code.
Let's say that you want to share a email-validating function with a server and
the client
```javascript
function isEmail(s) {
return !! s.match(/.\w+@\w+\.\w/);
}
```
You can share it with *addOb* -method:
```javascript
clientjs.addOb({MY: {
isEmail: isEmail
}
});
```
Now on the client you can find the isEmail-function from MY.isEmail.
*addOb* takes an object which will be merged to global window-object on the
client. So be careful when choosing the keys. The object can be almost any
JavaScript object. It will be serialized and sent to the browser. Few caveats:
1. No circural references
1. Functions will be serialized using Function.prototype.toString. So closures
won't transferred to the client!
### Pattern for sharing full modules
This is nothing specific to *Piler*, but this is a nice pattern which can be
used to share modules between the server and the client.
share.js
```javascript
(function(exports){
exports.test = function(){
return 'This is a function from shared module';
};
}(typeof exports === 'undefined' ? this.share = {} : exports));
```
In Node.js you can use it by just requiring it as any other module
```javascript
var share = require("./share.js");
```
and you can share it the client using *addFile*:
```javascript
clientjs.addFile(__dirname + "./share.js");
```
Now you can use it in both as you would expect
```javascript
share.test();
```
You can read more about the pattern from [here](http://caolanmcmahon.com/posts/writing_for_node_and_the_browser)
## Logging
Sometimes it is nessesary to control pilers output based on the system environment your running your application in.
In default mode Pilers logger will output any information it has by using the "console" javascript object. The following example shows
how to configure a custom logger
### Logger interface
The basic logger facility implements the following methods.
```javascript
exports.debug = console.debug
exports.notice = console.log
exports.info = console.info
exports.warn = console.warn
exports.warning = console.warn
exports.error = console.error
exports.critical = console.error
```
### Inject a custom logger
The following example injects "winston", a multi-transport async logging library into pilers logging mechanism.
```javascript
var piler = require('piler');
var logger = require('winston');
// [More logger configuration can take place here]
global.js = js = piler.createJSManager({ outputDirectory: assetTmpDir , "logger": logger});
global.css = css = piler.createCSSManager({ outputDirectory: assetTmpDir, "logger": logger});
```
More information about winston can be found [here](https://github.com/flatiron/winston).
## Awesome development mode!
Development and production modes works as in Express. By default the
development mode is active. To activate production mode set NODE\_ENV
environment variable to *production*.
### Live CSS editing
This is really cool! You don't want to edit CSS at all without this after you
try it!
Because *Piler* handles the script-tag rendering it can add some development
tools when in development mode.
Using Express you can add Live CSS editing in development mode:
```javascript
app.configure("development", function() {
clientjs.liveUpdate(clientcss);
});
```
This is similar to [Live.js][], but it does not use polling. It will add
Socket.IO which will push the CSS-changes to your browser as you edit them.
If your app already uses Socket.IO you need to add the *io*-object as second
parameter to liveUpdate:
```javascript
var io = require('socket.io').listen(app);
clientjs.liveUpdate(clientcss, io);
```
### Script-tag rendering
In development mode every JS- and CSS-file will be rendered as a separate tag.
For example js.renderTags("admin") will render
```javascript
clientjs.addFile(__dirname + "/helpers.js");
clientjs.addFile("admin", __dirname + "/editor.js");
clientjs.addFile("admin", __dirname + "/editor.extension.js");
```
to
```html
<script type="text/javascript" src="/pile/dev/_global/1710d-helpers.js?v=1317298508710" ></script>
<script type="text/javascript" src="/pile/dev/admin/3718d-editor.js?v=1317298508714" ></script>
<script type="text/javascript" src="/pile/dev/admin/1411d-editor.extension.js?v=1317298508716" ></script>
```
in development mode, but in production it will render to
```html
<script type="text/javascript" src="/pile/min/_global.js?v=f1d27a8d9b92447439f6ebd5ef8f7ea9d25bc41c" ></script>
<script type="text/javascript" src="/pile/min/admin.js?v=2d730ac54f9e63e1a7e99cd669861bda33905365" ></script>
```
So debugging should be as easy as directly using script-tags. Line numbers
will match your real files in the filesystem. No need to debug huge Javascript
bundle!
## Examples
Visit
[this](https://github.com/epeli/piler/blob/master/examples/simple/app.js)
directory to see a simple example using ExpressJS 2.x.
This
[example](https://github.com/epeli/piler/blob/master/examples/simple/app.js)
uses ExpressJS 3.x a custom logger (winston) and a global socket.io instance
together with Piler.
## API summary
Code will be rendered in the order you call these functions with the exception
of *addUrl* which will be rendered as first.
### createJSManager and createCSSManager
Can take an optional configuration object as an argument with following keys.
var jsclient = piler.createJSManager({
outputDirectory: __dirname + "/mydir",
urlRoot: "/my/root"
});
#### urlRoot
Url root to which Piler's paths are appended. For example urlRoot "/my/root"
will result in following script tag:
<script type="text/javascript" src="/my/root/min/code.js?v=f4ec8d2b2be16a4ae8743039c53a1a2c31e50570" ></script>
#### outputDirectory
If specified *Piler* will write the minified assets to this folder. Useful if
you want to share you assets from Apache etc. instead of directly serving from
Piler's Connect middleware.
### JavaScript pile
#### addFile( [namespace], path to a asset file )
File on filesystem.
#### addUrl( [namespace], url to a asset file )
Useful for CDNs and for dynamic assets in other libraries such as socket.io.
#### addOb( [namespace string], any Javascript object )
Keys of the object will be added to the global window object. So take care when
choosing those. Also remember that parent scope of functions will be lost.
You can also give a nested namespace for it
clientjs.addOb({"foo.bar": "my thing"});
Now on the client "my thing" string will be found from window.foo.bar.
The object will be serialized at the second it is passed to this method so you
won't be able modify it other than between server restarts. This is usefull for
sharing utility functions etc.
Use *res.addOb* to share more dynamically objects.
#### addExec( [namespace], Javascript function )
A function that will executed immediately in browser as it is parsed. Parent
scope is also lost here.
#### addRaw( [namespace], raw Javascript string )
Any valid Javascript string.
### CSS pile
These are similar to ones in JS pile.
#### addFile( [namespace], path to a asset file )
CSS asset on your filesystem.
#### addUrl( [namespace], url to a asset file )
CSS asset behind a url. Can be remote too. This will be directly linked to you
page. Use addFile if you want it be minified.
#### addRaw( [namespace], raw CSS string )
Any valid CSS string.
## Supported preprocessors
### JavaScript
For JavaScript the only supported one is [CoffeeScript][] and the compiler is
included in *Piler*.
### CSS
CSS-compilers are not included in *Piler*. Just install what you need using
[npm][].
* [Stylus][] with [nib][] (npm install stylus nib)
* [LESS][] (npm install less)
Adding support for new compilers should be
[easy](https://github.com/epeli/pile/blob/master/lib/compilers.coffee).
Feel free to contribute!
## Installing
From [npm][]
npm install piler
## Source code
Source code is licenced under [The MIT
License](https://github.com/epeli/piler/blob/master/LICENSE) and it is hosted
on [Github](https://github.com/epeli/piler).
## Changelog
v0.4.2 - 2013-04-16
* Fixes to work with ExpressJS 3.x
* Unit test fixes
* Make console output configurable
v0.4.1 - 2012-06-12
* Add getSources
* Put cache key to resource url instead of query string
v0.4.0 - 2012-06-17
* Remove Dynamic Helpers.
Dynamic Helpers where an Express 2.0 only API. This makes Piler more framework
agnostic and it will work with Express 3.0. This also removes support for
response object functions. We'll add those back if there is a need for them
(open up a issue if you miss them!) and we'll find good framework agnostic way
to implement them.
v0.3.6 - 2012-06-17
* Bind all production dependency versions
v0.3.5 - 2012-06-17
* Fix LESS @imports
* Fix Stylus without nib
* Use path module for Windows compatibility
v0.3.4 - 2012-03-29
* Fix Stylus @imports
v0.3.3 - noop
v0.3.2 - 2011-12-11
* Workaround compiler bug in CoffeeScript
v0.3.1 - 2011-11-17
* Fix CSS namespaces
v0.3.0 - 2011-10-13
* Rename to Piler
* Really minify CSS
* Implemented res.addOb
* Implement outputDirectory and urlRoot options.
* addOb can now take nested namespace string and it won't override existing
namespaces.
## Contact
Questions and suggestions are very welcome
- [Esa-Matti Suuronen](http://esa-matti.suuronen.org/)
- esa-matti [aet] suuronen dot org
- [EsaMatti](https://twitter.com/#!/EsaMatti) @ Twitter
- Epeli @ freenode/IRCnet
[Express]: http://expressjs.com/
[Node.js]: http://nodejs.org/
[Live.js]: http://livejs.com/
[LESS]: http://lesscss.org/
[Stylus]: http://learnboost.github.com/stylus/
[nib]: https://github.com/visionmedia/nib
[npm]: http://npmjs.org/
[CoffeeScript]: http://jashkenas.github.com/coffee-script/
| {
"pile_set_name": "Github"
} |
//Copyright (c) 2008-2017 Emil Dotchevski and Reverge Studios, Inc.
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_QVM_187092DA6454CEB1853E6915F8466A4
#define BOOST_QVM_187092DA6454CEB1853E6915F8466A4
//This file was generated by a program. Do not edit manually.
#include <boost/qvm/deduce_vec.hpp>
#include <boost/qvm/enable_if.hpp>
#include <boost/qvm/inline.hpp>
#include <boost/qvm/mat_traits.hpp>
#include <boost/qvm/vec_traits.hpp>
namespace
boost
{
namespace
qvm
{
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==4 && mat_traits<A>::cols==4 &&
vec_traits<B>::dim==4,
deduce_vec2<A,B,4> >::type
operator*( A const & a, B const & b )
{
typedef typename mat_traits<A>::scalar_type Ta;
typedef typename vec_traits<B>::scalar_type Tb;
Ta const a00 = mat_traits<A>::template read_element<0,0>(a);
Ta const a01 = mat_traits<A>::template read_element<0,1>(a);
Ta const a02 = mat_traits<A>::template read_element<0,2>(a);
Ta const a03 = mat_traits<A>::template read_element<0,3>(a);
Ta const a10 = mat_traits<A>::template read_element<1,0>(a);
Ta const a11 = mat_traits<A>::template read_element<1,1>(a);
Ta const a12 = mat_traits<A>::template read_element<1,2>(a);
Ta const a13 = mat_traits<A>::template read_element<1,3>(a);
Ta const a20 = mat_traits<A>::template read_element<2,0>(a);
Ta const a21 = mat_traits<A>::template read_element<2,1>(a);
Ta const a22 = mat_traits<A>::template read_element<2,2>(a);
Ta const a23 = mat_traits<A>::template read_element<2,3>(a);
Ta const a30 = mat_traits<A>::template read_element<3,0>(a);
Ta const a31 = mat_traits<A>::template read_element<3,1>(a);
Ta const a32 = mat_traits<A>::template read_element<3,2>(a);
Ta const a33 = mat_traits<A>::template read_element<3,3>(a);
Tb const b0 = vec_traits<B>::template read_element<0>(b);
Tb const b1 = vec_traits<B>::template read_element<1>(b);
Tb const b2 = vec_traits<B>::template read_element<2>(b);
Tb const b3 = vec_traits<B>::template read_element<3>(b);
typedef typename deduce_vec2<A,B,4>::type R;
BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim==4);
R r;
vec_traits<R>::template write_element<0>(r)=a00*b0+a01*b1+a02*b2+a03*b3;
vec_traits<R>::template write_element<1>(r)=a10*b0+a11*b1+a12*b2+a13*b3;
vec_traits<R>::template write_element<2>(r)=a20*b0+a21*b1+a22*b2+a23*b3;
vec_traits<R>::template write_element<3>(r)=a30*b0+a31*b1+a32*b2+a33*b3;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_mv_defined;
template <>
struct
mul_mv_defined<4,4>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<B>::rows==4 && mat_traits<B>::cols==4 &&
vec_traits<A>::dim==4,
deduce_vec2<A,B,4> >::type
operator*( A const & a, B const & b )
{
typedef typename vec_traits<A>::scalar_type Ta;
typedef typename mat_traits<B>::scalar_type Tb;
Ta const a0 = vec_traits<A>::template read_element<0>(a);
Ta const a1 = vec_traits<A>::template read_element<1>(a);
Ta const a2 = vec_traits<A>::template read_element<2>(a);
Ta const a3 = vec_traits<A>::template read_element<3>(a);
Tb const b00 = mat_traits<B>::template read_element<0,0>(b);
Tb const b01 = mat_traits<B>::template read_element<0,1>(b);
Tb const b02 = mat_traits<B>::template read_element<0,2>(b);
Tb const b03 = mat_traits<B>::template read_element<0,3>(b);
Tb const b10 = mat_traits<B>::template read_element<1,0>(b);
Tb const b11 = mat_traits<B>::template read_element<1,1>(b);
Tb const b12 = mat_traits<B>::template read_element<1,2>(b);
Tb const b13 = mat_traits<B>::template read_element<1,3>(b);
Tb const b20 = mat_traits<B>::template read_element<2,0>(b);
Tb const b21 = mat_traits<B>::template read_element<2,1>(b);
Tb const b22 = mat_traits<B>::template read_element<2,2>(b);
Tb const b23 = mat_traits<B>::template read_element<2,3>(b);
Tb const b30 = mat_traits<B>::template read_element<3,0>(b);
Tb const b31 = mat_traits<B>::template read_element<3,1>(b);
Tb const b32 = mat_traits<B>::template read_element<3,2>(b);
Tb const b33 = mat_traits<B>::template read_element<3,3>(b);
typedef typename deduce_vec2<A,B,4>::type R;
BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim==4);
R r;
vec_traits<R>::template write_element<0>(r)=a0*b00+a1*b10+a2*b20+a3*b30;
vec_traits<R>::template write_element<1>(r)=a0*b01+a1*b11+a2*b21+a3*b31;
vec_traits<R>::template write_element<2>(r)=a0*b02+a1*b12+a2*b22+a3*b32;
vec_traits<R>::template write_element<3>(r)=a0*b03+a1*b13+a2*b23+a3*b33;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_vm_defined;
template <>
struct
mul_vm_defined<4,4>
{
static bool const value=true;
};
}
}
}
#endif
| {
"pile_set_name": "Github"
} |
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Button @base: matches snapshot 1`] = `<button class="ion-button button button-ios button-default button-default-ios button-ios-primary"><span class="button-inner"><span>Test</span></span></button>`;
| {
"pile_set_name": "Github"
} |
package abi36_0_0.expo.modules.location.exceptions;
import abi36_0_0.org.unimodules.core.interfaces.CodedThrowable;
import abi36_0_0.org.unimodules.core.errors.CodedException;
public class LocationRequestRejectedException extends CodedException implements CodedThrowable {
public LocationRequestRejectedException(Exception cause) {
super("Location request has been rejected: " + cause.getMessage());
}
@Override
public String getCode() {
return "E_LOCATION_REQUEST_REJECTED";
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016-2019 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package benchmarks.immutableMap.builder
import benchmarks.*
import kotlinx.collections.immutable.persistentMapOf
import kotlinx.benchmark.*
@State(Scope.Benchmark)
open class Get {
@Param(BM_1, BM_10, BM_100, BM_1000, BM_10000, BM_100000, BM_1000000)
var size: Int = 0
@Param(HASH_IMPL, ORDERED_IMPL)
var implementation = ""
@Param(ASCENDING_HASH_CODE, RANDOM_HASH_CODE, COLLISION_HASH_CODE, NON_EXISTING_HASH_CODE)
var hashCodeType = ""
@Param(IP_100, IP_99_09, IP_95, IP_70, IP_50, IP_30, IP_0)
var immutablePercentage: Double = 0.0
private var keys = listOf<IntWrapper>()
private var builder = persistentMapOf<IntWrapper, String>().builder()
@Setup
fun prepare() {
keys = generateKeys(hashCodeType, size)
builder = persistentMapBuilderPut(implementation, keys, immutablePercentage)
if (hashCodeType == NON_EXISTING_HASH_CODE)
keys = generateKeys(hashCodeType, size)
}
@Benchmark
fun get(bh: Blackhole) {
repeat(times = size) { index ->
bh.consume(builder[keys[index]])
}
}
} | {
"pile_set_name": "Github"
} |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package context_test
import (
"fmt"
"time"
"golang.org/x/net/context"
)
// This example passes a context with a timeout to tell a blocking function that
// it should abandon its work after the timeout elapses.
func ExampleWithTimeout() {
// Pass a context with a timeout to tell a blocking function that it
// should abandon its work after the timeout elapses.
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err()) // prints "context deadline exceeded"
}
// Output:
// context deadline exceeded
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- qwsembedwidget.cpp -->
<head>
<title>Qt 4.6: QWSEmbedWidget Class Reference</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<a name="//apple_ref/cpp/cl//QWSEmbedWidget" />
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://qt.nokia.com/"><img src="images/qt-logo.png" align="left" border="0" /></a></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="functions.html"><font color="#004faf">All Functions</font></a> · <a href="overviews.html"><font color="#004faf">Overviews</font></a></td></tr></table><h1 class="title">QWSEmbedWidget Class Reference<br /><span class="small-subtitle">[<a href="qtgui.html">QtGui</a> module]</span>
</h1>
<p>The QWSEmbedWidget class enables embedded top-level widgets in Qt for Embedded Linux. <a href="#details">More...</a></p>
<pre> #include <QWSEmbedWidget></pre><p>Inherits <a href="qwidget.html">QWidget</a>.</p>
<p>This class was introduced in Qt 4.2.</p>
<ul>
<li><a href="qwsembedwidget-members.html">List of all members, including inherited members</a></li>
</ul>
<hr />
<a name="public-functions"></a>
<h2>Public Functions</h2>
<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qwsembedwidget.html#QWSEmbedWidget">QWSEmbedWidget</a></b> ( WId <i>id</i>, QWidget * <i>parent</i> = 0 )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"></td><td class="memItemRight" valign="bottom"><b><a href="qwsembedwidget.html#dtor.QWSEmbedWidget">~QWSEmbedWidget</a></b> ()</td></tr>
</table>
<ul>
<li><div bar="2" class="fn"></div>216 public functions inherited from <a href="qwidget.html#public-functions">QWidget</a></li>
<li><div bar="2" class="fn"></div>29 public functions inherited from <a href="qobject.html#public-functions">QObject</a></li>
<li><div bar="2" class="fn"></div>12 public functions inherited from <a href="qpaintdevice.html#public-functions">QPaintDevice</a></li>
</ul>
<hr />
<a name="reimplemented-protected-functions"></a>
<h2>Reimplemented Protected Functions</h2>
<table class="alignedsummary" border="0" cellpadding="0" cellspacing="0" width="100%">
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><b><a href="qwsembedwidget.html#changeEvent">changeEvent</a></b> ( QEvent * <i>event</i> )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual bool </td><td class="memItemRight" valign="bottom"><b><a href="qwsembedwidget.html#eventFilter">eventFilter</a></b> ( QObject * <i>object</i>, QEvent * <i>event</i> )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><b><a href="qwsembedwidget.html#hideEvent">hideEvent</a></b> ( QHideEvent * <i>event</i> )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><b><a href="qwsembedwidget.html#moveEvent">moveEvent</a></b> ( QMoveEvent * <i>event</i> )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><b><a href="qwsembedwidget.html#resizeEvent">resizeEvent</a></b> ( QResizeEvent * <i>event</i> )</td></tr>
<tr><td class="memItemLeft" align="right" valign="top">virtual void </td><td class="memItemRight" valign="bottom"><b><a href="qwsembedwidget.html#showEvent">showEvent</a></b> ( QShowEvent * <i>event</i> )</td></tr>
</table>
<ul>
<li><div bar="2" class="fn"></div>37 protected functions inherited from <a href="qwidget.html#protected-functions">QWidget</a></li>
<li><div bar="2" class="fn"></div>7 protected functions inherited from <a href="qobject.html#protected-functions">QObject</a></li>
<li><div bar="2" class="fn"></div>1 protected function inherited from <a href="qpaintdevice.html#protected-functions">QPaintDevice</a></li>
</ul>
<h3>Additional Inherited Members</h3>
<ul>
<li><div class="fn"></div>58 properties inherited from <a href="qwidget.html#properties">QWidget</a></li>
<li><div class="fn"></div>1 property inherited from <a href="qobject.html#properties">QObject</a></li>
<li><div class="fn"></div>19 public slots inherited from <a href="qwidget.html#public-slots">QWidget</a></li>
<li><div class="fn"></div>1 public slot inherited from <a href="qobject.html#public-slots">QObject</a></li>
<li><div class="fn"></div>1 signal inherited from <a href="qwidget.html#signals">QWidget</a></li>
<li><div class="fn"></div>1 signal inherited from <a href="qobject.html#signals">QObject</a></li>
<li><div class="fn"></div>4 static public members inherited from <a href="qwidget.html#static-public-members">QWidget</a></li>
<li><div class="fn"></div>5 static public members inherited from <a href="qobject.html#static-public-members">QObject</a></li>
<li><div class="fn"></div>37 protected functions inherited from <a href="qwidget.html#protected-functions">QWidget</a></li>
<li><div class="fn"></div>7 protected functions inherited from <a href="qobject.html#protected-functions">QObject</a></li>
<li><div class="fn"></div>1 protected function inherited from <a href="qpaintdevice.html#protected-functions">QPaintDevice</a></li>
<li><div class="fn"></div>1 protected slot inherited from <a href="qwidget.html#protected-slots">QWidget</a></li>
</ul>
<a name="details"></a>
<hr />
<h2>Detailed Description</h2>
<p>The QWSEmbedWidget class enables embedded top-level widgets in Qt for Embedded Linux.</p>
<p>Note that this class is only available in <a href="qt-embedded-linux.html">Qt for Embedded Linux</a>.</p>
<p>QWSEmbedWidget inherits <a href="qwidget.html">QWidget</a> and acts as any other widget, but in addition it is capable of embedding another top-level widget.</p>
<p>An example of use is when painting directly onto the screen using the <a href="qdirectpainter.html">QDirectPainter</a> class. Then the reserved region can be embedded into an instance of the QWSEmbedWidget class, providing for example event handling and size policies for the reserved region.</p>
<p>All that is required to embed a top-level widget is its window ID.</p>
<p>See also <a href="qt-embedded-architecture.html">Qt for Embedded Linux Architecture</a>.</p>
<hr />
<h2>Member Function Documentation</h2>
<a name="//apple_ref/cpp/instm/QWSEmbedWidget/QWSEmbedWidget" />
<h3 class="fn"><a name="QWSEmbedWidget"></a>QWSEmbedWidget::QWSEmbedWidget ( <a href="qwidget.html#WId-typedef">WId</a> <i>id</i>, <a href="qwidget.html">QWidget</a> * <i>parent</i> = 0 )</h3>
<p>Constructs a widget with the given <i>parent</i>, embedding the widget identified by the given window <i>id</i>.</p>
<a name="//apple_ref/cpp/instm/QWSEmbedWidget/~QWSEmbedWidget" />
<h3 class="fn"><a name="dtor.QWSEmbedWidget"></a>QWSEmbedWidget::~QWSEmbedWidget ()</h3>
<p>Destroys this widget.</p>
<a name="//apple_ref/cpp/instm/QWSEmbedWidget/changeEvent" />
<h3 class="fn"><a name="changeEvent"></a>void QWSEmbedWidget::changeEvent ( <a href="qevent.html">QEvent</a> * <i>event</i> ) <tt> [virtual protected]</tt></h3>
<p>Reimplemented from <a href="qwidget.html#changeEvent">QWidget::changeEvent</a>().</p>
<a name="//apple_ref/cpp/instm/QWSEmbedWidget/eventFilter" />
<h3 class="fn"><a name="eventFilter"></a>bool QWSEmbedWidget::eventFilter ( <a href="qobject.html">QObject</a> * <i>object</i>, <a href="qevent.html">QEvent</a> * <i>event</i> ) <tt> [virtual protected]</tt></h3>
<p>Reimplemented from <a href="qobject.html#eventFilter">QObject::eventFilter</a>().</p>
<a name="//apple_ref/cpp/instm/QWSEmbedWidget/hideEvent" />
<h3 class="fn"><a name="hideEvent"></a>void QWSEmbedWidget::hideEvent ( <a href="qhideevent.html">QHideEvent</a> * <i>event</i> ) <tt> [virtual protected]</tt></h3>
<p>Reimplemented from <a href="qwidget.html#hideEvent">QWidget::hideEvent</a>().</p>
<a name="//apple_ref/cpp/instm/QWSEmbedWidget/moveEvent" />
<h3 class="fn"><a name="moveEvent"></a>void QWSEmbedWidget::moveEvent ( <a href="qmoveevent.html">QMoveEvent</a> * <i>event</i> ) <tt> [virtual protected]</tt></h3>
<p>Reimplemented from <a href="qwidget.html#moveEvent">QWidget::moveEvent</a>().</p>
<a name="//apple_ref/cpp/instm/QWSEmbedWidget/resizeEvent" />
<h3 class="fn"><a name="resizeEvent"></a>void QWSEmbedWidget::resizeEvent ( <a href="qresizeevent.html">QResizeEvent</a> * <i>event</i> ) <tt> [virtual protected]</tt></h3>
<p>Reimplemented from <a href="qwidget.html#resizeEvent">QWidget::resizeEvent</a>().</p>
<a name="//apple_ref/cpp/instm/QWSEmbedWidget/showEvent" />
<h3 class="fn"><a name="showEvent"></a>void QWSEmbedWidget::showEvent ( <a href="qshowevent.html">QShowEvent</a> * <i>event</i> ) <tt> [virtual protected]</tt></h3>
<p>Reimplemented from <a href="qwidget.html#showEvent">QWidget::showEvent</a>().</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="40%" align="left">Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies)</td>
<td width="20%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="40%" align="right"><div align="right">Qt 4.6.0</div></td>
</tr></table></div></address></body>
</html>
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' ?>
<Plugin id='31186'>
<Lp>Yes</Lp>
<Implant>Yes</Implant>
<Windows>
<!-- NT family -->
<Platform id='2'>
<Version major='*' minor='*'>
<File>PacketScan_Implant.dll</File>
</Version>
</Platform>
</Windows>
</Plugin> | {
"pile_set_name": "Github"
} |
(module Valve_Mini_G (layer F.Cu) (tedit 5A030096)
(descr "Valve mini G")
(tags "Valve mini G")
(fp_text reference REF** (at -5.08 -2.34) (layer F.SilkS)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_text value Valve_Mini_G (at 8.38 18.29) (layer F.Fab)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_text user %R (at -5.08 2.91) (layer F.Fab)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_text user mounting (at -5.08 8.89) (layer Dwgs.User)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_text user d=15.6mm (at -5.08 11.18) (layer Dwgs.User)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_line (start -11.33 -1.34) (end 1.17 -1.34) (layer F.CrtYd) (width 0.05))
(fp_line (start 1.17 -1.34) (end 9.17 7.41) (layer F.CrtYd) (width 0.05))
(fp_line (start 9.17 7.41) (end 9.17 12.91) (layer F.CrtYd) (width 0.05))
(fp_line (start 9.17 12.91) (end 9.17 13.91) (layer F.CrtYd) (width 0.05))
(fp_line (start 9.17 13.91) (end 2.17 21.66) (layer F.CrtYd) (width 0.05))
(fp_line (start 2.17 21.66) (end -11.58 21.66) (layer F.CrtYd) (width 0.05))
(fp_line (start -11.58 21.66) (end -19.83 13.91) (layer F.CrtYd) (width 0.05))
(fp_line (start -19.83 13.91) (end -19.83 7.41) (layer F.CrtYd) (width 0.05))
(fp_line (start -19.83 7.41) (end -19.83 6.66) (layer F.CrtYd) (width 0.05))
(fp_line (start -19.83 6.66) (end -12.08 -1.34) (layer F.CrtYd) (width 0.05))
(fp_line (start -12.08 -1.34) (end -11.33 -1.34) (layer F.CrtYd) (width 0.05))
(fp_line (start -18.01 8.84) (end -12.07 2.82) (layer F.Fab) (width 0.1))
(fp_line (start 7.82 11.53) (end 1.91 17.55) (layer F.Fab) (width 0.1))
(fp_line (start -18.01 11.51) (end -12.4 17.2) (layer F.Fab) (width 0.1))
(fp_line (start 1.91 2.87) (end 7.9 8.89) (layer F.Fab) (width 0.1))
(fp_circle (center -5.11 10.16) (end -8.92 13.97) (layer F.SilkS) (width 0.12))
(fp_circle (center -5.05 10.16) (end -1.24 13.97) (layer F.SilkS) (width 0.12))
(fp_circle (center -5.05 10.16) (end -1.24 13.97) (layer F.SilkS) (width 0.12))
(fp_circle (center -5.05 10.16) (end -1.24 13.97) (layer F.SilkS) (width 0.12))
(fp_circle (center -5.11 10.16) (end -8.92 13.97) (layer F.Fab) (width 0.1))
(fp_circle (center -5.05 10.16) (end -1.24 13.97) (layer F.Fab) (width 0.1))
(fp_circle (center -5.05 10.16) (end -1.24 13.97) (layer F.Fab) (width 0.1))
(fp_circle (center -5.05 10.16) (end -1.24 13.97) (layer F.Fab) (width 0.1))
(fp_arc (start -5.05 10.16) (end 2.01 17.44) (angle 90.6) (layer F.SilkS) (width 0.12))
(fp_arc (start -5.11 10.21) (end -12.07 2.82) (angle 86.8) (layer F.SilkS) (width 0.12))
(fp_arc (start -5.05 10.16) (end 2.01 17.44) (angle 90.6) (layer F.Fab) (width 0.1))
(fp_arc (start -5.11 10.21) (end -12.07 2.82) (angle 86.8) (layer F.Fab) (width 0.1))
(fp_arc (start 6.35 10.16) (end 7.9 8.89) (angle 83.6) (layer F.Fab) (width 0.1))
(fp_arc (start -16.51 10.16) (end -17.98 11.51) (angle 83.9) (layer F.Fab) (width 0.1))
(pad 1 thru_hole rect (at 0 0) (size 1.78 1.78) (drill 1) (layers *.Cu *.Mask))
(pad 2 thru_hole circle (at -10.16 0) (size 1.78 3.56) (drill 1) (layers *.Cu *.Mask))
(pad 3 thru_hole circle (at -16.51 5.08) (size 1.78 3.56) (drill 1) (layers *.Cu *.Mask))
(pad 4 thru_hole circle (at -16.51 15.24) (size 1.78 3.56) (drill 1) (layers *.Cu *.Mask))
(pad 5 thru_hole circle (at -10.16 20.32) (size 1.78 3.56) (drill 1) (layers *.Cu *.Mask))
(pad 6 thru_hole circle (at 0 20.32) (size 1.78 3.56) (drill 1) (layers *.Cu *.Mask))
(pad 7 thru_hole circle (at 6.35 15.24) (size 1.78 3.56) (drill 1) (layers *.Cu *.Mask))
(pad "" thru_hole circle (at -16.51 10.16) (size 5 5) (drill 4) (layers *.Cu *.Mask))
(pad "" thru_hole circle (at 6.35 10.16) (size 5 5) (drill 4) (layers *.Cu *.Mask))
(model ${KISYS3DMOD}/Valve.3dshapes/Valve_Mini_G.wrl
(at (xyz 0 0 0))
(scale (xyz 1 1 1))
(rotate (xyz 0 0 0))
)
)
| {
"pile_set_name": "Github"
} |
{
"channel": {
"_constructor": "inputChannelEmpty#ee8c1e86"
},
"users": [],
"_constructor": "channels.inviteToChannel#199f3a6c"
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2008 Hyperic, Inc.
*
* 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 <stdio.h>
#include "sigar.h"
int main(int argc, char **argv) {
int status, i;
sigar_t *sigar;
sigar_cpu_list_t cpulist;
sigar_open(&sigar);
status = sigar_cpu_list_get(sigar, &cpulist);
if (status != SIGAR_OK) {
printf("cpu_list error: %d (%s)\n",
status, sigar_strerror(sigar, status));
exit(1);
}
for (i=0; i<cpulist.number; i++) {
sigar_cpu_t cpu = cpulist.data[i];
/*...*/
}
sigar_cpu_list_destroy(sigar, &cpulist);
sigar_close(sigar);
return 0;
}
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !gccgo
#include "textflag.h"
//
// System calls for amd64, Solaris are implemented in runtime/syscall_solaris.go
//
TEXT ·sysvicall6(SB),NOSPLIT,$0-88
JMP syscall·sysvicall6(SB)
TEXT ·rawSysvicall6(SB),NOSPLIT,$0-88
JMP syscall·rawSysvicall6(SB)
| {
"pile_set_name": "Github"
} |
<?php
/**
* Validates a number as defined by the CSS spec.
*/
class HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef
{
/**
* Indicates whether or not only positive values are allowed.
* @type bool
*/
protected $non_negative = false;
/**
* @param bool $non_negative indicates whether negatives are forbidden
*/
public function __construct($non_negative = false)
{
$this->non_negative = $non_negative;
}
/**
* @param string $number
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return string|bool
* @warning Some contexts do not pass $config, $context. These
* variables should not be used without checking HTMLPurifier_Length
*/
public function validate($number, $config, $context)
{
$number = $this->parseCDATA($number);
if ($number === '') {
return false;
}
if ($number === '0') {
return '0';
}
$sign = '';
switch ($number[0]) {
case '-':
if ($this->non_negative) {
return false;
}
$sign = '-';
case '+':
$number = substr($number, 1);
}
if (ctype_digit($number)) {
$number = ltrim($number, '0');
return $number ? $sign . $number : '0';
}
// Period is the only non-numeric character allowed
if (strpos($number, '.') === false) {
return false;
}
list($left, $right) = explode('.', $number, 2);
if ($left === '' && $right === '') {
return false;
}
if ($left !== '' && !ctype_digit($left)) {
return false;
}
$left = ltrim($left, '0');
$right = rtrim($right, '0');
if ($right === '') {
return $left ? $sign . $left : '0';
} elseif (!ctype_digit($right)) {
return false;
}
return $sign . $left . '.' . $right;
}
}
// vim: et sw=4 sts=4
| {
"pile_set_name": "Github"
} |
// Copyright © 2019 Banzai Cloud
//
// 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.
// +build !linux
package kubernetes
import (
"io"
"emperror.dev/errors"
)
func (r *Runtime) installRuntime(w io.Writer) error {
return errors.Errorf("unsupported operating system")
}
| {
"pile_set_name": "Github"
} |
<!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 -->
<title>ProxyScanner (GWT Javadoc)</title>
<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="ProxyScanner (GWT Javadoc)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete 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/ProxyScanner.html">Use</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">GWT 2.9.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/google/web/bindery/requestfactory/apt/Messages.html" title="class in com.google.web.bindery.requestfactory.apt"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ReferredTypesCollector.html" title="class in com.google.web.bindery.requestfactory.apt"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/google/web/bindery/requestfactory/apt/ProxyScanner.html" target="_top">Frames</a></li>
<li><a href="ProxyScanner.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><a href="#fields.inherited.from.class.javax.lang.model.util.ElementScanner6">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </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">com.google.web.bindery.requestfactory.apt</div>
<h2 title="Class ProxyScanner" class="title">Class ProxyScanner</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>javax.lang.model.util.AbstractElementVisitor6<R,P></li>
<li>
<ul class="inheritance">
<li>javax.lang.model.util.ElementScanner6<R,<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a>></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html" title="class in com.google.web.bindery.requestfactory.apt">com.google.web.bindery.requestfactory.apt.ScannerBase</a><java.lang.Void></li>
<li>
<ul class="inheritance">
<li>com.google.web.bindery.requestfactory.apt.ProxyScanner</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>javax.lang.model.element.ElementVisitor<java.lang.Void,<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a>></dd>
</dl>
<hr>
<br>
<pre>class <span class="typeNameLabel">ProxyScanner</span>
extends <a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html" title="class in com.google.web.bindery.requestfactory.apt">ScannerBase</a><java.lang.Void></pre>
<div class="block">Examines the methods declared in a proxy interface. Also records the client
to domain mapping for the proxy type.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields.inherited.from.class.javax.lang.model.util.ElementScanner6">
<!-- -->
</a>
<h3>Fields inherited from class javax.lang.model.util.ElementScanner6</h3>
<code>DEFAULT_VALUE</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ProxyScanner.html#ProxyScanner--">ProxyScanner</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== 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="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete 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>protected boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ProxyScanner.html#shouldIgnore-javax.lang.model.element.ExecutableElement-com.google.web.bindery.requestfactory.apt.State-">shouldIgnore</a></span>(javax.lang.model.element.ExecutableElement x,
<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a> state)</code>
<div class="block">Ignore all static initializers and methods defined in the base
RequestFactory interfaces</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>java.lang.Void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ProxyScanner.html#visitExecutable-javax.lang.model.element.ExecutableElement-com.google.web.bindery.requestfactory.apt.State-">visitExecutable</a></span>(javax.lang.model.element.ExecutableElement x,
<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a> state)</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>java.lang.Void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ProxyScanner.html#visitType-javax.lang.model.element.TypeElement-com.google.web.bindery.requestfactory.apt.State-">visitType</a></span>(javax.lang.model.element.TypeElement x,
<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a> state)</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>java.lang.Void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ProxyScanner.html#visitVariable-javax.lang.model.element.VariableElement-com.google.web.bindery.requestfactory.apt.State-">visitVariable</a></span>(javax.lang.model.element.VariableElement x,
<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a> state)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.com.google.web.bindery.requestfactory.apt.ScannerBase">
<!-- -->
</a>
<h3>Methods inherited from class com.google.web.bindery.requestfactory.apt.<a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html" title="class in com.google.web.bindery.requestfactory.apt">ScannerBase</a></h3>
<code><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html#isGetter-javax.lang.model.element.ExecutableElement-com.google.web.bindery.requestfactory.apt.State-">isGetter</a>, <a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html#isSetter-javax.lang.model.element.ExecutableElement-com.google.web.bindery.requestfactory.apt.State-">isSetter</a>, <a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html#poisonIfAnnotationPresent-com.google.web.bindery.requestfactory.apt.State-javax.lang.model.element.TypeElement-java.lang.annotation.Annotation...-">poisonIfAnnotationPresent</a>, <a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html#scan-javax.lang.model.element.Element-com.google.web.bindery.requestfactory.apt.State-">scan</a>, <a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html#scanAllInheritedMethods-javax.lang.model.element.TypeElement-com.google.web.bindery.requestfactory.apt.State-">scanAllInheritedMethods</a>, <a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html#viewIn-javax.lang.model.element.TypeElement-javax.lang.model.element.ExecutableElement-com.google.web.bindery.requestfactory.apt.State-">viewIn</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.javax.lang.model.util.ElementScanner6">
<!-- -->
</a>
<h3>Methods inherited from class javax.lang.model.util.ElementScanner6</h3>
<code>scan, scan, visitPackage, visitTypeParameter</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.javax.lang.model.util.AbstractElementVisitor6">
<!-- -->
</a>
<h3>Methods inherited from class javax.lang.model.util.AbstractElementVisitor6</h3>
<code>visit, visit, visitUnknown</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="ProxyScanner--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ProxyScanner</h4>
<pre>ProxyScanner()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="visitExecutable-javax.lang.model.element.ExecutableElement-com.google.web.bindery.requestfactory.apt.State-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>visitExecutable</h4>
<pre>public java.lang.Void visitExecutable(javax.lang.model.element.ExecutableElement x,
<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a> state)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>visitExecutable</code> in interface <code>javax.lang.model.element.ElementVisitor<java.lang.Void,<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a>></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>visitExecutable</code> in class <code>javax.lang.model.util.ElementScanner6<java.lang.Void,<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a>></code></dd>
</dl>
</li>
</ul>
<a name="visitType-javax.lang.model.element.TypeElement-com.google.web.bindery.requestfactory.apt.State-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>visitType</h4>
<pre>public java.lang.Void visitType(javax.lang.model.element.TypeElement x,
<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a> state)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>visitType</code> in interface <code>javax.lang.model.element.ElementVisitor<java.lang.Void,<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a>></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>visitType</code> in class <code>javax.lang.model.util.ElementScanner6<java.lang.Void,<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a>></code></dd>
</dl>
</li>
</ul>
<a name="visitVariable-javax.lang.model.element.VariableElement-com.google.web.bindery.requestfactory.apt.State-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>visitVariable</h4>
<pre>public java.lang.Void visitVariable(javax.lang.model.element.VariableElement x,
<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a> state)</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code>visitVariable</code> in interface <code>javax.lang.model.element.ElementVisitor<java.lang.Void,<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a>></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code>visitVariable</code> in class <code>javax.lang.model.util.ElementScanner6<java.lang.Void,<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a>></code></dd>
</dl>
</li>
</ul>
<a name="shouldIgnore-javax.lang.model.element.ExecutableElement-com.google.web.bindery.requestfactory.apt.State-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>shouldIgnore</h4>
<pre>protected boolean shouldIgnore(javax.lang.model.element.ExecutableElement x,
<a href="../../../../../../com/google/web/bindery/requestfactory/apt/State.html" title="class in com.google.web.bindery.requestfactory.apt">State</a> state)</pre>
<div class="block"><span class="descfrmTypeLabel">Description copied from class: <code><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html#shouldIgnore-javax.lang.model.element.ExecutableElement-com.google.web.bindery.requestfactory.apt.State-">ScannerBase</a></code></span></div>
<div class="block">Ignore all static initializers and methods defined in the base
RequestFactory interfaces</div>
<dl>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html#shouldIgnore-javax.lang.model.element.ExecutableElement-com.google.web.bindery.requestfactory.apt.State-">shouldIgnore</a></code> in class <code><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ScannerBase.html" title="class in com.google.web.bindery.requestfactory.apt">ScannerBase</a><java.lang.Void></code></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/ProxyScanner.html">Use</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">GWT 2.9.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/google/web/bindery/requestfactory/apt/Messages.html" title="class in com.google.web.bindery.requestfactory.apt"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../com/google/web/bindery/requestfactory/apt/ReferredTypesCollector.html" title="class in com.google.web.bindery.requestfactory.apt"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/google/web/bindery/requestfactory/apt/ProxyScanner.html" target="_top">Frames</a></li>
<li><a href="ProxyScanner.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><a href="#fields.inherited.from.class.javax.lang.model.util.ElementScanner6">Field</a> | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
# disable z3 for cross-platform stability
from test_support import *
prove_all (prover=["cvc4"])
| {
"pile_set_name": "Github"
} |
#pragma once
#include <algorithm>
#include <optional>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include "base/not_null.hpp"
#include "base/traits.hpp"
#include "geometry/hilbert.hpp"
#include "geometry/point.hpp"
#include "quantities/named_quantities.hpp"
#include "quantities/tuples.hpp"
#include "serialization/numerics.pb.h"
namespace principia {
namespace numerics {
FORWARD_DECLARE_FROM(polynomial,
TEMPLATE(typename Value, typename Argument, int degree_,
template<typename, typename, int> class Evaluator)
class,
PolynomialInMonomialBasis);
} // namespace numerics
namespace mathematica {
FORWARD_DECLARE_FUNCTION_FROM(
mathematica,
TEMPLATE(typename Value, typename Argument, int degree_,
template<typename, typename, int> class Evaluator,
typename OptionalExpressIn = std::nullopt_t) std::string,
ToMathematicaExpression,
(numerics::
PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator> const&
polynomial,
OptionalExpressIn express_in = std::nullopt));
} // namespace mathematica
namespace numerics {
namespace internal_polynomial {
using base::is_instance_of_v;
using base::not_constructible;
using base::not_null;
using geometry::Hilbert;
using geometry::Point;
using quantities::Derivative;
using quantities::Derivatives;
using quantities::Primitive;
using quantities::Product;
using quantities::Quotient;
// |Value| must belong to an affine space. |Argument| must belong to a ring or
// to Point based on a ring.
// TODO(phl): We would like the base case to be the affine case (not limited to
// Point) and the specialized case to check for the existence of Sum and Product
// for Argument, and that works with Clang but not with VS2015. Revisit once
// MSFT has fixed their bugs.
template<typename Value, typename Argument>
class Polynomial {
public:
// This virtual destructor makes this class and its subclasses non-literal, so
// constexpr-ness is a bit of a lie for polynomials.
// TODO(phl): Consider providing an explicit deleter function that would allow
// making the destructor protected and nonvirtual.
virtual ~Polynomial() = default;
virtual Value Evaluate(Argument const& argument) const = 0;
virtual Derivative<Value, Argument> EvaluateDerivative(
Argument const& argument) const = 0;
// Only useful for benchmarking, analyzing performance or for downcasting. Do
// not use in other circumstances.
virtual int degree() const = 0;
// Only useful for logging. Do not use in real code.
virtual bool is_zero() const = 0;
virtual void WriteToMessage(
not_null<serialization::Polynomial*> message) const = 0;
// The evaluator is not part of the serialization because it's fine to read
// with a different evaluator than the one the polynomial was written with.
template<template<typename, typename, int> class Evaluator>
static not_null<std::unique_ptr<Polynomial>> ReadFromMessage(
serialization::Polynomial const& message);
};
template<typename Value, typename Argument, int degree_,
template<typename, typename, int> class Evaluator>
class PolynomialInMonomialBasis : public Polynomial<Value, Argument> {
public:
using Result = Value;
// Equivalent to:
// std::tuple<Value,
// Derivative<Value, Argument>,
// Derivative<Derivative<Value, Argument>>...>
using Coefficients = Derivatives<Value, Argument, degree_ + 1>;
// The coefficients are applied to powers of argument.
explicit constexpr PolynomialInMonomialBasis(
Coefficients coefficients);
// A polynomial may be explicitly converted to a higher degree (possibly with
// a different evaluator).
template<int higher_degree_,
template<typename, typename, int> class HigherEvaluator>
explicit operator PolynomialInMonomialBasis<
Value, Argument, higher_degree_, HigherEvaluator>() const;
FORCE_INLINE(inline) Value
Evaluate(Argument const& argument) const override;
FORCE_INLINE(inline) Derivative<Value, Argument>
EvaluateDerivative(Argument const& argument) const override;
constexpr int degree() const override;
bool is_zero() const override;
template<int order = 1>
PolynomialInMonomialBasis<
Derivative<Value, Argument, order>, Argument, degree_ - order, Evaluator>
Derivative() const;
// The constant term of the result is zero.
template<typename V = Value,
typename = std::enable_if_t<!base::is_instance_of_v<Point, V>>>
PolynomialInMonomialBasis<Primitive<Value, Argument>, Argument,
degree_ + 1, Evaluator>
Primitive() const;
PolynomialInMonomialBasis& operator+=(PolynomialInMonomialBasis const& right);
PolynomialInMonomialBasis& operator-=(PolynomialInMonomialBasis const& right);
void WriteToMessage(
not_null<serialization::Polynomial*> message) const override;
static PolynomialInMonomialBasis ReadFromMessage(
serialization::Polynomial const& message);
private:
Coefficients coefficients_;
template<typename V, typename A, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<V, A, r, E>
friend operator-(PolynomialInMonomialBasis<V, A, r, E> const& right);
template<typename V, typename A, int l, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<V, A, std::max(l, r), E>
friend operator+(PolynomialInMonomialBasis<V, A, l, E> const& left,
PolynomialInMonomialBasis<V, A, r, E> const& right);
template<typename V, typename A, int l, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<V, A, std::max(l, r), E>
friend operator-(PolynomialInMonomialBasis<V, A, l, E> const& left,
PolynomialInMonomialBasis<V, A, r, E> const& right);
template<typename S,
typename V, typename A, int d,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<Product<S, V>, A, d, E>
friend operator*(S const& left,
PolynomialInMonomialBasis<V, A, d, E> const& right);
template<typename S,
typename V, typename A, int d,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<Product<V, S>, A, d, E>
friend operator*(PolynomialInMonomialBasis<V, A, d, E> const& left,
S const& right);
template<typename S,
typename V, typename A, int d,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<Quotient<V, S>, A, d, E>
friend operator/(PolynomialInMonomialBasis<V, A, d, E> const& left,
S const& right);
template<typename L, typename R, typename A,
int l, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<Product<L, R>, A, l + r, E>
friend operator*(
PolynomialInMonomialBasis<L, A, l, E> const& left,
PolynomialInMonomialBasis<R, A, r, E> const& right);
template<typename L, typename R, typename A,
int l, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<
typename Hilbert<L, R>::InnerProductType, A, l + r, E>
friend PointwiseInnerProduct(
PolynomialInMonomialBasis<L, A, l, E> const& left,
PolynomialInMonomialBasis<R, A, r, E> const& right);
template<typename V, typename A, int d,
template<typename, typename, int> class E>
friend std::ostream& operator<<(
std::ostream& out,
PolynomialInMonomialBasis<V, A, d, E> const& polynomial);
template<typename V, typename A, int d,
template<typename, typename, int> class E,
typename O>
friend std::string mathematica::internal_mathematica::ToMathematicaExpression(
PolynomialInMonomialBasis<V, A, d, E> const& polynomial,
O express_in);
};
template<typename Value, typename Argument, int degree_,
template<typename, typename, int> class Evaluator>
class PolynomialInMonomialBasis<Value, Point<Argument>, degree_, Evaluator>
: public Polynomial<Value, Point<Argument>> {
public:
// TODO(phl): Use the |Value_| style.
using Result = Value;
// Equivalent to:
// std::tuple<Value,
// Derivative<Value, Argument>,
// Derivative<Derivative<Value, Argument>>...>
using Coefficients = Derivatives<Value, Argument, degree_ + 1>;
// The coefficients are relative to origin; in other words they are applied to
// powers of (argument - origin).
constexpr PolynomialInMonomialBasis(Coefficients coefficients,
Point<Argument> const& origin);
// A polynomial may be explicitly converted to a higher degree (possibly with
// a different evaluator).
template<int higher_degree_,
template<typename, typename, int> class HigherEvaluator>
explicit operator PolynomialInMonomialBasis<
Value, Point<Argument>, higher_degree_, HigherEvaluator>() const;
FORCE_INLINE(inline) Value
Evaluate(Point<Argument> const& argument) const override;
FORCE_INLINE(inline) Derivative<Value, Argument>
EvaluateDerivative(Point<Argument> const& argument) const override;
constexpr int degree() const override;
bool is_zero() const override;
Point<Argument> const& origin() const;
// Returns a copy of this polynomial adjusted to the given origin.
PolynomialInMonomialBasis AtOrigin(Point<Argument> const& origin) const;
template<int order = 1>
PolynomialInMonomialBasis<
Derivative<Value, Argument, order>, Point<Argument>, degree_ - order,
Evaluator>
Derivative() const;
// The constant term of the result is zero.
template<typename V = Value,
typename = std::enable_if_t<!base::is_instance_of_v<Point, V>>>
PolynomialInMonomialBasis<Primitive<Value, Argument>, Point<Argument>,
degree_ + 1, Evaluator>
Primitive() const;
PolynomialInMonomialBasis& operator+=(const PolynomialInMonomialBasis& right);
PolynomialInMonomialBasis& operator-=(const PolynomialInMonomialBasis& right);
void WriteToMessage(
not_null<serialization::Polynomial*> message) const override;
static PolynomialInMonomialBasis ReadFromMessage(
serialization::Polynomial const& message);
private:
Coefficients coefficients_;
Point<Argument> origin_;
template<typename V, typename A, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<V, A, r, E>
friend operator-(PolynomialInMonomialBasis<V, A, r, E> const& right);
template<typename V, typename A, int l, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<V, A, std::max(l, r), E>
friend operator+(PolynomialInMonomialBasis<V, A, l, E> const& left,
PolynomialInMonomialBasis<V, A, r, E> const& right);
template<typename V, typename A, int l, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<V, A, std::max(l, r), E>
friend operator-(PolynomialInMonomialBasis<V, A, l, E> const& left,
PolynomialInMonomialBasis<V, A, r, E> const& right);
template<typename S,
typename V, typename A, int d,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<Product<S, V>, A, d, E>
friend operator*(S const& left,
PolynomialInMonomialBasis<V, A, d, E> const& right);
template<typename S,
typename V, typename A, int d,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<Product<V, S>, A, d, E>
friend operator*(PolynomialInMonomialBasis<V, A, d, E> const& left,
S const& right);
template<typename S,
typename V, typename A, int d,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<Quotient<V, S>, A, d, E>
friend operator/(PolynomialInMonomialBasis<V, A, d, E> const& left,
S const& right);
template<typename L, typename R, typename A,
int l, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<Product<L, R>, A, l + r, E>
friend operator*(
PolynomialInMonomialBasis<L, A, l, E> const& left,
PolynomialInMonomialBasis<R, A, r, E> const& right);
template<typename L, typename R, typename A,
int l, int r,
template<typename, typename, int> class E>
constexpr PolynomialInMonomialBasis<
typename Hilbert<L, R>::InnerProductType, A, l + r, E>
friend PointwiseInnerProduct(
PolynomialInMonomialBasis<L, A, l, E> const& left,
PolynomialInMonomialBasis<R, A, r, E> const& right);
template<typename V, typename A, int d,
template<typename, typename, int> class E>
friend std::ostream& operator<<(
std::ostream& out,
PolynomialInMonomialBasis<V, A, d, E> const& polynomial);
template<typename V, typename A, int d,
template<typename, typename, int> class E,
typename O>
friend std::string mathematica::internal_mathematica::ToMathematicaExpression(
PolynomialInMonomialBasis<V, A, d, E> const& polynomial,
O express_in);
};
// Vector space of polynomials.
template<typename Value, typename Argument, int rdegree_,
template<typename, typename, int> class Evaluator>
constexpr PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator>
operator+(PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator> const&
right);
template<typename Value, typename Argument, int rdegree_,
template<typename, typename, int> class Evaluator>
constexpr PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator>
operator-(PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator> const&
right);
template<typename Value, typename Argument, int ldegree_, int rdegree_,
template<typename, typename, int> class Evaluator>
constexpr PolynomialInMonomialBasis<Value, Argument,
std::max(ldegree_, rdegree_), Evaluator>
operator+(
PolynomialInMonomialBasis<Value, Argument, ldegree_, Evaluator> const& left,
PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator> const&
right);
template<typename Value, typename Argument, int ldegree_, int rdegree_,
template<typename, typename, int> class Evaluator>
constexpr PolynomialInMonomialBasis<Value, Argument,
std::max(ldegree_, rdegree_), Evaluator>
operator-(
PolynomialInMonomialBasis<Value, Argument, ldegree_, Evaluator> const& left,
PolynomialInMonomialBasis<Value, Argument, rdegree_, Evaluator> const&
right);
template<typename Scalar,
typename Value, typename Argument, int degree_,
template<typename, typename, int> class Evaluator>
constexpr PolynomialInMonomialBasis<Product<Scalar, Value>, Argument,
degree_, Evaluator>
operator*(Scalar const& left,
PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator> const&
right);
template<typename Scalar,
typename Value, typename Argument, int degree_,
template<typename, typename, int> class Evaluator>
constexpr PolynomialInMonomialBasis<Product<Value, Scalar>, Argument,
degree_, Evaluator>
operator*(PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator> const&
left,
Scalar const& right);
template<typename Scalar,
typename Value, typename Argument, int degree_,
template<typename, typename, int> class Evaluator>
constexpr PolynomialInMonomialBasis<Quotient<Value, Scalar>, Argument,
degree_, Evaluator>
operator/(PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator> const&
left,
Scalar const& right);
// Algebra of polynomials.
template<typename LValue, typename RValue,
typename Argument, int ldegree_, int rdegree_,
template<typename, typename, int> class Evaluator>
constexpr PolynomialInMonomialBasis<Product<LValue, RValue>, Argument,
ldegree_ + rdegree_, Evaluator>
operator*(
PolynomialInMonomialBasis<LValue, Argument, ldegree_, Evaluator> const&
left,
PolynomialInMonomialBasis<RValue, Argument, rdegree_, Evaluator> const&
right);
// Returns a scalar polynomial obtained by pointwise inner product of two
// vector-valued polynomials.
template<typename LValue, typename RValue,
typename Argument, int ldegree_, int rdegree_,
template<typename, typename, int> class Evaluator>
constexpr PolynomialInMonomialBasis<
typename Hilbert<LValue, RValue>::InnerProductType, Argument,
ldegree_ + rdegree_, Evaluator>
PointwiseInnerProduct(
PolynomialInMonomialBasis<LValue, Argument, ldegree_, Evaluator> const&
left,
PolynomialInMonomialBasis<RValue, Argument, rdegree_, Evaluator> const&
right);
// Output.
template<typename Value, typename Argument, int degree_,
template<typename, typename, int> class Evaluator>
std::ostream& operator<<(
std::ostream& out,
PolynomialInMonomialBasis<Value, Argument, degree_, Evaluator> const&
polynomial);
} // namespace internal_polynomial
using internal_polynomial::Polynomial;
using internal_polynomial::PolynomialInMonomialBasis;
} // namespace numerics
} // namespace principia
#include "numerics/polynomial_body.hpp"
| {
"pile_set_name": "Github"
} |
# Copyright 2020 Hewlett Packard Enterprise Development LP
# Copyright 2004-2019 Cray Inc.
# Other additional copyright holders may be indicated within.
#
# The entirety of this work is 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.
RUNTIME_ROOT = ../../..
RUNTIME_SUBDIR = src/comm/ofi
ifndef CHPL_MAKE_HOME
export CHPL_MAKE_HOME=$(shell pwd)/$(RUNTIME_ROOT)/..
endif
#
# standard header
#
include $(RUNTIME_ROOT)/make/Makefile.runtime.head
COMM_OBJDIR = $(RUNTIME_OBJDIR)
COMM_LAUNCHER_OBJDIR = $(LAUNCHER_OBJDIR)
include Makefile.share
ifneq ($(MAKE_LAUNCHER),1)
TARGETS = \
$(COMM_OBJS) \
else
TARGETS = \
$(COMM_LAUNCHER_OBJS) \
endif
include $(RUNTIME_ROOT)/make/Makefile.runtime.subdirrules
#
# standard footer
#
include $(RUNTIME_ROOT)/make/Makefile.runtime.foot
| {
"pile_set_name": "Github"
} |
#include <gtest/gtest.h>
#include <cpp-utils/data/DataFixture.h>
#include <cryfs/impl/config/crypto/inner/InnerConfig.h>
using cpputils::Data;
using cpputils::DataFixture;
using boost::none;
using std::ostream;
using namespace cryfs;
// This is needed for google test
namespace boost {
ostream &operator<<(ostream &stream, const InnerConfig &config) {
return stream << "InnerConfig(" << config.cipherName << ", [data])";
}
}
#include <boost/optional/optional_io.hpp>
TEST(InnerConfigTest, SomeValues) {
Data serialized = InnerConfig{"myciphername", DataFixture::generate(1024)}.serialize();
InnerConfig deserialized = InnerConfig::deserialize(serialized).value();
EXPECT_EQ("myciphername", deserialized.cipherName);
EXPECT_EQ(DataFixture::generate(1024), deserialized.encryptedConfig);
}
TEST(InnerConfigTest, DataEmpty) {
Data serialized = InnerConfig{"myciphername", Data(0)}.serialize();
InnerConfig deserialized = InnerConfig::deserialize(serialized).value();
EXPECT_EQ("myciphername", deserialized.cipherName);
EXPECT_EQ(Data(0), deserialized.encryptedConfig);
}
TEST(InnerConfigTest, CipherNameEmpty) {
Data serialized = InnerConfig{"", DataFixture::generate(1024)}.serialize();
InnerConfig deserialized = InnerConfig::deserialize(serialized).value();
EXPECT_EQ("", deserialized.cipherName);
EXPECT_EQ(DataFixture::generate(1024), deserialized.encryptedConfig);
}
TEST(InnerConfigTest, DataAndCipherNameEmpty) {
Data serialized = InnerConfig{"", Data(0)}.serialize();
InnerConfig deserialized = InnerConfig::deserialize(serialized).value();
EXPECT_EQ("", deserialized.cipherName);
EXPECT_EQ(Data(0), deserialized.encryptedConfig);
}
TEST(InnerConfigTest, InvalidSerialization) {
auto deserialized = InnerConfig::deserialize(DataFixture::generate(1024));
EXPECT_EQ(none, deserialized);
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.