answer
stringlengths
15
1.25M
package http import ( "bytes" "fmt" "net/http" "strconv" "strings" "text/template" dsconfig "github.com/mneudert/devel.serve/ds/config" dstpl "github.com/mneudert/devel.serve/ds/templates/reloader" ) type <API key> struct{} type <API key> struct { http.ResponseWriter deferredStatus int } func (this <API key>) WriteHeader(status int) { // defer setting of status until modified content is generated this.deferredStatus = status } func (this <API key>) Write(data []byte) (int, error) { injectAt := 0 content := string(data) if strings.Contains(content, "</head>") { injectAt = strings.Index(content, "</head>") } else if strings.Contains(content, "<html>") { injectAt = strings.Index(content, "<html>") + 6 } if 0 < injectAt { content = fmt.Sprint( content[:injectAt], "<script src=\""+dsconfig.Reloader.PathScript+"\" type=\"text/javascript\"></script>", content[injectAt:], ) } this.ResponseWriter.Header().Set("Content-Type", "text/html; charset=utf-8") this.ResponseWriter.Header().Set("Content-Length", strconv.FormatInt(int64(len(content)), 10)) this.ResponseWriter.WriteHeader(this.deferredStatus) return this.ResponseWriter.Write([]byte(content)) } func (this *<API key>) ServeHTTP(res http.ResponseWriter, req *http.Request) { var data = make(map[string]interface{}) data["PathSocket"] = dsconfig.Reloader.PathSocket data["PathXhr"] = dsconfig.Reloader.PathXhr data["WsAddress"] = fmt.Sprintf("%s:%d", dsconfig.Server.Host, dsconfig.Server.Port) data["XhrInterval"] = dsconfig.Reloader.XhrInterval var reloader bytes.Buffer tplReloader := template.New("reloader") tplReloader.Parse(dstpl.TplScript) tplReloader.Execute(&reloader, &data) content := reloader.Bytes() res.Header().Set("Content-Type", "text/javascript; charset=utf-8") res.Header().Set("Content-Length", strconv.FormatInt(int64(len(content)), 10)) res.Write(content) } func <API key>() *<API key> { return new(<API key>) }
#pragma once #include <bitset> #include <map> #include <stack> #include "graphics/Camera.h" #include "graphics/Sprite.h" const int MAX_ENTITY_NUMBER = 500; namespace core { class World { public: World(); int createEntity(std::string name = ""); void destroyEntity(int id); int getEntityIdByName(const std::string& name); bool matchesPattern(int id, std::bitset<2> pattern); graphics::Camera* assignCamera(int id); graphics::Camera* getCamera(int id); void unassignCamera(int id); graphics::Sprite* assignSprite(int id); graphics::Sprite* getSprite(int id); void unassignSprite(int id); private: std::bitset<2> entities[MAX_ENTITY_NUMBER]; std::stack<int> freeEntities; std::map<std::string, int> entityIdMap; graphics::Camera cameras[MAX_ENTITY_NUMBER]; graphics::Sprite sprites[MAX_ENTITY_NUMBER]; }; }
<?php namespace Stripe\Util; /** * @internal * @covers \Stripe\Util\<API key> */ final class <API key> extends \Stripe\TestCase { use \Stripe\TestHelper; public function testArrayAccess() { $arr = new <API key>(['One' => '1', 'TWO' => '2']); $arr['thrEE'] = '3'; static::assertSame('1', $arr['one']); static::assertSame('1', $arr['One']); static::assertSame('1', $arr['ONE']); static::assertSame('2', $arr['two']); static::assertSame('2', $arr['twO']); static::assertSame('2', $arr['TWO']); static::assertSame('3', $arr['three']); static::assertSame('3', $arr['ThReE']); static::assertSame('3', $arr['THREE']); } public function testCount() { $arr = new <API key>(['One' => '1', 'TWO' => '2']); static::assertCount(2, $arr); } public function testIterable() { $arr = new <API key>(['One' => '1', 'TWO' => '2']); $seen = []; foreach ($arr as $k => $v) { $seen[$k] = $v; } static::assertSame('1', $seen['one']); static::assertSame('2', $seen['two']); } }
using System; using Newtonsoft.Json; namespace Tweetinvi { <summary> Provide a set of preconfigured solutions that you can use to track the Twitter rate limits. </summary> public enum <API key> { <summary> By default Tweetinvi let you handle the RateLimits on your own </summary> None, <summary> This option will track the actions performed and update the internal RateLimits. If not enought RateLimits are available to perform the query, the current thread will await for the RateLimits to be available before continuing its process. </summary> TrackAndAwait, <summary> This option will only track the actions performed and update the internal RateLimits. This option won't pause a thread if you do not have enough RateLimits to perform a query. </summary> TrackOnly, } <summary> Specify whether you want your tweet to use Twitter extended mode. </summary> public enum TweetMode { Extended = 0, Compat = 1, None = 2 } public interface ITweetinviSettings { <summary> Proxy used to execute Http Requests. </summary> IProxyConfig ProxyConfig { get; set; } <summary> Http Requests Timeout duration in milliseconds. </summary> TimeSpan HttpRequestTimeout { get; set; } <summary> Solution used to track the RateLimits. </summary> <API key> <API key> { get; set; } <summary> How much additional time to wait than should be strictly necessary for a new batch of Twitter rate limits to be available. Required to account for timing discrepancies both within Twitter's servers and between Twitter and us. </summary> TimeSpan RateLimitWaitFudge { get; set; } <summary> Specify whether you want your tweet to use the extended mode. </summary> TweetMode? TweetMode { get; set; } <summary> A method allowing developers to specify how to retrieve the current DateTime. The DateTime must be valid for the HttpRequest signature to be accepted by Twitter. </summary> Func<DateTime> GetUtcDateTime { get; set; } <summary> Converters used by Tweetinvi to transform json received from Twitter into models understandable by Tweetinvi. </summary> JsonConverter[] Converters { get; set; } <summary> Limits that Tweetinvi will use to communicate with Twitter </summary> TwitterLimits Limits { get; set; } <summary> Initialize a setting from another one. </summary> void Initialize(ITweetinviSettings other); } public class TweetinviSettings : ITweetinviSettings { public IProxyConfig ProxyConfig { get; set; } public TimeSpan HttpRequestTimeout { get; set; } public <API key> <API key> { get; set; } public TimeSpan RateLimitWaitFudge { get; set; } public TweetMode? TweetMode { get; set; } public Func<DateTime> GetUtcDateTime { get; set; } public TwitterLimits Limits { get; set; } public TweetinviSettings() { GetUtcDateTime = () => DateTime.UtcNow; Limits = new TwitterLimits(); HttpRequestTimeout = TimeSpan.FromSeconds(10); TweetMode = Tweetinvi.TweetMode.Extended; } public TweetinviSettings(ITweetinviSettings source) : this() { if (source == null) { return; } ProxyConfig = source.ProxyConfig == null || source.ProxyConfig.Address == null ? null : new ProxyConfig(source.ProxyConfig); HttpRequestTimeout = source.HttpRequestTimeout; <API key> = source.<API key>; RateLimitWaitFudge = source.RateLimitWaitFudge; TweetMode = source.TweetMode; GetUtcDateTime = source.GetUtcDateTime; Converters = source.Converters; Limits = new TwitterLimits(source.Limits); } public JsonConverter[] Converters { get; set; } public void Initialize(ITweetinviSettings other) { ProxyConfig = other.ProxyConfig; HttpRequestTimeout = other.HttpRequestTimeout; <API key> = other.<API key>; RateLimitWaitFudge = other.RateLimitWaitFudge; TweetMode = other.TweetMode; GetUtcDateTime = other.GetUtcDateTime; Converters = other.Converters; Limits = new TwitterLimits(other.Limits); } } }
<?php @ini_set("display_errors","1"); @ini_set("<API key>","1"); require_once("include/dbcommon.php"); add_nocache_headers(); require_once("classes/searchclause.php"); require_once("include/<API key>.php"); require_once("classes/searchcontrol.php"); require_once("classes/<API key>.php"); require_once("classes/panelsearchcontrol.php"); if( !isLogged() ) { Security::saveRedirectURL(); redirectToLogin(); } $cname = postvalue("cname"); $rname = postvalue("rname"); $accessGranted = <API key>($strTableName, "S"); if(!$accessGranted) { HeaderRedirect("menu"); } $layout = new TLayout("search2", "RoundedOffice", "MobileOffice"); $layout->version = 2; $layout->blocks["top"] = array(); $layout->containers["search"] = array(); $layout-><API key>["search"] = array( ); $layout->containers["search"][] = array("name"=>"srchheader", "block"=>"searchheader", "substyle"=>2 ); $layout->containers["search"][] = array("name"=>"srchconditions", "block"=>"conditions_block", "substyle"=>1 ); $layout->containers["search"][] = array("name"=>"wrapper", "block"=>"", "substyle"=>1 , "container"=>"fields" ); $layout->containers["fields"] = array(); $layout-><API key>["fields"] = array( ); $layout->containers["fields"][] = array("name"=>"srchfields", "block"=>"", "substyle"=>1 ); $layout->containers["fields"][] = array("name"=>"srchbuttons", "block"=>"searchbuttons", "substyle"=>2 ); $layout->skins["fields"] = "fields"; $layout->skins["search"] = "1"; $layout->blocks["top"][] = "search"; $page_layouts["<API key>"] = $layout; $layout->skinsparams = array(); $layout->skinsparams["empty"] = array("button"=>"button2"); $layout->skinsparams["menu"] = array("button"=>"button1"); $layout->skinsparams["hmenu"] = array("button"=>"button1"); $layout->skinsparams["undermenu"] = array("button"=>"button1"); $layout->skinsparams["fields"] = array("button"=>"button1"); $layout->skinsparams["form"] = array("button"=>"button1"); $layout->skinsparams["1"] = array("button"=>"button1"); $layout->skinsparams["2"] = array("button"=>"button1"); $layout->skinsparams["3"] = array("button"=>"button1"); require_once('include/xtempl.php'); require_once('classes/searchpage.php'); require_once('classes/searchpage_dash.php'); $xt = new Xtempl(); // id that used to add to controls names $id = postvalue("id"); $id = $id ? $id : 1; $mode = SEARCH_SIMPLE; if( postvalue("mode") == "dashsearch" ) $mode = SEARCH_DASHBOARD; else if( postvalue("mode") == "inlineLoadCtrl" ) { // load search panel control $mode = SEARCH_LOAD_CONTROL; $layoutVersion = postvalue("layoutVersion"); } $params = array(); $params["id"] = $id; $params['xt'] = &$xt; $params["mode"] = $mode; $params['chartName'] = $cname; $params['reportName'] = $rname; $params['tName'] = $strTableName; $params['pageType'] = PAGE_SEARCH; $params['templatefile'] = $templatefile; $params['shortTableName'] = 'accountsLookUp'; $params['layoutVersion'] = $layoutVersion; $params['searchControllerId'] = postvalue('searchControllerId') ? postvalue('searchControllerId') : $id; $params['ctrlField'] = postvalue('ctrlField'); //crosstab report params $params['axis_x'] = postvalue('axis_x'); $params['axis_y'] = postvalue('axis_y'); $params['field'] = postvalue('field'); $params['group_func'] = postvalue('group_func'); if( $mode == SEARCH_DASHBOARD ) { $params["dashTName"] = postvalue("table"); $params["dashElementName"] = postvalue("dashelement"); } $pageObject = new SearchPage($params); if( $mode == SEARCH_LOAD_CONTROL ) { $pageObject-><API key>(); return; } $pageObject->init(); $pageObject->process(); ?>
import type { AdapterPool } from './types' const executeSequence = async ( pool: AdapterPool, statements: string[], log: any, convertToKnownError: (error: any) => any ): Promise<any[]> => { const errors: any[] = [] for (const statement of statements) { try { log.debug(`executing query`) log.verbose(statement) await pool.execute(statement) log.debug(`query executed successfully`) } catch (error) { if (error != null) { let errorToThrow = error const knownError = convertToKnownError(error) if (knownError != null) { errorToThrow = knownError } else { log.error(errorToThrow.message) log.verbose(errorToThrow.stack) } errors.push(errorToThrow) } } } return errors } export default executeSequence
using System.Collections.Generic; namespace MyStaging.Interface.Core { <summary> </summary> <typeparam name="T"></typeparam> public interface IInsertBuilder<T> : ISaveChanged where T : class { T Add(T model); <summary> SaveChange() </summary> <param name="items"></param> <returns></returns> IInsertBuilder<T> AddRange(List<T> items); } }
<?php (defined('BASEPATH')) OR exit('No direct script access allowed'); class MX_Config extends CI_Config { public function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE, $_module = '') { if (in_array($file, $this->is_loaded, TRUE)) return $this->item($file); $_module OR $_module = CI::$APP->router->fetch_module(); list($path, $file) = Modules::find($file, $_module, 'config/'); if ($path === FALSE) { parent::load($file, $use_sections, $fail_gracefully); return $this->item($file); } if ($config = Modules::load_file($file, $path, 'config')) { /* reference to the config array */ $current_config =& $this->config; if ($use_sections === TRUE) { if (isset($current_config[$file])) { $current_config[$file] = array_merge($current_config[$file], $config); } else { $current_config[$file] = $config; } } else { $current_config = array_merge($current_config, $config); } $this->is_loaded[] = $file; unset($config); return $this->item($file); } } function site_url($uri = '', $protocol = NULL) { if (is_array($uri)) { $uri = implode('/', $uri); } if (class_exists('CI_Controller')) { $CI = & get_instance(); $uri = $CI->lang->localized($uri); } return parent::site_url($uri); } }
.login-container { position: fixed; overflow: hidden; top: 0; left: 0; right: 0; bottom: 0; height: 100%; padding: 0; } .login-container>.col { color: #ffffff; height: 100%; padding: 10% 0; position: relative; } .login-container>.col>div { position: absolute; width: 90%; top: 50%; left: 50%; transform: translate(-50%,-50%); } .login-container h6 { padding: 0 20px 10px; line-height: 1.5; } .hero-image>div { min-height: 500px; max-height: 500px; display: inline-block; width: 100%; max-width: 500px; background-size: contain; background-repeat: no-repeat; background-position: center center; } @media only screen and (max-width: 768px) { .login-container { overflow: scroll; } }
var mongoose = require('mongoose'), Schema = mongoose.Schema; var PriceRule = new Schema({ listingID: {type: mongoose.Schema.Types.ObjectId, ref: 'listing', required: true}, title: String, order: Number, scale: String, //(Fixed Value, Gradual Value, Fixed Percentage, Gradual Percentage) amount: Number, event: String, // floatingPeriod, orphanPeriod, specificDates, weekends, weekdays <API key>: Number, <API key>: Number, orphanPeriodLength: Number, <API key>: Date, <API key>: Date, }); module.exports = mongoose.model('PriceRule', PriceRule);
using System; using System.Runtime.InteropServices; using System.Text; namespace SDRSharp.HackRF { #region HackRF Transfer Structure [StructLayout(LayoutKind.Sequential)] public unsafe struct hackrf_transfer { public IntPtr device; public byte* buffer; public int buffer_length; public int valid_length; public IntPtr rx_ctx; public IntPtr tx_ctx; } #endregion #region HackRF Callback Delegate [<API key>(CallingConvention.StdCall)] public unsafe delegate int <API key>(hackrf_transfer* ptr); #endregion public class NativeMethods { private const string LibHackRF = "libhackrf"; #region Native Methods [DllImport(LibHackRF, EntryPoint = "hackrf_init", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_init(); [DllImport(LibHackRF, EntryPoint = "hackrf_exit", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_exit(); [DllImport(LibHackRF, EntryPoint = "hackrf_open", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_open(out IntPtr dev); [DllImport(LibHackRF, EntryPoint = "hackrf_close", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_close(IntPtr dev); [DllImport(LibHackRF, EntryPoint = "hackrf_start_rx", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_start_rx(IntPtr dev, <API key> cb, IntPtr rx_ctx); [DllImport(LibHackRF, EntryPoint = "hackrf_stop_rx", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_stop_rx(IntPtr dev); [DllImport(LibHackRF, EntryPoint = "hackrf_is_streaming", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_is_streaming(IntPtr dev); [DllImport(LibHackRF, EntryPoint = "<API key>", CallingConvention = CallingConvention.StdCall)] private static extern IntPtr <API key>(uint index); public static string <API key>(uint index) { try { var strptr = <API key>(index); return Marshal.PtrToStringAnsi(strptr); } catch (<API key> e) { Console.WriteLine("{0}:\n {1}", e.GetType().Name, e.Message); return "HackRF"; } } [DllImport(LibHackRF, EntryPoint = "<API key>", CallingConvention = CallingConvention.StdCall)] public static extern int <API key>(IntPtr dev, double rate); [DllImport(LibHackRF, EntryPoint = "hackrf_set_freq", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_set_freq(IntPtr dev, long freq); [DllImport(LibHackRF, EntryPoint = "<API key>", CallingConvention = CallingConvention.StdCall)] public static extern int <API key>(IntPtr dev, byte value); [DllImport(LibHackRF, EntryPoint = "<API key>", CallingConvention = CallingConvention.StdCall)] public static extern int <API key>(IntPtr dev, uint bandwidth_hz); [DllImport(LibHackRF, EntryPoint = "<API key>", CallingConvention = CallingConvention.StdCall)] public static extern uint <API key>(uint bandwidth_hz); [DllImport(LibHackRF, EntryPoint = "<API key>", CallingConvention = CallingConvention.StdCall)] public static extern uint <API key>(uint bandwidth_hz); [DllImport(LibHackRF, EntryPoint = "hackrf_set_lna_gain", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_set_lna_gain(IntPtr dev, uint value); [DllImport(LibHackRF, EntryPoint = "hackrf_set_vga_gain", CallingConvention = CallingConvention.StdCall)] public static extern int hackrf_set_vga_gain(IntPtr dev, uint value); #endregion } }
using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Sockets; using System.Net.Security; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. public class <API key> { readonly ITestOutputHelper _output; private const string ExpectedContent = "Test contest"; private const string Username = "testuser"; private const string Password = "password"; private readonly NetworkCredential _credential = new NetworkCredential(Username, Password); public static bool IsNotWindows7 => !PlatformDetection.IsWindows7; public static readonly object[][] EchoServers = Configuration.Http.EchoServers; public static readonly object[][] VerifyUploadServers = Configuration.Http.VerifyUploadServers; public static readonly object[][] CompressedServers = Configuration.Http.CompressedServers; public static readonly object[][] HeaderValueAndUris = { new object[] { "X-CustomHeader", "x-value", Configuration.Http.RemoteEchoServer }, new object[] { "<API key>", "" , Configuration.Http.RemoteEchoServer }, new object[] { "X-CustomHeader", "x-value", Configuration.Http.<API key>( secure:false, statusCode:302, destinationUri:Configuration.Http.RemoteEchoServer, hops:1) }, new object[] { "<API key>", "" , Configuration.Http.<API key>( secure:false, statusCode:302, destinationUri:Configuration.Http.RemoteEchoServer, hops:1) }, }; public static readonly object[][] Http2Servers = Configuration.Http.Http2Servers; public static readonly object[][] Http2NoPushServers = Configuration.Http.Http2NoPushServers; public static readonly object[][] RedirectStatusCodes = { new object[] { 300 }, new object[] { 301 }, new object[] { 302 }, new object[] { 303 }, new object[] { 307 } }; // Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3 // "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE" public static readonly IEnumerable<object[]> HttpMethods = GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1"); public static readonly IEnumerable<object[]> <API key> = GetMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "CUSTOM1"); public static readonly IEnumerable<object[]> <API key> = GetMethods("HEAD", "TRACE"); private static bool <API key> => PlatformDetection.<API key>; private static IEnumerable<object[]> GetMethods(params string[] methods) { foreach (string method in methods) { foreach (bool secure in new[] { true, false }) { yield return new object[] { method, secure }; } } } public <API key>(ITestOutputHelper output) { _output = output; if (PlatformDetection.IsFullFramework) { // On .NET Framework, the default limit for connections/server is very low (2). // On .NET Core, the default limit is higher. Since these tests run in parallel, // the limit needs to be increased to avoid timeouts when running the tests. System.Net.ServicePointManager.<API key> = int.MaxValue; } } [Fact] public void <API key>() { using (var handler = new HttpClientHandler()) { // Same as .NET Framework (Desktop). Assert.Equal(<API key>.None, handler.<API key>); Assert.True(handler.AllowAutoRedirect); Assert.Equal(<API key>.Manual, handler.<API key>); CookieContainer cookies = handler.CookieContainer; Assert.NotNull(cookies); Assert.Equal(0, cookies.Count); Assert.Null(handler.Credentials); Assert.Equal(50, handler.<API key>); Assert.False(handler.PreAuthenticate); Assert.Equal(null, handler.Proxy); Assert.True(handler.<API key>); Assert.True(handler.SupportsProxy); Assert.True(handler.<API key>); Assert.True(handler.UseCookies); Assert.False(handler.<API key>); Assert.True(handler.UseProxy); // Changes from .NET Framework (Desktop). if (!PlatformDetection.IsFullFramework) // TODO Issue #17691 { Assert.Equal(0, handler.<API key>); } Assert.NotNull(handler.Properties); } } [<API key>(<API key>.NetFramework, "<API key> not used on .NET Core due to architecture differences")] [Fact] public void <API key>() { using (var handler = new HttpClientHandler()) { Assert.Equal(0, handler.<API key>); } } [<API key>(<API key>.NetFramework, "<API key> not used on .NET Core due to architecture differences")] [Fact] public void <API key>() { using (var handler = new HttpClientHandler()) { Assert.Throws<<API key>>(() => handler.<API key> = 1024); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task <API key><API key>(bool useProxy) { var handler = new HttpClientHandler(); handler.UseProxy = useProxy; handler.<API key> = false; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.Negotiate<API key>(secure: false); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Fact] public void <API key>() { using (var handler = new HttpClientHandler()) { IDictionary<String, object> dict = handler.Properties; Assert.Same(dict, handler.Properties); Assert.Equal(0, dict.Count); } } [Fact] public void <API key>() { using (var handler = new HttpClientHandler()) { IDictionary<String, object> dict = handler.Properties; var item = new Object(); dict.Add("item", item); object value; Assert.True(dict.TryGetValue("item", out value)); Assert.Equal(item, value); } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task <API key>(Uri remoteServer) { using (var client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(remoteServer)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(<API key>))] public async Task <API key>(IPAddress address) { using (var client = new HttpClient()) { var options = new LoopbackServer.Options { Address = address }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.<API key>( LoopbackServer.<API key>(server, options: options), client.GetAsync(url)); }, options); } } public static IEnumerable<object[]> <API key>() { foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback, LoopbackServer.<API key>() }) { if (addr != null) { yield return new object[] { addr }; } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { using (var client = new HttpClient()) { for (int i = 0; i < 3; i++) { using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { using (var client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.<API key>)) { client.Dispose(); Assert.NotNull(response); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody(responseContent, response.Content.Headers.ContentMD5, false, null); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { var cts = new <API key>(); cts.Cancel(); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer); <API key> ex = await Assert.ThrowsAsync<<API key>>(() => client.SendAsync(request, cts.Token)); Assert.True(cts.Token.<API key>, "cts <API key>); if (!PlatformDetection.IsFullFramework) { // .NET Framework has bug where it doesn't propagate token information. Assert.True(ex.CancellationToken.<API key>, "exception <API key>); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(CompressedServers))] public async Task <API key>(Uri server) { var handler = new HttpClientHandler(); handler.<API key> = <API key>.GZip | <API key>.Deflate; using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(server)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(CompressedServers))] public async Task <API key>(Uri server) { var handler = new HttpClientHandler(); handler.<API key> = <API key>.GZip | <API key>.Deflate; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(server, <API key>.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found"); Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found"); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key><API key>() { var handler = new HttpClientHandler(); handler.Credentials = CredentialCache.DefaultCredentials; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.<API key>(secure: false, userName: Username, password: Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key><API key>() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.<API key>(secure: false, userName: Username, password: Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key><API key>() { using (var client = new HttpClient()) { Uri uri = Configuration.Http.<API key>(secure: false, userName: Username, password: Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData("WWW-Authenticate: CustomAuth\r\n")] [InlineData("")] // RFC7235 requires servers to send this header with 401 but some servers don't. public async Task <API key><API key>(string authHeaders) { string responseHeaders = $"HTTP/1.1 401 Unauthorized\r\nDate: {DateTimeOffset.UtcNow:R}\r\n{authHeaders}Content-Length: 0\r\n\r\n"; _output.WriteLine(responseHeaders); await LoopbackServer.CreateServerAsync(async (server, url) => { var handler = new HttpClientHandler(); handler.Credentials = new NetworkCredential("unused", "unused"); using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponse = client.GetAsync(url); await LoopbackServer.<API key>(server, responseHeaders); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } }); } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task <API key>(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.<API key>( secure: false, statusCode: statusCode, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(statusCode, (int)response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task <API key>(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.<API key>( secure: false, statusCode: statusCode, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.<API key>( secure: false, statusCode: 302, destinationUri: Configuration.Http.<API key>, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.<API key>, response.RequestMessage.RequestUri); } } } [<API key>(<API key>.NetFramework, ".NET Framework allows HTTPS to HTTP redirection")] [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.<API key>( secure: true, statusCode: 302, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; Uri targetUri = Configuration.Http.<API key>(secure: false, userName: Username, password: Password); using (var client = new HttpClient(handler)) { Uri uri = Configuration.Http.<API key>( secure: false, statusCode: 302, destinationUri: targetUri, hops: 1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal(targetUri, response.RequestMessage.RequestUri); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(3, 2)] [InlineData(3, 3)] [InlineData(3, 4)] public async Task <API key>(int maxHops, int hops) { if (PlatformDetection.IsWindows && !PlatformDetection.<API key>) { // Skip this test if running on Windows but on a release prior to Windows 10 Creators Update. _output.WriteLine("Skipping test due to Windows 10 version prior to Version 1703."); return; } else if (PlatformDetection.IsFullFramework) { // Skip this test if running on .NET Framework. Exceeding max redirections will not throw // exception. Instead, it simply returns the 3xx response. _output.WriteLine("Skipping test on .NET Framework due to behavior difference."); return; } using (var client = new HttpClient(new HttpClientHandler() { <API key> = maxHops })) { Task<HttpResponseMessage> t = client.GetAsync(Configuration.Http.<API key>( secure: false, statusCode: 302, destinationUri: Configuration.Http.RemoteEchoServer, hops: hops)); if (hops <= maxHops) { using (HttpResponseMessage response = await t) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri); } } else { await Assert.ThrowsAsync<<API key>>(() => t); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { using (var client = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = true })) { Uri uri = Configuration.Http.<API key>( secure: false, statusCode: 302, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1, relative: true); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(Configuration.Http.RemoteEchoServer, response.RequestMessage.RequestUri); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(200)] [InlineData(201)] [InlineData(400)] public async Task <API key>(int statusCode) { using (var handler = new HttpClientHandler() { AllowAutoRedirect = true }) using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { await LoopbackServer.CreateServerAsync(async (redirectServer, redirectUrl) => { Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl); Task redirectTask = LoopbackServer.<API key>(redirectServer); await LoopbackServer.<API key>(origServer, $"HTTP/1.1 {statusCode} OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Location: {redirectUrl}\r\n" + "\r\n"); using (HttpResponseMessage response = await getResponse) { Assert.Equal(statusCode, (int)response.StatusCode); Assert.Equal(origUrl, response.RequestMessage.RequestUri); Assert.False(redirectTask.IsCompleted, "Should not have redirected to Location"); } }); }); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(IsNotWindows7))] // Skip test on Win7 since WinHTTP has bugs w/ fragments. [InlineData("#origFragment", "", "#origFragment", false)] [InlineData("#origFragment", "", "#origFragment", true)] [InlineData("", "#redirFragment", "#redirFragment", false)] [InlineData("", "#redirFragment", "#redirFragment", true)] [InlineData("#origFragment", "#redirFragment", "#redirFragment", false)] [InlineData("#origFragment", "#redirFragment", "#redirFragment", true)] public async Task <API key>( string origFragment, string redirFragment, string expectedFragment, bool useRelativeRedirect) { using (var handler = new HttpClientHandler() { AllowAutoRedirect = true }) using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (origServer, origUrl) => { origUrl = new Uri(origUrl.ToString() + origFragment); Uri redirectUrl = useRelativeRedirect ? new Uri(origUrl.PathAndQuery + redirFragment, UriKind.Relative) : new Uri(origUrl.ToString() + redirFragment); Uri expectedUrl = new Uri(origUrl.ToString() + expectedFragment); Task<HttpResponseMessage> getResponse = client.GetAsync(origUrl); Task firstRequest = LoopbackServer.<API key>(origServer, $"HTTP/1.1 302 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Location: {redirectUrl}\r\n" + "\r\n"); Assert.Equal(firstRequest, await Task.WhenAny(firstRequest, getResponse)); Task secondRequest = LoopbackServer.<API key>(origServer, $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "\r\n"); await TestHelper.<API key>(secondRequest, getResponse); using (HttpResponseMessage response = await getResponse) { Assert.Equal(200, (int)response.StatusCode); Assert.Equal(expectedUrl, response.RequestMessage.RequestUri); } }); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri redirectUri = Configuration.Http.RedirectUriForCreds( secure: false, statusCode: 302, userName: Username, password: Password); using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task <API key>(int statusCode) { Uri uri = Configuration.Http.<API key>(secure: false, userName: Username, password: Password); Uri redirectUri = Configuration.Http.RedirectUriForCreds( secure: false, statusCode: statusCode, userName: Username, password: Password); _output.WriteLine(uri.AbsoluteUri); _output.WriteLine(redirectUri.AbsoluteUri); var credentialCache = new CredentialCache(); credentialCache.Add(uri, "Basic", _credential); var handler = new HttpClientHandler(); handler.Credentials = credentialCache; using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(uri, response.RequestMessage.RequestUri); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage httpResponse = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.False(TestHelper.<API key>(responseText, "Cookie")); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task <API key>(string cookieName, string cookieValue) { var handler = new HttpClientHandler(); var cookieContainer = new CookieContainer(); cookieContainer.Add(Configuration.Http.RemoteEchoServer, new Cookie(cookieName, cookieValue)); handler.CookieContainer = cookieContainer; using (var client = new HttpClient(handler)) { using (HttpResponseMessage httpResponse = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.<API key>(responseText, cookieName, cookieValue)); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task <API key>(string cookieName, string cookieValue) { Uri uri = Configuration.Http.<API key>( secure: false, statusCode: 302, destinationUri: Configuration.Http.RemoteEchoServer, hops: 1); using (HttpClient client = new HttpClient()) { client.<API key>.Add( "X-SetCookie", string.Format("{0}={1};Path=/", cookieName, cookieValue)); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.<API key>(responseText, cookieName, cookieValue)); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(HeaderValueAndUris))] public async Task <API key>(string name, string value, Uri uri) { using (var client = new HttpClient()) { client.<API key>.Add(name, value); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); Assert.True(TestHelper.<API key>(responseText, name, value)); } } } private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int <API key>) { string emptyHeaderValue = $"{name}=; Path=/"; Debug.Assert(<API key> > emptyHeaderValue.Length); int valueCount = <API key> - emptyHeaderValue.Length; string value = new string(repeat, valueCount); return new KeyValuePair<string, string>(name, value); } public static object[][] CookieNameValues = { // WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values, // using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders // returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer. // Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the // iteration index, which would cause header values to be missed if not handled correctly. // In particular, WinHttpQueryHeader behaves as follows for the following header value lengths: // * 0-127 chars: succeeds, index advances from 0 to 1. // * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1. // * 256+ chars: fails due to insufficient buffer, index stays at 0. // The below overall header value lengths were chosen to exercise reading header values at these // edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers. new object[] { GenerateCookie(name: "foo", repeat: 'a', <API key>: 126) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', <API key>: 127) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', <API key>: 128) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', <API key>: 129) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', <API key>: 254) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', <API key>: 255) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', <API key>: 256) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', <API key>: 257) }, new object[] { new KeyValuePair<string, string>( ".AspNetCore.Antiforgery.Xam7_OeLcN4", "<API key><API key>RAExEmXpoCbueP_QYM") } }; [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(CookieNameValues))] public async Task <API key>(KeyValuePair<string, string> cookie1) { var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM"); var cookie3 = new KeyValuePair<string, string>("name", "value"); await LoopbackServer.CreateServerAsync(async (server, url) => { using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponse = client.GetAsync(url); await LoopbackServer.<API key>(server, $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Set-Cookie: {cookie1.Key}={cookie1.Value}; Path=/\r\n" + $"Set-Cookie : {cookie2.Key}={cookie2.Value}; Path=/\r\n" + // space before colon to verify header is trimmed and recognized $"Set-Cookie: {cookie3.Key}={cookie3.Value}; Path=/\r\n" + "\r\n"); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); CookieCollection cookies = handler.CookieContainer.GetCookies(url); Assert.Equal(3, cookies.Count); Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value); Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value); Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value); } } }); } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(17174, TestPlatforms.AnyUnix)] [Theory] [InlineData(false)] [InlineData(true)] public async Task <API key>(bool <API key>) { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponse = client.GetAsync(url); await LoopbackServer.<API key>(server, "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + (<API key> ? "Trailer: MyCoolTrailerHeader\r\n" : "") + "\r\n" + "4\r\n" + "data\r\n" + "0\r\n" + "MyCoolTrailerHeader: amazingtrailer\r\n" + "\r\n"); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); if (<API key>) { Assert.Contains("MyCoolTrailerHeader", response.Headers.GetValues("Trailer")); } Assert.False(response.Headers.Contains("MyCoolTrailerHeader"), "Trailer should have been ignored"); } } }); } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { using (var client = new HttpClient()) { const int NumGets = 5; Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets) select client.GetAsync(Configuration.Http.RemoteEchoServer, <API key>.ResponseHeadersRead)).ToArray(); for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available { using (HttpResponseMessage response = await responseTasks[i]) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.<API key>); using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.SendAsync(request, <API key>.ResponseHeadersRead)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [<API key>(<API key>.NetFramework, "netfx's ConnectStream.ReadAsync tries to read beyond data already buffered, causing hangs #18864")] [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.GetAsync(url, <API key>.ResponseHeadersRead); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(reader.ReadLine())) ; await writer.WriteAsync( "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 16000\r\n" + "\r\n" + "less than 16000 bytes"); using (HttpResponseMessage response = await getResponse) { var buffer = new byte[8000]; using (Stream clientStream = await response.Content.ReadAsStreamAsync()) { int bytesRead = await clientStream.ReadAsync(buffer, 0, buffer.Length); _output.WriteLine($"Bytes read from stream: {bytesRead}"); Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length"); } } return null; }); } }); } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { await LoopbackServer.CreateServerAsync(async (socket1, url1) => { await LoopbackServer.CreateServerAsync(async (socket2, url2) => { await LoopbackServer.CreateServerAsync(async (socket3, url3) => { var unblockServers = new <API key><bool>(<API key>.<API key>); // First server connects but doesn't send any response yet Task server1 = LoopbackServer.AcceptSocketAsync(socket1, async (s, stream, reader, writer) => { await unblockServers.Task; return null; }); // Second server connects and sends some but not all headers Task server2 = LoopbackServer.AcceptSocketAsync(socket2, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; await writer.WriteAsync($"HTTP/1.1 200 OK\r\n"); await unblockServers.Task; return null; }); // Third server connects and sends all headers and some but not all of the body Task server3 = LoopbackServer.AcceptSocketAsync(socket3, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 20\r\n\r\n"); await writer.WriteAsync("1234567890"); await unblockServers.Task; await writer.WriteAsync("1234567890"); s.Shutdown(SocketShutdown.Send); return null; }); // Make three requests Task<HttpResponseMessage> get1, get2; HttpResponseMessage response3; using (var client = new HttpClient()) { get1 = client.GetAsync(url1, <API key>.ResponseHeadersRead); get2 = client.GetAsync(url2, <API key>.ResponseHeadersRead); response3 = await client.GetAsync(url3, <API key>.ResponseHeadersRead); } // Requests 1 and 2 should be canceled as we haven't finished receiving their headers await Assert.ThrowsAnyAsync<<API key>>(() => get1); await Assert.ThrowsAnyAsync<<API key>>(() => get2); // Request 3 should still be active, and we should be able to receive all of the data. unblockServers.SetResult(true); using (response3) { Assert.Equal("<API key>", await response3.Content.ReadAsStringAsync()); } }); }); }); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(200)] [InlineData(500)] [InlineData(600)] [InlineData(900)] [InlineData(999)] public async Task <API key>(int statusCode) { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.GetAsync(url); await LoopbackServer.<API key>(server, $"HTTP/1.1 {statusCode}\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "\r\n"); using (HttpResponseMessage response = await getResponse) { Assert.Equal(statusCode, (int)response.StatusCode); } } }); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(99)] [InlineData(1000)] public async Task <API key>(int statusCode) { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.GetAsync(url); await LoopbackServer.<API key>(server, $"HTTP/1.1 {statusCode}\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "\r\n"); await Assert.ThrowsAsync<<API key>>(() => getResponse); } }); } #region Post Methods Tests [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(VerifyUploadServers))] public async Task <API key>(Uri remoteServer) { using (var client = new HttpClient()) { string data = "Test String"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); HttpResponseMessage response; using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Repeat call. content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(VerifyUploadServers))] public async Task <API key>(Uri remoteServer) { using (var client = new HttpClient()) { string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(<API key>))] public async Task <API key>(Uri remoteServer, HttpContent content, byte[] expectedData) { using (var client = new HttpClient()) { content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } private sealed class <API key> : StreamContent { private readonly Stream _stream; private readonly bool _syncCopy; public <API key>(Stream stream, bool syncCopy) : base(stream) { _stream = stream; _syncCopy = syncCopy; } protected override Task <API key>(Stream stream, TransportContext context) { if (_syncCopy) { try { _stream.CopyTo(stream, 128); // arbitrary size likely to require multiple read/writes return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } } return base.<API key>(stream, context); } } public static IEnumerable<object[]> <API key> { get { foreach (object[] serverArr in VerifyUploadServers) // target server foreach (bool syncCopy in new[] { true, false }) // force the content copy to happen via Read/Write or ReadAsync/WriteAsync { Uri server = (Uri)serverArr[0]; byte[] data = new byte[1234]; new Random(42).NextBytes(data); // A MemoryStream { var memStream = new MemoryStream(data, writable: false); yield return new object[] { server, new <API key>(memStream, syncCopy: syncCopy), data }; } // A multipart content that provides its own stream from <API key> { var mc = new MultipartContent(); mc.Add(new ByteArrayContent(data)); var memStream = new MemoryStream(); mc.CopyToAsync(memStream).GetAwaiter().GetResult(); yield return new object[] { server, mc, memStream.ToArray() }; } // A stream that provides the data synchronously and has a known length { var wrappedMemStream = new MemoryStream(data, writable: false); var <API key> = new DelegateStream( canReadFunc: () => wrappedMemStream.CanRead, canSeekFunc: () => wrappedMemStream.CanSeek, lengthFunc: () => wrappedMemStream.Length, positionGetFunc: () => wrappedMemStream.Position, positionSetFunc: p => wrappedMemStream.Position = p, readFunc: (buffer, offset, count) => wrappedMemStream.Read(buffer, offset, count), readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token)); yield return new object[] { server, new <API key>(<API key>, syncCopy: syncCopy), data }; } // A stream that provides the data synchronously and has an unknown length { int <API key> = 0; Func<byte[], int, int, int> readFunc = (buffer, offset, count) => { int bytesRemaining = data.Length - <API key>; int bytesToCopy = Math.Min(bytesRemaining, count); Array.Copy(data, <API key>, buffer, offset, bytesToCopy); <API key> += bytesToCopy; return bytesToCopy; }; var <API key> = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readFunc: readFunc, readAsyncFunc: (buffer, offset, count, token) => Task.FromResult(readFunc(buffer, offset, count))); yield return new object[] { server, new <API key>(<API key>, syncCopy: syncCopy), data }; } // A stream that provides the data asynchronously { int asyncStreamOffset = 0, maxDataPerRead = 100; Func<byte[], int, int, int> readFunc = (buffer, offset, count) => { int bytesRemaining = data.Length - asyncStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count)); Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy); asyncStreamOffset += bytesToCopy; return bytesToCopy; }; var asyncStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readFunc: readFunc, readAsyncFunc: async (buffer, offset, count, token) => { await Task.Delay(1).ConfigureAwait(false); return readFunc(buffer, offset, count); }); yield return new object[] { server, new <API key>(asyncStream, syncCopy: syncCopy), data }; } // Providing data from a <API key>'s stream { var formContent = new <API key>(new[] { new KeyValuePair<string, string>("key", "val") }); yield return new object[] { server, formContent, Encoding.GetEncoding("iso-8859-1").GetBytes("key=val") }; } } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task <API key>(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.PostAsync(remoteServer, null)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] public async Task <API key>(Uri remoteServer) { using (var client = new HttpClient()) { var content = new StringContent(string.Empty); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public async Task <API key>(bool secure) { const string ContentString = "This is the content string."; var content = new StringContent(ContentString); Uri redirectUri = Configuration.Http.<API key>( secure, 302, secure ? Configuration.Http.<API key> : Configuration.Http.RemoteEchoServer, 1); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain(ContentString, responseContent); Assert.DoesNotContain("Content-Length", responseContent); } } [OuterLoop] // takes several seconds [Theory] [InlineData(302, false)] [InlineData(307, true)] public async Task <API key>(int statusCode, bool <API key>) { using (var fs = new FileStream(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x1000, FileOptions.DeleteOnClose)) { string contentString = string.Join("", Enumerable.Repeat("Content", 100000)); byte[] contentBytes = Encoding.UTF32.GetBytes(contentString); fs.Write(contentBytes, 0, contentBytes.Length); fs.Flush(flushToDisk: true); fs.Position = 0; Uri redirectUri = Configuration.Http.<API key>(false, statusCode, Configuration.Http.<API key>, 1); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, new StreamContent(fs))) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); if (<API key>) { Assert.InRange(response.Content.Headers.ContentLength.GetValueOrDefault(), contentBytes.Length, int.MaxValue); } } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(EchoServers))] // NOTE: will not work for in-box System.Net.Http.dll due to disposal of request content public async Task <API key>(Uri remoteServer) { const string ContentString = "This is the content string."; using (var client = new HttpClient()) { var content = new StringContent(ContentString); for (int i = 0; i < 2; i++) { using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Contains(ContentString, await response.Content.ReadAsStringAsync()); } } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")] [InlineData(HttpStatusCode.MethodNotAllowed, "")] public async Task <API key>(HttpStatusCode statusCode, string reasonPhrase) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.StatusCodeUri( false, (int)statusCode, reasonPhrase))) { Assert.Equal(statusCode, response.StatusCode); Assert.Equal(reasonPhrase, response.ReasonPhrase); } } } [OuterLoop] // TODO: Issue #11345 [PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix [Fact] public async Task <API key>() { using (var client = new HttpClient()) { string expectedContent = "Test contest"; var content = new <API key>(expectedContent); using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.<API key>, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); ChannelBinding channelBinding = content.ChannelBinding; Assert.NotNull(channelBinding); _output.WriteLine("Channel Binding: {0}", channelBinding); } } } #endregion #region Various HTTP Method Tests [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(HttpMethods))] public async Task <API key>( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? Configuration.Http.<API key> : Configuration.Http.RemoteEchoServer); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(<API key>))] public async Task <API key>( string method, bool secureServer) { if (PlatformDetection.IsFullFramework) { // .NET Framework doesn't allow a content body with this HTTP verb. // It will throw a System.Net.ProtocolViolation exception. if (method == "GET") { return; } } using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? Configuration.Http.<API key> : Configuration.Http.RemoteEchoServer); request.Content = new StringContent(ExpectedContent); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, ExpectedContent); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData("12345678910", 0)] [InlineData("12345678910", 5)] public async Task <API key>(string stringContent, int startingPosition) { using (var handler = new HttpMessageInvoker(new HttpClientHandler())) { byte[] byteContent = Encoding.ASCII.GetBytes(stringContent); var content = new MemoryStream(); content.Write(byteContent, 0, byteContent.Length); content.Position = startingPosition; var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer) { Content = new StreamContent(content) }; for (int iter = 0; iter < 2; iter++) { using (HttpResponseMessage response = await handler.SendAsync(request, CancellationToken.None)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent); Assert.Contains(stringContent.Substring(startingPosition), responseContent); if (startingPosition != 0) { Assert.DoesNotContain(stringContent.Substring(0, startingPosition), responseContent); } } } } } [OuterLoop] // TODO: Issue #11345 [Theory, MemberData(nameof(<API key>))] public async Task <API key>( string method, bool secureServer) { if (PlatformDetection.IsFullFramework) { // .NET Framework doesn't allow a content body with this HTTP verb. // It will throw a System.Net.ProtocolViolation exception. if (method == "HEAD") { return; } } using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? Configuration.Http.<API key> : Configuration.Http.RemoteEchoServer) { Content = new StringContent(ExpectedContent) }; using (HttpResponseMessage response = await client.SendAsync(request)) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && method == "TRACE") { // .NET Framework also allows the HttpWebRequest and HttpClient APIs to send a request using 'TRACE' // verb and a request body. The usual response from a server is "400 Bad Request". Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } else { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); Assert.False(responseContent.Contains(ExpectedContent)); } } } } #endregion #region Version tests [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { Version <API key> = await <API key>(new Version(1, 0)); Assert.Equal(new Version(1, 0), <API key>); } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { Version <API key> = await <API key>(new Version(1, 1)); Assert.Equal(new Version(1, 1), <API key>); } [<API key>(<API key>.NetFramework, "Throws exception sending request using Version(0,0)")] [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { // The default value for HttpRequestMessage.Version is Version(1,1). // So, we need to set something different (0,0), to test the "unknown" version. Version <API key> = await <API key>(new Version(0, 0)); Assert.Equal(new Version(1, 1), <API key>); } [<API key>(<API key>.NetFramework, "Specifying Version(2,0) throws exception on netfx")] [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(Http2Servers))] public async Task <API key>(Uri server) { if (PlatformDetection.IsWindows && !PlatformDetection.<API key>) { // Skip this test if running on Windows but on a release prior to Windows 10 Creators Update. _output.WriteLine("Skipping test due to Windows 10 version prior to Version 1703."); return; } // We don't currently have a good way to test whether HTTP/2 is supported without // using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses. var request = new HttpRequestMessage(HttpMethod.Get, server); request.Version = new Version(2, 0); using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler, false)) { // It is generally expected that the test hosts will be trusted, so we don't register a validation // callback in the usual case. // However, on our Debian 8 test machines, a combination of a server side TLS chain, // the client chain processor, and the distribution's CA bundle results in an incomplete/untrusted if (PlatformDetection.IsDebian8) { // Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> handler.<API key> = (msg, cert, chain, errors) => { Assert.InRange(chain.ChainStatus.Length, 0, 1); if (chain.ChainStatus.Length > 0) { Assert.Equal(<API key>.PartialChain, chain.ChainStatus[0].Status); } return true; }; } using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True( response.Version == new Version(2, 0) || response.Version == new Version(1, 1), "Response version " + response.Version); } } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(<API key>)), MemberData(nameof(Http2NoPushServers))] public async Task <API key>(Uri server) { _output.WriteLine(server.AbsoluteUri.ToString()); var request = new HttpRequestMessage(HttpMethod.Get, server); request.Version = new Version(2, 0); var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(new Version(2, 0), response.Version); } } } private async Task<Version> <API key>(Version requestVersion) { Version <API key> = null; await LoopbackServer.CreateServerAsync(async (server, url) => { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Version = requestVersion; using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.SendAsync(request); List<string> receivedRequest = await LoopbackServer.<API key>(server); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } string statusLine = receivedRequest[0]; if (statusLine.Contains("/1.0")) { <API key> = new Version(1, 0); } else if (statusLine.Contains("/1.1")) { <API key> = new Version(1, 1); } else { Assert.True(false, "Invalid HTTP request version"); } } }); return <API key>; } #endregion #region Proxy tests [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(CredentialsForProxy))] public void <API key>(ICredentials creds, bool wrapCredsInCache) { int port; Task<<API key>.ProxyResult> proxyTask = <API key>.StartAsync( out port, requireAuth: creds != null && creds != CredentialCache.DefaultCredentials, expectCreds: true); Uri proxyUrl = new Uri($"http://localhost:{port}"); const string BasicAuth = "Basic"; if (wrapCredsInCache) { Assert.IsAssignableFrom<NetworkCredential>(creds); var cache = new CredentialCache(); cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds); creds = cache; } using (var handler = new HttpClientHandler() { Proxy = new <API key>(proxyUrl, creds) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer); Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap(); Task.WaitAll(proxyTask, responseTask, responseStringTask); using (responseTask.Result) { TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null); Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result); NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth); string expectedAuth = nc == null || nc == CredentialCache.DefaultCredentials ? null : string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" : $"{nc.Domain}\\{nc.UserName}:{nc.Password}"; Assert.Equal(expectedAuth, proxyTask.Result.<API key>); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(BypassedProxies))] public async Task <API key>(IWebProxy proxy) { using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy })) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void <API key><API key>() { int port; Task<<API key>.ProxyResult> proxyTask = <API key>.StartAsync( out port, requireAuth: true, expectCreds: false); Uri proxyUrl = new Uri($"http://localhost:{port}"); using (var handler = new HttpClientHandler() { Proxy = new <API key>(proxyUrl, null) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer); Task.WaitAll(proxyTask, responseTask); using (responseTask.Result) { Assert.Equal(HttpStatusCode.Proxy<API key>, responseTask.Result.StatusCode); } } } private static IEnumerable<object[]> BypassedProxies() { yield return new object[] { null }; yield return new object[] { new <API key>(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) }; } private static IEnumerable<object[]> CredentialsForProxy() { yield return new object[] { null, false }; foreach (bool wrapCredsInCache in new[] { true, false }) { yield return new object[] { new NetworkCredential("user:name", "password"), wrapCredsInCache }; yield return new object[] { new NetworkCredential("username", "password", "dom:\\ain"), wrapCredsInCache }; } } #endregion #region Uri wire transmission encoding tests [OuterLoop] // TODO: Issue #11345 [Fact] public async Task <API key>() { await LoopbackServer.CreateServerAsync(async (server, rootUrl) => { var uri = new Uri($"http://{rootUrl.Host}:{rootUrl.Port}/test[]"); _output.WriteLine(uri.AbsoluteUri.ToString()); var request = new HttpRequestMessage(HttpMethod.Get, uri); string statusLine = string.Empty; using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.SendAsync(request); List<string> receivedRequest = await LoopbackServer.<API key>(server); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(receivedRequest[0].Contains(uri.PathAndQuery), $"statusLine should contain {uri.PathAndQuery}"); } } }); } #endregion } }
(function() { describe('scalarInput', function() { describe('#constructor', function() { it('can handle single unit', function() { var si; si = $('<input>').scalarInput({ units: 'meters' }).scalarInput('instance'); return expect(si.option('units')).toEqual('meters'); }); it('can handle multiple units', function() { var si; si = $('<input>').scalarInput({ units: ['meters', 'centimeters'] }).scalarInput('instance'); return expect(si.option('units')).toEqual(['meters', 'centimeters']); }); it('gets proper prefixed default', function() { var si; si = $('<input>').scalarInput({ units: ['meters'] }).scalarInput('instance'); return expect(si.option('prefixed')).toBe(false); }); return it('complains if applied to non-input element', function() { var bomb; bomb = function() { return $('<div></div>').scalarInput({ units: ['meters'] }); }; return expect(bomb).toThrow(); }); }); describe('units dropdown', function() { beforeEach(function() { return $('body').append("<div id='testEnvelope'><input id='testTarget'></div>"); }); afterEach(function() { return $('#testEnvelope').remove(); }); describe('select element', function() { it("isn't added if no units specified", function() { var si; si = $('#testTarget').scalarInput(); return expect(si.next().length).toBe(0); }); it("isn't added if blank unit specified", function() { var si; si = $('#testTarget').scalarInput({ units: '' }); return expect(si.next().length).toBe(0); }); it('is added if single unit specified', function() { var select, si; si = $('#testTarget').scalarInput({ units: 'meters' }); select = si.next(); return expect(select.is('select')).toBe(true); }); it('is disabled if single unit specified', function() { var select, si; si = $('#testTarget').scalarInput({ units: 'meters' }); select = si.next(); return expect(select.prop('disabled')).toBe(true); }); it('is disabled if single unit specified via array', function() { var select, si; si = $('#testTarget').scalarInput({ units: ['meters'] }); select = si.next(); return expect(select.prop('disabled')).toBe(true); }); it('is added if multiple units specified', function() { var select, si; si = $('#testTarget').scalarInput({ units: ['meters', 'inches'] }); select = si.next(); return expect(select.is('select')).toBe(true); }); it('is enabled if multiple units specified', function() { var select, si; si = $('#testTarget').scalarInput({ units: ['meters', 'inches'] }); select = si.next(); return expect(select.prop('disabled')).toBe(false); }); return it('is added before magnitude if prefixed specified', function() { var empty, select, si; si = $('#testTarget').scalarInput({ prefixed: true, units: ['meters', 'inches'] }); select = si.prev(); empty = si.next(); expect(select.is('select')).toBe(true); return expect(empty.length).toBe(0); }); }); return describe('option elements', function() { it('are correct if single unit specified', function() { var option, si; si = $('#testTarget').scalarInput({ units: 'meters' }); option = si.next().children(); expect(option.is('option')).toBe(true); expect(option.text()).toEqual('meters'); return expect(option.val()).toEqual('meters'); }); it('are correct if single unit specified via array', function() { var option, si; si = $('#testTarget').scalarInput({ units: ['meters'] }); option = si.next().children(); expect(option.is('option')).toBe(true); expect(option.text()).toEqual('meters'); return expect(option.val()).toEqual('meters'); }); return it('are correct if multiple units specified', function() { var options, si; si = $('#testTarget').scalarInput({ units: ['meters', 'inches'] }); options = si.next().children(); expect(options.first().is('option')).toBe(true); expect(options.last().is('option')).toBe(true); expect(options.first().text()).toEqual('meters'); expect(options.first().val()).toEqual('meters'); expect(options.last().text()).toEqual('inches'); return expect(options.last().val()).toEqual('inches'); }); }); }); describe('accessors', function() { var envelope, inputMagnitude, inputUnit, scalarInstance; envelope = scalarInstance = inputMagnitude = inputUnit = null; beforeEach(function() { var inputScalar; envelope = $("<div id='testEnvelope'></div>").appendTo('body'); inputMagnitude = $("<input id='testTarget' value='10'>").appendTo(envelope); inputScalar = $(inputMagnitude).scalarInput({ units: ['meters', 'feet'] }); inputUnit = inputMagnitude.next(); return scalarInstance = inputScalar.scalarInput('instance'); }); afterEach(function() { return envelope.remove(); }); describe('#magnitude()', function() { it('gets initialized magnitude', function() { return expect(scalarInstance.magnitude()).toEqual('10'); }); return it('gets changed magnitude', function() { inputMagnitude.val('20'); return expect(scalarInstance.magnitude()).toEqual('20'); }); }); describe('#unit()', function() { it('gets initialized unit', function() { return expect(scalarInstance.unit()).toEqual('meters'); }); return it('gets changed unit', function() { inputUnit.val('feet'); return expect(scalarInstance.unit()).toEqual('feet'); }); }); return describe('#val()', function() { it('gets initialized value', function() { return expect(scalarInstance.val()).toEqual('10 meters'); }); it('gets changed value', function() { inputMagnitude.val('20'); expect(scalarInstance.val()).toEqual('20 meters'); inputUnit.val('feet'); return expect(scalarInstance.val()).toEqual('20 feet'); }); return it('can have default format overridden', function() { scalarInstance.options.valueFormat = '{{unit}} were {{magnitude}}'; return expect(scalarInstance.val()).toEqual('meters were 10'); }); }); }); return describe('change event', function() { var callback, envelope, inputMagnitude, inputScalar, inputUnit; callback = envelope = inputMagnitude = inputScalar = inputUnit = null; beforeEach(function() { callback = jasmine.createSpy('callback'); envelope = $("<div id='testEnvelope'></div>").appendTo('body'); inputMagnitude = $("<input id='testTarget' value='10'>").appendTo(envelope); inputScalar = $(inputMagnitude).scalarInput({ units: ['meters', 'feet'], change: callback }); return inputUnit = inputScalar.next(); }); afterEach(function() { return envelope.remove(); }); it('is triggered when user changes magnitude', function() { inputMagnitude.change(); expect(callback).toHaveBeenCalled(); return expect(callback.calls.count()).toEqual(1); }); it('is triggered when user changes unit', function() { inputUnit.change(); expect(callback).toHaveBeenCalled(); return expect(callback.calls.count()).toEqual(1); }); it('passes correct arguments when magnitude changed', function() { var args; inputMagnitude.val(33).change(); args = callback.calls.first().args; return expect(args[1]).toEqual({ changed: 'magnitude', magnitude: '33', value: '33 meters' }); }); return it('passes correct arguments when unit changed', function() { var args; inputUnit.val('feet').change(); args = callback.calls.first().args; return expect(args[1]).toEqual({ changed: 'unit', unit: 'feet', value: '10 feet' }); }); }); }); }).call(this); //# sourceMappingURL=scalarInputSpec.js.map
import os import sys import string import contextlib from subprocess import Popen, PIPE check_output = None def <API key>(command_args, **kwargs): kwargs['stdout'] = PIPE return Popen(' '.join(command_args), **kwargs).stdout.read() try: from subprocess import check_output except ImportError: check_output = <API key> _SPACE = string.whitespace[-1] _BLANK = str() class Command(object): NO_OP = '(...no op...)\n{0}>{1}' def __init__(self, text=None): self._command = [text] if text is not None else [] self._working_location = os.getcwd() self._no_op = False self._verbose = False self._async = False self._output = None def no_op(self): self._no_op = True return self def verbose(self): self._verbose = True return self def arg(self, argument): self._command.append(argument) return self def args(self, arguments): self._command.extend(arguments) return self def within(self, working_location): self._working_location = working_location return self def async(self, output=sys.stdout): self._async = True self._output = output return self def run(self): if self._no_op: return self._no_op_report() if self._verbose: print self._command with self._working_context(self._working_location): if self._async: return Popen(self._command, stdout=self._output, stderr=self._output) return check_output(self._command, shell=True) def _no_op_report(self): print Command.NO_OP.format(self._working_location, _SPACE.join(self._command)) return _BLANK @contextlib.contextmanager def _working_context(self, location): initial = os.getcwd() try: os.chdir(location) yield finally: os.chdir(initial)
package se.cs.eventsourcing.infrastructure.store.jdbc.sample; import se.cs.eventsourcing.domain.event.DomainEvent; public class ChangeLastName implements DomainEvent { private String name; private ChangeLastName() {} public ChangeLastName(String name) { this.name = name; } public String getName() { return name; } @Override public String toString() { return "ChangeLastName{" + "name='" + name + '\'' + '}'; } }
@font-face { font-family:ciconv1; src:url(CarIcons.ttf); } [class*=gic-] { font-family:ciconv1; } .gic-newUser:before { display:inline-block; content:'\0021'; } .gic-info:before { display:inline-block; content:'\0022'; } .gic-slideright:before { display:inline-block; content:'\0023'; } .gic-slideleft:before { display:inline-block; content:'\0024'; } .gic-store:before { display:inline-block; content:'\0025'; } .gic-gallery:before { display:inline-block; content:'\0026'; } .gic-News:before { display:inline-block; content:'\0027'; } .<API key>:before { display:inline-block; content:'\0029'; } .<API key>:before { display:inline-block; content:'\0028'; } .gic-Diagnostic:before { display:inline-block; content:'\002A'; } .gic-Search:before { display:inline-block; content:'\002B'; }
Bootstrap tooltip helper ===================== Helper for Bootstrap 3 tooltip http://getbootstrap.com/javascript/#tooltips # Summary The script applies the `tooltip` to all `.do_tooltip` elements in the page once the DOM is loaded. It takes care to merge both the default options (`js`) and the custom options (`html5 data attributes`). > I use `do_tooltip` because the `tooltip` class applies styles. But if you don't like the class name, change it. ## Example `<div class="do_tooltip" data-placement="right" title="Hello world!"></div>` > Will apply the `tooltip()` function to the div, and override the `placement`option by using the `right` value. > All other data attributes works the same way. ## Dependencies - **Underscore.js**: Wonderful library that helps a lot to manage `arrays` and `collections` in `javascript`. http://underscorejs.org/ - **Objects merger**: Merge objects. Priority to the last object. (Erase values if same keys) https://github.com/Vadorequest/javascript-helpers/blob/master/object-merger/object_merge.js - **Font-Awesome**: [*Optional*] The script use `font-awesome` plugin (`fa fa-question-circle`) that will add the `question-circle` icon before all tooltips. *If font-awesome is not installed, the icon won't appear*. (*close enough to glyphicon, but better :)*) https://github.com/FortAwesome/Font-Awesome/ # Installation 1. Import the script. **Must*** be imported after `underscore.js`, `object-merge.js` and `bootstrap`. # Utilities - **Namespace**: I didn't use any namespace because the original plugins doesn't. But if you want to, you can. This means that all data attributes will be contained in `data-{namespace_name}` namespace to avoid conflicts. - **Case**: The case of the options doesn't matter since we `toLowerCase()` the keys, it's not possible to have html5 data attribute element with an upper character. (*but it's possible to have a key with it*) - **Title**: If no title is found in the element (`title` attribute) then the script won't apply the `tooltip` function to the element. (*makes no sense*) - **Icon**: It's possible to add an icon before each text. I use `font-awesome` to do so, using CSS classes, but it would be exactly the same by using `glyphicon`. You can also remove the classes and no icon will appear. - **Icon custom**: The icon defined inside the script is the default, it's possible to add a custom icon. If your `title` attribute contains another `fa ` class then the icon won't be applied to let you use the custom and avoid to have two icons displayed. # Data attributes Basically the script contains all `data-attribute` in an `javascript` object with default values. All options **must** be present in this object since the script uses the keys to search in the data attributes. If a key is not present in this default config object the data-attribute associated won't be found. # Customize Of course, this helper could not fill entirely your needs, don't hesitate to customize it for your application. *If you think that youre changes are useful, please share/discuss/PR.* # Contributing This script doesn't need to evolve too much, but if the `bootstrap#tooltip` evolves and add new options then we'll need to update this helper too. You're welcome to make a **PR**, I will take a look at it as soon as possible. # Roadmap 1. Don't use the `object_merge` function but use `underscore` instead. 2. Make a version that doesn't require `underscore`. (*I won't, but if someone want to, feel free!*)
import { DomSanitizer, SafeHtml } from '@angular/platform-browser' import { QuillService } from './quill.service' import { Component, Inject, Input, OnChanges, SimpleChanges, ViewEncapsulation } from '@angular/core' @Component({ encapsulation: ViewEncapsulation.None, selector: 'quill-view-html', styles: [` .ql-container.ngx-quill-view-html { border: 0; } `], template: ` <div class="ql-container" [ngClass]="themeClass"> <div class="ql-editor" [innerHTML]="innerHTML"> </div> </div> ` }) export class <API key> implements OnChanges { @Input() content = '' @Input() theme?: string innerHTML: SafeHtml = '' themeClass = 'ql-snow' constructor( @Inject(DomSanitizer) private sanitizer: DomSanitizer, protected service: QuillService ) {} ngOnChanges(changes: SimpleChanges) { if (changes.theme) { const theme = changes.theme.currentValue || (this.service.config.theme ? this.service.config.theme : 'snow') this.themeClass = `ql-${theme} ngx-quill-view-html` } else if (!this.theme) { const theme = this.service.config.theme ? this.service.config.theme : 'snow' this.themeClass = `ql-${theme} ngx-quill-view-html` } if (changes.content) { this.innerHTML = this.sanitizer.<API key>(changes.content.currentValue) } } }
#ifndef _WORDEXP_H #define _WORDEXP_H 1 #include <features.h> #define __need_size_t #include <stddef.h> __BEGIN_DECLS /* Bits set in the FLAGS argument to `wordexp'. */ enum { WRDE_DOOFFS = (1 << 0), /* Insert PWORDEXP->we_offs NULLs. */ WRDE_APPEND = (1 << 1), /* Append to results of a previous call. */ WRDE_NOCMD = (1 << 2), /* Don't do command substitution. */ WRDE_REUSE = (1 << 3), /* Reuse storage in PWORDEXP. */ WRDE_SHOWERR = (1 << 4), /* Don't redirect stderr to /dev/null. */ WRDE_UNDEF = (1 << 5), /* Error for expanding undefined variables. */ __WRDE_FLAGS = (WRDE_DOOFFS | WRDE_APPEND | WRDE_NOCMD | WRDE_REUSE | WRDE_SHOWERR | WRDE_UNDEF) }; /* Structure describing a word-expansion run. */ typedef struct { size_t we_wordc; /* Count of words matched. */ char **we_wordv; /* List of expanded words. */ size_t we_offs; /* Slots to reserve in `we_wordv'. */ } wordexp_t; /* Possible nonzero return values from `wordexp'. */ enum { #ifdef __USE_XOPEN WRDE_NOSYS = -1, /* Never used since we support `wordexp'. */ #endif WRDE_NOSPACE = 1, /* Ran out of memory. */ WRDE_BADCHAR, /* A metachar appears in the wrong place. */ WRDE_BADVAL, /* Undefined var reference with WRDE_UNDEF. */ WRDE_CMDSUB, /* Command substitution with WRDE_NOCMD. */ WRDE_SYNTAX /* Shell syntax error. */ }; /* Do word expansion of WORDS into PWORDEXP. */ extern int wordexp (const char *__restrict __words, wordexp_t *__restrict __pwordexp, int __flags); /* Free the storage allocated by a `wordexp' call. */ extern void wordfree (wordexp_t *__wordexp) __THROW; __END_DECLS #endif /* wordexp.h */
package calculator.operations; import java.util.function.<API key>; /** * * @author Michael Syme */ public enum Operations implements <API key> { PLUS ("+", (o1, o2) -> o1 + o2), MINUS ("-", (o1, o2) -> o1 - o2), MULTIPLY("*", (o1, o2) -> o1 * o2), DIVIDE ("/", (o1, o2) -> o1 / o2), SQUARE ("^", (o1, o2) -> Math.pow(o1, o2)); // Test document speaks of 'next iteration' using sin, cos, etc... //SINE ("sin", (o1, o2) -> Math.sin(o1)), //COSINE ("cos", (o1, o2) -> Math.cos(o1)), //TANGENT ("tan", (o1, o2) -> Math.tan(o1)); private final String symbol; private final <API key> func; private Operations(final String symbol, final <API key> func) { this.symbol = symbol; this.func = func; } public String getSymbol() { return symbol; } @Override public double applyAsDouble(final double left, final double right) { return func.applyAsDouble(left, right); } }
# RuntimeMeshLoader RuntimeMeshLoader for UE4 Use this plugin with <API key>, you can load mesh with Blueprint in runtime,support relative and absolute Path. Supported file formats 3DS BLEND (Blender) DAE/Collada FBX IFC-STEP ASE DXF HMP MD2 MD3 MD5 MDC MDL NFF PLY STL X OBJ OpenGEX SMD LWO LXO LWS TER AC3D MS3D COB Q3BSP XGL CSM BVH B3D NDO Ogre Binary Ogre XML Q3D ASSBIN (Assimp custom format) glTF (partial) 3MF
# <API key>: true require "rails_helper" RSpec.describe GraphqlController, type: :controller do let!(:app) do FactoryBot.create(:app) end let!(:user) do app.add_user(email: "test@test.cl") end let!(:agent_role) do app.add_agent({ email: "test2@test.cl" }) end let(:app_user) do app.add_user(email: "test@test.cl", first_name: "dsdsa") end let(:app_user2) do app.add_user(email: "admin@test.cl", first_name: "dsdsa") end let!(:conversation) do app.start_conversation( message: { html_content: "message" }, from: app_user ) end let(:<API key>) do app.start_conversation( message: { html_content: "message" }, from: agent_role.agent ) end before do ActiveJob::Base.queue_adapter = :test # ActiveJob::Base.queue_adapter.<API key> = true # Rails.application.config.active_job.queue_adapter = :test end before :each do stub_current_user(agent_role) end it "conversations" do graphql_post(type: "CONVERSATIONS", variables: { appKey: app.key, page: 1, filter: nil, sort: nil }) expect(graphql_response.errors).to be_nil expect(graphql_response.data.app.conversations.meta).to be_present expect(graphql_response.data.app.conversations.collection).to be_any end it "get unexisting conversation" do graphql_post(type: "CONVERSATION", variables: { appKey: app.key, id: "999" }) expect(graphql_response.data.app.conversation).to be_blank end it "create_conversation" do expect(app.conversations.count).to be == 1 expect(conversation.messages.count).to be == 1 expect(conversation.assignee).to be_blank graphql_post(type: "CONVERSATION", variables: { appKey: app.key, id: conversation.key, page: 1 }) expect(graphql_response.data.app.conversation).to_not be_blank expect(graphql_response.data.app.conversation.messages.meta).to_not be_blank expect(graphql_response.data.app.conversation.messages.collection).to be_any end it "agent add message" do # <API key>(Mutations::Conversations::InsertComment).to receive(:current_user).and_return(agent_role.agent) graphql_post(type: "INSERT_COMMMENT", variables: { appKey: app.key, id: conversation.key, message: "<p>helo</p>" }) expect(graphql_response.data.insertComment.message.message).to_not be_blank end end
var mongoose = require('mongoose'), Schema = mongoose.Schema; var serviceSchema = new Schema({ name: String, version: String, status: Boolean, success: Boolean }); mongoose.model('Service', serviceSchema);
/** * Just initialize the variables * * @class init */ /** * * @class restFactory */ window.rest = (function () { 'use strict'; /** * Array of modules list of the rest factory accepts. * * Every Module is a Obect like this: * <pre> * { * {resourceName} : {Object} * } * </pre> * @property modules * @type {Object} * @default null */ var modules = {}; return { /** * Register a new module object. * * Every Module is a Obect like this: * <pre> * { * {resourceName} : {Object} * } * </pre> * * @method register * @param {Object} resourceHandler A object to be instanced */ 'register': function(name, resourceHandler){ if(!resourceHandler || !name){ return; } modules[name] = resourceHandler; }, /** * Get a list of string of the accepts modules. * * @method getAccepts * @return {Array} accepts Array of string */ 'getAccepts': function(){ var accepts = []; for (var key in modules) { accepts.push(key); } return accepts; }, /** * Get a list of string of the accepts modules. * * @method convertResource * @param {String} contentType * @param {Resource} Response * @return {Object} modeule A instance of module */ 'convertResource' : function(contentType, response){ return new modules[contentType](response); } }; }()); 'use strict'; (function(){ /** * * @description * Determines if a reference is a `Function`. * * @private * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value) { return typeof value === 'function'; } /** * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. Note that JavaScript arrays are objects. * * @private * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value) { return value !== null && typeof value === 'object'; } /** * @ngdoc function * @name angular.isArray * @module ng * @kind function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ var isArray = Array.isArray; /** * @description * Determines if a value is a date. * * @private * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value) { return toString.call(value) === '[object Date]'; } /** * Determines if a value is a regular expression object. * * @private * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `RegExp`. */ function isRegExp(value) { return toString.call(value) === '[object RegExp]'; } /** * Determines if a value is a regular expression object. * * @private * @param {array} array Array to slice. * @param {Integer} start Where will start. * @returns {Array} newArray Cutted array . */ function slice(array, start){ var newArray = []; for (var i = start; i < array.length; i++) { newArray.push(array[i]); } return newArray; } /** * Set or clear the hashkey for an object. * @param obj object * @param h the hashkey (!truthy to delete the hashkey) */ function setHashKey(obj, h) { if (h) { obj.$$hashKey = h; } else { delete obj.$$hashKey; } } function baseExtend(dst, objs, deep) { var h = dst.$$hashKey; for (var i = 0, ii = objs.length; i < ii; ++i) { var obj = objs[i]; if (!isObject(obj) && !isFunction(obj)){ continue; } var keys = Object.keys(obj); for (var j = 0, jj = keys.length; j < jj; j++) { var key = keys[j]; var src = obj[key]; if (deep && isObject(src)) { if (isDate(src)) { dst[key] = new Date(src.valueOf()); } else if (isRegExp(src)) { dst[key] = new RegExp(src); } else { if (!isObject(dst[key])){ dst[key] = isArray(src) ? [] : {}; } window.rest.extend(dst[key], [src], true); } } else { dst[key] = src; } } } setHashKey(dst, h); return dst; } /** * * @description * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`. * * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use * {@link angular.merge} for this. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ window.rest.extend = function(dst) { return baseExtend(dst, slice(arguments, 1), false); }; /** * @description * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`. * * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source * objects, performing a deep copy. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ window.rest.merge = function(dst) { return baseExtend(dst, slice(arguments, 1), true); }; })();
<?php namespace Inodata\FloraBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\<API key>; use Symfony\Component\OptionsResolver\<API key>; class PaymentContactType extends AbstractType { public function buildForm(<API key> $builder, array $options) { $builder ->add('name', 'hidden') ->add('department', null, [ 'label' => 'label.department', ] ) ->add('employeeNumber', null, [ 'label' => 'label.employee_number', ] ) ->add('phone', null, [ 'label' => 'label.phone', ] ) ->add('extension', null, [ 'label' => 'label.extension', ] ) ->add('email', null, [ 'label' => 'label.email', ] ); } public function getName() { return '<API key>'; } public function setDefaultOptions(<API key> $resolver) { $resolver->setDefaults([ 'data_class' => 'Inodata\FloraBundle\Entity\PaymentContact', 'translation_domain' => 'InodataFloraBundle', ]); } }
<!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <meta name="generator" content="pandoc" /> <title>Corona Docs: guide > graphics > group</title> <meta name="revised" content="14-Nov-2013" /> <meta name="description" content="Whether you're new to Corona or want to take your app to the next level, we've got a wealth of resources for you including extensive documentation, API reference, sample code, and videos. guide > graphics > group" /> <style type="text/css"> table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode { margin: 0; padding: 0; vertical-align: baseline; border: none; } table.sourceCode { width: 100%; } td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; } td.sourceCode { padding-left: 5px; } code > span.kw { color: #007020; font-weight: bold; } code > span.dt { color: #902000; } code > span.dv { color: #40a070; } code > span.bn { color: #40a070; } code > span.fl { color: #40a070; } code > span.ch { color: #4070a0; } code > span.st { color: #4070a0; } code > span.co { color: #60a0b0; font-style: italic; } code > span.ot { color: #007020; } code > span.al { color: #ff0000; font-weight: bold; } code > span.fu { color: #06287e; } code > span.er { color: #ff0000; font-weight: bold; } </style> <link rel="stylesheet" href="../../css/style.css" type="text/css" /> <script src=" </head> <body> <div class="header"></div> <div class="title"> <span class="titleimg" onclick="window.location='http://docs.coronalabs.com/'"></span> <div id="nav"> <ul> <li><a href="../../api/index.html">SDK APIs</a></li> <li><a href="../../native/index.html">Enterprise APIs</a></li> <li><a href="../../plugin/index.html">Plugins</a></li> <li><a href="../index.html">Guides</a></li> <li><a href="http: </ul> <div id="resources-link"><a href="http://www.coronalabs.com/resources/">Corona Resources</a> &#9657;</div> </div> </div> <div class="SearchBar"> <form action="http: <input type="hidden" name="cx" value="<API key>:g40gqt2m6rq" /> <input type="hidden" name="ie" value="UTF-8" /> <input type="text" name="q" id="q" autocomplete="off" size="40" style="width:150px;float:left" /> <input type="submit" name="sa" value="Search" style="float:right; font-size: 13px;" /> </form> </div> <div id="TOC"> <ul> <li><a href="#<API key>">Group Programming Guide</a><ul> <li><a href="#creating-groups">Creating Groups</a></li> <li><a href="#child-properties">Child Properties</a><ul> <li><a href="#propagation">Propagation</a></li> <li><a href="#invalidation">Invalidation</a></li> </ul></li> <li><a href="#transforms">Transforms</a></li> <li><a href="#anchor-points">Anchor points</a><ul> <li><a href="#aligning-children">Aligning children</a></li> <li><a href="#alternatives">Alternatives:</a></li> </ul></li> <li><a href="#offscreen-culling">Offscreen culling</a></li> <li><a href="#containers">Containers</a></li> </ul></li> </ul> </div> <div id="breadcrumb"> <a href="http: </div> <div class="section level1" id="<API key>"> <h1><a href="#TOC">Group Programming Guide</a></h1> <p><a href="../../api/type/GroupObject/index.html">Groups</a> are the standard way to organize objects hierarchically.</p> <div class="section level2" id="creating-groups"> <h2><a href="#TOC">Creating Groups</a></h2> <p>Snapshot objects are easily created using Corona's <a href="../../api/library/display/newGroup.html">display.newGroup()</a> factory method.</p> <pre class="sourceCode lua"><code class="sourceCode lua"><span class="kw">local</span> <span class="kw">group</span> <span class="ot">=</span> <span class="kw">display</span><span class="ot">.</span>newGroup<span class="ot">(</span> <span class="dv">200</span>, <span class="dv">200</span> <span class="ot">)</span> <span class="fu">math.randomseed</span><span class="ot">(</span> <span class="dv">0</span> <span class="ot">)</span> <span class="co">-- Add fish to the screen</span> <span class="kw">for</span> <span class="kw">i</span><span class="ot">=</span><span class="dv">1</span>,<span class="dv">4</span> <span class="kw">do</span> <span class="kw">local</span> <span class="kw">fish</span> <span class="ot">=</span> <span class="kw">display</span><span class="ot">.</span>newImage<span class="ot">(</span> <span class="st">&quot;fish.small.red.png&quot;</span> <span class="ot">)</span> <span class="co">-- move to random position in a 200x200 region relative to group&#39;s origin</span> <span class="kw">fish</span>:translate<span class="ot">(</span> <span class="fu">math.random</span><span class="ot">(</span> <span class="ot">-</span><span class="dv">100</span>, <span class="dv">100</span> <span class="ot">)</span>, <span class="fu">math.random</span><span class="ot">(</span> <span class="ot">-</span><span class="dv">100</span>, <span class="dv">100</span> <span class="ot">)</span> <span class="ot">)</span> <span class="co">-- insert fish into group</span> <span class="kw">group</span>:insert<span class="ot">(</span> <span class="kw">fish</span> <span class="ot">)</span> <span class="kw">end</span> <span class="kw">local</span> <span class="kw">halfW</span>, <span class="kw">halfH</span> <span class="ot">=</span> <span class="kw">display</span><span class="ot">.</span><span class="kw">contentCenterX</span>, <span class="kw">display</span><span class="ot">.</span><span class="kw">contentCenterY</span> <span class="kw">group</span>:translate<span class="ot">(</span> <span class="kw">halfW</span>, <span class="kw">halfH</span> <span class="ot">)</span> <span class="co">-- Center group</span> <span class="kw">transition</span><span class="ot">.</span>to<span class="ot">(</span> <span class="kw">group</span>, <span class="ot">{</span> <span class="kw">alpha</span> <span class="ot">=</span> <span class="dv">0</span>, <span class="kw">time</span> <span class="ot">=</span> <span class="dv">2000</span><span class="ot">}</span> <span class="ot">)</span> <span class="co">-- Fade out</span></code></pre> <div class="figure"> <img src="../../images/sdk/graphics/Group-alpha.png" alt="Group with 4 fish" /><p class="caption">Group with 4 fish</p> </div> </div> <div class="section level2" id="child-properties"> <h2><a href="#TOC">Child Properties</a></h2> <div class="section level3" id="propagation"> <h3><a href="#TOC">Propagation</a></h3> <p>When you modify a group’s properties, the children are affected. For example, if you set the alpha on a group, then each child’s alpha is effectively multiplied by that alpha of the parent group.</p> </div> <div class="section level3" id="invalidation"> <h3><a href="#TOC">Invalidation</a></h3> <p>Groups automatically detect when a child's properties have changed such as position. Thus, on the next render pass, the child will re-render.</p> </div> </div> <div class="section level2" id="transforms"> <h2><a href="#TOC">Transforms</a></h2> <p>Transforms are applied hierarchically to the group's children. The child's transform is applied first, followed by the transform of its parent, followed by each ancestor, all the way to the stage.</p> <p>Consequently, children in a group are positioned relative to their parent group's position. Consequently, when you modify the transform a group, it affects the transform of the children.</p> <p>For example, if the group's x-position is increased by 100, then the child will appear to move by 100.</p> </div> <div class="section level2" id="anchor-points"> <h2><a href="#TOC">Anchor points</a></h2> <p>By defaults, groups do not honor anchor points. This is because children are normally positioned relative to the group's origin, so the location of the origin and the bounds of the children are not guaranteed to overlap, i.e. the anchor value would fall outside the range from 0 to 1.</p> <div class="section level3" id="aligning-children"> <h3><a href="#TOC">Aligning children</a></h3> <p>Sometimes it's convenient to treat the children of a group as a single object and then anchor them like you would a single rectangle. This allows you to position the children relative to the group's origin.</p> <p>You can do this by setting the following group property:</p> <pre><code>group.anchorChildren = true</code></pre> <p>By default, this property is <code>false</code>. However, for containers, this property defaults to <code>true</code>.</p> <p>In this case, the children are all offset by the same amount. That offset is calculated by looking at the bounding box for all the children. In essence, the children are treated as if they were a single rectangle and the group's origin was the anchor point for that rectangle.</p> <p>For example, if the group's anchor were (0.5,0.5), the children would collectively move so that their relative positions are preserved, but as a whole, they are centered about the group's origin.</p> </div> <div class="section level3" id="alternatives"> <h3><a href="#TOC">Alternatives:</a></h3> <ol style="list-style-type: decimal"> <li><p>You can use a special type of group called a [container][api.type.ContainerObject] if you need to work apply anchor points to a group-like object.</p></li> <li><p>Place your group as a child of another group (we'll call this the 'parent group'). Changing the position, rotation, or scale of the parent group will produce similar behavior.</p></li> </ol> </div> </div> <div class="section level2" id="offscreen-culling"> <h2><a href="#TOC">Offscreen culling</a></h2> <p>Corona will cull child objects that are outside the boundary of the screen.</p> <p>Groups have an infinite boundary, so if the screen were infinitely large, the child objects would always be drawn.</p> </div> <div class="section level2" id="containers"> <h2><a href="#TOC">Containers</a></h2> <p>A special type of group called [containers][api.type.ContainerObject] limit the boundary to a pre-defined region, so children are clipped by a dynamic rectangular mask.</p> <div id="footer"> <p style="font-size: 13px"> © 2013 Corona Labs Inc. All Rights Reserved. (Last updated: 14-Nov-2013) </p> <br /> <p> <strong>Help us help you! Give us feedback on this page:</strong> </p> <ul> <li> <a href="https://coronalabs.wufoo.com/forms/z7p9w5/def/field3=guide.graphics.group&field4=Current+Public+Release+%282013%2E2076%29" target="_blank">Love it</a> </li> <li> <a href="https://coronalabs.wufoo.com/forms/z7p9m3/def/field103=guide.graphics.group&field104=Current+Public+Release+%282013%2E2076%29" target="_blank">Like it, but...</a> </li> <li> <a href="https://coronalabs.wufoo.com/forms/z7p8x1/def/field103=guide.graphics.group&field104=Current+Public+Release+%282013%2E2076%29" target="_blank">Hate it</a> </li> </ul> </div> </div> </div> </body> </html>
package com.facetime.core.utils; import java.beans.BeanInfo; import java.beans.<API key>; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.<API key>; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.math.BigInteger; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.facetime.core.coercion.Coercer; import com.facetime.core.coercion.<API key>; import com.facetime.core.file.IOUtils; import com.facetime.core.io.StringInputStream; import com.facetime.core.io.StringOutputStream; import com.facetime.core.io.StringReader2; import com.facetime.core.io.StringWriter2; public class LE { /** * @return */ public static RuntimeException notImplementYet() { return new RuntimeException("No implements yet! May be *do not* need implement."); } /** * @return */ public static RuntimeException impossible() { return new RuntimeException("It is impossible! But it happpend. Check codes."); } /** * * * @param format * * @param args * * @return */ public static RuntimeException makeThrow(String format, Object... args) { return new RuntimeException(String.format(format, args)); } /** * * * @param classOfT * * @param format * * @param args * * @return */ public static <T extends Throwable> T makeThrow(Class<T> classOfT, String format, Object... args) { return CE.of(classOfT).create(String.format(format, args)); } /** * * * @param e * * @param fmt * * @param args * * @return */ public static RuntimeException wrapThrow(Throwable e, String fmt, Object... args) { return new RuntimeException(String.format(fmt, args), e); } /** * * <p> * <API key> TargetException * * @param e * * @return */ public static RuntimeException wrapThrow(Throwable e) { if (e instanceof RuntimeException) return (RuntimeException) e; if (e instanceof <API key>) return wrapThrow(((<API key>) e).getTargetException()); return new RuntimeException(e); } /** * Throwable * * @param e * * @param wrapper * * @return */ @SuppressWarnings("unchecked") public static <T extends Throwable> T wrapThrow(Throwable e, Class<T> wrapper) { if (wrapper.isAssignableFrom(e.getClass())) return (T) e; return CE.of(wrapper).create(e); } /** * * @param e * * @return * */ public static Throwable unwrapThrow(Throwable e) { if (e == null) return null; if (e instanceof <API key>) { <API key> itE = (<API key>) e; if (itE.getTargetException() != null) return unwrapThrow(itE.getTargetException()); } if (e.getCause() != null) return unwrapThrow(e.getCause()); return e; } /** * Exception<p> * * @param t * * @param type * * @return * NULL */ public static <T extends Throwable> T findCause(Throwable t, Class<T> type) { Throwable current = t; while (current != null) { if (type.isInstance(current)) return type.cast(current); // Not a match, work down. current = current.getCause(); } return null; } /** * Field<code>setAccessible(true)<br> * JVMSecurityManager * * @param field * Accessible * @see java.lang.reflect.Field#setAccessible */ public static void makeAccessible(Field field) { if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { field.setAccessible(true); } } public static void makeAccessible(Method method) { if (!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) { method.setAccessible(true); } } /** * : * <ul> * <li> null, null * <li>IdentifiablegetId() * <li> Number * <li>Map * </ul> * equals * * @param a1 * 1 * @param a2 * 2 * @return */ @SuppressWarnings("unchecked") public static boolean equals(Object a1, Object a2) { if (a1 == null && a2 == null) return true; if (a1 == null || a2 == null) return false; if (a1.equals(a2)) return true; CE<?> ce1 = CE.of(a1); if (ce1.isStringLike()) { return a1.toString().equals(a2.toString()); } if (ce1.isDateLike()) { Calendar calendar1 = Calendar.getInstance(); calendar1.setTime((java.util.Date) a1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime((java.util.Date) a2); if (calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR) && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH) && calendar1.get(Calendar.DATE) == calendar2.get(Calendar.DATE)) { return true; } else { return false; } } if (ce1.isTimeLike()) { return a1.equals(a2); } if (ce1.isNumber()) { return a2 instanceof Number && a1.toString().equals(a2.toString()); } if ((a1 instanceof Identifiable) && (a2 instanceof Identifiable)) { return equals(((Identifiable) a1).getId(), ((Identifiable) a2).getId()); } if (!a1.getClass().isAssignableFrom(a2.getClass()) && !a2.getClass().isAssignableFrom(a1.getClass())) return false; if (a1 instanceof Map && a2 instanceof Map) { Map<?, ?> m1 = (Map<?, ?>) a1; Map<?, ?> m2 = (Map<?, ?>) a2; if (m1.size() != m2.size()) return false; for (Map.Entry<?, ?> e : m1.entrySet()) { Object key = e.getKey(); if (!m2.containsKey(key) || !equals(m1.get(key), m2.get(key))) return false; } return true; } else if (a1.getClass().isArray()) { if (a2.getClass().isArray()) { int len = Array.getLength(a1); if (len != Array.getLength(a2)) return false; for (int i = 0; i < len; i++) { if (!equals(Array.get(a1, i), Array.get(a2, i))) return false; } return true; } else if (a2 instanceof List) { return equals(a1, LE.coll2array((List<Object>) a2, Object.class)); } return false; } else if (a1 instanceof List) { if (a2 instanceof List) { List<?> l1 = (List<?>) a1; List<?> l2 = (List<?>) a2; if (l1.size() != l2.size()) return false; int i = 0; for (Iterator<?> it = l1.iterator(); it.hasNext();) { if (!equals(it.next(), l2.get(i++))) return false; } return true; } else if (a2.getClass().isArray()) { return equals(LE.coll2array((List<Object>) a1, Object.class), a2); } return false; } else if (a1 instanceof Collection && a2 instanceof Collection) { Collection<?> c1 = (Collection<?>) a1; Collection<?> c2 = (Collection<?>) a2; if (c1.size() != c2.size()) return false; return c1.containsAll(c2) && c2.containsAll(c1); } return false; } /** * Bean<br> * LE.equalsFieldtrim{@link #equal_trick_trim}"NULL"null * @param bean1 * 1 * @param bean2 * 2 * @return * Bean */ public static boolean equalsForBean(Object bean1, Object bean2) { if (bean1.getClass() != bean2.getClass()) return false; CE ce = CE.of(bean1.getClass()); Field[] fields = ce.getFields(); Set<String> fns = new HashSet<String>(); for (Field field : fields) { fns.add(field.getName()); try { //trim LE.makeAccessible(field); Object v1 = equal_trick_trim(field.get(bean1)); Object v2 = equal_trick_trim(field.get(bean2)); if (!LE.equals(v1, v2)) { return false; } } catch (Exception e) { return false; } } return true; } /** * CE() <br></> * public private ... * * @param src * CE * @param name * * @param value * * * @return */ public static Object invoke(Object src, String name, Object... value) { Class<?>[] param_cls = LE.evalToTypes(value); CE<?> ce = CE.of(src); try { Method method = ce.findMethod(name, param_cls); LE.makeAccessible(method); return method.invoke(src, value); } catch (<API key> e) { throw new <API key>(e, "Can not find any method [ %s ( %s ) ] on class[ %s ]", name, value.getClass(), src.getClass()); } catch (Throwable e) { throw new <API key>(e, "Invoke method [ %s ] on class[ %s ] error.", name, src.getClass()); } } /** * * * @return Array of property names, or null if an error occurred. */ public static String[] getPropertyNames(Class<?> clazz) { return getPropertyNames(clazz, false); } private static String[] getPropertyNames(Class<?> clazz, boolean only4Copy) { List<String> ret_all = new ArrayList<String>(); List<String> ret = new ArrayList<String>(); Field[] fields = CE.of(clazz).getFields(Object.class); for (Field fld : fields) { if (fld.getModifiers() == Modifier.PUBLIC) { ret.add(fld.getName()); } ret_all.add(fld.getName()); } BeanInfo info = null; try { info = Introspector.getBeanInfo(clazz); } catch (<API key> e) { } if (info != null) { PropertyDescriptor[] properties = info.<API key>(); for (int i = 0; i < properties.length; i++) { PropertyDescriptor pd = properties[i]; if (ret_all.contains(pd.getName()) && !ret.contains(pd.getName())) { if (!only4Copy || (pd.getReadMethod() != null && pd.getWriteMethod() != null)) ret.add(properties[i].getName()); } } } return ret.toArray(new String[ret.size()]); } /** * (GetterPUBLIC Field)<br></> * (CE)(getter)<br></> * obj.property. obj.getProperty(), obj.isProperty(), obj.property(),. * <API key> * @param object * * @param property * * @return * */ public static Object getPropertyValue(Object object, String property) { Class<?> clzz = object.getClass(); try { Field fld = object.getClass().getField(property); return fld.get(object); } catch (Throwable t) { Method m = null; try { m = clzz.getMethod("get" + StringUtils.capitalize(property)); } catch (<API key> t1) { try { m = clzz.getMethod("is" + StringUtils.capitalize(property)); } catch (<API key> t2) { try { m = clzz.getMethod(property); } catch (<API key> e) { throw new <API key>( "Can NOT find any public property or getter named [ %s ] on class[ %s ]", property, object.getClass()); } } } try { return m.invoke(object); } catch (Throwable e) { throw new <API key>(e, "Get property[%s] value on class[%s] failed.", property, object.getClass()); } } } /** * * @param bean * @param property * @param value */ public static void setPropertyValue(Object bean, String property, Object value) { Class<?> clss = bean.getClass(); try { Field fld = clss.getField(property); fld.set(bean, value); } catch (Throwable t) { Method m = null; try { PropertyDescriptor pd = new PropertyDescriptor(property, clss); m = pd.getWriteMethod(); } catch (<API key> e) { throw new <API key>(e, "Failed to find writeMethod of property[%s] on class[%s] failed.", property, bean.getClass()); } if (null == m) { throw new <API key>("Failed to find writeMethod of property[%s] on class[%s] failed.", property, bean.getClass()); } try { m.invoke(bean, value); } catch (Throwable e) { throw new <API key>(e, "Set property[%s] value[%s] with type[%s] on class[%s] failed.", property, value, value == null ? "NULL type" : LE.toString(CE.of(value.getClass()) .getExtractTypes(), ""), bean.getClass()); } } } /** * Bean getClass()copyclone * @param src * * @param to * */ public static void copy(Object src, Object to) { if (src.getClass() != to.getClass()) return; String[] props = LE.getPropertyNames(to.getClass(), true); for (String prop : props) { Object value = LE.getPropertyValue(src, prop); LE.setPropertyValue(to, prop, value); } } /** * trick_trim * @param v * @return */ public static Object equal_trick_trim(Object v) { if (v == null) { return v; } if (v instanceof String) { if (v.equals("null") || ((String) v).trim().length() == 0) { return null; } } if (v instanceof Boolean || boolean.class == v.getClass()) { if (!((Boolean) v).booleanValue()) { return null; } } return v; } /** * equals(Object,Object) * * @param array * * @param ele * * @return true false */ public static <T> boolean contains(T[] array, T ele) { if (null == array) return false; for (T e : array) { if (equals(e, ele)) return true; } return false; } /** * * * @param reader * * @return */ public static String readAll(Reader reader) { if (!(reader instanceof BufferedReader)) reader = new BufferedReader(reader); try { StringBuilder sb = new StringBuilder(); char[] data = new char[64]; int len; while (true) { if ((len = reader.read(data)) == -1) break; sb.append(data, 0, len); } return sb.toString(); } catch (IOException e) { throw LE.wrapThrow(e); } finally { IOUtils.close(reader); } } /** * * * @param writer * * @param str * */ public static void writeAll(Writer writer, String str) { try { writer.write(str); writer.flush(); } catch (IOException e) { throw LE.wrapThrow(e); } finally { IOUtils.close(writer); } } /** * <br/> * * @param cs * * @return */ public static InputStream ins(CharSequence cs) { return new StringInputStream(cs); } /** * * * @param cs * * @return */ public static Reader inr(CharSequence cs) { return new StringReader2(cs); } /** * StringBuilder * * @param sb * StringBuilder * @return */ public static Writer opw(StringBuilder sb) { return new StringWriter2(sb); } /** * StringBuilder * * @param sb * StringBuilder * @return */ public static StringOutputStream ops(StringBuilder sb) { return new StringOutputStream(sb); } /** * * * <pre> * Pet[] pets = LE.array(pet1, pet2, pet3); * </pre> * * @param eles * * @return */ public static <T> T[] array(T... eles) { return eles; } /** * Returns true if the <code>Method</code> creating is a getter, meaning if * it's getName starts with "get" or "is", takes no parameters, and returns a * symbol. False if not. * * @param method The method to validate if it is a getter method. * @return True if the <code>Method</code> creating is a getter. False if * not. */ public static boolean isGetter(Method method) { if (method.getParameterTypes().length > 0) { return false; } if (method.getReturnType() == void.class || method.getReturnType() == null) { return false; } return method.getName().startsWith("get") || method.getName().startsWith("is"); } /** * Returns true if the <code>Method</code> creating is a setter method, * meaning if the method getName starts with "set" and it takes exactly one * parameter. * * @param member The <code>Method</code> creating to validate if is a setter * method. * @return True if the <code>Method</code> creating is a setter. False if * not. */ public static boolean isSetter(Method member) { if (!member.getName().startsWith("set")) { return false; } if (member.getParameterTypes().length != 1) { return false; } return true; } /** * * * @param f * @return */ public static boolean isIgnoredField(Field f) { int mods = f.getModifiers(); return Modifier.isStatic(mods) || Modifier.isFinal(mods) || Modifier.isTransient(mods) || f.getName().startsWith("this$"); } /** * * @param o * * @return */ public static boolean isArray(Object o) { if (o == null) return false; return o.getClass().isArray(); } /** * * <ul> * <li>null : * <li> * <li> * <li>Map * <li> : * </ul> * * @param o * * @return */ public static boolean isEmpty(Object o) { if (o == null) return true; if (o instanceof Collection<?>) return ((Collection<?>) o).isEmpty(); if (o instanceof Map<?, ?>) return ((Map<?, ?>) o).isEmpty(); if (o.getClass().isArray()) return Array.getLength(o) == 0; if (o instanceof String) return StringUtils.isEmpty((String) o); return false; } /** * * @param obj * * @return */ public static boolean isNotEmpty(Object obj) { return !isEmpty(obj); } /** * * * @param ary * * @return null true false */ public static <T> boolean isEmptyArray(T[] array) { return array == null || array.length == 0; } /** * * * <pre> * ListPet pets = LE.list(pet1, pet2, pet3); * </pre> * * List ArrayList * * @param eles * * @return */ public static <T> ArrayList<T> list(T... eles) { ArrayList<T> list = new ArrayList<T>(eles.length); for (T ele : eles) list.add(ele); return list; } /** * null * * @param arys * * @return */ @SuppressWarnings("unchecked") public static <T> T[] merge(T[]... arys) { Queue<T> list = new LinkedList<T>(); for (T[] ary : arys) if (null != ary) for (T e : ary) if (null != e) list.add(e); if (list.isEmpty()) return null; Class<T> type = (Class<T>) list.peek().getClass(); return list.toArray((T[]) Array.newInstance(type, list.size())); } /** * * <p> * %s, %d * * @param fmt * * @param arrays * * @return */ public static <T> StringBuilder joinBy(String fmt, T[] arrays) { StringBuilder sb = new StringBuilder(); for (T obj : arrays) sb.append(String.format(fmt, obj)); return sb; } /** * * <p> * %s, %d * <p> * * * @param ptn * * @param glue * * @param arrays * * @return */ public static <T> StringBuilder joinBy(String ptn, Object glue, T[] arrays) { StringBuilder sb = new StringBuilder(); for (T obj : arrays) sb.append(String.format(ptn, obj)).append(glue); if (sb.length() > 0) sb.deleteCharAt(sb.length() - String.valueOf(glue).length()); return sb; } /** * * <p> * * * @param glue * * @param arrays * * @return */ public static <T> StringBuilder join(Object glue, T[] arrays) { StringBuilder sb = new StringBuilder(); if (null == arrays || 0 == arrays.length) return sb; sb.append(arrays[0]); for (int i = 1; i < arrays.length; i++) sb.append(glue).append(arrays[i]); return sb; } /** * * <p> * * * * @param glue * * @param objs * * @param offset * * @param len * * @return */ public static <T> StringBuilder join(Object glue, T[] objs, int offset, int len) { StringBuilder sb = new StringBuilder(); if (null == objs || len < 0 || 0 == objs.length) return sb; if (offset < objs.length) { sb.append(objs[offset]); for (int i = 1; i < len && i + offset < objs.length; i++) { sb.append(glue).append(objs[i + offset]); } } return sb; } /** * * <p> * * * @param glue * * @param vals * * @return */ public static StringBuilder join(Object glue, long[] vals) { StringBuilder sb = new StringBuilder(); if (null == vals || 0 == vals.length) return sb; sb.append(vals[0]); for (int i = 1; i < vals.length; i++) sb.append(glue).append(vals[i]); return sb; } /** * * <p> * * * @param glue * * @param vals * * @return */ public static StringBuilder join(Object glue, int[] vals) { StringBuilder sb = new StringBuilder(); if (null == vals || 0 == vals.length) return sb; sb.append(vals[0]); for (int i = 1; i < vals.length; i++) sb.append(glue).append(vals[i]); return sb; } /** * * * @param arrays * * @return */ public static <T> StringBuilder join(T[] arrays) { StringBuilder sb = new StringBuilder(); for (T e : arrays) sb.append(String.valueOf(e)); return sb; } /** * * * * @param array * * @param offset * * @param len * * @return */ public static <T> StringBuilder join(T[] array, int offset, int len) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { sb.append(String.valueOf(array[i + offset])); } return sb; } /** * * <p> * * * @param glue * * @param coll * * @return */ public static <T> StringBuilder join(Object glue, Collection<T> coll) { StringBuilder sb = new StringBuilder(); if (null == coll || coll.isEmpty()) return sb; Iterator<T> it = coll.iterator(); sb.append(it.next()); while (it.hasNext()) sb.append(glue).append(it.next()); return sb; } /** * Map * * @param typeOfMap * Map * @param coll * * @param keyFieldName * * @return Map */ public static <T extends Map<Object, Object>> Map<?, ?> coll2map(Class<T> typeOfMap, Collection<?> coll, String keyFieldName) { if (null == coll) return null; Map<Object, Object> map = createMap(typeOfMap); if (coll.size() > 0) { Iterator<?> it = coll.iterator(); Object obj = it.next(); Object key = LE.getPropertyValue(obj, keyFieldName); map.put(key, obj); for (; it.hasNext();) { obj = it.next(); key = LE.getPropertyValue(obj, keyFieldName); map.put(key, obj); } } return map; } /** * * * @param col * * @param eleType * * @return */ public static <E> List<E> coll2list(Collection<?> col, Class<E> eleType) { if (null == col) return null; List<E> list = new ArrayList<E>(col.size()); for (Object obj : col) list.add(Coercer.get().coerce(obj, eleType)); return list; } /** * null * * @param coll * * @return */ @SuppressWarnings("unchecked") public static <E> E[] coll2array(Collection<E> coll) { if (coll == null || coll.size() == 0) return (E[]) new Object[0]; Class<E> eleType = (Class<E>) LE.first(coll).getClass(); return coll2array(coll, eleType); } /** * * * @param coll * * @param elemType * * @return */ @SuppressWarnings("unchecked") public static <E> E[] coll2array(Collection<?> coll, Class<E> elemType) { if (null == coll) return null; Object re = Array.newInstance(elemType, coll.size()); int i = 0; for (Iterator<?> it = coll.iterator(); it.hasNext();) { Object obj = it.next(); if (null == obj) Array.set(re, i++, null); else Array.set(re, i++, Coercer.get().coerce(obj, elemType)); } return (E[]) re; } /** * Map * * @param typeOfMap * Map * @param array * * @param keyFieldName * * @return Map */ public static <T extends Map<Object, Object>> Map<?, ?> array2map(Class<T> typeOfMap, Object array, String keyFieldName) { if (array == null) return null; Map<Object, Object> map = createMap(typeOfMap); int len = Array.getLength(array); if (len > 0) { Object obj = Array.get(array, 0); //CE<?> ce = CE.of(obj.getClass()); for (int i = 0; i < len; i++) { obj = Array.get(array, i); Object key = LE.getPropertyValue(obj, keyFieldName); map.put(key, obj); } } return map; } private static <T extends Map<Object, Object>> Map<Object, Object> createMap(Class<T> mapClass) { Map<Object, Object> map; try { map = mapClass.newInstance(); } catch (Exception e) { map = new HashMap<Object, Object>(); } if (!mapClass.isAssignableFrom(map.getClass())) { throw LE.makeThrow("Fail to create map [%s]", mapClass.getName()); } return map; } /** * * * @param array * * @return */ public static <T> List<T> array2list(T[] array) { if (null == array) return null; List<T> re = new ArrayList<T>(array.length); for (T obj : array) re.add(obj); return re; } /** * Coercion * * @param array * * @param eleType * * @return * */ public static <T, E> List<E> array2list(Object array, Class<E> eleType) { if (null == array) return null; int len = Array.getLength(array); List<E> re = new ArrayList<E>(len); for (int i = 0; i < len; i++) { Object obj = Array.get(array, i); re.add(Coercer.get().coerce(obj, eleType)); } return re; } /** * CoercionTuple * * @param array * * @param eleType * * @return * @throws com.facetime.core.coercion.street.common.coercion.<API key> */ public static Object array2array(Object array, Class<?> eleType) throws <API key> { if (array == null) return null; int len = Array.getLength(array); Object re = Array.newInstance(eleType, len); for (int i = 0; i < len; i++) { Array.set(re, i, Coercer.get().coerce(Array.get(array, i), eleType)); } return re; } /** * * * @param args * * @return */ public static Class<?>[] evalToTypes(Object... args) { if (args == null || args.length == 0) return new Class<?>[0]; Class<?>[] types = new Class[args.length]; int i = 0; for (Object arg : args) types[i++] = null == arg ? Object.class : arg.getClass(); return types; } /** * Object[] T[] * * @param args * * @return , null */ public static Object evalArgToRealArray(Object... args) { if (args == null || args.length == 0 || args[0] == null) return null; Object result = null; /* * Check inside the arguments list, to see if all element is in same * type */ Class<?> type = null; for (Object arg : args) { if (arg == null) break; if (null == type) { type = arg.getClass(); continue; } if (arg.getClass() != type) { type = null; break; } } /* * If all argument elements in same type, make a new ArrayEx by the Type */ if (type != null) { result = Array.newInstance(type, args.length); for (int i = 0; i < args.length; i++) { Array.set(result, i, args[i]); } return result; } return args; } /** * * * @param methodParamTypes * * @param args * * @return * * @see MatchType */ public static MatchType matchParamTypes(Class<?>[] methodParamTypes, Object... args) { return matchParamTypes(methodParamTypes, evalToTypes(args)); } /** * * * @param paramTypes * * @param argTypes * * @return * * @see MatchType */ public static MatchType matchParamTypes(Class<?>[] paramTypes, Class<?>[] argTypes) { int len = argTypes == null ? 0 : argTypes.length; if (len == 0 && paramTypes.length == 0) return MatchType.YES; if (paramTypes.length == len) { for (int i = 0; i < len; i++) if (!CE.of(argTypes[i]).isOf((paramTypes[i]))) return MatchType.NO; return MatchType.YES; } else if (len + 1 == paramTypes.length) { if (!paramTypes[len].isArray()) return MatchType.NO; for (int i = 0; i < len; i++) if (!CE.of(argTypes[i]).isOf((paramTypes[i]))) return MatchType.NO; return MatchType.LACK; } return MatchType.NO; } /** * * * @param pts * * @return */ public static Object[] blankArrayArg(Class<?>[] pts) { return (Object[]) Array.newInstance(pts[pts.length - 1].getComponentType(), 0); } /** * Object[] CoercionTuple * * @param args * * @param pts * * @return * @throws com.facetime.core.coercion.street.common.coercion.<API key> * */ public static <T> Object[] array2ObjectArray(T[] args, Class<?>[] pts) throws <API key> { if (null == args) return null; Object[] newArgs = new Object[args.length]; for (int i = 0; i < args.length; i++) { newArgs[i] = Coercer.get().coerce(args[i], pts[i]); } return newArgs; } /** * * <ul> * <li>null - 0</li> * <li>23.78 - Float</li> * <li>0x45 - 16 Integer</li> * <li>78L - Long</li> * <li>69 - Integer</li> * </ul> * * @param s * * @return */ public static Number toNumber(String s) { // null if (null == s) return 0; s = s.toLowerCase(); if (s.indexOf('.') != -1) { char c = s.charAt(s.length() - 1); if (c == 'f') { return Float.valueOf(s); } return Double.valueOf(s); } if (s.startsWith("0x")) { try { return Integer.valueOf(s.substring(2), 16); } catch (Exception e) { return new BigInteger(s.substring(2), 16); } } Long re = Long.parseLong(s); if (Integer.MAX_VALUE >= re && re >= Integer.MIN_VALUE) { return re.intValue(); } return re; } /** * * * @param cs * * @return */ public static byte[] toBytes(char[] cs) { byte[] bs = new byte[cs.length]; for (int i = 0; i < cs.length; i++) bs[i] = (byte) cs[i]; return bs; } /** * * * @param is * * @return */ public static byte[] toBytes(int[] is) { byte[] bs = new byte[is.length]; for (int i = 0; i < is.length; i++) bs[i] = (byte) is[i]; return bs; } /** * each */ public static void exist() throws ExitLoop { throw new ExitLoop(); } /** * * <ul> * <li> * <li> * <li>Map * <li> * </ul> * * @param elems * * @param callback * */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> void each(Object elems, Each<T> callback) { if (null == elems || null == callback) return; try { Class<T> eType = getTypeParam(callback.getClass(), 0); if (elems.getClass().isArray()) { int len = Array.getLength(elems); for (int i = 0; i < len; i++) try { callback.loop(i, (T) Array.get(elems, i), len); } catch (ExitLoop e) { break; } } else if (elems instanceof Collection) { int len = ((Collection) elems).size(); int i = 0; for (Iterator<T> it = ((Collection) elems).iterator(); it.hasNext();) try { callback.loop(i++, it.next(), len); } catch (ExitLoop e) { break; } } else if (elems instanceof Map) { Map map = (Map) elems; int len = map.size(); int i = 0; if (null != eType && eType != Object.class && eType.isAssignableFrom(Map.Entry.class)) { for (Object v : map.entrySet()) try { callback.loop(i++, (T) v, len); } catch (ExitLoop e) { break; } } else { for (Object v : map.entrySet()) try { callback.loop(i++, (T) ((Map.Entry) v).getValue(), len); } catch (ExitLoop e) { break; } } } else if (elems instanceof Iterator<?>) { Iterator<?> it = (Iterator<?>) elems; int i = 0; while (it.hasNext()) { try { callback.loop(i++, (T) it.next(), -1); } catch (ExitLoop e) { break; } } } else try { callback.loop(0, (T) elems, 1); } catch (ExitLoop e) { } } catch (LoopException e) { throw LE.wrapThrow(e.getCause()); } } /** * Map JAVA * * @param obj * * @return */ public static Object first(Object obj) { final Object[] re = new Object[1]; each(obj, new Each<Object>() { public void loop(int i, Object obj, int length) throws ExitLoop { re[0] = obj; LE.exist(); } }); return re[0]; } /** * null * * @param coll * * @return */ public static <T> T first(Collection<T> coll) { if (null == coll || coll.isEmpty()) return null; return coll.iterator().next(); } /** * * * @param map * * @return */ public static <K, V> Map.Entry<K, V> first(Map<K, V> map) { if (null == map || map.isEmpty()) return null; return map.entrySet().iterator().next(); } /** * * * @param e * * @return */ public static String getStackTrace(Throwable e) { StringBuilder sb = new StringBuilder(); StringOutputStream sbo = new StringOutputStream(sb); PrintStream ps = new PrintStream(sbo); e.printStackTrace(ps); ps.flush(); return sbo.toString(); } /** * boolean * <ul> * <li>1 | 0 * <li>yes | no * <li>on | off * <li>true | false * </ul> * * @param s * @return */ public static boolean parseBoolean(String s) { if (null == s || s.length() == 0) return false; if ("0".equals(s)) return false; s = s.toLowerCase(); return "true".equals(s) || "yes".equals(s) || "t".equals(s) || "on".equals(s); } /** * Thread.sleep(long), * * @param millisecond * */ public void sleepQuite(long millisecond) { try { if (millisecond > 0) Thread.sleep(millisecond); } catch (Throwable e) { } } /** * objcastToString(),nulldef * * @param src * @param def * src==null * @return toString, coerciontoString() */ public static String toString(Object src, String def) { if (src == null) return def; try { return Coercer.get().coerce(src, String.class); } catch (<API key> e) { return String.valueOf(src); } } /** * TypeClass */ public static Class<?> asClass(Type actualType) { if (actualType instanceof Class) return (Class<?>) actualType; if (actualType instanceof ParameterizedType) { final Type rawType = ((ParameterizedType) actualType).getRawType(); // The sun implementation returns getRawType as Class<?>, but there is room in the interface for it to be // some other Type. We'll assume it's a Class. // TODO: consider logging or throwing our own exception for that day when "something else" causes some confusion return (Class) rawType; } if (actualType instanceof GenericArrayType) { final Type type = ((GenericArrayType) actualType).<API key>(); return Array.newInstance(asClass(type), 0).getClass(); } if (actualType instanceof TypeVariable) { // Support for List<T extends Number> // There is always at least one bound. If no bound is specified in the source then it will be Object.class return asClass(((TypeVariable) actualType).getBounds()[0]); } if (actualType instanceof WildcardType) { final WildcardType wildcardType = (WildcardType) actualType; final Type[] bounds = wildcardType.getLowerBounds(); if (bounds != null && bounds.length > 0) { return asClass(bounds[0]); } // If there is no lower bounds then the only thing that makes sense is Object. return Object.class; } throw new RuntimeException(String.format("Unable to convert %s to Class.", actualType)); } /** * null */ public static Type[] extractTypeParams(Class<?> clazz) { if (clazz == null || clazz == Object.class) return null; Type superclass = clazz.<API key>(); if (null != superclass && superclass instanceof ParameterizedType) return ((ParameterizedType) superclass).<API key>(); Type[] interfaces = clazz.<API key>(); for (Type inf : interfaces) { if (inf instanceof ParameterizedType) { return ((ParameterizedType) inf).<API key>(); } } return extractTypeParams(clazz.getSuperclass()); } private static final Pattern PTN = Pattern.compile("(<)(.+)(>)"); /** * * * @param field * * @return */ public static Class<?>[] getGenericTypes(Field field) { String gts = field.toGenericString(); Matcher m = PTN.matcher(gts); if (m.find()) { String s = m.group(2); String[] ss = StringUtils.splitIgnoreBlank(s, ","); if (ss.length > 0) { Class<?>[] re = new Class<?>[ss.length]; for (int i = 0; i < ss.length; i++) { String className = ss[i]; if (className.length() > 0 && className.charAt(0) == '?') re[i] = Object.class; else { int pos = className.indexOf('<'); if (pos < 0) re[i] = ClassUtils.loadClass(className); else re[i] = ClassUtils.loadClass(className.substring(0, pos)); } } return re; } } return new Class<?>[0]; } /** * null * * @param field * * @return */ public static Class<?> getGenericTypes(Field field, int index) { Class<?>[] types = getGenericTypes(field); if (null == types || types.length <= index) return null; return types[index]; } /** * * * @param klass * * @param index * 0 * @return */ @SuppressWarnings("unchecked") public static <T> Class<T> getTypeParam(Class<?> klass, int index) { Type[] types = extractTypeParams(klass); if (index >= 0 && index < types.length) { Type t = types[index]; Class<T> tClass = (Class<T>) LE.asClass(t); if (tClass == null) throw LE.makeThrow("Type '%s' is not a Class", t.toString()); return tClass; } throw LE.makeThrow("Class type param out of range %d/%d", index, types.length); } /** * @param clazz * * @return */ public static String getPath(Class<?> clazz) { return clazz.getName().replace('.', '/'); } /** * @param parameterTypes * * @return */ public static String getParamDescriptor(Class<?>[] parameterTypes) { StringBuilder sb = new StringBuilder(); sb.append('('); for (Class<?> pt : parameterTypes) sb.append(getTypeDescriptor(pt)); sb.append(')'); String s = sb.toString(); return s; } /** * @param method * * @return */ public static String getMethodDescriptor(Method method) { return getParamDescriptor(method.getParameterTypes()) + getTypeDescriptor(method.getReturnType()); } /** * @param c * * @return */ public static String <API key>(Constructor<?> c) { return getParamDescriptor(c.getParameterTypes()) + "V"; } /** * @param klass * * @return */ public static String getTypeDescriptor(Class<?> klass) { if (klass.isPrimitive()) { if (klass == void.class) return "V"; else if (klass == int.class) return "I"; else if (klass == long.class) return "J"; else if (klass == byte.class) return "B"; else if (klass == short.class) return "S"; else if (klass == float.class) return "F"; else if (klass == double.class) return "D"; else if (klass == char.class) return "C"; else /* if(_clazz == boolean.class) */ return "Z"; } StringBuilder sb = new StringBuilder(); if (klass.isArray()) { return sb.append('[').append(getTypeDescriptor(klass.getComponentType())).toString(); } return sb.append('L').append(getPath(klass)).append(';').toString(); } /** * * <p/> * <ul> * <li>YES: * <li>LACK: * <li>NO: * </ul> */ public static enum MatchType { YES, LACK, NO, NEED_CAST } public static void main(String[] args) { String ss = " "; System.out.println(LE.isEmpty(ss)); } }
package demo.binea.com.pulltorefreshlib; import demo.binea.com.pulltorefreshlib.indicator.PtrIndicator; /** * A single linked list to wrap PtrUIHandler */ class PtrUIHandlerHolder implements PtrUIHandler { private PtrUIHandler mHandler; private PtrUIHandlerHolder mNext; private boolean contains(PtrUIHandler handler) { return mHandler != null && mHandler == handler; } private PtrUIHandlerHolder() { } public boolean hasHandler() { return mHandler != null; } private PtrUIHandler getHandler() { return mHandler; } public static void addHandler(PtrUIHandlerHolder head, PtrUIHandler handler) { if (null == handler) { return; } if (head == null) { return; } if (null == head.mHandler) { head.mHandler = handler; return; } PtrUIHandlerHolder current = head; for (; ; current = current.mNext) { // duplicated if (current.contains(handler)) { return; } if (current.mNext == null) { break; } } PtrUIHandlerHolder newHolder = new PtrUIHandlerHolder(); newHolder.mHandler = handler; current.mNext = newHolder; } public static PtrUIHandlerHolder create() { return new PtrUIHandlerHolder(); } public static PtrUIHandlerHolder removeHandler(PtrUIHandlerHolder head, PtrUIHandler handler) { if (head == null || handler == null || null == head.mHandler) { return head; } PtrUIHandlerHolder current = head; PtrUIHandlerHolder pre = null; do { // delete current: link pre to next, unlink next from current; // pre will no change, current move to next element; if (current.contains(handler)) { // current is head if (pre == null) { head = current.mNext; current.mNext = null; current = head; } else { pre.mNext = current.mNext; current.mNext = null; current = pre.mNext; } } else { pre = current; current = current.mNext; } } while (current != null); if (head == null) { head = new PtrUIHandlerHolder(); } return head; } @Override public void onUIReset(PtrFrameLayout frame) { PtrUIHandlerHolder current = this; do { final PtrUIHandler handler = current.getHandler(); if (null != handler) { handler.onUIReset(frame); } } while ((current = current.mNext) != null); } @Override public void onUIRefreshPrepare(PtrFrameLayout frame) { if (!hasHandler()) { return; } PtrUIHandlerHolder current = this; do { final PtrUIHandler handler = current.getHandler(); if (null != handler) { handler.onUIRefreshPrepare(frame); } } while ((current = current.mNext) != null); } @Override public void onUIRefreshBegin(PtrFrameLayout frame) { PtrUIHandlerHolder current = this; do { final PtrUIHandler handler = current.getHandler(); if (null != handler) { handler.onUIRefreshBegin(frame); } } while ((current = current.mNext) != null); } @Override public void onUIRefreshComplete(PtrFrameLayout frame) { PtrUIHandlerHolder current = this; do { final PtrUIHandler handler = current.getHandler(); if (null != handler) { handler.onUIRefreshComplete(frame); } } while ((current = current.mNext) != null); } @Override public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) { PtrUIHandlerHolder current = this; do { final PtrUIHandler handler = current.getHandler(); if (null != handler) { handler.onUIPositionChange(frame, isUnderTouch, status, ptrIndicator); } } while ((current = current.mNext) != null); } }
(function() { 'use strict'; angular .module('<%= moduleName %>') .controller('<%= moduleName %>Ctrl', controller); controller.$inject = []; function controller() { } })();
package android.protype.datashade; import java.util.ArrayList; import com.example.datashade.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class BlockOfShade extends View { Paint mWhite = new Paint(); Paint mRed = new Paint(); Paint mGreen = new Paint(); Paint mShade = new Paint(); Paint mBlack = new Paint(); float h; public float tempX; public float tempY; int count = 0; boolean mShowText; int mTextPos; boolean mIsShaded = false; public BlockOfShade(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().<API key>( attrs, R.styleable.BlockOfShade, 0, 0); try { mShowText = a.getBoolean(R.styleable.<API key>, true); mTextPos = a.getInteger(R.styleable.<API key>, 0); //mIsShaded = a.getBoolean(R.styleable.<API key>, false); } finally { a.recycle(); } this.mWhite.setColor(0xff000000); this.mBlack.setColor(0xff000000); this.mRed.setColor(0xffff0000); this.mGreen.setColor(0xff00ff00); this.mShade.setColor(0xff005500); ArrayList<View> test = new ArrayList<View>(); test.add(this); this.addTouchables( test ); } @Override protected void onDraw(Canvas canvas) { float w = this.getWidth(); h = this.getHeight(); float c = w/28; canvas.drawRect(0, 0, w, h/2, this.mGreen); canvas.drawRect(0, h/2, w, h, this.mRed ); canvas.drawRect((3*w)/8, h/4 - c, (5*w)/8, h/4 + c, this.mWhite); canvas.drawRect(w/2 - c, h/4 - w/8, w/2 + c, h/4 + w/8, this.mWhite); canvas.drawRect((3*w)/8, (3*h)/4 - c, (5*w)/8, (3*h)/4 + c, this.mWhite); // Draw borders canvas.drawRect(0, 0, c, h, this.mBlack); canvas.drawRect(0, 0, w, c, this.mBlack); canvas.drawRect(0, h - c, w, h, this.mBlack); canvas.drawRect(w - c, 0, w, h, this.mBlack); if (this.mIsShaded) { canvas.drawRect(0, 0, w, h, this.mShade); } this.setOnTouchListener( new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { tempX = event.getX(); tempY = event.getY(); return false; } }); this.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if( (v.getHeight() / 2 ) > tempY ) { // Top click count++; } else { // Bottom click count } if( count > 4 ) mIsShaded = true; v.invalidate(); } }); } }
#include "Tools/Math/utils.h" #include "Tools/Code/Turbo/<API key>/Scaling_factor/<API key>.hpp" using namespace aff3ct; using namespace aff3ct::tools; template <typename B, typename R> <API key><B,R> ::<API key>(const int n_ite) : Scaling_factor<B,R>(n_ite) { } template <typename B, typename R> bool <API key><B,R> ::siso_n(const int ite, const mipp::vector<R>& sys, mipp::vector<R>& ext, mipp::vector<B>& s) { const auto loop_size = (int)ext.size(); if (ite == 1 || ite == 2) // sf = 0.50 for (auto i = 0; i < loop_size; i++) ext[i] = div2<R>(ext[i]); /* else if (ite == this->n_ite) // sf = 1.00 {}*/ else // sf = 0.875 instead of 0.85?! for (auto i = 0; i < loop_size; i++) ext[i] *= (R)0.85; //div4<R>(div2<R>(ext[i])) + div4<R>(div2<R>(ext[i])) + div4<R>(div2<R>(ext[i])) + div2<R>(ext[i]); return false; } template <typename B, typename R> <API key><B,R>* <API key><B,R> ::clone() const { auto t = new <API key>(*this); t->deep_copy(*this); return t; } template <typename B, typename R> bool <API key><B,R> ::siso_i(const int ite, const mipp::vector<R>& sys, mipp::vector<R>& ext) { const auto loop_size = (int)ext.size(); if (ite == 1 || ite == 2) // sf = 0.50 for (auto i = 0; i < loop_size; i++) ext[i] = div2<R>(ext[i]); /* else if (ite == this->n_ite) // sf = 1.00 {}*/ else // sf = 0.875 instead of 0.85?! for (auto i = 0; i < loop_size; i++) ext[i] *= (R)0.85; //div4<R>(div2<R>(ext[i])) + div4<R>(div2<R>(ext[i])) + div4<R>(div2<R>(ext[i])) + div2<R>(ext[i]); return false; } #include "Tools/types.h" #ifdef AFF3CT_MULTI_PREC template class aff3ct::tools::<API key><B_8,Q_8>; template class aff3ct::tools::<API key><B_16,Q_16>; template class aff3ct::tools::<API key><B_32,Q_32>; template class aff3ct::tools::<API key><B_64,Q_64>; #else template class aff3ct::tools::<API key><B,Q>; #endif
#include <Saba/Base/Log.h> #include <Saba/Viewer/Viewer.h> #include <Saba/Viewer/ViewerCommand.h> #include <nlohmann/json.hpp> #include <sol.hpp> #include <fstream> #include <vector> namespace { /* @brief Load initial setting from "init.json". */ void <API key>( saba::Viewer::InitializeParameter& viewerInitParam, std::vector<saba::ViewerCommand>& viewerCommands ) { bool msaaEnable = false; int msaaCount = 4; std::ifstream initJsonFile; initJsonFile.open("init.json"); if (initJsonFile.is_open()) { nlohmann::json initJ; initJsonFile >> initJ; initJsonFile.close(); if (initJ["MSAAEnable"].is_boolean()) { viewerInitParam.m_msaaEnable = initJ["MSAAEnable"].get<bool>(); } if (initJ["MSAACount"].is_number_integer()) { viewerInitParam.m_msaaCount = initJ["MSAACount"].get<int>(); } if (initJ["Commands"].is_array()) { viewerCommands.clear(); for (auto& commandJ : initJ["Commands"]) { if (commandJ.is_object()) { saba::ViewerCommand viewerCmd; if (commandJ["Cmd"].is_string()) { viewerCmd.SetCommand(commandJ["Cmd"].get<std::string>()); } if (commandJ["Args"].is_array()) { for (auto& argJ : commandJ["Args"]) { if (argJ.is_string()) { viewerCmd.AddArg(argJ.get<std::string>()); } } } } } } } } /* @brief Load initial setting from "init.lua". */ void <API key>( const std::vector<std::string>& args, saba::Viewer::InitializeParameter& viewerInitParam, std::vector<saba::ViewerCommand>& viewerCommands ) { try { sol::state lua; lua.open_libraries(sol::lib::base, sol::lib::package); auto result = lua.load_file("init.lua"); if (result) { sol::table argsTable = lua.create_table(args.size(), 0); for (const auto& arg : args) { argsTable.add(arg.c_str()); } lua["Args"] = argsTable; result(); auto msaa = lua["MSAA"]; if (msaa) { viewerInitParam.m_msaaEnable = msaa["Enable"].get_or(false); viewerInitParam.m_msaaCount = msaa["Count"].get_or(4); } auto initCamera = lua["InitCamera"]; if (initCamera) { bool useInitCamera = true; auto center = initCamera["Center"]; auto eye = initCamera["Eye"]; auto nearClip = initCamera["NearClip"]; auto farClip = initCamera["FarClip"]; auto radius = initCamera["Radius"]; if (center.valid() && eye.valid() && nearClip.valid() && farClip.valid() && radius.valid() ) { if (center["x"].valid() && center["y"].valid() && center["z"].valid()) { viewerInitParam.m_initCameraCenter.x = center["x"].get<float>(); viewerInitParam.m_initCameraCenter.y = center["y"].get<float>(); viewerInitParam.m_initCameraCenter.z = center["z"].get<float>(); } else { useInitCamera = false; } if (eye["x"].valid() && eye["y"].valid() && eye["z"].valid()) { viewerInitParam.m_initCameraEye.x = eye["x"].get<float>(); viewerInitParam.m_initCameraEye.y = eye["y"].get<float>(); viewerInitParam.m_initCameraEye.z = eye["z"].get<float>(); } else { useInitCamera = false; } viewerInitParam.<API key> = nearClip.get<float>(); viewerInitParam.m_initCameraFarClip = farClip.get<float>(); viewerInitParam.m_initCameraRadius = radius.get<float>(); viewerInitParam.m_initCamera = useInitCamera; } auto initScene = lua["InitScene"]; if (initScene) { auto unitScale = initScene["UnitScale"]; if (unitScale.valid()) { viewerInitParam.<API key> = unitScale.get<float>(); viewerInitParam.m_initScene = true; } } } sol::object commandsObj = lua["Commands"]; if (commandsObj.is<sol::table>()) { sol::table commands = commandsObj; viewerCommands.clear(); for (auto cmdIt = commands.begin(); cmdIt != commands.end(); ++cmdIt) { sol::table cmd = (*cmdIt).second; saba::ViewerCommand viewerCmd; std::string cmdText = cmd["Cmd"].get_or(std::string("")); viewerCmd.SetCommand(cmdText); sol::object argsObj = cmd["Args"]; if (argsObj.is<sol::table>()) { sol::table args = argsObj; for (auto argIt = args.begin(); argIt != args.end(); ++argIt) { std::string argText = (*argIt).second.as<std::string>(); viewerCmd.AddArg(argText); } } viewerCommands.emplace_back(viewerCmd); } } } } catch (sol::error e) { SABA_ERROR("Failed to load init.lua.\n{}", e.what()); } } } // namespace int SabaViewerMain(const std::vector<std::string>& args) { SABA_INFO("Start"); saba::Viewer viewer; saba::Viewer::InitializeParameter viewerInitParam; std::vector<saba::ViewerCommand> viewerCommands; <API key>(viewerInitParam, viewerCommands); <API key>(args, viewerInitParam, viewerCommands); if (viewerInitParam.m_msaaEnable) { SABA_INFO("Enable MSAA"); if (viewerInitParam.m_msaaCount != 2 && viewerInitParam.m_msaaCount != 4 && viewerInitParam.m_msaaCount != 8 ) { SABA_WARN("MSAA Count Force Change : 4"); viewerInitParam.m_msaaCount = 4; } SABA_INFO("MSAA Count : {}", viewerInitParam.m_msaaCount); } else { SABA_INFO("Disable MSAA"); } if (!viewer.Initialize(viewerInitParam)) { return -1; } for (const auto& viewerCommand : viewerCommands) { viewer.ExecuteCommand(viewerCommand); } int ret = viewer.Run(); viewer.Uninitislize(); SABA_INFO("Exit"); return ret; } #if _WIN32 #include <Windows.h> #include <shellapi.h> #endif int main(int argc, char** argv) { std::vector<std::string> args(argc); #if _WIN32 { WCHAR* cmdline = GetCommandLineW(); int wArgc; WCHAR** wArgs = CommandLineToArgvW(cmdline, &wArgc); for (int i = 0; i < argc; i++) { args[i] = saba::ToUtf8String(wArgs[i]); } } #else // _WIN32 for (int i = 0; i < argc; i++) { args[i] = argv[i]; } #endif auto ret = SabaViewerMain(args); saba::SingletonFinalizer::Finalize(); return ret; }
package com.controller; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.<API key>; import com.repofetcher.<API key>; import com.repofetcher.R; import com.repofetcher.RepoListFragment; import com.service.holder.RepoServiceType; import java.util.List; public class RepoListPageAdapter extends <API key> { private Bundle[] repos; private List<RepoListFragment> fragments; private Context context; public RepoListPageAdapter(FragmentManager fm, @NonNull Context context, @NonNull List<RepoListFragment> fragments, @NonNull Bundle[] repos) { super(fm); this.context = context; this.fragments = fragments; this.repos = repos; } @Override public CharSequence getPageTitle(int position) { int repo = repos[position].getInt(<API key>.SERVICE_ALIAS); switch (repo){ case RepoServiceType.GITHUB: return context.getResources().getString(R.string.github); case RepoServiceType.BITBUCKET: return context.getResources().getString(R.string.bitbucket); } return super.getPageTitle(position); } @Override public Fragment getItem(int position) { RepoListFragment repoListFragment = null; if(position < fragments.size()){ repoListFragment = fragments.get(position); } Bundle dataHolder = repos[position]; if(repoListFragment == null){ repoListFragment = new RepoListFragment(); fragments.add(position, repoListFragment); } repoListFragment.setArguments(dataHolder); return repoListFragment; } @Override public int getCount() { return repos.length; } }
class InitQa < ActiveRecord::Migration def change create_table :qavotes do |t| t.boolean :vote t.integer :user_id t.integer :question_id t.integer :answer_id t.timestamps end create_table :qaquestions do |t| t.text :title t.text :content t.integer :user_id t.timestamps end create_table :qaanswers do |t| t.text :content t.integer :question_id t.integer :user_id t.timestamps end end end
<?xml version="1.0" ?> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head><link href="http://search.cpan.org/s/style.css" rel="stylesheet" type="text/css"> <title>Planimeter(1)</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link rev="made" href="mailto:root@localhost" /> </head> <body style="background-color: white"> <h1 id="NAME">NAME</h1> <p>Planimeter -- compute the area of geodesic polygons</p> <h1 id="SYNOPSIS">SYNOPSIS</h1> <p><b>Planimeter</b> [ <b>-r</b> ] [ <b>-s</b> ] [ <b>-l</b> ] [ <b>-e</b> <i>a</i> <i>f</i> ] [ <b>-p</b> <i>prec</i> ] [ <b>-G</b> | <b>-E</b> | <b>-Q</b> | <b>-R</b> ] [ <b>--comment-delimiter</b> <i>commentdelim</i> ] [ <b>--version</b> | <b>-h</b> | <b>--help</b> ] [ <b>--input-file</b> <i>infile</i> | <b>--input-string</b> <i>instring</i> ] [ <b>--line-separator</b> <i>linesep</i> ] [ <b>--output-file</b> <i>outfile</i> ]</p> <h1 id="DESCRIPTION">DESCRIPTION</h1> <p>Measure the area of a geodesic polygon. Reads polygon vertices from standard input, one per line. Vertices may be given as latitude and longitude, UTM/UPS, or MGRS coordinates, interpreted in the same way as GeoConvert(1). (MGRS coordinates signify the center of the corresponding MGRS square.) The end of input, a blank line, or a line which can&#39;t be interpreted as a vertex signals the end of one polygon and the start of the next. For each polygon print a summary line with the number of points, the perimeter (in meters), and the area (in meters^2).</p> <p>The edges of the polygon are given by the <i>shortest</i> geodesic between consecutive vertices. In certain cases, there may be two or many such shortest geodesics, and in that case, the polygon is not uniquely specified by its vertices. This only happens with very long edges (for the WGS84 ellipsoid, any edge shorter than 19970 km is uniquely specified by its end points). In such cases, insert an additional vertex near the middle of the long edge to define the boundary of the polygon.</p> <p>By default, polygons traversed in a counter-clockwise direction return a positive area and those traversed in a clockwise direction return a negative area. This sign convention is reversed if the <b>-r</b> option is given.</p> <p>Of course, encircling an area in the clockwise direction is equivalent to encircling the rest of the ellipsoid in the counter-clockwise direction. The default interpretation used by <b>Planimeter</b> is the one that results in a smaller magnitude of area; i.e., the magnitude of the area is less than or equal to one half the total area of the ellipsoid. If the <b>-s</b> option is given, then the interpretation used is the one that results in a positive area; i.e., the area is positive and less than the total area of the ellipsoid.</p> <p>Only simple (i.e., <API key>) polygons are supported for the area computation. Polygons may include one or both poles. There is no need to close the polygon.</p> <h1 id="OPTIONS">OPTIONS</h1> <dl> <dt id="r"><b>-r</b></dt> <dd> <p>toggle whether counter-clockwise traversal of the polygon returns a positive (the default) or negative result.</p> </dd> <dt id="s"><b>-s</b></dt> <dd> <p>toggle whether to return a signed result (the default) or not.</p> </dd> <dt id="l"><b>-l</b></dt> <dd> <p>toggle whether the vertices represent a polygon (the default) or a polyline. For a polyline, the number of points and the length of the path joining them is returned; the path is not closed and the area is not reported.</p> </dd> <dt id="e"><b>-e</b></dt> <dd> <p>specify the ellipsoid via <i>a</i> <i>f</i>; the equatorial radius is <i>a</i> and the flattening is <i>f</i>. Setting <i>f</i> = 0 results in a sphere. Specify <i>f</i> &lt; 0 for a prolate ellipsoid. A simple fraction, e.g., 1/297, is allowed for <i>f</i>. (Also, if <i>f</i> &gt; 1, the flattening is set to 1/<i>f</i>.) By default, the WGS84 ellipsoid is used, <i>a</i> = 6378137 m, <i>f</i> = 1/298.257223563. If entering vertices as UTM/UPS or MGRS coordinates, use the default ellipsoid, since the conversion of these coordinates to latitude and longitude always uses the WGS84 parameters.</p> </dd> <dt id="p"><b>-p</b></dt> <dd> <p>set the output precision to <i>prec</i> (default 6); the perimeter is given (in meters) with <i>prec</i> digits after the decimal point; the area is given (in meters^2) with (<i>prec</i> - 5) digits after the decimal point.</p> </dd> <dt id="G"><b>-G</b></dt> <dd> <p>use the series formulation for the geodesics. This is the default option and is recommended for terrestrial applications. This option, <b>-G</b>, and the following three options, <b>-E</b>, <b>-Q</b>, and <b>-R</b>, are mutually exclusive.</p> </dd> <dt id="E"><b>-E</b></dt> <dd> <p>use &quot;exact&quot; algorithms (based on elliptic integrals) for the geodesic calculations. These are more accurate than the (default) series expansions for |<i>f</i>| &gt; 0.02. (But note that the implementation of areas in GeodesicExact uses a high order series and this is only accurate for modest flattenings.)</p> </dd> <dt id="Q"><b>-Q</b></dt> <dd> <p>perform the calculation on the authalic sphere. The area calculation is accurate even if the flattening is large, <i>provided</i> the edges are sufficiently short. The perimeter calculation is not accurate.</p> </dd> <dt id="R"><b>-R</b></dt> <dd> <p>The lines joining the vertices are rhumb lines instead of geodesics.</p> </dd> <dt id="comment-delimiter"><b>--comment-delimiter</b></dt> <dd> <p>set the comment delimiter to <i>commentdelim</i> (e.g., &quot;#&quot; or &quot;//&quot;). If set, the input lines will be scanned for this delimiter and, if found, the delimiter and the rest of the line will be removed prior to processing. For a given polygon, the last such string found will be appended to the output line (separated by a space).</p> </dd> <dt id="version"><b>--version</b></dt> <dd> <p>print version and exit.</p> </dd> <dt id="h"><b>-h</b></dt> <dd> <p>print usage and exit.</p> </dd> <dt id="help"><b>--help</b></dt> <dd> <p>print full documentation and exit.</p> </dd> <dt id="input-file"><b>--input-file</b></dt> <dd> <p>read input from the file <i>infile</i> instead of from standard input; a file name of &quot;-&quot; stands for standard input.</p> </dd> <dt id="input-string"><b>--input-string</b></dt> <dd> <p>read input from the string <i>instring</i> instead of from standard input. All occurrences of the line separator character (default is a semicolon) in <i>instring</i> are converted to newlines before the reading begins.</p> </dd> <dt id="line-separator"><b>--line-separator</b></dt> <dd> <p>set the line separator character to <i>linesep</i>. By default this is a semicolon.</p> </dd> <dt id="output-file"><b>--output-file</b></dt> <dd> <p>write output to the file <i>outfile</i> instead of to standard output; a file name of &quot;-&quot; stands for standard output.</p> </dd> </dl> <h1 id="EXAMPLES">EXAMPLES</h1> <p>Example (the area of the 100km MGRS square 18SWK)</p> <pre><code> Planimeter &lt;&lt;EOF 18n 500000 4400000 18n 600000 4400000 18n 600000 4500000 18n 500000 4500000 EOF =&gt; 4 400139.53295860 10007388597.1913</code></pre> <p>The following code takes the output from gdalinfo and reports the area covered by the data (assuming the edges of the image are geodesics).</p> <pre><code> #! /bin/sh egrep &#39;^((Upper|Lower) (Left|Right)|Center) &#39; | sed -e &#39;s/d /d/g&#39; -e &quot;s/&#39; /&#39;/g&quot; | tr -s &#39;(),\r\t&#39; &#39; &#39; | awk &#39;{ if ($1 $2 == &quot;UpperLeft&quot;) ul = $6 &quot; &quot; $5; else if ($1 $2 == &quot;LowerLeft&quot;) ll = $6 &quot; &quot; $5; else if ($1 $2 == &quot;UpperRight&quot;) ur = $6 &quot; &quot; $5; else if ($1 $2 == &quot;LowerRight&quot;) lr = $6 &quot; &quot; $5; else if ($1 == &quot;Center&quot;) { printf &quot;%s\n%s\n%s\n%s\n\n&quot;, ul, ll, lr, ur; ul = ll = ur = lr = &quot;&quot;; } } &#39; | Planimeter | cut -f3 -d&#39; &#39;</code></pre> <h1 id="SEE-ALSO">SEE ALSO</h1> <p>GeoConvert(1), GeodSolve(1).</p> <p>An online version of this utility is availbable at <a href="http: <p>The algorithm for the area of geodesic polygon is given in Section 6 of C. F. F. Karney, <i>Algorithms for geodesics</i>, J. Geodesy 87, 43-55 (2013); DOI <a href="https: <h1 id="AUTHOR">AUTHOR</h1> <p><b>Planimeter</b> was written by Charles Karney.</p> <h1 id="HISTORY">HISTORY</h1> <p><b>Planimeter</b> was added to GeographicLib, <a href="http: </body> </html>
package org.seqcode.viz.preferences; public interface PreferencesListener { public void preferencesUpdated(PreferencesEvent evt); public void <API key>(PreferencesEvent evt); }
<html> <head> <meta charset="utf-8"> <link href="main.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script> </head> <body> <span class="midiSelectContainer"> <select id="midiSelect"> <option value="">No MIDI Inputs</option> </select> </span> <div id="container"> <video muted="true" id="<API key>" src="../../vid-output/ff/48__0__dS9cvu13jKs.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/48__0__fTy-6Wt27ks.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/48__0__hqr46XZhtRg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/50__0__fTy-6Wt27ks.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/51__0__sExe1soAFLI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/52__0__fTy-6Wt27ks.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/52__0__hqr46XZhtRg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/52__0__kCka94jeGTk.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/53__0__a5nUpraxJr8.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/53__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/53__0__r9hTlhsNY5g.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/53__0__sExe1soAFLI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/53__0__UZJdd2ZEyd0.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/54__0__hqr46XZhtRg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/54__0__LPSZoyU1EQE.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__3NxAsRNtvoc.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__BK9OOhnso4M.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__C_p1eOVO-Q4.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__eubh7DdA4Ak.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__f4QgLfTR1Bg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__LPSZoyU1EQE.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__o872WzNiF3U.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__oiv_TXQTYOg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__pl0gIkpOFUo.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/55__0__VJtDpJT2gz8.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/56__0__AAp88YhKHGw.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/56__0__dHriGHv43ms.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/56__0__eubh7DdA4Ak.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/56__0__LPSZoyU1EQE.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/57__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/57__0__hqr46XZhtRg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/57__0__kCka94jeGTk.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/58__0__bSDPkUUaiwY.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/58__0__hrGiRaNN9Es.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/59__0__Q1Si1DOAcHA.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/60__0__C_p1eOVO-Q4.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/60__0__eubh7DdA4Ak.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/60__0__f4QgLfTR1Bg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/60__0__o872WzNiF3U.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/60__0__pl0gIkpOFUo.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/60__0__sExe1soAFLI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/60__0__VJtDpJT2gz8.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/61__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/61__0__tpXrGzfE5dM.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/62__0__C_p1eOVO-Q4.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/62__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/62__0__e2p8UPJOBdI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/62__0__f4QgLfTR1Bg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/62__0__hrGiRaNN9Es.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/62__0__n6MHoxZc8zQ.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/62__0__o872WzNiF3U.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/62__0__tL7CSJXNwCg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/62__0__ve3_CyTcdyg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/63__0__3C0FeuUcEsg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/63__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/63__0__DsY-ywdOfDw.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/63__0__LPSZoyU1EQE.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/63__0__Pk3Sj9bnFrY.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/63__0__RsspYwyHjA4.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/63__0__VjPsATEpSFA.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/64__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/64__0__DsY-ywdOfDw.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/64__0__dxCrIb6kuXU.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/64__0__LPSZoyU1EQE.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/64__0__Q1Si1DOAcHA.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/64__0__VjPsATEpSFA.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/65__0__1R-SmhEcZAc.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/65__0__7h1EpGyE35g.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/65__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/65__0__ntGiqQWuZzU.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/65__0__sExe1soAFLI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/66__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/66__0__h2xe4DBm-UU.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/66__0__zt-v8Os0o4A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/67__0__3NxAsRNtvoc.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/67__0__AAp88YhKHGw.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/67__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/67__0__R6PQeJOqfGk.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/68__0__hqr46XZhtRg.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/68__0__i6nr7GU6v1o.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/69__0__6YdWlwE-onU.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/69__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/69__0__Q1Si1DOAcHA.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/69__0__R6PQeJOqfGk.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/70__0__uH4nwb3vogU.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__0m-SOFYUdik.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__7j8QPDPhoNo.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__8QhSd4wKbdw.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__a5nUpraxJr8.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__AmXO_PTyHWk.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__Cup98pb2wr4.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__eYHYFo2mmzk.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__iR5GgoPRlUU.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__lAMgvKfehpQ.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__n6IghwuHUaI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__QL_UepVU_Zc.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__r9hTlhsNY5g.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__sExe1soAFLI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/71__0__vj8poDE_g5g.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/72__0__6YdWlwE-onU.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/72__0__32zGeLKUQDA.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/72__0__c5mKajntRuE.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/72__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/72__0__sExe1soAFLI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/72__0__tvxBjtnCxHc.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/72__0__vj8poDE_g5g.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/72__0__WyvbQ26nRns.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/72__0__znY_8YI8jns.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/73__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/73__0__pe0RxB3X6To.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/74__0__AAp88YhKHGw.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/74__0__ccS_qGoxV6A.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/74__0__pbLCqIjT3NQ.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/74__0__sExe1soAFLI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/75__0__pbLCqIjT3NQ.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/75__0__sExe1soAFLI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/76__0__sExe1soAFLI.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/77__0__pbLCqIjT3NQ.mkv" style="display: none;" preload></video> <video muted="true" id="<API key>" src="../../vid-output/ff/78__0__sExe1soAFLI.mkv" style="display: none;" preload></video> </div> <samp id="noteLog"></samp> <script src="video.js"></script> </body> </html>
// NOTE This file documents the data structure of v1. const c = require('./common'); module.exports = { collections: { config: [], // Denotes that collection doesn't exist and must be removed. users: [{ name: 'admin', email: 'admin@example.com', hash: c.PASSWORD, admin: true, }], locations: [{ name: 'Irbene', lat: 57.55341, lng: 21.857705, locator_id: 604, // eslint-disable-line camelcase }], }, };
package beans.relation.summary; public class SemanticQual { private String lang; private String qualifier; private int id; /** * see static definitions of categories 1-11. */ private int category; private int deleteFlag = 0; /** * opposite of another semantic qualifier (e.g. left vs. right) */ private int contrasts = -1; public static final int CATEGORY_PATIENT = 1; //patient characteristic (male, tall,...) public static final int CATEGORY_SETTING = 2; //exercise-induced,... public static final int CATEGORY_ONSET = 3; //e.g. acute, recurrence,... public static final int CATEGORY_DURATION = 4; //e.g. always, slowly,... public static final int CATEGORY_COURSE = 5; //e.g. initial, reversible,... public static final int CATEGORY_LOCATION = 6; //e.g. anterior, external,... public static final int CATEGORY_QUALITY = 7; //e.g. benign, dry,... public static final int CATEGORY_QUANTITY = 8; //unique, mono public static final int CATEGORY_SEVERITY = 9; //urgent, mild public static final int CATEGORY_AGGR_REL = 10; //aggravating/relieving, e.g. lying down, horizontal public static final int CATEGORY_ASSOCIATED = 11; //local, complementary public String getLang() {return lang;} public void setLang(String lang) {this.lang = lang;} public String getQualifier() {return qualifier;} public void setQualifier(String qualifier) {this.qualifier = qualifier;} public int getId() {return id;} public void setId(int id) {this.id = id;} public int getCategory() {return category;} public void setCategory(int category) {this.category = category;} public int getDeleteFlag() {return deleteFlag;} public void setDeleteFlag(int deleteFlag) {this.deleteFlag = deleteFlag;} public int getContrasts() {return contrasts;} public void setContrasts(int contrasts) {this.contrasts = contrasts;} /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o){ if(o !=null && o instanceof SemanticQual){ SemanticQual ssq = (SemanticQual) o; if(ssq.getId() == this.id) return true; } return false; } public boolean isContrast(SemanticQual sq){ if(sq.getId()==this.contrasts) return true; if(this.id==sq.getContrasts()) return true; return false; } }
require 'sqlite3' require 'sequel_core/adapters/shared/sqlite' module Sequel module SQLite class Database < Sequel::Database include ::Sequel::SQLite::DatabaseMethods set_adapter_scheme :sqlite def self.uri_to_options(uri) # :nodoc: { :database => (uri.host.nil? && uri.path == '/') ? nil : "#{uri.host}#{uri.path}" } end <API key> :uri_to_options def connect @opts[:database] = ':memory:' if @opts[:database].blank? db = ::SQLite3::Database.new(@opts[:database]) db.busy_timeout(@opts.fetch(:timeout, 5000)) db.type_translation = true # fix for timestamp translation db.translator.add_translator("timestamp") do |t, v| v =~ /^\d+$/ ? Time.at(v.to_i) : Time.parse(v) end db end def dataset(opts = nil) SQLite::Dataset.new(self, opts) end def disconnect @pool.disconnect {|c| c.close} end def execute(sql) begin log_info(sql) @pool.hold {|conn| conn.execute_batch(sql); conn.changes} rescue SQLite3::Exception => e raise Error::InvalidStatement, "#{sql}\r\n#{e.message}" end end def execute_insert(sql) begin log_info(sql) @pool.hold {|conn| conn.execute(sql); conn.last_insert_row_id} rescue SQLite3::Exception => e raise Error::InvalidStatement, "#{sql}\r\n#{e.message}" end end def single_value(sql) begin log_info(sql) @pool.hold {|conn| conn.get_first_value(sql)} rescue SQLite3::Exception => e raise Error::InvalidStatement, "#{sql}\r\n#{e.message}" end end def execute_select(sql, &block) begin log_info(sql) @pool.hold {|conn| conn.query(sql, &block)} rescue SQLite3::Exception => e raise Error::InvalidStatement, "#{sql}\r\n#{e.message}" end end def transaction(&block) @pool.hold do |conn| if conn.transaction_active? return yield(conn) end begin result = nil conn.transaction {result = yield(conn)} result rescue ::Exception => e raise (SQLite3::Exception === e ? Error.new(e.message) : e) unless Error::Rollback === e end end end private def <API key> o = super.merge(:<API key>=>false) # Default to only a single connection if a memory database is used, # because otherwise each connection will get a separate database o[:max_connections] = 1 if @opts[:database] == ':memory:' || @opts[:database].blank? o end end class Dataset < Sequel::Dataset include ::Sequel::SQLite::DatasetMethods EXPLAIN = 'EXPLAIN %s'.freeze def explain res = [] @db.result_set(EXPLAIN % select_sql(opts), nil) {|r| res << r} res end def fetch_rows(sql) @db.execute_select(sql) do |result| @columns = result.columns.map {|c| c.to_sym} column_count = @columns.size result.each do |values| row = {} column_count.times {|i| row[@columns[i]] = values[i]} yield row end end end def literal(v) case v when LiteralString v when String "'#{::SQLite3::Database.quote(v)}'" when Time literal(v.iso8601) when Date, DateTime literal(v.to_s) else super end end end end end
var csc = require('../index'); csc({
// 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, // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // included in all copies or substantial portions of the Software. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // 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. #include "CompressionOptions.h" #include "nvimage/DirectDrawSurface.h" #include "nvmath/Vector.inl" using namespace nv; using namespace nvtt; Constructor. Sets compression options to the default values. CompressionOptions::CompressionOptions() : m(*new CompressionOptions::Private()) { reset(); } Destructor. CompressionOptions::~CompressionOptions() { delete &m; } Set default compression options. void CompressionOptions::reset() { m.format = Format_DXT1; m.quality = Quality_Normal; m.colorWeight.set(1.0f, 1.0f, 1.0f, 1.0f); m.bitcount = 32; m.bmask = 0x000000FF; m.gmask = 0x0000FF00; m.rmask = 0x00FF0000; m.amask = 0xFF000000; m.rsize = 8; m.gsize = 8; m.bsize = 8; m.asize = 8; m.pixelType = <API key>; m.pitchAlignment = 1; m.<API key> = false; m.<API key> = false; m.binaryAlpha = false; m.alphaThreshold = 127; m.decoder = Decoder_D3D10; } Set desired compression format. void CompressionOptions::setFormat(Format format) { m.format = format; } Set compression quality settings. void CompressionOptions::setQuality(Quality quality) { m.quality = quality; } Set the weights of each color channel. The choice for these values is subjective. In most cases uniform color weights (1.0, 1.0, 1.0) work very well. A popular choice is to use the NTSC luma encoding weights (0.2126, 0.7152, 0.0722), but I think that blue contributes to our perception more than a 7%. A better choice in my opinion is (3, 4, 2). void CompressionOptions::setColorWeights(float red, float green, float blue, float alpha/*=1.0f*/) { // float total = red + green + blue; // float x = red / total; // float y = green / total; // m.colorWeight.set(x, y, 1.0f - x - y); m.colorWeight.set(red, green, blue, alpha); } Set color mask to describe the RGB/RGBA format. void CompressionOptions::setPixelFormat(uint bitCount, uint rmask, uint gmask, uint bmask, uint amask) { // Validate arguments. nvCheck(bitCount <= 32); nvCheck((rmask & gmask) == 0); nvCheck((rmask & bmask) == 0); nvCheck((rmask & amask) == 0); nvCheck((gmask & bmask) == 0); nvCheck((gmask & amask) == 0); nvCheck((bmask & amask) == 0); if (bitCount != 32) { uint maxMask = (1 << bitCount); nvCheck(maxMask > rmask); nvCheck(maxMask > gmask); nvCheck(maxMask > bmask); nvCheck(maxMask > amask); } m.bitcount = bitCount; m.rmask = rmask; m.gmask = gmask; m.bmask = bmask; m.amask = amask; m.rsize = 0; m.gsize = 0; m.bsize = 0; m.asize = 0; } void CompressionOptions::setPixelFormat(uint8 rsize, uint8 gsize, uint8 bsize, uint8 asize) { nvCheck(rsize <= 32 || gsize <= 32 || bsize <= 32 || asize <= 32); m.bitcount = 0; m.rmask = 0; m.gmask = 0; m.bmask = 0; m.amask = 0; m.rsize = rsize; m.gsize = gsize; m.bsize = bsize; m.asize = asize; } Set pixel type. void CompressionOptions::setPixelType(PixelType pixelType) { m.pixelType = pixelType; } Set pitch alignment in bytes. void CompressionOptions::setPitchAlignment(int pitchAlignment) { nvDebugCheck(pitchAlignment > 0 && isPowerOfTwo(pitchAlignment)); m.pitchAlignment = pitchAlignment; } Use external compressor. void CompressionOptions::<API key>(const char * name) { m.externalCompressor = name; } Set quantization options. @warning Do not enable dithering unless you know what you are doing. Quantization introduces errors. It's better to let the compressor quantize the result to minimize the error, instead of quantizing the data before handling it to the compressor. void CompressionOptions::setQuantization(bool colorDithering, bool alphaDithering, bool binaryAlpha, int alphaThreshold/*= 127*/) { nvCheck(alphaThreshold >= 0 && alphaThreshold < 256); m.<API key> = colorDithering; m.<API key> = alphaDithering; m.binaryAlpha = binaryAlpha; m.alphaThreshold = alphaThreshold; } Set target decoder to optimize for. void CompressionOptions::setTargetDecoder(Decoder decoder) { m.decoder = decoder; } // Translate to and from D3D formats. unsigned int CompressionOptions::d3d9Format() const { if (m.format == Format_RGB) { if (m.pixelType == <API key>) { uint bitcount = m.bitcount; uint rmask = m.rmask; uint gmask = m.gmask; uint bmask = m.bmask; uint amask = m.amask; if (bitcount == 0) { bitcount = m.rsize + m.gsize + m.bsize + m.asize; rmask = ((1 << m.rsize) - 1) << (m.asize + m.bsize + m.gsize); gmask = ((1 << m.gsize) - 1) << (m.asize + m.bsize); bmask = ((1 << m.bsize) - 1) << m.asize; amask = ((1 << m.asize) - 1) << 0; } if (bitcount <= 32) { return nv::findD3D9Format(bitcount, rmask, gmask, bmask, amask); } else { //if (m.rsize == 16 && m.gsize == 16 && m.bsize == 0 && m.asize == 0) return D3DFMT_G16R16; if (m.rsize == 16 && m.gsize == 16 && m.bsize == 16 && m.asize == 16) return D3DFMT_A16B16G16R16; } } else if (m.pixelType == PixelType_Float) { if (m.rsize == 16 && m.gsize == 0 && m.bsize == 0 && m.asize == 0) return D3DFMT_R16F; if (m.rsize == 32 && m.gsize == 0 && m.bsize == 0 && m.asize == 0) return D3DFMT_R32F; if (m.rsize == 16 && m.gsize == 16 && m.bsize == 0 && m.asize == 0) return D3DFMT_G16R16F; if (m.rsize == 32 && m.gsize == 32 && m.bsize == 0 && m.asize == 0) return D3DFMT_G32R32F; if (m.rsize == 16 && m.gsize == 16 && m.bsize == 16 && m.asize == 16) return <API key>; if (m.rsize == 32 && m.gsize == 32 && m.bsize == 32 && m.asize == 32) return <API key>; } return 0; } else { uint d3d9_formats[] = { 0, // Format_RGB, FOURCC_DXT1, // Format_DXT1 FOURCC_DXT1, // Format_DXT1a FOURCC_DXT3, // Format_DXT3 FOURCC_DXT5, // Format_DXT5 FOURCC_DXT5, // Format_DXT5n FOURCC_ATI1, // Format_BC4 FOURCC_ATI2, // Format_BC5 FOURCC_DXT1, // Format_DXT1n 0, // Format_CTX1 0, // Format_BC6 0, // Format_BC7 0, // Format_RGBE }; return d3d9_formats[m.format]; } } /* bool CompressionOptions::setDirect3D9Format(unsigned int format) { } unsigned int CompressionOptions::dxgiFormat() const { } bool CompressionOptions::setDXGIFormat(unsigned int format) { } */
namespace Tresor.Utilities { using System.Collections.ObjectModel; using Tresor.Contracts.Utilities; <summary>Beschreibt einen Tab der innerhalb der Anwendung angezeigt werden kann.</summary> public class Tab : <API key> { #region Fields <summary>Mitglied der Eigenschaft <see cref="Content"/>.</summary> private object content; <summary>Mitglied der Eigenschaft <see cref="IsCloseable"/>.</summary> private bool isCloseable = true; <summary>Mitglied der Eigenschaft <see cref="IsSelected"/>.</summary> private bool isSelected; #endregion #region Constructors and Destructors <summary>Initialisiert eine neue Instanz der <see cref="Tab"/> Klasse. </summary> <param name="content">Der Inhalt des Tabs.</param> public Tab(IPassword content) { Content = content; } <summary>Initialisiert eine neue Instanz der <see cref="Tab"/> Klasse.</summary> <param name="content">Der Inhalt des Tabs.</param> public Tab(<API key><IPassword> content) { Content = content; } #endregion #region Public Properties <summary>Holt oder setzt den Inhalt des Tabs.</summary> public object Content { get { return content; } set { content = value; if (content is IPassword) { ((IPassword)content).PropertyChanged += (sender, arguments) => OnPropertyChanged(); } OnPropertyChanged(); } } <summary>Holt oder setzt einen Wert, der angibt, ob ein Tab schließbar ist.</summary> public bool IsCloseable { get { return isCloseable; } set { isCloseable = value; OnPropertyChanged(); } } <summary>Holt oder setzt einen Wert, der angibt, ob der Tab selektiert ist.</summary> public bool IsSelected { get { return isSelected; } set { isSelected = value; OnPropertyChanged(); } } #endregion } }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="pragma" content="no-cache"/> <meta name="<API key>" content="yes" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" /> <meta name="<API key>" content="black-translucent" /> <meta charset="utf-8"/> <!-- Set the title bar of the page --> <title>GameMaker: Studio ThreeJS Extension by Derme</title> <!-- Set the background colour of the document --> <link rel='stylesheet' href='html5game/theme.css' type='text/css' media='all' /> <!-- Call JS References --> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script type='text/javascript' src="html5game/three.min.js"></script> </head> <body> <div class="gm4html5_div_class" id="gm4html5_div_id"> <div id="container"></div> <!-- Create the canvas element the game draws to --> <canvas id="canvas" width="640" height="480"> <p>Your browser doesn't support HTML5 canvas.</p> </canvas> </div> <!-- Run the game code --> <script type="text/javascript" src="html5game/J3D - Extension.js"></script> </body> </html>
## REPLACED BY [PathNameUtils](..%2FPathNameUtils.md) This will be removed as soon. js // Removes the last component of the path, which is often the file name. // Leaves the trailing "/" if any. // UPDATED: 2016/07/08 15:16 PDT <API key>: function(path) { var i = path.lastIndexOf("/"); return i < 0 ? "" : path.substring(0, i + 1); }
class <API key> < ActiveRecord::Migration def change add_column :contacts, :is_active, :boolean, default: true end end
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Windows.AI.MachineLearning.Preview; using Windows.Graphics.DirectX.Direct3D11; using Windows.Graphics.Imaging; using Windows.Media; using Windows.Storage; namespace BuildIt.ML { <inheritdoc /> public class <API key> : <API key> { private const string Data = "data"; private const string ClassLabel = "classLabel"; private const string Loss = "loss"; private string[] labels; private <API key> learningModel; private EvaluationOutput evaluationOutput; <inheritdoc /> public async Task InitAsync(string modelName, string[] labels) { this.labels = labels; var file = await StorageFile.<API key>(new Uri($"ms-appx:///Assets/{modelName}.onnx")); learningModel = await <API key>.<API key>(file); evaluationOutput = new EvaluationOutput(labels); } <inheritdoc /> public async Task<IReadOnlyList<ImageClassification>> ClassifyAsync(Stream imageStream) { var decoder = await BitmapDecoder.CreateAsync(imageStream.<API key>()); using (var softwareBitmap = await decoder.<API key>()) { using (var videoFrame = VideoFrame.<API key>(softwareBitmap)) { var customVisionOutput = new EvaluationOutput(labels); var binding = new <API key>(learningModel); binding.Bind(Data, videoFrame); binding.Bind(ClassLabel, customVisionOutput.ClassLabel); binding.Bind(Loss, customVisionOutput.Loss); var result = await learningModel.EvaluateAsync(binding, string.Empty); return customVisionOutput.Loss.Select(l => new ImageClassification(l.Key, l.Value)).ToList().AsReadOnly(); } } } <inheritdoc /> public async Task<IReadOnlyList<ImageClassification>> <API key>(object obj) { try { using (var surface = obj as IDirect3DSurface) { if (surface != null) { using (var videoFrame = VideoFrame.<API key>(surface)) { var binding = new <API key>(learningModel); binding.Bind(Data, videoFrame); binding.Bind(ClassLabel, evaluationOutput.ClassLabel); binding.Bind(Loss, evaluationOutput.Loss); var result = await learningModel.EvaluateAsync(binding, string.Empty); return evaluationOutput.Loss.Select(l => new ImageClassification(l.Key, l.Value)).ToList().AsReadOnly(); } } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } return new List<ImageClassification>().AsReadOnly(); } } }
# PowerShell Governance ## Terms * [**PowerShell Committee**](#<API key>): A committee of project owners who are responsible for design decisions, approving [RFCs][RFC-repo], and approving new maintainers/committee members * [**Repository maintainer**](#<API key>): An individual responsible for merging pull requests (PRs) into `master` when all requirements are met (code review, tests, docs, and RFC approval as applicable). Repository Maintainers are the only people with write permissions for the `master` branch. * [**Area experts**](#area-experts): People who are experts for specific components (e.g. PSReadline, the parser) or technologies (e.g. security, performance). Area experts are responsible for code reviews, issue triage, and providing their expertise to others. * **Corporation**: The Corporation owns the PowerShell repository and, under extreme circumstances, reserves the right to dissolve or reform the PowerShell Committee, the Project Leads, and the Corporate Maintainer. The Corporation for PowerShell is Microsoft. * **Corporate Maintainer**: The Corporate Maintainer is an entity, person or set of persons, with the ability to veto decisions made by the PowerShell Committee or any other collaborators on the PowerShell project. This veto power will be used with restraint since it is intended that the community drive the project. The Corporate Maintainer is determined by the Corporation both initially and in continuation. The initial Corporate Maintainer for PowerShell is Jeffrey Snover ([jpsnover](https://github.com/jpsnover)). * [**RFC process**][RFC-repo]: The "review-for-comment" (RFC) process whereby design decisions get made. ## PowerShell Committee The PowerShell Committee and its members (aka Committee Members) are the primary caretakers of the PowerShell experience, including the PowerShell language, design, and project. Current Committee Members * Bruce Payette ([BrucePay](https://github.com/BrucePay)) * Dongbo Wang ([daxian-dbw](https://github.com/daxian-dbw)) * Hemant Mahawar ([HemantMahawar](https://github.com/HemantMahawar)) * Jim Truher ([JamesWTruher](https://github.com/JamesWTruher)) * Joey Aiello ([joeyaiello](https://github.com/joeyaiello)) * Kenneth Hansen ([khansen00](https://github.com/khansen00)) * Steve Lee ([SteveL-MSFT](https://github.com/SteveL-MSFT)) Committee Member Responsibilities Committee Members are responsible for reviewing and approving [PowerShell RFCs][RFC-repo] proposing new features or design changes. # Changes that require an [RFC][RFC-repo] The following types of decisions require a written RFC and ample time for the community to respond with their feedback before a contributor begins work on the issue: * new features or capabilities in PowerShell (e.g. PowerShell classes, PSRP over SSH, etc.) * anything that might require a breaking change, as defined in our [Breaking Changes Contract][breaking-changes] * new modules, cmdlets, or parameters that ship in the core PowerShell modules (e.g. `Microsoft.PowerShell.*`, `PackageManagement`, `PSReadLine`) * the addition of new PowerShell Committee Members or Repository Maintainers * any changes to the process of maintaining the PowerShell repository (including the responsibilities of Committee Members, Repository Maintainers, and Area Experts) # Changes that don't require an RFC In some cases, a new feature or behavior may be deemed small enough to forgo the RFC process (e.g. changing the default PSReadline `EditMode` to `Emacs` on Mac/Linux). In these cases, [issues marked as `1 - Planning`][issue-process] require only a simple majority of Committee Members to sign off. After that, a Repository Maintainer should relabel the issue as `2 - Ready` so that a contributor can begin working on it. If any Committee Members feels like this behavior is large enough to warrant an RFC, they can add the label `RFC-required` and the issue owner is expected to follow the RFC process. # Committee Member DOs and DON'Ts As a PowerShell Committee Member: 1. **DO** reply to issues and pull requests with design opinions (this could include offering support for good work or exciting new features) 1. **DO** encourage healthy discussion about the direction of PowerShell 1. **DO** raise "red flags" on PRs that haven't followed the proper RFC process when applicable 1. **DO** contribute to documentation and best practices 1. **DO** maintain a presence in the PowerShell community outside of GitHub (Twitter, blogs, StackOverflow, Reddit, Hacker News, etc.) 1. **DO** heavily incorporate community feedback into the weight of your decisions 1. **DO** be polite and respectful to a wide variety of opinions and perspectives 1. **DO** make sure contributors are following the [contributor guidelines](../../.github/CONTRIBUTING.md) 1. **DON'T** constantly raise "red flags" for unimportant or minor problems to the point that the progress of the project is being slowed 1. **DON'T** offer up your opinions as the absolute opinion of the PowerShell Committee. Members are encouraged to share their opinions, but they should be presented as such. PowerShell Committee Membership The initial PowerShell Committee consists of Microsoft employees. It is expected that over time, PowerShell experts in the community will be made Committee Members. Membership is heavily dependent on the level of contribution and expertise: individuals who contribute in meaningful ways to the project will be recognized accordingly. At any point in time, a Committee Member can nominate a strong community member to join the Committee. Nominations should be submitted in the form of [RFCs][RFC-repo] detailing why that individual is qualified and how they will contribute. After the RFC has been discussed, a unanimous vote will be required for the new Committee Member to be confirmed. ## Repository Maintainers Repository Maintainers are trusted stewards of the PowerShell community/repository responsible for maintaining consistency and quality of PowerShell code. One of their primary responsibilities is merging pull requests after all requirements have been fulfilled. For more information on Repository Maintainers--their responsibilities, who they are, and how one becomes a Maintainer--see the [README for Repository Maintainers][maintainers]. ## Area Experts Area Experts are people with knowledge of specific components or technologies in the PowerShell domain. They are responsible for code reviews, issue triage, and providing their expertise to others. They have [write access](https://help.github.com/articles/<API key>/) to the PowerShell repository which gives them the power to: 1. `git push` to all branches *except* `master`. 1. Merge pull requests to all branches *except* `master` (though this should not be common given that [`master`is the only long-living branch](../git/README.md#understand-branches)). 1. Assign labels, milestones, and people to [issues](https://guides.github.com/features/issues/). A list of Area Experts can be found [here][experts]. Area Expert Responsibilities If you are an Area Expert, you are expected to be actively involved in any development, design, or contributions in your area of expertise. If you are an Area Expert: 1. **DO** assign the [correct labels][issue-process] 1. **DO** assign yourself to issues labeled with your area of expertise 1. **DO** code reviews for issues where you're assigned or in your areas of expertise. 1. **DO** reply to new issues and pull requests that are related to your area of expertise (while reviewing PRs, leave your comment even if everything looks good - a simple "Looks good to me" or "LGTM" will suffice, so that we know someone has already taken a look at it). 1. **DO** make sure contributors are following the [contributor guidelines](../../.github/CONTRIBUTING.md). 1. **DO** ask people to resend a pull request, if it [doesn't target `master`](../../.github/CONTRIBUTING.md#<API key>). 1. **DO** ensure that contributors [write Pester tests][pester] for all new/changed functionality 1. **DO** ensure that contributors [write documentation][docs-contributing] for all new-/changed functionality 1. **DO** encourage contributors to refer to issues in their pull request description (e.g. `Resolves issue #123`). 1. **DO** encourage contributors to create meaningful titles for all PRs. Edit title if necessary. 1. **DO** verify that all contributors are following the [Coding Guidelines](../dev-process/coding-guidelines.md). 1. **DON'T** create new features, new designs, or change behaviors without following the [RFC][RFC-repo] or approval process ## Issue Management Process See our [Issue Management Process][issue-process] ## Pull Request Process See our [Pull Request Process][<API key>] [RFC-repo]: https://github.com/PowerShell/PowerShell-RFC [pester]: ../testing-guidelines/WritingPesterTests.md [ci-system]: ../testing-guidelines/testing-guidelines.md#ci-system [breaking-changes]: ../dev-process/<API key>.md [issue-process]: ../maintainers/issue-management.md [<API key>]: ../../.github/CONTRIBUTING.md#<API key> [docs-contributing]: https://github.com/PowerShell/PowerShell-Docs/blob/staging/CONTRIBUTING.md [maintainers]: ../maintainers/README.md [experts]: ../../.github/CODEOWNERS
<?php namespace AppBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; class AppExtension implements ExtensionInterface { public function getAlias() { return 'app'; } public function getNamespace() { // TODO: Implement getNamespace() method. } public function <API key>() { // TODO: Implement <API key>() method. } public function load(array $config, ContainerBuilder $container) { //fos_user.model_manager_name } }
Busted === [![travis-ci status](https: busted is a unit testing framework with a focus on being **easy to use**. Check out the [official docs](http: extended info. busted test specs read naturally without being too verbose. You can even chain asserts and negations, such as `assert.not.equals`. Nest blocks of tests with contextual descriptions using `describe`, and add tags to blocks so you can run arbitrary groups of tests. An extensible assert library allows you to extend and craft your own assert functions specific to your case with method chaining. A modular output library lets you add on your own output format, along with the default pretty and plain terminal output, JSON with and without streaming, and TAP-compatible output that allows you to run busted specs within most CI servers. lua describe("Busted unit testing framework", function() describe("should be awesome", function() it("should be easy to use", function() assert.truthy("Yup.") end) it("should have lots of features", function() -- deep check comparisons! assert.same({ table = "great"}, { table = "great" }) -- or check by reference! assert.is_not.equals({ table = "great"}, { table = "great"}) assert.true(1 == 1) assert.falsy(nil) assert.error(function() error("Wat") end) end) it("should provide some shortcuts to common functions", function() assert.unique({{ thing = 1 }, { thing = 2 }, { thing = 3 }}) end) it("should have mocks and spies for functional tests", function() local thing = require("thing_module") spy.spy_on(thing, "greet") thing.greet("Hi!") assert.spy(thing.greet).was.called() assert.spy(thing.greet).was.called_with("Hi!") end) end) end)
@(resource: BaseEntity.Resource, resourceDetail: List[BaseEntity.ResourceDetail])(implicit flash: play.api.mvc.Flash, messages: Messages)
#include "f2c.h" #include "blaswrap.h" /* Table of constant values */ static integer c__1 = 1; static doublereal c_b23 = 0.; static integer c__0 = 0; static doublereal c_b39 = 1.; /* Subroutine */ int dlatme_(integer *n, char *dist, integer *iseed, doublereal *d__, integer *mode, doublereal *cond, doublereal *dmax__, char *ei, char *rsign, char *upper, char *sim, doublereal *ds, integer *modes, doublereal *conds, integer *kl, integer *ku, doublereal *anorm, doublereal *a, integer *lda, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; doublereal d__1, d__2, d__3; /* Local variables */ integer i__, j, ic, jc, ir, jr, jcr; doublereal tau; logical bads; extern /* Subroutine */ int dger_(integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, integer *); integer isim; doublereal temp; logical badei; doublereal alpha; extern /* Subroutine */ int dscal_(integer *, doublereal *, doublereal *, integer *); extern logical lsame_(char *, char *); extern /* Subroutine */ int dgemv_(char *, integer *, integer *, doublereal *, doublereal *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *); integer iinfo; doublereal tempa[1]; integer icols; logical useei; integer idist; extern /* Subroutine */ int dcopy_(integer *, doublereal *, integer *, doublereal *, integer *); integer irows; extern /* Subroutine */ int dlatm1_(integer *, doublereal *, integer *, integer *, integer *, doublereal *, integer *, integer *); extern doublereal dlange_(char *, integer *, integer *, doublereal *, integer *, doublereal *); extern /* Subroutine */ int dlarge_(integer *, doublereal *, integer *, integer *, doublereal *, integer *), dlarfg_(integer *, doublereal *, doublereal *, integer *, doublereal *); extern doublereal dlaran_(integer *); extern /* Subroutine */ int dlaset_(char *, integer *, integer *, doublereal *, doublereal *, doublereal *, integer *), xerbla_(char *, integer *), dlarnv_(integer *, integer *, integer *, doublereal *); integer irsign, iupper; doublereal xnorms; /* -- LAPACK test routine (version 3.1) -- */ /* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ /* November 2006 */ /* .. Scalar Arguments .. */ /* .. Array Arguments .. */ /* Purpose */ /* DLATME generates random non-symmetric square matrices with */ /* specified eigenvalues for testing LAPACK programs. */ /* DLATME operates by applying the following sequence of */ /* operations: */ /* 1. Set the diagonal to D, where D may be input or */ /* computed according to MODE, COND, DMAX, and RSIGN */ /* as described below. */ /* 2. If complex conjugate pairs are desired (MODE=0 and EI(1)='R', */ /* or MODE=5), certain pairs of adjacent elements of D are */ /* interpreted as the real and complex parts of a complex */ /* conjugate pair; A thus becomes block diagonal, with 1x1 */ /* and 2x2 blocks. */ /* 3. If UPPER='T', the upper triangle of A is set to random values */ /* out of distribution DIST. */ /* 4. If SIM='T', A is multiplied on the left by a random matrix */ /* X, whose singular values are specified by DS, MODES, and */ /* CONDS, and on the right by X inverse. */ /* 5. If KL < N-1, the lower bandwidth is reduced to KL using */ /* Householder transformations. If KU < N-1, the upper */ /* bandwidth is reduced to KU. */ /* 6. If ANORM is not negative, the matrix is scaled to have */ /* <API key> ANORM. */ /* (Note: since the matrix cannot be reduced beyond Hessenberg form, */ /* no packing options are available.) */ /* Arguments */ /* N - INTEGER */ /* The number of columns (or rows) of A. Not modified. */ /* DIST - CHARACTER*1 */ /* On entry, DIST specifies the type of distribution to be used */ /* to generate the random eigen-/singular values, and for the */ /* upper triangle (see UPPER). */ /* 'U' => UNIFORM( 0, 1 ) ( 'U' for uniform ) */ /* 'S' => UNIFORM( -1, 1 ) ( 'S' for symmetric ) */ /* 'N' => NORMAL( 0, 1 ) ( 'N' for normal ) */ /* Not modified. */ /* ISEED - INTEGER array, dimension ( 4 ) */ /* On entry ISEED specifies the seed of the random number */ /* generator. They should lie between 0 and 4095 inclusive, */ /* and ISEED(4) should be odd. The random number generator */ /* uses a linear congruential sequence limited to small */ /* integers, and so should produce machine independent */ /* random numbers. The values of ISEED are changed on */ /* exit, and can be used in the next call to DLATME */ /* to continue the same random number sequence. */ /* Changed on exit. */ /* D - DOUBLE PRECISION array, dimension ( N ) */ /* This array is used to specify the eigenvalues of A. If */ /* MODE=0, then D is assumed to contain the eigenvalues (but */ /* see the description of EI), otherwise they will be */ /* computed according to MODE, COND, DMAX, and RSIGN and */ /* placed in D. */ /* Modified if MODE is nonzero. */ /* MODE - INTEGER */ /* On entry this describes how the eigenvalues are to */ /* be specified: */ /* MODE = 0 means use D (with EI) as input */ /* MODE = 1 sets D(1)=1 and D(2:N)=1.0/COND */ /* MODE = 2 sets D(1:N-1)=1 and D(N)=1.0/COND */ /* MODE = 3 sets D(I)=COND**(-(I-1)/(N-1)) */ /* MODE = 4 sets D(i)=1 - (i-1)/(N-1)*(1 - 1/COND) */ /* MODE = 5 sets D to random numbers in the range */ /* ( 1/COND , 1 ) such that their logarithms */ /* are uniformly distributed. Each odd-even pair */ /* of elements will be either used as two real */ /* eigenvalues or as the real and imaginary part */ /* of a complex conjugate pair of eigenvalues; */ /* the choice of which is done is random, with */ /* 50-50 probability, for each pair. */ /* MODE = 6 set D to random numbers from same distribution */ /* as the rest of the matrix. */ /* MODE < 0 has the same meaning as ABS(MODE), except that */ /* the order of the elements of D is reversed. */ /* Thus if MODE is between 1 and 4, D has entries ranging */ /* from 1 to 1/COND, if between -1 and -4, D has entries */ /* ranging from 1/COND to 1, */ /* Not modified. */ /* COND - DOUBLE PRECISION */ /* On entry, this is used as described under MODE above. */ /* If used, it must be >= 1. Not modified. */ /* DMAX - DOUBLE PRECISION */ /* If MODE is neither -6, 0 nor 6, the contents of D, as */ /* computed according to MODE and COND, will be scaled by */ /* DMAX / max(abs(D(i))). Note that DMAX need not be */ /* positive: if DMAX is negative (or zero), D will be */ /* scaled by a negative number (or zero). */ /* Not modified. */ /* EI - CHARACTER*1 array, dimension ( N ) */ /* If MODE is 0, and EI(1) is not ' ' (space character), */ /* this array specifies which elements of D (on input) are */ /* real eigenvalues and which are the real and imaginary parts */ /* of a complex conjugate pair of eigenvalues. The elements */ /* of EI may then only have the values 'R' and 'I'. If */ /* EI(j)='R' and EI(j+1)='I', then the j-th eigenvalue is */ /* CMPLX( D(j) , D(j+1) ), and the (j+1)-th is the complex */ /* conjugate thereof. If EI(j)=EI(j+1)='R', then the j-th */ /* eigenvalue is D(j) (i.e., real). EI(1) may not be 'I', */ /* nor may two adjacent elements of EI both have the value 'I'. */ /* If MODE is not 0, then EI is ignored. If MODE is 0 and */ /* EI(1)=' ', then the eigenvalues will all be real. */ /* Not modified. */ /* RSIGN - CHARACTER*1 */ /* If MODE is not 0, 6, or -6, and RSIGN='T', then the */ /* elements of D, as computed according to MODE and COND, will */ /* be multiplied by a random sign (+1 or -1). If RSIGN='F', */ /* they will not be. RSIGN may only have the values 'T' or */ /* Not modified. */ /* UPPER - CHARACTER*1 */ /* If UPPER='T', then the elements of A above the diagonal */ /* (and above the 2x2 diagonal blocks, if A has complex */ /* eigenvalues) will be set to random numbers out of DIST. */ /* If UPPER='F', they will not. UPPER may only have the */ /* values 'T' or 'F'. */ /* Not modified. */ /* SIM - CHARACTER*1 */ /* If SIM='T', then A will be operated on by a "similarity */ /* transform", i.e., multiplied on the left by a matrix X and */ /* on the right by X inverse. X = U S V, where U and V are */ /* random unitary matrices and S is a (diagonal) matrix of */ /* singular values specified by DS, MODES, and CONDS. If */ /* SIM='F', then A will not be transformed. */ /* Not modified. */ /* DS - DOUBLE PRECISION array, dimension ( N ) */ /* This array is used to specify the singular values of X, */ /* in the same way that D specifies the eigenvalues of A. */ /* If MODE=0, the DS contains the singular values, which */ /* may not be zero. */ /* Modified if MODE is nonzero. */ /* MODES - INTEGER */ /* CONDS - DOUBLE PRECISION */ /* Same as MODE and COND, but for specifying the diagonal */ /* of S. MODES=-6 and +6 are not allowed (since they would */ /* result in randomly ill-conditioned eigenvalues.) */ /* KL - INTEGER */ /* This specifies the lower bandwidth of the matrix. KL=1 */ /* specifies upper Hessenberg form. If KL is at least N-1, */ /* then A will have full lower bandwidth. KL must be at */ /* least 1. */ /* Not modified. */ /* KU - INTEGER */ /* This specifies the upper bandwidth of the matrix. KU=1 */ /* specifies lower Hessenberg form. If KU is at least N-1, */ /* then A will have full upper bandwidth; if KU and KL */ /* are both at least N-1, then A will be dense. Only one of */ /* KU and KL may be less than N-1. KU must be at least 1. */ /* Not modified. */ /* ANORM - DOUBLE PRECISION */ /* If ANORM is not negative, then A will be scaled by a non- */ /* negative real number to make the <API key> of A */ /* to be ANORM. */ /* Not modified. */ /* A - DOUBLE PRECISION array, dimension ( LDA, N ) */ /* On exit A is the desired test matrix. */ /* Modified. */ /* LDA - INTEGER */ /* LDA specifies the first dimension of A as declared in the */ /* calling program. LDA must be at least N. */ /* Not modified. */ /* WORK - DOUBLE PRECISION array, dimension ( 3*N ) */ /* Workspace. */ /* Modified. */ /* INFO - INTEGER */ /* Error code. On exit, INFO will be set to one of the */ /* following values: */ /* 0 => normal return */ /* -1 => N negative */ /* -5 => MODE not in range -6 to 6 */ /* -6 => COND less than 1.0, and MODE neither -6, 0 nor 6 */ /* -8 => EI(1) is not ' ' or 'R', EI(j) is not 'R' or 'I', or */ /* two adjacent elements of EI are 'I'. */ /* -9 => RSIGN is not 'T' or 'F' */ /* -10 => UPPER is not 'T' or 'F' */ /* -11 => SIM is not 'T' or 'F' */ /* -12 => MODES=0 and DS has a zero singular value. */ /* -13 => MODES is not in the range -5 to 5. */ /* -14 => MODES is nonzero and CONDS is less than 1. */ /* -15 => KL is less than 1. */ /* -16 => KU is less than 1, or KL and KU are both less than */ /* -19 => LDA is less than N. */ /* 1 => Error return from DLATM1 (computing D) */ /* 2 => Cannot scale to DMAX (max. eigenvalue is 0) */ /* 3 => Error return from DLATM1 (computing DS) */ /* 4 => Error return from DLARGE */ /* 5 => Zero singular value from DLATM1. */ /* .. Parameters .. */ /* .. Local Scalars .. */ /* .. Local Arrays .. */ /* .. External Functions .. */ /* .. External Subroutines .. */ /* .. Intrinsic Functions .. */ /* .. Executable Statements .. */ /* 1) Decode and Test the input parameters. */ /* Initialize flags & seed. */ /* Parameter adjustments */ --iseed; --d__; --ei; --ds; a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --work; /* Function Body */ *info = 0; /* Quick return if possible */ if (*n == 0) { return 0; } /* Decode DIST */ if (lsame_(dist, "U")) { idist = 1; } else if (lsame_(dist, "S")) { idist = 2; } else if (lsame_(dist, "N")) { idist = 3; } else { idist = -1; } /* Check EI */ useei = TRUE_; badei = FALSE_; if (lsame_(ei + 1, " ") || *mode != 0) { useei = FALSE_; } else { if (lsame_(ei + 1, "R")) { i__1 = *n; for (j = 2; j <= i__1; ++j) { if (lsame_(ei + j, "I")) { if (lsame_(ei + (j - 1), "I")) { badei = TRUE_; } } else { if (! lsame_(ei + j, "R")) { badei = TRUE_; } } /* L10: */ } } else { badei = TRUE_; } } /* Decode RSIGN */ if (lsame_(rsign, "T")) { irsign = 1; } else if (lsame_(rsign, "F")) { irsign = 0; } else { irsign = -1; } /* Decode UPPER */ if (lsame_(upper, "T")) { iupper = 1; } else if (lsame_(upper, "F")) { iupper = 0; } else { iupper = -1; } /* Decode SIM */ if (lsame_(sim, "T")) { isim = 1; } else if (lsame_(sim, "F")) { isim = 0; } else { isim = -1; } /* Check DS, if MODES=0 and ISIM=1 */ bads = FALSE_; if (*modes == 0 && isim == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (ds[j] == 0.) { bads = TRUE_; } /* L20: */ } } /* Set INFO if an error */ if (*n < 0) { *info = -1; } else if (idist == -1) { *info = -2; } else if (abs(*mode) > 6) { *info = -5; } else if (*mode != 0 && abs(*mode) != 6 && *cond < 1.) { *info = -6; } else if (badei) { *info = -8; } else if (irsign == -1) { *info = -9; } else if (iupper == -1) { *info = -10; } else if (isim == -1) { *info = -11; } else if (bads) { *info = -12; } else if (isim == 1 && abs(*modes) > 5) { *info = -13; } else if (isim == 1 && *modes != 0 && *conds < 1.) { *info = -14; } else if (*kl < 1) { *info = -15; } else if (*ku < 1 || *ku < *n - 1 && *kl < *n - 1) { *info = -16; } else if (*lda < max(1,*n)) { *info = -19; } if (*info != 0) { i__1 = -(*info); xerbla_("DLATME", &i__1); return 0; } /* Initialize random number generator */ for (i__ = 1; i__ <= 4; ++i__) { iseed[i__] = (i__1 = iseed[i__], abs(i__1)) % 4096; /* L30: */ } if (iseed[4] % 2 != 1) { ++iseed[4]; } /* 2) Set up diagonal of A */ /* Compute D according to COND and MODE */ dlatm1_(mode, cond, &irsign, &idist, &iseed[1], &d__[1], n, &iinfo); if (iinfo != 0) { *info = 1; return 0; } if (*mode != 0 && abs(*mode) != 6) { /* Scale by DMAX */ temp = abs(d__[1]); i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { /* Computing MAX */ d__2 = temp, d__3 = (d__1 = d__[i__], abs(d__1)); temp = max(d__2,d__3); /* L40: */ } if (temp > 0.) { alpha = *dmax__ / temp; } else if (*dmax__ != 0.) { *info = 2; return 0; } else { alpha = 0.; } dscal_(n, &alpha, &d__[1], &c__1); } dlaset_("Full", n, n, &c_b23, &c_b23, &a[a_offset], lda); i__1 = *lda + 1; dcopy_(n, &d__[1], &c__1, &a[a_offset], &i__1); /* Set up complex conjugate pairs */ if (*mode == 0) { if (useei) { i__1 = *n; for (j = 2; j <= i__1; ++j) { if (lsame_(ei + j, "I")) { a[j - 1 + j * a_dim1] = a[j + j * a_dim1]; a[j + (j - 1) * a_dim1] = -a[j + j * a_dim1]; a[j + j * a_dim1] = a[j - 1 + (j - 1) * a_dim1]; } /* L50: */ } } } else if (abs(*mode) == 5) { i__1 = *n; for (j = 2; j <= i__1; j += 2) { if (dlaran_(&iseed[1]) > .5) { a[j - 1 + j * a_dim1] = a[j + j * a_dim1]; a[j + (j - 1) * a_dim1] = -a[j + j * a_dim1]; a[j + j * a_dim1] = a[j - 1 + (j - 1) * a_dim1]; } /* L60: */ } } /* 3) If UPPER='T', set upper triangle of A to random numbers. */ /* (but don't modify the corners of 2x2 blocks.) */ if (iupper != 0) { i__1 = *n; for (jc = 2; jc <= i__1; ++jc) { if (a[jc - 1 + jc * a_dim1] != 0.) { jr = jc - 2; } else { jr = jc - 1; } dlarnv_(&idist, &iseed[1], &jr, &a[jc * a_dim1 + 1]); /* L70: */ } } /* 4) If SIM='T', apply similarity transformation. */ /* Transform is X A X , where X = U S V, thus */ /* it is U S V A V' (1/S) U' */ if (isim != 0) { /* Compute S (singular values of the eigenvector matrix) */ /* according to CONDS and MODES */ dlatm1_(modes, conds, &c__0, &c__0, &iseed[1], &ds[1], n, &iinfo); if (iinfo != 0) { *info = 3; return 0; } /* Multiply by V and V' */ dlarge_(n, &a[a_offset], lda, &iseed[1], &work[1], &iinfo); if (iinfo != 0) { *info = 4; return 0; } /* Multiply by S and (1/S) */ i__1 = *n; for (j = 1; j <= i__1; ++j) { dscal_(n, &ds[j], &a[j + a_dim1], lda); if (ds[j] != 0.) { d__1 = 1. / ds[j]; dscal_(n, &d__1, &a[j * a_dim1 + 1], &c__1); } else { *info = 5; return 0; } /* L80: */ } /* Multiply by U and U' */ dlarge_(n, &a[a_offset], lda, &iseed[1], &work[1], &iinfo); if (iinfo != 0) { *info = 4; return 0; } } /* 5) Reduce the bandwidth. */ if (*kl < *n - 1) { /* Reduce bandwidth -- kill column */ i__1 = *n - 1; for (jcr = *kl + 1; jcr <= i__1; ++jcr) { ic = jcr - *kl; irows = *n + 1 - jcr; icols = *n + *kl - jcr; dcopy_(&irows, &a[jcr + ic * a_dim1], &c__1, &work[1], &c__1); xnorms = work[1]; dlarfg_(&irows, &xnorms, &work[2], &c__1, &tau); work[1] = 1.; dgemv_("T", &irows, &icols, &c_b39, &a[jcr + (ic + 1) * a_dim1], lda, &work[1], &c__1, &c_b23, &work[irows + 1], &c__1); d__1 = -tau; dger_(&irows, &icols, &d__1, &work[1], &c__1, &work[irows + 1], & c__1, &a[jcr + (ic + 1) * a_dim1], lda); dgemv_("N", n, &irows, &c_b39, &a[jcr * a_dim1 + 1], lda, &work[1] , &c__1, &c_b23, &work[irows + 1], &c__1); d__1 = -tau; dger_(n, &irows, &d__1, &work[irows + 1], &c__1, &work[1], &c__1, &a[jcr * a_dim1 + 1], lda); a[jcr + ic * a_dim1] = xnorms; i__2 = irows - 1; dlaset_("Full", &i__2, &c__1, &c_b23, &c_b23, &a[jcr + 1 + ic * a_dim1], lda); /* L90: */ } } else if (*ku < *n - 1) { /* Reduce upper bandwidth -- kill a row at a time. */ i__1 = *n - 1; for (jcr = *ku + 1; jcr <= i__1; ++jcr) { ir = jcr - *ku; irows = *n + *ku - jcr; icols = *n + 1 - jcr; dcopy_(&icols, &a[ir + jcr * a_dim1], lda, &work[1], &c__1); xnorms = work[1]; dlarfg_(&icols, &xnorms, &work[2], &c__1, &tau); work[1] = 1.; dgemv_("N", &irows, &icols, &c_b39, &a[ir + 1 + jcr * a_dim1], lda, &work[1], &c__1, &c_b23, &work[icols + 1], &c__1); d__1 = -tau; dger_(&irows, &icols, &d__1, &work[icols + 1], &c__1, &work[1], & c__1, &a[ir + 1 + jcr * a_dim1], lda); dgemv_("C", &icols, n, &c_b39, &a[jcr + a_dim1], lda, &work[1], & c__1, &c_b23, &work[icols + 1], &c__1); d__1 = -tau; dger_(&icols, n, &d__1, &work[1], &c__1, &work[icols + 1], &c__1, &a[jcr + a_dim1], lda); a[ir + jcr * a_dim1] = xnorms; i__2 = icols - 1; dlaset_("Full", &c__1, &i__2, &c_b23, &c_b23, &a[ir + (jcr + 1) * a_dim1], lda); /* L100: */ } } /* Scale the matrix to have norm ANORM */ if (*anorm >= 0.) { temp = dlange_("M", n, n, &a[a_offset], lda, tempa); if (temp > 0.) { alpha = *anorm / temp; i__1 = *n; for (j = 1; j <= i__1; ++j) { dscal_(n, &alpha, &a[j * a_dim1 + 1], &c__1); /* L110: */ } } } return 0; /* End of DLATME */ } /* dlatme_ */
#include <algorithm> #include <cassert> #include <iterator> #include <ostream> #include <set> #include <string> #include <sstream> #include <boost/shared_ptr.hpp> #include <mdds/flat_segment_tree.hpp> #include <quickcheck/quickcheck.hh> namespace { using quickcheck::Property; using std::ostream; using std::pair; using std::string; typedef mdds::flat_segment_tree<unsigned, unsigned> fst_type; typedef fst_type::key_type key_type; typedef fst_type::value_type value_type; class fst_wrapper { public: fst_type* get() const { return m_pimpl.get(); } fst_type& operator*() const { assert(initialized()); return *get(); } fst_type* operator->() const { assert(initialized()); return get(); } bool initialized() const { return m_pimpl.get(); } void initialize(key_type low_, key_type high_, value_type value_) { assert(!initialized()); m_pimpl.reset(new fst_type(low_, high_, value_)); } private: boost::shared_ptr<fst_type> m_pimpl; }; template<typename Key, typename Value> ostream& operator<<(ostream& out_, mdds::flat_segment_tree<Key, Value> const& fst_) { out_ << "["; bool first(true); typedef typename mdds::flat_segment_tree<Key, Value>::const_iterator iterator_type; iterator_type cur(fst_.begin()); for (iterator_type end(fst_.end()); cur != end; ++cur) { if (first) first = false; else out_ << ", "; out_ << cur->first << ": " << cur->second; } out_ << ", " << cur->first << "), default = " << fst_.default_value(); return out_; } ostream& operator<<(ostream& out_, fst_wrapper const& fst_) { return fst_.initialized() ? out_ << *fst_ : out_; } template<typename T> struct generator { generator(size_t n_) : m_n(n_) { } T operator()() const { using quickcheck::generate; T val; generate(m_n, val); return val; } private: size_t m_n; }; void generate(size_t n_, fst_wrapper& fst_) { using quickcheck::generate; value_type default_value; generate(n_, default_value); // generate a number of segments size_t segments(0); generate(n_, segments); segments = std::max<size_t>(segments, 1); using std::set; set<key_type> points; { size_t count(segments + 1); while (count > 0) { generator<key_type> gen(n_); if (points.insert(gen()).second) --count; } } using std::vector; vector<value_type> values; values.reserve(segments); std::generate_n( std::back_inserter(values), segments, generator<value_type>(n_)); fst_.initialize(*points.begin(), *points.rbegin(), default_value); // insert segments if (segments >= 2) { assert(points.size() == values.size() + 1); typedef set<key_type>::const_iterator points_iterator; points_iterator last(points.begin()); points_iterator cur(points.begin()); points_iterator end(points.end()); typedef vector<value_type>::const_iterator values_iterator; values_iterator cur_val(values.begin()); values_iterator end_val(values.end()); ++cur; while (cur != end && cur_val != end_val) { fst_->insert_back(*last, *cur, *cur_val); last = cur; ++cur; ++cur_val; } } } bool is_valid_key(fst_type const& fst_, key_type const& key_) { return key_ >= fst_.begin()->first && key_ < fst_.rbegin()->first; } bool is_valid_range(fst_type const& fst_, key_type const& low_, key_type const& high_) { return low_ < high_ && is_valid_key(fst_, low_) && is_valid_key(fst_, high_); } bool is_empty_tree(fst_type const& fst_) { return fst_.rbegin()->first - fst_.begin()->first == 1; } bool is_single_segment(fst_type const& fst_) { fst_type::const_iterator begin(fst_.begin()); ++begin; return begin == fst_.end(); } class <API key> : public Property<fst_wrapper, key_type, key_type, key_type> { public: typedef fst_type::const_iterator const_iterator; virtual bool accepts( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, value_type const&) { return is_valid_range(*fst_, low_, high_); } }; class <API key> : public <API key> { public: virtual bool isTrivialFor( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, value_type const&) { return is_empty_tree(*fst_); } }; class <API key> : public <API key> { virtual bool holdsFor( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, value_type const& value_) { fst_type insert_front(*fst_); fst_type insert_back(*fst_); insert_front.insert_front(low_, high_, value_); insert_back.insert_back(low_, high_, value_); return insert_front == insert_back; } }; class <API key> : public <API key> { virtual bool holdsFor( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, value_type const& value_) { fst_type insert(*fst_); fst_type insert_back(*fst_); insert.insert(insert.begin(), low_, high_, value_); insert_back.insert_back(low_, high_, value_); return insert == insert_back; } }; class <API key> : public <API key> { virtual bool holdsFor( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, value_type const& value_) { fst_type fst(*fst_); const_iterator const pos(fst.insert_front(low_, high_, value_).first); fst_type orig(fst); fst.build_tree(); pair<const_iterator, bool> result(fst.insert(pos, low_, high_, value_)); return !result.second && result.first == pos && fst == orig; } }; class PKeyInLimitsIsFound : public <API key> { virtual bool holdsFor( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, value_type const& value_) { fst_type fst(*fst_); value_type dummy; pair<const_iterator, bool> result(fst.search(low_, dummy)); return result.second && result.first != fst.end() && result.first->first <= low_; } }; class <API key> : public <API key> { virtual bool holdsFor( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, value_type const& value_) { fst_type fst(*fst_); pair<const_iterator, bool> insert(fst.insert_front(low_, high_, value_)); value_type value; pair<const_iterator, bool> search(fst.search(insert.first, low_, value)); return search.second && search.first == insert.first && value == value_; } }; class <API key> : public Property<fst_wrapper, key_type> { virtual bool holdsFor(fst_wrapper const& fst_, key_type const& key_) { fst_type fst(*fst_); value_type value; key_type low; key_type high; pair<fst_type::const_iterator, bool> search(fst.search(key_, value, &low, &high)); if (!fst.is_tree_valid()) fst.build_tree(); value_type value_tree; key_type low_tree; key_type high_tree; bool const search_tree(fst.search_tree(key_, value_tree, &low_tree, &high_tree)); return search.second == search_tree && low == low_tree && high == high_tree && value == value_tree; } virtual bool accepts(fst_wrapper const& fst_, key_type const& key_) { return is_valid_key(*fst_, key_); } }; class <API key> : public Property<fst_wrapper, key_type> { virtual bool holdsFor(fst_wrapper const& fst_, key_type const& key_) { fst_type& orig(*fst_); fst_type fst(orig); value_type dummy; fst.search(key_, dummy); return fst == orig; } virtual bool accepts(fst_wrapper const& fst_, key_type const& key_) { return is_valid_key(*fst_, key_); } }; class <API key> : public Property<fst_wrapper> { virtual bool holdsFor(fst_wrapper const& fst_) { fst_type& orig(*fst_); fst_type& fst(orig); fst.build_tree(); return fst == orig; } virtual bool isTrivialFor(fst_wrapper const& fst_) { return fst_->is_tree_valid(); } }; class <API key> : public Property<fst_wrapper, key_type, key_type> { virtual bool holdsFor(fst_wrapper const& fst_, key_type const& low_, key_type const& high_) { fst_type& orig(*fst_); fst_type fst(orig); fst.shift_left(low_, high_); return fst != orig; } virtual bool accepts(fst_wrapper const& fst_, key_type const& low_, key_type const& high_) { return is_valid_range(*fst_, low_, high_) && !is_single_segment(*fst_); } }; class PShiftRightWorks : public Property<fst_wrapper, key_type, key_type, bool> { virtual bool holdsFor( fst_wrapper const& fst_, key_type const& key_, key_type const& size_, bool const& skip_start_) { fst_type& orig(*fst_); fst_type fst(orig); fst.shift_right(key_, size_, skip_start_); return isTrivialFor(fst_, key_, size_, skip_start_) ? fst == orig : fst != orig; } virtual bool accepts( fst_wrapper const& fst_, key_type const& key_, key_type const& size_, bool const&) { return is_valid_key(*fst_, key_); } virtual bool isTrivialFor( fst_wrapper const& fst_, key_type const& key_, key_type const& size_, bool const& skip_start_) { return (is_single_segment(*fst_) && fst_->begin()->second == fst_->default_value()) || size_ == 0 || (skip_start_ && key_ == fst_->max_key() - 1); } }; bool keys_ordered(fst_type const& fst_) { fst_type::const_iterator cur(fst_.begin()); fst_type::const_iterator end(fst_.end()); fst_type::const_iterator last(cur); ++cur; while (cur != end) { if (last->first >= cur->first) return false; ++cur; } return last->first < cur->first; } class <API key> : public <API key> { virtual bool holdsFor( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, value_type const& value_) { fst_type fst(*fst_); fst.insert_front(low_, high_, value_); return keys_ordered(fst); } virtual bool isTrivialFor( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, value_type const& value_) { fst_type fst(*fst_); return !fst.insert_front(low_, high_, value_).second; } }; class <API key> : public Property<fst_wrapper, key_type, key_type> { virtual bool holdsFor(fst_wrapper const& fst_, key_type const& low_, key_type const& high_) { fst_type fst(*fst_); fst.shift_left(low_, high_); return keys_ordered(fst); } virtual bool accepts(fst_wrapper const& fst_, key_type const& low_, key_type const& high_) { return is_valid_range(*fst_, low_, high_); } virtual bool isTrivialFor(fst_wrapper const& fst_, key_type const& low_, key_type const& high_) { fst_type& fst(*fst_); return is_single_segment(fst) && fst.begin()->second == fst.default_value(); } }; class <API key> : public Property<fst_wrapper, key_type, key_type, bool> { virtual bool holdsFor( fst_wrapper const& fst_, key_type const& key_, key_type const& size_, bool const& skip_start_) { fst_type fst(*fst_); fst.shift_right(key_, size_, skip_start_); return keys_ordered(fst); } virtual bool accepts( fst_wrapper const& fst_, key_type const& key_, key_type const& size_, bool const&) { return is_valid_key(*fst_, key_); } virtual bool isTrivialFor( fst_wrapper const& fst_, key_type const& low_, key_type const& high_, bool const&) { fst_type& fst(*fst_); return is_single_segment(fst) && fst.begin()->second == fst.default_value(); } }; } int main() { size_t const tests(200); using quickcheck::check; check<<API key>>( "insert_front is the same as insert_back", tests); check<<API key>>("insert is same as insert_back", tests); check<<API key>>("repeated insert does nothing", tests); check<PKeyInLimitsIsFound>("key in tree limits is found", tests); check<<API key>>( "key in just inserted segment is found at the right pos", tests); check<<API key>>("search_tree is the same as search", tests); check<<API key>>("search does not change tree", tests); check<<API key>>("build_tree does not change tree", tests); check<<API key>>("shift_left removes something", tests); // check<PShiftRightWorks>("shift_right works", tests); check<<API key>>("keys remain ordered after insert", tests); check<<API key>>("keys remain ordered after shift_left", tests); check<<API key>>("keys remain ordered after shift_right", tests); } // vim: set ts=4 sw=4 et:
if ENV['AIRBRAKE_KEY'] Airbrake.configure do |config| config.api_key = ENV['AIRBRAKE_KEY'] config.params_filters << "ssh_key" config.params_filters << "mysql_password" end end module CustomNotifier def self.notify(exception, parameters=nil) options = {} if exception.instance_of?(Hash) options = exception.merge(:backtrace => caller) else options = { :error_class => exception.class, :error_message => exception.message, :backtrace => exception.backtrace } end Airbrake.notify(options.merge(:parameters => parameters)) end end
var test = require('tape'); var fs = require('fs'); var parseKey = require('../index'); var rsa1024 = { private: fs.readFileSync(__dirname + '/rsa.1024.priv'), public: fs.readFileSync(__dirname + '/rsa.1024.pub') }; var rsa2028 = { private: fs.readFileSync(__dirname + '/rsa.2028.priv'), public: fs.readFileSync(__dirname + '/rsa.2028.pub') }; var nonrsa1024 = { private: fs.readFileSync(__dirname + '/1024.priv'), public: fs.readFileSync(__dirname + '/1024.pub') }; var pass1024 = { private: { passphrase: 'fooo', key: fs.readFileSync(__dirname + '/pass.1024.priv') }, public: fs.readFileSync(__dirname + '/pass.1024.pub') }; var ec = { private: fs.readFileSync(__dirname + '/ec.priv'), public: fs.readFileSync(__dirname + '/ec.pub') }; var ecpass = { private: { key: fs.readFileSync(__dirname + '/ec.pass.priv'), passphrase: 'bard' }, public: fs.readFileSync(__dirname + '/ec.pub') }; var dsa = { private: fs.readFileSync(__dirname + '/dsa.1024.priv'), public: fs.readFileSync(__dirname + '/dsa.1024.pub') }; var dsa2 = { private: fs.readFileSync(__dirname + '/dsa.2048.priv'), public: fs.readFileSync(__dirname + '/dsa.2048.pub') }; var dsapass = { private: { key: fs.readFileSync(__dirname + '/pass.dsa.1024.priv'), passphrase: 'password' }, public: fs.readFileSync(__dirname + '/pass.dsa.1024.pub') }; var dsapass2 = { private: { key: fs.readFileSync(__dirname + '/pass2.dsa.1024.priv'), passphrase: 'password' }, public: fs.readFileSync(__dirname + '/pass2.dsa.1024.pub') }; var rsapass = { private: { key: fs.readFileSync(__dirname + '/pass.rsa.1024.priv'), passphrase: 'password' }, public: fs.readFileSync(__dirname + '/pass.rsa.1024.pub') }; var rsapass2 = { private: { key: fs.readFileSync(__dirname + '/pass.rsa.2028.priv'), passphrase: 'password' }, public: fs.readFileSync(__dirname + '/pass.rsa.2028.pub') }; var cert = { private: fs.readFileSync(__dirname + '/rsa.1024.priv'), public: fs.readFileSync(__dirname + '/node.cert') }; var i = 0; function testIt(keys) { test('key ' + (++i), function(t) { t.plan(2); t.ok(parseKey(keys.public), 'public key'); t.ok(parseKey(keys.private), 'private key'); }); } testIt(dsa); testIt(dsa2); testIt(rsa1024); testIt(ec); testIt(rsa2028); testIt(nonrsa1024); testIt(ecpass); testIt(dsapass); testIt(dsapass2); testIt(rsapass); testIt(rsapass2); testIt(pass1024); testIt(pass1024); testIt(cert);
#!/usr/bin/env bash set -o nounset set -o errexit set -o pipefail realpath=$(realpath "${BASH_SOURCE[0]}") scripts_dir=$(dirname "${realpath}") root_dir=$(dirname "${scripts_dir}") echo "${root_dir}" cd "${root_dir}" target_branch="origin/master" mapfile -t changed_fies < <(git diff --name-only HEAD.."${target_branch}") roles=( ) echo echo echo " for file in "${changed_fies[@]}"; do echo "Changed file: ${file}" role_path=$(echo "${file}" | cut -f1,2 -d'/') if [[ "${role_path}" =~ roles/.* ]]; then roles+=("${role_path}") echo "Adding ${role_path}" fi if [[ "${file}" == requirements.txt ]]; then echo "requirements.txt changed, testing all roles..." all_roles=( $( ls roles ) ) for role in "${all_roles[@]}" do roles+=("roles/${role}") done fi if [[ "${GITHUB_EVENT_NAME}" == schedule ]]; then echo "Scheduled run, testing all roles..." all_roles=( $( ls roles ) ) for role in "${all_roles[@]}" do roles+=("roles/${role}") done fi done echo echo echo " echo "Listing roles: ${roles[*]}" # shellcheck disable=SC2207 unique_roles=($(echo "${roles[*]}" | tr ' ' '\n' | sort -u | tr '\n' ' ')) echo "Unique roles: ${unique_roles[*]}" echo " for role in "${unique_roles[@]}" do echo echo echo " echo "Testing role: ${role}" { pushd "${role}" >/dev/null molecule test popd >/dev/null } done
<?php namespace Elastica\Rescore; use Elastica\Query as BaseQuery; class Query extends AbstractRescore { /** * Constructor * * @param string|\Elastica\Query\AbstractQuery $rescoreQuery * @param string|\Elastica\Query\AbstractQuery $query */ public function __construct($query = null) { $this->setParam('query', array()); $this->setRescoreQuery($query); } /** * Override default implementation so params are in the format * expected by elasticsearch * * @return array Rescore array */ public function toArray() { $data = $this->getParams(); if (!empty($this->_rawParams)) { $data = array_merge($data, $this->_rawParams); } return $data; } /** * Sets rescoreQuery object * * @param string|\Elastica\Query|\Elastica\Query\AbstractQuery $query * @return $this */ public function setRescoreQuery($rescoreQuery) { $query = BaseQuery::create($rescoreQuery); $data = $query->toArray(); $query = $this->getParam('query'); $query['rescore_query'] = $data['query']; return $this->setParam('query', $query); } /** * Sets query_weight * * @param float $weight * @return $this */ public function setQueryWeight($weight) { $query = $this->getParam('query'); $query['query_weight'] = $weight; return $this->setParam('query', $query); } /** * Sets <API key> * * @param float $size * @return $this */ public function <API key>($weight) { $query = $this->getParam('query'); $query['<API key>'] = $weight; return $this->setParam('query', $query); } }
<?php // Carico tutt i file php Richiesti require('config_freamwork.php'); require('json_call.php'); global $json; ?> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <!-- Includo il Css per in base al broswer !--> <link href="css/style.css" rel="stylesheet" type="text/css"/> <!-- Includo il freamwork !--> <script type="text/javascript" src="js/core.js"></script> </head> <body> <?php include('function/scroll.php'); require('lingua_setting.php'); require ('../language/'.$lingua.'/'.$lingua.'.php'); ?> <div id="sfoglia_file_menu"> <div id="info_file"> <div id="title" > <a href="stagioni_id_id.php?season=<?php echo $_GET['season']; ?>&episodes=<?php echo $_GET['episodes']; ?>" onMouseOver="window.parent.document.getElementById('img_cambia').src=('core/img/back.png');" onMouseOut="window.parent.document.getElementById('img_cambia').src=('core/img/xbmc.png');">&ensp;&ensp;&ensp; <?php echo $t_episoditv ; ?> </a></div> <div id="playlist"><a href="stagioni_id_id.php?season=<?php echo $_GET['season']; ?>&episodes=<?php echo $_GET['episodes']; ?>"></a></div> <div id="type" ><a href="stagioni_id_id.php?season=<?php echo $_GET['season']; ?>&episodes=<?php echo $_GET['episodes']; ?>"><img src="img/back.png" width="28" height="28"/></a></div> </div> <?php stagioniepisodifile(); $curl = stagioniepisodifile("$json"); //echo $curl; $array = json_decode($curl,true); $results = $array['result']["episodes"]; foreach ($results as $value){ if ($value['episodeid'] == $_GET['id']){ echo ' <div id="info_file"> <div id="titolo" > &ensp;&ensp;&ensp; '.$value['label'].'</div> <div id="playlist"></div> <div id="type" ><a href="play.php?metod=episodeid&id='.$value['file'].'&title='.$value['label'].'" target="control"><img src="img/play.png" width="28" height="28" /></a></div> </div> <div id="info_file"> <div id="title" > &ensp;&ensp;&ensp; '.$t_stagione_videos.' : '.$value['season'].'</div> <div id="playlist"></div> <div id="type" ></div> </div> <div id="info_file"> <div id="trama" > <a href="play.php?metod=episodeid&id='.$value['file'].'&title='.$value['label'].'" target="control">'.$value['plot'].'</a> </div> </div> '; } } ?> </div> </body> </html>
# onepage [![Python](https://img.shields.io/badge/python-3.6-blue.svg)]() [![License](https: One page is a WebApp created in Starter Geek Jam. http://blog.seekgeeks.net/p/startergeekjam.html
<?php namespace Ixudra\Core\Repositories\Eloquent; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder; use Illuminate\Support\Collection; abstract class <API key> { /** * Return all instances of the repository model * * @return Collection */ public function all() { return $this->getModel()->all(); } /** * Return a single instance of the repository model by id * * @param integer $id * @return Model */ public function find($id) { return $this->getModel()->find($id); } /** * Find all instances of the repository model that match a particular filter * * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @return Collection */ public function findByFilter($filters) { $results = $this->getModel(); $results = $this->applyFilters( $results, $filters ); return $results->get(); } /** * Find all instances of the repository model that match a particular filter * * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @param int $size The amount of results that we expect to receive from the paginator * @return Collection */ public function search($filters, $size = 25) { $results = $this->getModel(); return $this->paginated($results, $filters, $size); } /** * Return the paginated result of the query * * @param Builder $results The query builder that contains all the clauses that have been applied * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @param int $size The amount of results that we expect to receive from the paginator * @return mixed */ protected function paginated($results, $filters = array(), $size = 25) { return $results ->select($this->getTable() .'.*') ->paginate($size) ->appends($filters) ->appends('size', $size); } /** * Return a new instance of the repository model * * @return Builder */ abstract protected function getModel(); /** * Return the name of the repository table * * @return string */ abstract protected function getTable(); /** * Apply various filters to the query builder. All filters must be applied using the '=' operator. Filters that * require other operators or additional operations such as joins, must be applied in a different way * * @param Builder $query The query builder that contains all the clauses that have been applied * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @param array $excludeFilters The filters that are to be ignored. This might be useful if the filters require a join before they can be applied or if they require a different operator * @return mixed */ protected function applyFilters($query, $filters = array(), $excludeFilters = array()) { foreach( $this->preProcessFilters($filters) as $key => $value ) { if( $value == '' || in_array( $key, $excludeFilters ) ) { continue; } $query = $query->where($key, '=', $value); } return $query; } /** * Apply various foreign key filters to the query builder. All filters must be applied using the '=' operator. * Filters that require other operators or additional operations such as joins, must be applied in a different way * * @param Builder $query The query builder that contains all the clauses that have been applied * @param array $foreignKeys The list of keys that are identified as foreign keys * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @return mixed */ protected function applyForeignKeys($query, $foreignKeys, $filters = array()) { foreach( $foreignKeys as $key ) { if( !$this->hasKey( $filters, $key ) ) { continue; } $query = $query->where($key, '=', $filters[ $key ]); } return $query; } /** * Apply various boolean key filters to the query builder. All filters must be applied using the '=' operator. * Filters that require other operators or additional operations such as joins, must be applied in a different way * * @param Builder $query The query builder that contains all the clauses that have been applied * @param array $booleanKeys The list of keys that are identified as boolean keys * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @return mixed */ protected function applyBoolean($query, $booleanKeys, $filters = array()) { foreach( $booleanKeys as $key ) { if( !$this->hasBoolean( $filters, $key ) ) { continue; } $query = $query->where($key, '=', $filters[ $key ]); } return $query; } /** * Verify if a specific filter key can be used as a filter value * * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @param string $key The filter key that must be verified * @return boolean */ protected function hasKey($filters, $key) { return ( array_key_exists($key, $filters) && $filters[ $key ] != 0 && $filters[ $key ] != '' ); } /** * Verify if a specific filter key can be used as a string filter * * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @param string $key The filter key that must be verified * @return boolean */ protected function hasString($filters, $key) { return ( array_key_exists($key, $filters) && $filters[ $key ] != '' ); } /** * Verify if a specific filter key can be used as a boolean filter * * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @param string $key The filter key that must be verified * @return boolean */ protected function hasBoolean($filters, $key) { return ( array_key_exists($key, $filters) && $filters[ $key ] != '' ); } /** * Pre process the filters before applying them to the query builder. By default it will only convert boolean * values to integer values * * @param array $filters The filters that are to be applied to the query. The key identifies the database column, the value in the array is the value that is to be matched in the query * @return mixed */ protected function preProcessFilters($filters) { foreach( $filters as $key => $value ) { if( $value === true ) { $filters[ $key ] = '1'; continue; } if( $value === false ) { $filters[ $key ] = '0'; continue; } } return $filters; } }
require 'spec_helper' module RequestLumberjack describe Config, ".database" do it "should return a sqlite3 database connection" do Config.database(nil).should be_instance_of DataMapper::Adapters::Sqlite3Adapter end end end
<?php include_once('../../config/config.inc.php'); include_once('../../init.php'); include_once('homeslider.php'); $context = Context::getContext(); $home_slider = new HomeSlider(); $slides = array(); if (!Tools::isSubmit('secure_key') || Tools::getValue('secure_key') != $home_slider->secure_key || !Tools::getValue('action')) die(1); if (Tools::getValue('action') == '<API key>' && Tools::getValue('slides')) { $slides = Tools::getValue('slides'); foreach ($slides as $position => $id_slide) { $res = Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'homeslider_slides` SET `position` = '.(int)$position.' WHERE `<API key>` = '.(int)$id_slide ); } }
__all__ = ['pe'] from .pe import *
package com.testproject.testclasses; /** * Hello world! * */ public class App { public static void main( String[] args ) { DownClass downClass = new DownClass(); Inline inline = new Inline("xyz"); System.out.println( "321" + inline.inlineMethod() ); } }
using System; using System.Windows.Forms; using myoddweb.viewer.forms; using Classifier.Interfaces; using System.IO; using System.Linq; using System.Reflection; using myoddweb.viewer.utils; namespace myoddweb.viewer { internal class CommandLineInfo { private readonly string[] _args; public CommandLineInfo(string[] args) { // set the args. _args = args; } public bool DisplayHelp() { // either we have '-h' or w are missing '-d' and/or '-db' arguments. if (!HasCommand("h") && HasCommand("db") && HasCommand("d")) { return false; } MessageBox.Show( $"--h : Display this message box{Environment.NewLine}" + Environment.NewLine + $"--d : Directory that contains the classifier engines, Classifier.Engine.dll).{Environment.NewLine}" + $" The directory must contain 2 sub directories x64 and x86, depending on the version been debuged{Environment.NewLine}" + Environment.NewLine + $"--db : The full path of the classifier database.{Environment.NewLine}", @"Help", MessageBoxButtons.OK, // display the error icon if we are not asking for help // and we are missing some values. (!HasCommand("h") && (!HasCommand("db") || !HasCommand("d")) ? MessageBoxIcon.Error : MessageBoxIcon.Information) ); return true; } <summary> Check if a command exists, (but it does not have to have a value. So you can look for -h and -db even if one has a value and the other does not. </summary> <param name="command">The value we are looking for.</param> <returns></returns> protected bool HasCommand(string command) { return _args.Any(s => s == $"--{command}"); } <summary> Get the path of the database including the name. This is where the file is located. </summary> <returns></returns> public string GetDatabasePath() { var db = GetValue("db"); if (null == db) { return null; } // if the file does not exist, return null. return !File.Exists(db) ? null : db; } <summary> Get the engines path, the engines are located in x86 and x64 sub paths We are looking to the root path that contains both those directories. </summary> <returns></returns> public string GetEnginePath() { var d = GetValue("d"); if (null == d) { return null; } // if the file does not exist, return null. return !Directory.Exists( d) ? null : d; } protected string GetValue( string command ) { for (var i = 0; i < _args.Length; ++i ) { var s = _args[i]; if (s != $"--{command}") { continue; } // do we have a value after that? if (i + 1 == _args.Length) { return null; } var posibleValue = _args[i + 1]; // is it another argument? if (posibleValue.Length > 2 && posibleValue.Substring(0, 2) == " { return null; } // remove the spaces and quotes. return posibleValue.Trim().Trim('"'); } // if we are here, we could not get it. return null; } } internal static class Program { <summary> Name for logging in the event viewer, </summary> private const string EventViewSource = "myoddweb.classifier"; <summary> Initialise the engine and load all the resources neeed. Will load the database and so on to get the plugin ready for use. </summary> <param name="directoryName">string the directory we are loading from.</param> <param name="databasePath">string the name/path of the database we will be loading.</param> <param name="lastError">If needed, set the last error.</param> <returns></returns> private static IClassify1 InitialiseEngine(string directoryName, string databasePath, out string lastError ) { lastError = ""; var dllInteropPath = Path.Combine(directoryName, "x86\\Classifier.Interop.dll"); var dllEnginePath = Path.Combine(directoryName, "x86\\Classifier.Engine.dll"); if (Environment.Is64BitProcess) { dllInteropPath = Path.Combine(directoryName, "x64\\Classifier.Interop.dll"); dllEnginePath = Path.Combine(directoryName, "x64\\Classifier.Engine.dll"); } else { if (!File.Exists(dllInteropPath)) { dllInteropPath = Path.Combine(directoryName, "win32\\Classifier.Interop.dll"); dllEnginePath = Path.Combine(directoryName, "win32\\Classifier.Engine.dll"); } } // look for the Assembly asm; try { asm = Assembly.LoadFrom(dllInteropPath); if (null == asm) { lastError = $"Unable to load the interop file. '{dllInteropPath}'."; return null; } } catch (ArgumentException ex) { lastError = $"The interop file name/path does not appear to be valid. '{dllInteropPath}'.{Environment.NewLine}{Environment.NewLine}{ex.Message}"; return null; } catch (<API key> ex) { lastError = $"Unable to load the interop file. '{dllInteropPath}'.{Environment.NewLine}{Environment.NewLine}{ex.Message}"; return null; } // look for the interop interface var classifyEngine = TypeLoader.<API key><IClassify1>(asm); if (null == classifyEngine) { // could not locate the interface. lastError = $"Unable to load the IClasify1 interface in the interop file. '{dllInteropPath}'."; return null; } if( !classifyEngine.Initialise(EventViewSource, dllEnginePath, databasePath)) { return null; } // initialise the engine itself. return classifyEngine; } <summary> The main entry point for the application. </summary> [STAThread] private static void Main(string[] args) { // get the command line info. var ci = new CommandLineInfo(args); // is it help? if (ci.DisplayHelp()) { return; } Application.EnableVisualStyles(); Application.<API key>(false); var databasePath = ci.GetDatabasePath(); if (null == databasePath) { MessageBox.Show(@"Unknown or missing database path.", @"Help", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var directoryName = ci.GetEnginePath(); if (null == directoryName) { MessageBox.Show(@"Unknown or missing engines path.", @"Help", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // the text const string text = @"meh"; string lastError; var engine = InitialiseEngine(directoryName, databasePath, out lastError); Application.Run(new DetailsForm( engine, text )); // release it then. engine?.Release(); } } }
using Xunit; namespace StakHappy.Core.UnitTest.Data.Model.Currency.Currency { public class SetCurrencyFixture { [Fact] public void <API key>() { var currency = new Core.Data.Model.Currency.Currency(23456); Assert.Equal(234.56, currency.Value); } [Fact] public void OneDollar() { var currency = new Core.Data.Model.Currency.Currency(100); Assert.Equal(1, currency.Value); } [Fact] public void LessThanOneDollar() { var currency = new Core.Data.Model.Currency.Currency(50); Assert.Equal(.5, currency.Value); } [Fact] public void OneCent() { var currency = new Core.Data.Model.Currency.Currency(1); Assert.Equal(.01, currency.Value); } [Fact] public void Zero() { var currency = new Core.Data.Model.Currency.Currency(0); Assert.Equal(0, currency.Value); } [Fact] public void Negative() { var currency = new Core.Data.Model.Currency.Currency(-20); Assert.Equal(-0.2, currency.Value); } } }
package vcs import ( "bytes" "encoding/json" "fmt" "io" "log" "os/exec" "path/filepath" "regexp" "strings" ) const defaultRef = "master" var headBranchRegexp = regexp.MustCompile(`HEAD branch: (?P<branch>.+)`) func init() { Register(newGit, "git") } type GitDriver struct { DetectRef bool `json:"detect-ref"` Ref string `json:"ref"` refDetetector refDetetector } type refDetetector interface { detectRef(dir string) string } type headBranchDetector struct { } func newGit(b []byte) (Driver, error) { var d GitDriver if b != nil { if err := json.Unmarshal(b, &d); err != nil { return nil, err } } d.refDetetector = &headBranchDetector{} return &d, nil } func (g *GitDriver) HeadRev(dir string) (string, error) { cmd := exec.Command( "git", "rev-parse", "HEAD") cmd.Dir = dir r, err := cmd.StdoutPipe() if err != nil { return "", err } defer r.Close() if err := cmd.Start(); err != nil { return "", err } var buf bytes.Buffer if _, err := io.Copy(&buf, r); err != nil { return "", err } return strings.TrimSpace(buf.String()), cmd.Wait() } func run(desc, dir, cmd string, args ...string) (string, error) { c := exec.Command(cmd, args...) c.Dir = dir out, err := c.CombinedOutput() if err != nil { log.Printf( "Failed to %s %s, see output below\n%sContinuing...", desc, dir, out) } return string(out), nil } func (g *GitDriver) Pull(dir string) (string, error) { targetRef := g.targetRef(dir) if _, err := run("git fetch", dir, "git", "fetch", "--prune", "--no-tags", "--depth", "1", "origin", fmt.Sprintf("+%s:remotes/origin/%s", targetRef, targetRef)); err != nil { return "", err } if _, err := run("git reset", dir, "git", "reset", "--hard", fmt.Sprintf("origin/%s", targetRef)); err != nil { return "", err } return g.HeadRev(dir) } func (g *GitDriver) targetRef(dir string) string { var targetRef string if g.Ref != "" { targetRef = g.Ref } else if g.DetectRef { targetRef = g.refDetetector.detectRef(dir) } if targetRef == "" { targetRef = defaultRef } return targetRef } func (g *GitDriver) Clone(dir, url string) (string, error) { par, rep := filepath.Split(dir) cmd := exec.Command( "git", "clone", "--depth", "1", url, rep) cmd.Dir = par out, err := cmd.CombinedOutput() if err != nil { log.Printf("Failed to clone %s, see output below\n%sContinuing...", url, out) return "", err } return g.Pull(dir) } func (g *GitDriver) SpecialFiles() []string { return []string{ ".git", } } func (d *headBranchDetector) detectRef(dir string) string { output, err := run("git show remote info", dir, "git", "remote", "show", "origin", ) if err != nil { log.Printf( "error occured when fetching info to determine target ref in %s: %s. Will fall back to default ref %s", dir, err, defaultRef, ) return "" } matches := headBranchRegexp.FindStringSubmatch(output) if len(matches) != 2 { log.Printf( "could not determine target ref in %s. Will fall back to default ref %s", dir, defaultRef, ) return "" } return matches[1] }
# <API key>: true require "cases/helper" require "models/author" require "models/post" class SQLite3ExplainTest < ActiveRecord::SQLite3TestCase fixtures :authors def <API key> explain = Author.where(id: 1).explain assert_match %r(EXPLAIN for: SELECT "authors"\.\* FROM "authors" WHERE "authors"\."id" = (?:\? \[\["id", 1\]\]|1)), explain assert_match(/(SEARCH )?(TABLE )?authors USING (INTEGER )?PRIMARY KEY/, explain) end def <API key> explain = Author.where(id: 1).includes(:posts).explain assert_match %r(EXPLAIN for: SELECT "authors"\.\* FROM "authors" WHERE "authors"\."id" = (?:\? \[\["id", 1\]\]|1)), explain assert_match(/(SEARCH )?(TABLE )?authors USING (INTEGER )?PRIMARY KEY/, explain) assert_match %r(EXPLAIN for: SELECT "posts"\.\* FROM "posts" WHERE "posts"\."author_id" = (?:\? \[\["author_id", 1\]\]|1)), explain assert_match(/(SEARCH |(SCAN )?(TABLE ))posts/, explain) end end
<template name="newPalettes"> <div class="row"> <div class="col-lg-8"> {{> paletteList options}} </div> <div class="col-lg-4"> <p>This is the side bar</p> </div> </div> </template> <template name="bestPalettes"> <div class="row"> <div class="col-lg-8"> {{> paletteList options}} </div> <div class="col-lg-4"> <p>This is the side bar</p> </div> </div> </template> <template name="paletteList"> {{#each palettes}} {{> paletteItem}} {{/each}} {{#if palettesReady}} {{#unless allPalettesLoaded}} <a class="load-more" href="#">Load more</a> {{/unless}} {{else}} <div>{{> spinner}}</div> {{/if}} </template> <template name="paletteItem"> <div class="paletteBox"> <div class="vote"> <a href="#" class="upvote btn {{upvotedClass}}"><span class="glyphicon glyphicon-arrow-up"></span></a> </div> <div class="content"> <a href="{{pathFor 'palettePage' this}}"><h3>{{name}}</h3></a> <small>{{pluralize votes "Vote"}}, submitted by {{creator}}</small> | <small><a href="{{pathFor 'palettePage' this}}">{{pluralize commentsCount "comment"}}</a></small> | <small>{{#if ownPost}}<a href="{{pathFor 'paletteEdit' this}}">Edit</a>{{/if}}</small> <div class="swatches"> {{#each swatches}}<span style="background-color: {{this.hexString}}; height: 40px; display: inline-block; width: 30px; margin: 0; padding:0;"></span>{{/each}} </div> </div> </div> </template> <template name="paletteList-old"> <div class="palettes"> <div id="colorList"> <div class="row"> {{#each palettes}} {{> paletteItem}} {{/each}} </div> {{#if palettesReady}} {{#unless allPalettesLoaded}} <a class="load-more" href="#">Load more</a> {{/unless}} {{else}} <div>{{> spinner}}</div> {{/if}} </div> </div> </template> <template name="paletteItem-old"> <div class="col-sm-6 col-md-3"> <div class="palette"> {{#each swatches}}{{#with rgbValue}}<span style="background-color: rgb({{this.[0]}},{{this.[1]}},{{this.[2]}});" class="swatch"></span>{{/with}}{{/each}} </div> <div class="caption"> <a href="#" class="upvote btn {{upvotedClass}}"><span class="glyphicon glyphicon-arrow-up"></span></a> <p><a href="{{pathFor 'palettePage' this}}">{{name}}</a></p> <div class="palette-content"> <p>{{pluralize votes "Vote"}}, submitted by {{author}}</p> <a href="{{pathFor 'palettePage' this}}">{{pluralize commentsCount "comment"}}</a> {{#if ownPost}}<h4><a href="{{pathFor 'paletteEdit' this}}">Edit</a></h4>{{/if}} </div> </div> </div> </template>
<footer class="bs-docs-footer" role="contentinfo"> <div class="container"> <p>© 2016 Bushidian</p> </div> </footer>
# Acknowledgements This application makes use of the following third party libraries: ## SwiftyJSON The MIT License (MIT) Copyright (c) 2014 Ruoyu Fu 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. ## <API key> The MIT License (MIT) Copyright (c) 2013 tokorom 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. Generated by CocoaPods - http://cocoapods.org
<?php // autoload_real.php @generated by Composer class <API key> { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } <API key>(array('<API key>', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); <API key>(array('<API key>', 'loadClassLoader')); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('<API key>') || !<API key>()); if ($useStaticLoader) { require_once __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\<API key>::getInitializer($loader)); } else { $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); return $loader; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace LucyManager.MVC { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.<API key>(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
<?php if (! defined('BASEPATH')) { exit('No direct script access allowed'); } class Test_Controller extends MY_Controller { public function __construct() { parent::__construct(); } public function index() { print "<p>Hello World</p>"; } public function userError() { trigger_error("User Error", E_USER_ERROR); print "<p>Hello World</p>"; } public function userWarning() { trigger_error("User Warning", E_USER_WARNING); print "<p>Hello World</p>"; } public function userNotice() { trigger_error("User Notice", E_USER_NOTICE); print "<p>Hello World</p>"; } public function warning() { trigger_error("Warning", E_WARNING); print "<p>Hello World</p>"; } public function exception() { throw new Exception("Test exception"); } public function exceptionJson() { header("Content-Type: application/json"); throw new Exception("Test exception"); } public function dumpSession() { print '<pre>' . "Session Name: " . session_name() . "\n\n"; print_r($_SESSION); } public function info() { phpinfo(); } public function errorReporting() { $type = error_reporting(); $levels = array( 'E_ERROR' => (($type & E_ERROR) == E_ERROR), 'E_WARNING' => (($type & E_WARNING) == E_WARNING), 'E_PARSE' => (($type & E_PARSE) == E_PARSE), 'E_NOTICE' => (($type & E_NOTICE) == E_NOTICE), 'E_CORE_ERROR' => (($type & E_CORE_ERROR) == E_CORE_ERROR), 'E_CORE_WARNING' => (($type & E_CORE_WARNING) == E_CORE_WARNING), 'E_COMPILE_ERROR' => (($type & E_COMPILE_ERROR) == E_COMPILE_ERROR), 'E_COMPILE_WARNING' => (($type & E_COMPILE_WARNING) == E_COMPILE_WARNING), 'E_USER_ERROR' => (($type & E_USER_ERROR) == E_USER_ERROR), 'E_USER_WARNING' => (($type & E_USER_WARNING) == E_USER_WARNING), 'E_USER_NOTICE' => (($type & E_USER_NOTICE) == E_USER_NOTICE), 'E_STRICT' => (defined('E_STRICT') && (($type & E_STRICT) == E_STRICT)), 'E_RECOVERABLE_ERROR' => (defined( 'E_RECOVERABLE_ERROR' ) && (($type & E_RECOVERABLE_ERROR) == E_RECOVERABLE_ERROR)), 'E_DEPRECATED' => (defined('E_DEPRECATED') && (($type & E_DEPRECATED) == E_DEPRECATED)), 'E_USER_DEPRECATED' => (defined('E_USER_DEPRECATED') && (($type & E_USER_DEPRECATED) == E_USER_DEPRECATED)), 'E_ALL' => (($type & E_ALL) == E_ALL), ); print '<pre>'; print_r($levels); } public function passwordCost() { /** * This code will benchmark your server to determine how high of a cost you can * afford. You want to set the highest cost that you can without slowing down * you server too much. 10 is a good baseline, and more is good if your servers * are fast enough. */ $timeTarget = 0.2; $cost = 9; do { $cost++; $start = microtime(true); password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]); $end = microtime(true); } while (($end - $start) < $timeTarget); echo "Appropriate Cost Found: " . $cost . "\n"; } }
import { expect } from "chai"; import processor from "../../../src/core/monoProcessor"; describe("core/monoProcessor", () => { it("multiplies mono color by value", () => { const c = color({ mono: 40 }); processor.mul(c, 3); expect(c).to.eql(color({ mono: 120 })); }); it("adds a value to mono color", () => { const c = color({ mono: 25 }); processor.add(c, 20); expect(c).to.eql( color({ mono: 45 })); }); it("divides mono color by a value", () => { const c = color({ mono: 60 }); processor.div(c, 2); expect(c).to.eql(color({ mono: 30 })); }); it("inverts mono color", () => { const c = color({ mono: 5 }); processor.inverse(c); expect(c).to.eql({ r: 10, g: 20, b: 30, mono: 250 }); }); const color = ({ r = 10, g = 20, b = 30, mono = 40 }) => ({ r, g, b, mono }); });
require 'listen/compat/wrapper' module Listen module Compat module Test class Fake < Listen::Compat::Wrapper::Common def self.fire_events(thread, *args) processed = _processed(thread) processed.pop until processed.empty? _events(thread) << args processed.pop end def self.collect_instances(thread) return [] if _instances(thread).empty? result = [] result << _instances(thread).pop until _instances(thread).empty? result end attr_reader :directories def initialize thread = Thread.current thread[:fake_instances] = Queue.new thread[:fake_events] = Queue.new thread[:<API key>] = Queue.new Fake._instances(thread) << self end private def _start_and_wait(*args, &block) @directories = args[0..-2] loop do ev = Fake._events(Thread.current).pop block.call(*ev) Fake._processed(Thread.current) << ev end end def _stop end def self._processed(thread) thread[:<API key>] end def self._events(thread) thread[:fake_events] end def self._instances(thread) thread[:fake_instances] end end end end end
class Entry < ActiveRecord::Base audited belongs_to :stuff validates :stuff_id, :amount, presence: true after_save :update_stuff_amount scope :ordered, -> { order created_at: :desc } def update_stuff_amount stuff.update(amount: (stuff.amount + amount)) end end
layout: post category: notes title: "Logic and the flow of Control" author: elliott * Community engagement - Get started now! * Open Source contributions - now Extra Credit # TurtleHacks <! Nice use of Goto: <iframe src="https://trinket.io/embed/python/0304bd2b21" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Hello world! Doing this the hard way is a great way to learn: <iframe src="https://trinket.io/embed/python/deb914d084" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Simple but effective: <iframe src="https://trinket.io/embed/python/8764885c49" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Very well commented: <iframe src="https://trinket.io/embed/python/25e3de32dc" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Checkers! <iframe src="https://trinket.io/embed/python/582996e6a8" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Sup, robot? <iframe src="https://trinket.io/embed/python/0b6bd5bf80" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Great design: <iframe src="https://trinket.io/embed/python/99ab53d1b7" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Very creative: <iframe src="https://trinket.io/embed/python/609aa3b6cd" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Using some Functions, which we'll learn about soon: <iframe src="https://trinket.io/embed/python/17cdca3460" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Baking a custom cake: <iframe src="https://trinket.io/embed/python/27186f1f20" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> Preview of how our lives will get better: Using some loops! <iframe src="https://trinket.io/embed/python/9475228430" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> A place to celebrate your hacking... # Logistics Moving forward, you'll review and merge each others' work in class. Review, fix, and close issues assigned to you. We'll have some catch-up time where we can review any outstanding issues. Gittr chat. # Merging! With great power comes great responsibility * Never merge your own pull request * Never commit directly to the `gh-pages` branch ![Imgur](http://i.imgur.com/sEFqgU7.png) * Never merge broken or failing code # Review & Merge Posts Volunteer: Merging with Tommy Tester. * Reviewing PRs - comment on them directly * Merging - Your responsibility to make sure your partner's post works! Check that it shows up on our site * Assigning issues - already merged work with problems ~10 minutes reviewing & merging posts with a partner. # Discussion: Logic and the Flow of Control Boolean values are very simple but very powerful. There are tons of useful ways to construct **expressions** that evaluate to `True` or `False` in Python, and we use these to change the behavior of our program. Basic `if` statements act as 'gates' to control whether blocks of code get executed. `elif` and `else` statements enhance this control. # Logical Turtles code talks 3-4 student volunteers * Story of your approach * Your triumphs * Your despairs * Problem Solving attitudes and strategies # Functions & Refactoring for Next time Read up on functions and then use the power of custom functions to make your previous code more concise!
import Discord from 'discord.js' import generateHelp from './util/generateHelp' import runHooks from './util/runHooks' import runPlugins from './util/runPlugins' import getChannel from './util/getChannel' import getCommands from './util/getCommands' import messageHandler from './util/messageHandler' import filterTags from './util/filterTags' import config from '../config.json' const client = new Discord.Client(); client.on('ready', () => console.log('I am ready!') ) client.on('message', messageHandler .bind( null, config, getChannel .bind(null, config.channels), getCommands .bind(null, filterTags), generateHelp .bind(null, config, filterTags), runHooks, runPlugins .bind(null, config) ) ) client.login(config.token) export default client
<img class="left w40" src="w3school/great-wall.jpg" ng-show="page.currentSlide.index < 1" /> <ul class="left m4"> <li>Angular js == FRAMEWORK</li> <li>Router<div code="js;route.js" ng-show="page.currentSlide.index == 1"></div></li> <li>Resolve</li> <li>Promise</li> <li>Dependency injection</li> <li>Service / Factory / Provider</li> <li>Scope</li> <li>Filter</li> <li>Digest cycle</li> <li>..</li> </ul>
package com.gvalidate.utils; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; public class PropertyUtils { static Properties instance = getInstance(); private static final Logger logger = Logger.getLogger(PropertyUtils.class .getName()); private static Properties getInstance() { try { instance = new Properties(); instance.load(PropertyUtils.class.getClassLoader() .getResourceAsStream("g-validate.properties")); return instance; } catch (Exception e) { logger.log(Level.CONFIG, "Problem locating 'g-validate.properties' file. Please add the file on classpath."); } return instance; } public static String getProperty(String name) { try { return instance.getProperty(name).trim(); } catch (<API key> e) { logger.log(Level.INFO, "No entity found for "+name+" in g-validate.properties file."); } return null; } }
layout: default <article class="posts"> <h1>{{ page.title }}</h1> <div clsss="meta"> <span class="date"> {{ page.date | date: "%Y-%m-%d" }} </span> <ul class="tag"> {% for tag in page.tags %} <li> <a href="{{ site.url }}{{ site.baseurl }}/tags#{{ tag }}"> {{ tag }} </a> </li> {% endfor %} </ul> </div> <div class="entry"> {{ content }} </div> {% include disqus.html %} </article> <div class="pagination"> {% if page.previous.url %} <span class="prev" > <a href="{{ site.url }}{{ site.baseurl }}{{ page.previous.url }}"> ← {{page.previous.title}} </a> </span> {% endif %} {% if page.next.url %} <span class="next" > <a href="{{ site.url }}{{ site.baseurl }}{{ page.next.url }}"> {{page.next.title}} → </a> </span> {% endif %} </div>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; using ASF.Entities; namespace ASF.Services.Contracts.Responses { [DataContract] public class AllRatingResponse { [DataMember] public List<Rating> Result { get; set; } } }
import gpdraw.*; import java.awt.*; import java.util.Random; public class DrawHouse{ DrawingTool pen; SketchPad paper; Color randomColor; Color moonShine; int roofInc = 7; int bodyLength = 325; public DrawHouse(){ paper = new SketchPad(700, 700); pen = new DrawingTool(paper); Random rand = new Random(); randomColor = new Color((rand.nextInt(255)), (rand.nextInt(255)), (rand.nextInt(255))); moonShine = new Color(0xFEFCD7); pen.fillRect(700, 700); } public static void main (String [] args){ DrawHouse x = new DrawHouse(); x.drawBody(); x.drawRoof(); x.drawMoon(); } void drawBody(){ while(pen.getYPos() > -350){ pen.setDirection(180); sweepThruHouse(); pen.turnLeft(179); sweepThruHouse(); } pen.up(); pen.move(0,0); pen.setDirection(135); pen.down(); } void drawRoof(){ int counter = 0; for(int i = 0 ; i < 32 ; i++){ pen.forward(roofInc); pen.setDirection(270); while(pen.getYPos() > 0){ pen.forward(1); counter++; } pen.turnRight(180); while(counter > 0){ pen.forward(1); counter } pen.setDirection(135); } for(int i = 0; i < 34; i++){ pen.forward(roofInc); pen.setDirection(270); while(pen.getYPos() > 0){ pen.forward(1); counter++; } pen.turnLeft(180); while(counter > 0){ pen.forward(1); counter } pen.setDirection(225); } } void drawMoon(){ pen.up(); pen.setColor(moonShine); pen.move(175, 175); pen.down(); pen.fillCircle(100); pen.up(); pen.setColor(Color.black); pen.move(215, 195); pen.down(); pen.fillCircle(100); } void sweepThruHouse(){ for(int i = 0 ; i < bodyLength; i++){ if(//windows pen.getXPos() < -70 && pen.getXPos() > -140 && pen.getYPos() < -70 && pen.getYPos() > -140 || pen.getXPos() < -210 && pen.getXPos() > -280 && pen.getYPos() < -70 && pen.getYPos() > -140 || //door pen.getXPos() < -140 && pen.getXPos() > -210 && pen.getYPos() < -210){ pen.setColor(Color.black); pen.forward(1); }else{ pen.setColor(randomColor); pen.forward(1); } } } }
#!/usr/bin/env ruby # fri: access RI documentation through DRb require 'fastri/util' require 'fastri/full_text_index' default_local_mode = File.basename($0)[/^qri/] ? true : false # we bind to 127.0.0.1 by default, because otherwise Ruby will try with # 0.0.0.0, which results in a DNS request, adding way too much latency options = { :addr => "127.0.0.1", :format => case RUBY_PLATFORM when /win/ if /darwin|cygwin/ =~ RUBY_PLATFORM "ansi" else "plain" end else "ansi" end, :width => 72, :lookup_order => [ :exact, :exact_ci, :nested, :nested_ci, :partial, :partial_ci, :nested_partial, :nested_partial_ci, ], :show_matches => false, :do_full_text => false, :full_text_dir => File.join(FastRI::Util.find_home, ".fastri-fulltext"), :use_pager => nil, :pager => nil, :list_classes => nil, :list_methods => nil, :extended => false, :index_file => File.join(FastRI::Util.find_home, ".fastri-index"), :local_mode => default_local_mode, :do_second_guess => true } override_addr_env = false # only load optparse if actually needed # saves ~0.01-0.04s. if (arg = ARGV[0]) && arg[0, 1] == "-" or ARGV.empty? require 'optparse' optparser = OptionParser.new do |opts| opts.version = FastRI::FASTRI_VERSION opts.release = FastRI::FASTRI_RELEASE_DATE opts.banner = "Usage: #{File.basename($0)} [options] <query>" opts.on("-L", "--local", "Try to use local index instead of DRb service.", *[("(default)" if default_local_mode)].compact) do options[:local_mode] = true end opts.on("--index-file=FILE", "Use index file (forces --local mode).", "(default: #{options[:index_file]})") do |file| options[:index_file] = file options[:local_mode] = true end opts.on("-R", "--remote", "Use DRb service. #{'(default)' unless default_local_mode}") do options[:local_mode] = false end opts.on("-s", "--bind ADDR", "Bind to ADDR for incoming DRb connections.", "(default: 127.0.0.1)") do |addr| options[:addr] = addr override_addr_env = true end order_mapping = { 'e' => :exact, 'E' => :exact_ci, 'n' => :nested, 'N' => :nested_ci, 'p' => :partial, 'P' => :partial_ci, 'x' => :nested_partial, 'X' => :nested_partial_ci, 'a' => :anywhere, 'A' => :anywhere_ci, 'm' => :namespace_partial, 'M' => :<API key>, 'f' => :full_partial, 'F' => :full_partial_ci, } opts.on("-O", "--order ORDER", "Specify lookup order.", "(default: eEnNpPxX)", "Uppercase: case-indep.", "e:exact n:nested p:partial (completion)", "x:nested and partial m:complete namespace", "f:complete both class and method", "a:match method name anywhere") do |order| options[:lookup_order] = order.split(//).map{|x| order_mapping[x]}.compact end opts.on("-1", "--exact", "Does not do second guess(exact query).") do options[:do_second_guess] = false options[:lookup_order] = [ :exact ] end opts.on("-e", "--extended", "Show all methods for given namespace.") do options[:extended] = true options[:use_pager] = true options[:format] = "plain" end opts.on("--show-matches", "Only show matching entries."){ options[:show_matches] = true } opts.on("--classes", "List all known classes/modules.") do options[:use_pager] = true options[:list_classes] = true end opts.on("--methods", "List all known methods.") do options[:use_pager] = true options[:list_methods] = true end opts.on("-l", "--list-names", "List all known namespaces/methods.") do options[:use_pager] = true options[:list_classes] = true options[:list_methods] = true end opts.on("-S", "--full-text", "Perform full-text search.") do options[:do_full_text] = true options[:use_pager] = true if options[:use_pager].nil? options[:format] = "plain" end opts.on("-F", "--full-text-dir DIR", "Use full-text index in DIR", "(default: #{options[:full_text_dir]})") do |dir| options[:full_text_dir] = dir if dir options[:do_full_text] = true options[:use_pager] = true options[:format] = "plain" end opts.on("-f", "--format FMT", "Format to use when displaying output:", " ansi, plain (default: #{options[:format]})") do |format| options[:format] = format end opts.on("-P", "--[no-]pager", "Use pager.", "(default: don't)") do |usepager| options[:use_pager] = usepager options[:format] = "plain" if usepager end opts.on("-T", "Don't use a pager."){ options[:use_pager] = false } opts.on("--pager-cmd PAGER", "Use pager PAGER.", "(default: don't)") do |pager| options[:pager] = pager options[:use_pager] = true options[:format] = "plain" end opts.on("-w", "--width WIDTH", "Set the width of the output.") do |width| w = width.to_i options[:width] = w > 0 ? w : options[:width] end opts.on("-h", "--help", "Show this help message") do puts opts exit end end optparser.parse! if !options[:list_classes] && !options[:list_methods] && ARGV.empty? puts optparser exit end end # lazy optparse loading # {{{ try to find where the method comes from exactly include FastRI::Util::MagicHelp MAX_CONTEXT_LINES = 20 def context_wrap(text, width) "... " + text.gsub(/(.{1,#{width-4}})( +|$\n?)|(.{1,#{width-4}})/, "\\1\\3\n").chomp end def <API key>(results, gem_dir_info = FastRI::Util.<API key>, width = 78) return if results.empty? path = File.expand_path(results[0].path) gem_name, version, gem_path = FastRI::Util.gem_info_for_path(path, gem_dir_info) if gem_name rel_path = path[/#{Regexp.escape(gem_path)}\/(.*)/, 1] if rel_path entry_name = FastRI::Util.<API key>(rel_path) end puts "Found in #{gem_name} #{version} #{entry_name}" else rdoc_system_path = File.expand_path(RI::Paths::SYSDIR) if path.index(rdoc_system_path) rel_path = path[/#{Regexp.escape(rdoc_system_path)}\/(.*)/, 1] puts "Found in system #{FastRI::Util.<API key>(rel_path)}" else puts "Found in #{path}:" end end text = results.map do |result| context = result.context(120) from = (context.rindex("\n", context.index(result.query)) || -1) + 1 to = (context.index("\n", context.index(result.query)) || 0) - 1 context_wrap(context[from..to], width) end puts puts text.uniq[0...MAX_CONTEXT_LINES] puts end def <API key>(options) fulltext = File.join(options[:full_text_dir], "full_text.dat") suffixes = File.join(options[:full_text_dir], "suffixes.dat") begin index = FastRI::FullTextIndex.new_from_filenames(fulltext, suffixes) rescue Exception puts <<EOF Couldn't open the full-text index: #{fulltext} #{suffixes} The index needs to be rebuilt with fastri-server -B EOF exit(-1) end gem_dir_info = FastRI::Util.<API key> match_sets = ARGV.map do |query| result = index.lookup(query) if result index.next_matches(result) + [result] else [] end end path_map = Hash.new{|h,k| h[k] = []} match_sets.each{|matches| matches.each{|m| path_map[m.path] << m} } paths = match_sets[1..-1].inject(match_sets[0].map{|x| x.path}.uniq) do |s,x| s & x.map{|y| y.path}.uniq end if paths.empty? puts "nil" else puts "#{paths.size} hits" paths.sort_by{|path| 1.0 * -path_map[path].size / path_map[path].first.metadata[:size] ** 0.5}.map do |path| puts "=" * options[:width] puts 1.0 * path_map[path].size / path_map[path].first.metadata[:size] ** 0.5 <API key>(path_map[path], gem_dir_info, options[:width]) end end exit 0 end #{{{ set up pager if options[:use_pager] [options[:pager], ENV["PAGER"], "less", "more", "pager"].compact.uniq.each do |pager| begin $stdout = IO.popen(pager, "w") at_exit{ $stdout.close } break rescue Exception end end end #{{{ perform full text search if asked to <API key>(options) if options[:do_full_text] #{{{ normal query if options[:local_mode] require 'fastri/ri_service' ri_reader = open(options[:index_file], "rb"){|io| Marshal.load io } rescue nil unless ri_reader puts <<EOF Couldn't open the index: #{options[:index_file]} The index needs to be rebuilt with fastri-server -b EOF exit(-1) end service = FastRI::RiService.new(ri_reader) else # remote require 'rinda/ring' #{{{ determine the address to bind to if override_addr_env addr_spec = options[:addr] else addr_spec = ENV["FASTRI_ADDR"] || options[:addr] end ip = addr_spec[/^[^:]+/] || "127.0.0.1" port = addr_spec[/:(\d+)/, 1] || 0 addr = "druby://#{ip}:#{port}" #{{{ start DRb and perform request begin DRb.start_service(addr) ring_server = Rinda::RingFinger.primary rescue Exception $stderr.puts <<EOF Couldn't initialize DRb and locate the Ring server. Please make sure that: * the fastri-server is running, the server is bound to the correct interface, and the ACL setup allows connections from this host * fri is using the correct interface for incoming DRb requests: either set the FASTRI_ADDR environment variable, or use --bind ADDR, e.g export FASTRI_ADDR="192.168.1.12" fri Array EOF exit(-1) end service = ring_server.read([:name, :FastRI, nil, nil])[2] end info_options = { :formatter => options[:format], :width => options[:width], :lookup_order => options[:lookup_order], :extended => options[:extended], } # {{{ list classes or methods puts service.all_classes if options[:list_classes] puts service.all_methods if options[:list_methods] exit if options[:list_classes] || options[:list_methods] # {{{ normal query ARGV.each do |term| help_query = magic_help(term) if options[:show_matches] puts service.matches(help_query, info_options).sort else result = service.info(help_query, info_options) # second-guess the correct method type only as the last resort. if result puts result elsif options[:do_second_guess] and (new_query = FastRI::Util.<API key>(help_query)) != help_query puts service.info(new_query) else puts nil end end end # vi: set sw=2 expandtab:
"use strict"; var <API key> = require("@babel/runtime/helpers/<API key>"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = <API key>(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M6.7 18.29c.39.39 1.02.39 1.41 0L12 14.42l3.88 3.88c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L12.7 12.3a.9959.9959 0 0 0-1.41 0L6.7 16.88c-.39.39-.39 1.02 0 1.41z" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M6.7 11.7c.39.39 1.02.39 1.41 0L12 7.83l3.88 3.88c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L12.7 5.71a.9959.9959 0 0 0-1.41 0L6.7 10.29c-.39.39-.39 1.02 0 1.41z" }, "1")], '<API key>'); exports.default = _default;
# You Don't Know JS: ES6 & Beyond # Chapter 6: API Additions From conversions of values to mathematic calculations, ES6 adds many static properties and methods to various built-in natives and objects to help with common tasks. In addition, instances of some of the natives have new capabilities via various new prototype methods. **Note:** Most of these features can be faithfully polyfilled. We will not dive into such details here, but check out "ES6 Shim" (https://github.com/paulmillr/es6-shim/) for standards-compliant shims/polyfills. ## `Array` One of the most commonly extended features in JS by various user libraries is the Array type. It should be no surprise that ES6 adds a number of helpers to Array, both static and prototype (instance). `Array.of(..)` Static Function There's a well known gotcha with the `Array(..)` constructor, which is that if there's only one argument passed, and that argument is a number, instead of making an array of one element with that number value in it, it constructs an empty array with a `length` property equal to the number. This action produces the unfortunate and quirky "empty slots" behavior that's reviled about JS arrays. `Array.of(..)` replaces `Array(..)` as the preferred function-form constructor for arrays, because `Array.of(..)` does not have that special <API key> case. Consider: js var a = Array( 3 ); a.length; a[0]; // undefined var b = Array.of( 3 ); b.length; b[0]; var c = Array.of( 1, 2, 3 ); c.length; c; // [1,2,3] Under what circumstances would you want to use `Array.of(..)` instead of just creating an array with literal syntax, like `c = [1,2,3]`? There's two possible cases. If you have a callback that's supposed to wrap argument(s) passed to it in an array, `Array.of(..)` fits the bill perfectly. That's probably not terribly common, but it may scratch an itch for you. The other scenario is if you subclass `Array` (see "Classes" in Chapter 3) and want to be able to create and initialize elements in an instance of your subclass, such as: js class MyCoolArray extends Array { sum() { return this.reduce( function reducer(acc,curr){ return acc + curr; }, 0 ); } } var x = new MyCoolArray( 3 ); x.length; // 3 -- oops! x.sum(); // 0 -- oops! var y = [3]; // Array, not MyCoolArray y.length; y.sum(); // `sum` is not a function var z = MyCoolArray.of( 3 ); z.length; z.sum(); You can't just (easily) create a constructor for `MyCoolArray` that overrides the behavior of the `Array` parent constructor, because that constructor is necessary to actually create a well-behaving array value (initializing the `this`). The "inherited" static `of(..)` method on the `MyCoolArray` subclass provides a nice solution. `Array.from(..)` Static Function An "array-like object" in JavaScript is an object that has a `length` property on it, specifically with an integer value of zero or higher. These values have been notoriously frustrating to work with in JS; it's been quite common to need to transform them into an actual array, so that the various `Array.prototype` methods (`map(..)`, `indexOf(..)` etc.) are available to use with it. That process usually looks like: js // array-like object var arrLike = { length: 3, 0: "foo", 1: "bar" }; var arr = Array.prototype.slice.call( arrLike ); Another common task where `slice(..)` is often used is in duplicating a real array: js var arr2 = arr.slice(); In both cases, the new ES6 `Array.from(..)` method can be a more understandable and graceful -- if also less verbose -- approach: js var arr = Array.from( arrLike ); var arrCopy = Array.from( arr ); `Array.from(..)` looks to see if the first argument is an iterable (see "Iterators" in Chapter 3), and if so, it uses the iterator to produce values to "copy" into the returned array. Because real arrays have an iterator for those values, that iterator is automatically used. But if you pass an array-like object as the first argument to `Array.from(..)`, it behaves basically the same as `slice()` (no arguments!) or `apply(..)` does, which is that it simply loops over the value, accessing numerically named properties from `0` up to whatever the value of `length` is. Consider: js var arrLike = { length: 4, 2: "foo" }; Array.from( arrLike ); // [ undefined, undefined, "foo", undefined ] Because positions `0`, `1`, and `3` didn't exist on `arrLike`, the result was the `undefined` value for each of those slots. You could produce a similar outcome like this: js var emptySlotsArr = []; emptySlotsArr.length = 4; emptySlotsArr[2] = "foo"; Array.from( emptySlotsArr ); // [ undefined, undefined, "foo", undefined ] # Avoiding Empty Slots There's a subtle but important difference in the previous snippet between the `emptySlotsArr` and the result of the `Array.from(..)` call. `Array.from(..)` never produces empty slots. Prior to ES6, if you wanted to produce an array initialized to a certain length with actual `undefined` values in each slot (no empty slots!), you had to do extra work: js var a = Array( 4 ); // four empty slots! var b = Array.apply( null, { length: 4 } ); // four `undefined` values But `Array.from(..)` now makes this easier: js var c = Array.from( { length: 4 } ); // four `undefined` values **Warning:** Using an empty slot array like `a` in the previous snippets would work with some array functions, but others ignore empty slots (like `map(..)`, etc.). You should never intentionally work with empty slots, as it will almost certainly lead to strange/unpredictable behavior in your programs. # Mapping The `Array.from(..)` utility has another helpful trick up its sleeve. The second argument, if provided, is a mapping callback (almost the same as the regular `Array#map(..)` expects) which is called to map/transform each value from the source to the returned target. Consider: js var arrLike = { length: 4, 2: "foo" }; Array.from( arrLike, function mapper(val,idx){ if (typeof val == "string") { return val.toUpperCase(); } else { return idx; } } ); // [ 0, 1, "FOO", 3 ] **Note:** As with other array methods that take callbacks, `Array.from(..)` takes an optional third argument that if set will specify the `this` binding for the callback passed as the second argument. Otherwise, `this` will be `undefined`. See "TypedArrays" in Chapter 5 for an example of using `Array.from(..)` in translating values from an array of 8-bit values to an array of 16-bit values. Creating Arrays and Subtypes In the last couple of sections, we've discussed `Array.of(..)` and `Array.from(..)`, both of which create a new array in a similar way to a constructor. But what do they do in subclasses? Do they create instances of the base `Array` or the derived subclass? js class MyCoolArray extends Array { .. } Array.of( 1, 2 ) instanceof Array; // true Array.from( [1, 2] ) instanceof Array; // true MyCoolArray.of( 1, 2 ) instanceof Array; // false MyCoolArray.from( [1, 2] ) instanceof Array; // false MyCoolArray.of( 1, 2 ) instanceof MyCoolArray; // true MyCoolArray.from( [1, 2] ) instanceof MyCoolArray; // true Both `of(..)` and `from(..)` use the constructor that they're accessed from to construct the array. So if you use the base `Array.of(..)` you'll get an `Array` instance, but if you use `MyCoolArray.of(..)`, you'll get a `MyCoolArray` instance. In "Classes" in Chapter 3, we covered the `@@species` setting which all the built-in classes (like `Array`) have defined, which is used by any prototype methods if they create a new instance. `slice(..)` is a great example: js var x = new MyCoolArray( 1, 2, 3 ); x.slice( 1 ) instanceof MyCoolArray; // true Generally, that default behavior will probably be desired, but as we discussed in Chapter 3, you *can* override if you want: js class MyCoolArray extends Array { // force `species` to be parent constructor static get [Symbol.species]() { return Array; } } var x = new MyCoolArray( 1, 2, 3 ); x.slice( 1 ) instanceof MyCoolArray; // false x.slice( 1 ) instanceof Array; // true It's important to note that the `@@species` setting is only used for the prototype methods, like `slice(..)`. It's not used by `of(..)` and `from(..)`; they both just use the `this` binding (whatever constructor is used to make the reference). Consider: js class MyCoolArray extends Array { // force `species` to be parent constructor static get [Symbol.species]() { return Array; } } var x = new MyCoolArray( 1, 2, 3 ); x.slice( 1 ) instanceof Array; // true MyCoolArray.from( x ) instanceof Array; // false MyCoolArray.of( [2, 3] ) instanceof Array; // false MyCoolArray.from( x ) instanceof MyCoolArray; // true MyCoolArray.of( [2, 3] ) instanceof MyCoolArray; // true `copyWithin(..)` Prototype Method `Array#copyWithin(..)` is a new mutator method available to all arrays (including Typed Arrays; see Chapter 5). `copyWithin(..)` copies a portion of an array to another location in the same array, overwriting whatever was there before. The arguments are *target* (the index to copy to), *start* (the inclusive index to start the copying from), and optionally *end* (the exclusive index to stop copying). If any of the arguments are negative, they're taken to be relative from the end of the array. Consider: js [1,2,3,4,5].copyWithin( 3, 0 ); // [1,2,3,1,2] [1,2,3,4,5].copyWithin( 3, 0, 1 ); // [1,2,3,1,5] [1,2,3,4,5].copyWithin( 0, -2 ); // [4,5,3,4,5] [1,2,3,4,5].copyWithin( 0, -2, -1 ); // [4,2,3,4,5] The `copyWithin(..)` method does not extend the array's length, as the first example in the previous snippet shows. Copying simply stops when the end of the array is reached. Contrary to what you might think, the copying doesn't always go in left-to-right (ascending index) order. It's possible this would result in repeatedly copying an already copied value if the from and target ranges overlap, which is presumably not desired behavior. So internally, the algorithm avoids this case by copying in reverse order to avoid that gotcha. Consider: js [1,2,3,4,5].copyWithin( 2, 1 ); If the algorithm was strictly moving left to right, then the `2` should be copied to overwrite the `3`, then *that* copied `2` should be copied to overwrite `4`, then *that* copied `2` should be copied to overwrite `5`, and you'd end up with `[1,2,2,2,2]`. Instead, the copying algorithm reverses direction and copies `4` to overwrite `5`, then copies `3` to overwrite `4`, then copies `2` to overwrite `3`, and the final result is `[1,2,2,3,4]`. That's probably more "correct" in terms of expectation, but it can be confusing if you're only thinking about the copying algorithm in a naive left-to-right fashion. `fill(..)` Prototype Method Filling an existing array entirely (or partially) with a specified value is natively supported as of ES6 with the `Array#fill(..)` method: js var a = Array( 4 ).fill( undefined ); a; // [undefined,undefined,undefined,undefined] `fill(..)` optionally takes *start* and *end* parameters, which indicate a subset portion of the array to fill, such as: js var a = [ null, null, null, null ].fill( 42, 1, 3 ); a; // [null,42,42,null] `find(..)` Prototype Method The most common way to search for a value in an array has generally been the `indexOf(..)` method, which returns the index the value is found at or `-1` if not found: js var a = [1,2,3,4,5]; (a.indexOf( 3 ) != -1); // true (a.indexOf( 7 ) != -1); // false (a.indexOf( "2" ) != -1); // false The `indexOf(..)` comparison requires a strict `===` match, so a search for `"2"` fails to find a value of `2`, and vice versa. There's no way to override the matching algorithm for `indexOf(..)`. It's also unfortunate/ungraceful to have to make the manual comparison to the `-1` value. **Tip:** See the *Types & Grammar* title of this series for an interesting (and controversially confusing) technique to work around the `-1` ugliness with the `~` operator. Since ES5, the most common workaround to have control over the matching logic has been the `some(..)` method. It works by calling a function callback for each element, until one of those calls returns a `true`/truthy value, and then it stops. Because you get to define the callback function, you have full control over how a match is made: js var a = [1,2,3,4,5]; a.some( function matcher(v){ return v == "2"; } ); // true a.some( function matcher(v){ return v == 7; } ); // false But the downside to this approach is that you only get the `true`/`false` indicating if a suitably matched value was found, but not what the actual matched value was. ES6's `find(..)` addresses this. It works basically the same as `some(..)`, except that once the callback returns a `true`/truthy value, the actual array value is returned: js var a = [1,2,3,4,5]; a.find( function matcher(v){ return v == "2"; } ); a.find( function matcher(v){ return v == 7; // undefined }); Using a custom `matcher(..)` function also lets you match against complex values like objects: js var points = [ { x: 10, y: 20 }, { x: 20, y: 30 }, { x: 30, y: 40 }, { x: 40, y: 50 }, { x: 50, y: 60 } ]; points.find( function matcher(point) { return ( point.x % 3 == 0 && point.y % 4 == 0 ); } ); // { x: 30, y: 40 } **Note:** As with other array methods that take callbacks, `find(..)` takes an optional second argument that if set will specify the `this` binding for the callback passed as the first argument. Otherwise, `this` will be `undefined`. `findIndex(..)` Prototype Method While the previous section illustrates how `some(..)` yields a boolean result for a search of an array, and `find(..)` yields the matched value itself from the array search, there's also a need for finding the positional index of the matched value. `indexOf(..)` does that, but there's no control over its matching logic; it always uses `===` strict equality. So ES6's `findIndex(..)` is the answer: js var points = [ { x: 10, y: 20 }, { x: 20, y: 30 }, { x: 30, y: 40 }, { x: 40, y: 50 }, { x: 50, y: 60 } ]; points.findIndex( function matcher(point) { return ( point.x % 3 == 0 && point.y % 4 == 0 ); } ); points.findIndex( function matcher(point) { return ( point.x % 6 == 0 && point.y % 7 == 0 ); } ); Don't use `findIndex(..) != -1` (the way it's always been done with `indexOf(..)`) to get a boolean from the search, because `some(..)` already yields the `true`/`false` you want. And don't do `a[ a.findIndex(..) ]` to get the matched value, because that's what `find(..)` accomplishes. And finally, use `indexOf(..)` if you need the index of a strict match, or `findIndex(..)` if you need the index of a more customized match. **Note:** As with other array methods that take callbacks, `find(..)` takes an optional second argument that if set will specify the `this` binding for the callback passed as the first argument. Otherwise, `this` will be `undefined`. `entries()`, `values()`, `keys()` Prototype Methods In Chapter 3, we illustrated how data structures can provide a patterned item-by-item enumeration of their values, via an iterator. We then expounded on this approach in Chapter 5, as we explored how the new ES6 collections (Map, Set, etc.) provide several methods for producing different kinds of iterations. Because it's not new to ES6, `Array` might not be thought of traditionally as a "collection," but it is one in the sense that it provides these same iterator methods: `entries()`, `values()`, and `keys()`. Consider: js var a = [1,2,3]; [...a.values()]; // [1,2,3] [...a.keys()]; // [0,1,2] [...a.entries()]; // [ [0,1], [1,2], [2,3] ] [...a[Symbol.iterator]()]; // [1,2,3] Just like with `Set`, the default `Array` iterator is the same as what `values()` returns. In "Avoiding Empty Slots" earlier in this chapter, we illustrated how `Array.from(..)` treats empty slots in an array as just being present slots with `undefined` in them. That's actually because under the covers, the array iterators behave that way: js var a = []; a.length = 3; a[1] = 2; [...a.values()]; // [undefined,2,undefined] [...a.keys()]; // [0,1,2] [...a.entries()]; // [ [0,undefined], [1,2], [2,undefined] ] ## `Object` A few additional static helpers have been added to `Object`. Traditionally, functions of this sort have been seen as focused on the behaviors/capabilities of object values. However, starting with ES6, `Object` static functions will also be for general-purpose global APIs of any sort that don't already belong more naturally in some other location (i.e., `Array.from(..)`). `Object.is(..)` Static Function The `Object.is(..)` static function makes value comparisons in an even more strict fashion than the `===` comparison. `Object.is(..)` invokes the underlying `SameValue` algorithm (ES6 spec, section 7.2.9). The `SameValue` algorithm is basically the same as the `===` Strict Equality Comparison Algorithm (ES6 spec, section 7.2.13), with two important exceptions. Consider: js var x = NaN, y = 0, z = -0; x === x; // false y === z; // true Object.is( x, x ); // true Object.is( y, z ); // false You should continue to use `===` for strict equality comparisons; `Object.is(..)` shouldn't be thought of as a replacement for the operator. However, in cases where you're trying to strictly identify a `NaN` or `-0` value, `Object.is(..)` is now the preferred option. **Note:** ES6 also adds a `Number.isNaN(..)` utility (discussed later in this chapter) which may be a slightly more convenient test; you may prefer `Number.isNaN(x)` over `Object.is(x,NaN)`. You *can* accurately test for `-0` with a clumsy `x == 0 && 1 / x === -Infinity`, but in this case `Object.is(x,-0)` is much better. `Object.<API key>(..)` Static Function The "Symbols" section in Chapter 2 discusses the new Symbol primitive value type in ES6. Symbols are likely going to be mostly used as special (meta) properties on objects. So the `Object.<API key>(..)` utility was introduced, which retrieves only the symbol properties directly on an object: js var o = { foo: 42, [ Symbol( "bar" ) ]: "hello world", baz: true }; Object.<API key>( o ); // [ Symbol(bar) ] `Object.setPrototypeOf(..)` Static Function Also in Chapter 2, we mentioned the `Object.setPrototypeOf(..)` utility, which (unsurprisingly) sets the `[[Prototype]]` of an object for the purposes of *behavior delegation* (see the *this & Object Prototypes* title of this series). Consider: js var o1 = { foo() { console.log( "foo" ); } }; var o2 = { // .. o2's definition .. }; Object.setPrototypeOf( o2, o1 ); // delegates to `o1.foo()` o2.foo(); // foo Alternatively: js var o1 = { foo() { console.log( "foo" ); } }; var o2 = Object.setPrototypeOf( { // .. o2's definition .. }, o1 ); // delegates to `o1.foo()` o2.foo(); // foo In both previous snippets, the relationship between `o2` and `o1` appears at the end of the `o2` definition. More commonly, the relationship between an `o2` and `o1` is specified at the top of the `o2` definition, as it is with classes, and also with `__proto__` in object literals (see "Setting `[[Prototype]]`" in Chapter 2). **Warning:** Setting a `[[Prototype]]` right after object creation is reasonable, as shown. But changing it much later is generally not a good idea and will usually lead to more confusion than clarity. `Object.assign(..)` Static Function Many JavaScript libraries/frameworks provide utilities for copying/mixing one object's properties into another (e.g., jQuery's `extend(..)`). There are various nuanced differences between these different utilities, such as whether a property with value `undefined` is ignored or not. ES6 adds `Object.assign(..)`, which is a simplified version of these algorithms. The first argument is the *target*, and any other arguments passed are the *sources*, which will be processed in listed order. For each source, its enumerable and own (e.g., not "inherited") keys, including symbols, are copied as if by plain `=` assignment. `Object.assign(..)` returns the target object. Consider this object setup: js var target = {}, o1 = { a: 1 }, o2 = { b: 2 }, o3 = { c: 3 }, o4 = { d: 4 }; // setup read-only property Object.defineProperty( o3, "e", { value: 5, enumerable: true, writable: false, configurable: false } ); // setup non-enumerable property Object.defineProperty( o3, "f", { value: 6, enumerable: false } ); o3[ Symbol( "g" ) ] = 7; // setup non-enumerable symbol Object.defineProperty( o3, Symbol( "h" ), { value: 8, enumerable: false } ); Object.setPrototypeOf( o3, o4 ); Only the properties `a`, `b`, `c`, `e`, and `Symbol("g")` will be copied to `target`: js Object.assign( target, o1, o2, o3 ); target.a; target.b; target.c; Object.<API key>( target, "e" ); // { value: 5, writable: true, enumerable: true, // configurable: true } Object.<API key>( target ); // [Symbol("g")] The `d`, `f`, and `Symbol("h")` properties are omitted from copying; non-enumerable properties and non-owned properties are all excluded from the assignment. Also, `e` is copied as a normal property assignment, not duplicated as a read-only property. In an earlier section, we showed using `setPrototypeOf(..)` to set up a `[[Prototype]]` relationship between an `o2` and `o1` object. There's another form that leverages `Object.assign(..)`: js var o1 = { foo() { console.log( "foo" ); } }; var o2 = Object.assign( Object.create( o1 ), { // .. o2's definition .. } ); // delegates to `o1.foo()` o2.foo(); // foo **Note:** `Object.create(..)` is the ES5 standard utility that creates an empty object that is `[[Prototype]]`-linked. See the *this & Object Prototypes* title of this series for more information. ## `Math` ES6 adds several new mathematic utilities that fill in holes or aid with common operations. All of these can be manually calculated, but most of them are now defined natively so that in some cases the JS engine can either more optimally perform the calculations, or perform them with better decimal precision than their manual counterparts. It's likely that asm.js/transpiled JS code (see the *Async & Performance* title of this series) is the more likely consumer of many of these utilities rather than direct developers. Trigonometry: * `cosh(..)` - Hyperbolic cosine * `acosh(..)` - Hyperbolic arccosine * `sinh(..)` - Hyperbolic sine * `asinh(..)` - Hyperbolic arcsine * `tanh(..)` - Hyperbolic tangent * `atanh(..)` - Hyperbolic arctangent * `hypot(..)` - The squareroot of the sum of the squares (i.e., the generalized Pythagorean theorem) Arithmetic: * `cbrt(..)` - Cube root * `clz32(..)` - Count leading zeros in 32-bit binary representation * `expm1(..)` - The same as `exp(x) - 1` * `log2(..)` - Binary logarithm (log base 2) * `log10(..)` - Log base 10 * `log1p(..)` - The same as `log(x + 1)` * `imul(..)` - 32-bit integer multiplication of two numbers Meta: * `sign(..)` - Returns the sign of the number * `trunc(..)` - Returns only the integer part of a number * `fround(..)` - Rounds to nearest 32-bit (single precision) floating-point value ## `Number` Importantly, for your program to properly work, it must accurately handle numbers. ES6 adds some additional properties and functions to assist with common numeric operations. Two additions to `Number` are just references to the preexisting globals: `Number.parseInt(..)` and `Number.parseFloat(..)`. Static Properties ES6 adds some helpful numeric constants as static properties: * `Number.EPSILON` - The minimum value between any two numbers: `2^-52` (see Chapter 2 of the *Types & Grammar* title of this series regarding using this value as a tolerance for imprecision in floating-point arithmetic) * `Number.MAX_SAFE_INTEGER` - The highest integer that can "safely" be represented unambiguously in a JS number value: `2^53 - 1` * `Number.MIN_SAFE_INTEGER` - The lowest integer that can "safely" be represented unambiguously in a JS number value: `-(2^53 - 1)` or `(-2)^53 + 1`. **Note:** See Chapter 2 of the *Types & Grammar* title of this series for more information about "safe" integers. `Number.isNaN(..)` Static Function The standard global `isNaN(..)` utility has been broken since its inception, in that it returns `true` for things that are not numbers, not just for the actual `NaN` value, because it coerces the argument to a number type (which can falsely result in a NaN). ES6 adds a fixed utility `Number.isNaN(..)` that works as it should: js var a = NaN, b = "NaN", c = 42; isNaN( a ); // true isNaN( b ); // true -- oops! isNaN( c ); // false Number.isNaN( a ); // true Number.isNaN( b ); // false -- fixed! Number.isNaN( c ); // false `Number.isFinite(..)` Static Function There's a temptation to look at a function name like `isFinite(..)` and assume it's simply "not infinite". That's not quite correct, though. There's more nuance to this new ES6 utility. Consider: js var a = NaN, b = Infinity, c = 42; Number.isFinite( a ); // false Number.isFinite( b ); // false Number.isFinite( c ); // true The standard global `isFinite(..)` coerces its argument, but `Number.isFinite(..)` omits the coercive behavior: js var a = "42"; isFinite( a ); // true Number.isFinite( a ); // false You may still prefer the coercion, in which case using the global `isFinite(..)` is a valid choice. Alternatively, and perhaps more sensibly, you can use `Number.isFinite(+x)`, which explicitly coerces `x` to a number before passing it in (see Chapter 4 of the *Types & Grammar* title of this series). Integer-Related Static Functions JavaScript number valuess are always floating point (IEE-754). So the notion of determining if a number is an "integer" is not about checking its type, because JS makes no such distinction. Instead, you need to check if there's any non-zero decimal portion of the value. The easiest way to do that has commonly been: js x === Math.floor( x ); ES6 adds a `Number.isInteger(..)` helper utility that potentially can determine this quality slightly more efficiently: js Number.isInteger( 4 ); // true Number.isInteger( 4.2 ); // false **Note:** In JavaScript, there's no difference between `4`, `4.`, `4.0`, or `4.0000`. All of these would be considered an "integer", and would thus yield `true` from `Number.isInteger(..)`. In addition, `Number.isInteger(..)` filters out some clearly not-integer values that `x === Math.floor(x)` could potentially mix up: js Number.isInteger( NaN ); // false Number.isInteger( Infinity ); // false Working with "integers" is sometimes an important bit of information, as it can simplify certain kinds of algorithms. JS code by itself will not run faster just from filtering for only integers, but there are optimization techniques the engine can take (e.g., asm.js) when only integers are being used. Because of `Number.isInteger(..)`'s handling of `NaN` and `Infinity` values, defining a `isFloat(..)` utility would not be just as simple as `!Number.isInteger(..)`. You'd need to do something like: js function isFloat(x) { return Number.isFinite( x ) && !Number.isInteger( x ); } isFloat( 4.2 ); // true isFloat( 4 ); // false isFloat( NaN ); // false isFloat( Infinity ); // false **Note:** It may seem strange, but Infinity should neither be considered an integer nor a float. ES6 also defines a `Number.isSafeInteger(..)` utility, which checks to make sure the value is both an integer and within the range of `Number.MIN_SAFE_INTEGER`-`Number.MAX_SAFE_INTEGER` (inclusive). js var x = Math.pow( 2, 53 ), y = Math.pow( -2, 53 ); Number.isSafeInteger( x - 1 ); // true Number.isSafeInteger( y + 1 ); // true Number.isSafeInteger( x ); // false Number.isSafeInteger( y ); // false ## `String` Strings already have quite a few helpers prior to ES6, but even more have been added to the mix. Unicode Functions "Unicode-Aware String Operations" in Chapter 2 discusses `String.fromCodePoint(..)`, `String#codePointAt(..)`, and `String#normalize(..)` in detail. They have been added to improve Unicode support in JS string values. js String.fromCodePoint( 0x1d49e ); "abd".codePointAt( 2 ).toString( 16 ); // "1d49e" The `normalize(..)` string prototype method is used to perform Unicode normalizations that either combine characters with adjacent "combining marks" or decompose combined characters. Generally, the normalization won't create a visible effect on the contents of the string, but will change the contents of the string, which can affect how things like the `length` property are reported, as well as how character access by position behave: js var s1 = "e\u0301"; s1.length; var s2 = s1.normalize(); s2.length; s2 === "\xE9"; // true `normalize(..)` takes an optional argument that specifies the normalization form to use. This argument must be one of the following four values: `"NFC"` (default), `"NFD"`, `"NFKC"`, or `"NFKD"`. **Note:** Normalization forms and their effects on strings is well beyond the scope of what we'll discuss here. See "Unicode Normalization Forms" (http: `String.raw(..)` Static Function The `String.raw(..)` utility is provided as a built-in tag function to use with template string literals (see Chapter 2) for obtaining the raw string value without any processing of escape sequences. This function will almost never be called manually, but will be used with tagged template literals: js var str = "bc"; String.raw`\ta${str}d\xE9`; In the resultant string, `\` and `t` are separate raw characters, not the one escape sequence character `\t`. The same is true with the Unicode escape sequence. `repeat(..)` Prototype Function In languages like Python and Ruby, you can repeat a string as: js "foo" * 3; // "foofoofoo" That doesn't work in JS, because `*` multiplication is only defined for numbers, and thus `"foo"` coerces to the `NaN` number. However, ES6 defines a string prototype method `repeat(..)` to accomplish the task: js "foo".repeat( 3 ); // "foofoofoo" String Inspection Functions In addition to `String#indexOf(..)` and `String#lastIndexOf(..)` from prior to ES6, three new methods for searching/inspection have been added: `startsWith(..)`, `endsWidth(..)`, and `includes(..)`. js var palindrome = "step on no pets"; palindrome.startsWith( "step on" ); // true palindrome.startsWith( "on", 5 ); // true palindrome.endsWith( "no pets" ); // true palindrome.endsWith( "no", 10 ); // true palindrome.includes( "on" ); // true palindrome.includes( "on", 6 ); // false For all the string search/inspection methods, if you look for an empty string `""`, it will either be found at the beginning or the end of the string. **Warning:** These methods will not by default accept a regular expression for the search string. See "Regular Expression Symbols" in Chapter 7 for information about disabling the `isRegExp` check that is performed on this first argument. ## Review ES6 adds many extra API helpers on the various built-in native objects: * `Array` adds `of(..)` and `from(..)` static functions, as well as prototype functions like `copyWithin(..)` and `fill(..)`. * `Object` adds static functions like `is(..)` and `assign(..)`. * `Math` adds static functions like `acosh(..)` and `clz32(..)`. * `Number` adds static properties like `Number.EPSILON`, as well as static functions like `Number.isFinite(..)`. * `String` adds static functions like `String.fromCodePoint(..)` and `String.raw(..)`, as well as prototype functions like `repeat(..)` and `includes(..)`. Most of these additions can be polyfilled (see ES6 Shim), and were inspired by utilities in common JS libraries/frameworks.
<!DOCTYPE html> <!--[if IEMobile 7 ]> <html class="no-js iem7"> <![endif]--> <!--[if (gt IEMobile 7)|!(IEMobile)]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <title>Paint Code</title> <meta name="description" content=""> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"> <!-- Cleartype for Windows Phone - uncomment below 1 line to apply--> <!--<meta http-equiv="cleartype" content="on">--> <link rel="<API key>" sizes="144x144" href="images/touch/<API key>.png"> <link rel="<API key>" sizes="114x114" href="images/touch/<API key>.png"> <link rel="<API key>" sizes="72x72" href="images/touch/<API key>.png"> <link rel="<API key>" href="images/touch/<API key>.png"> <link rel="shortcut icon" href="images/touch/apple-touch-icon.png"> <!-- Tile icon for Win8 (144x144 + tile color) - uncomment below 2 lines to apply--> <!--<meta name="<API key>" content="images/touch/<API key>.png">--> <!--<meta name="<API key>" content="#222222">--> <! <meta name="<API key>" content="yes"> <meta name="<API key>" content="black"> <meta name="<API key>" content=""> <! <script>(function(a,b,c){if(c in b&&b[c]){var d,e=a.location,f=/^(a|html)$/i;a.addEventListener("click",function(a){d=a.target;while(!f.test(d.nodeName))d=d.parentNode;"href"in d&&(d.href.indexOf("http")||~d.href.indexOf(e.host))&&(a.preventDefault(),e.href=d.href)},!1)}})(document,window.navigator,"standalone")</script> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:100,200,300,400' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Josefin+Sans:100,300' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="css/normalize.css"> <!--<link rel="stylesheet" href="css/jquery.mobile-1.2.0.min.css">--> <link rel="stylesheet" href="css/jquery.mobile.structure-1.2.0.min.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script> <link rel="stylesheet" href="css/flexslider.css"> <link rel="stylesheet" href="css/photoswipe/photoswipe.css"> <!-- change rel to rel="stylesheet/less" if you are using main-less.css file --> <link rel="stylesheet" href="css/main.css"> <script src="js/less-1.3.3.min.js"></script> <!--<script src="js/vendor/zepto.min.js"></script>--> <script src="js/jquery-1.8.2.min.js"></script> <script src="js/jquery.mobile-1.2.0.min.js"></script> <script src="js/helper.js"></script> <script src="js/jquery.flexslider-min.js"></script> <script src="js/photoswipe/klass.min.js"></script> <script src="js/photoswipe/code.photoswipe.jquery-3.0.5.min.js"></script> <script src="js/jquery.easyListSplitter.js"></script> <script src="http://maps.google.com/maps/api/js?sensor=false"></script> <script src="js/forms.js"></script> <script src="js/main.js"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> var _gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]]; (function(d,t){var g=d.createElement(t),s=d.<API key>(t)[0];g.async=1; g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js"; s.parentNode.insertBefore(g,s)}(document,"script")); </script> </head> <body class="my-body"> <!-- Add your site or application content here --> <div id="home-page" class="page dark-page" data-theme="a" data-role="page"> <div class="black-overlay"></div> <div id="header" data-role="header"> <div class="margpage"> <a href="info.html" data-role="none" data-transition="slideup" class="top-button left">i</a> <p></p><p></p><p></p><p></p><p></p><p></p><h1>Paint Code</h1> <h2>Ellis Color Supply, Inc.</h2> </div> </div><p></p> <div class="ui-body padpage"> <div class="menu"> <ul class="child-left"> <li> <a href="GM.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="GM"> <span>GM</span> </a> </li> <li> <a href="chrysler.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="chrysler"> <span>Chrysler</span> </a> </li> <li> <a href="ford.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="ford"> <span>Ford</span> </a> </li> <li> <a href="hyundai.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="hyundai"> <span>Hyundai</span> </a> </li> <li> <a href="nissan.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="nissan"> <span>Nissan</span> </a> </li> <li> <a href="izuzu.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="izuzu"> <span>Izuzu</span> </a> </li> <li> <a href="kia.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="kia"> <span>Kia</span> </a> </li> <li> <a href="mazda.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="mazda"> <span>Mazda</span> </a> </li> <li> <a href="toyota.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="toyota"> <span>Toyota</span> </a> </li> <li> <a href="volvo.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="volvo"> <span>Volvo</span> </a> </li> <li> <a href="mercedes.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="mercedes"> <span>Mercedes</span> </a> </li> <li> <a href="mitsubishi.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="Mitsubishi"> <span>Mitsubishi</span> </a> </li> <li> <a href="Porsche.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="Porsche"> <span>Porsche</span> </a> </li> <li> <a href="saab.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="Saab"> <span>Saab</span> </a> </li> <li> <a href="Subaru.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="Subaru"> <span>Subaru</span> </a> </li> <li> <a href="Suzuki.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="Suzuki"> <span>Suzuki</span> </a> </li> <li> <a href="Honda.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="honda"> <span>Honda</span> </a> </li> <li> <a href="Volkswagen.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="Volkswagen"> <span>Volkswagen</span> </a> </li> <li> <a href="BMW.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="bmw"> <span>BMW</span> </a> </li> <li> <a href="jaguar.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="jaguar"> <span>Jaguar</span> </a> </li> <li> <a href="lamborghini.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="lamborghini"> <span>Lamborghini</span> </a> </li> <li> <a href="landrover.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="landrover"> <span>Land Rover</span> </a> </li> <li> <a href="daewoo.html" class="menu-item"> <img src="images/home-icons/app icon1.jpg" alt="daewoo"> <span>Daewoo</span> </a> </li> </ul> </div> </div> <div id="footer" data-role="footer"> <div class="padpage group"> <div class="social left "> <ul class="child-left"> <li> <a href="https://twitter.com/elliscolorinc" class="twitter" title="Follow us on Twitter"><img src="images/social/icon-twitter-black.png" alt="twitter"></a> </li> <li> <a href="https: <li> <a href="https: </ul> </div> <div class="slogan right"> We match color so you can paint... </div> </div> </div> </div> </body> </html>
A = [[0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 1, 0], [1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0]] def Distancias(n, origem): d = [-1] * n d[origem] = 0 f = [] f.append(origem) while len(f) > 0: x = f[0] del f[0] for y in range(n): if A[x][y] == 1 and d[y] == -1: d[y] = d[x] + 1 print (y) f.append(y) return d print (Distancias(6, 3))
layout: post title: "Final Project" subtitle: "Music Tastes Analysis" date: 2017-03-22 12:00:00 author: "Cindy Lai" header-img: "img/music.jpg" ## Can you extract cultural trends from the top music hits? I worked with Colin Santos and Kavi Tan to analyze the top musical trends from 1958 to 2015 using the songs from the Billboard charts. The process includes web scraping, calls to the Spotify API, natural language processing, and visualization. You can view our analysis [on this site](https://jiahtan.github.io/STA141B/).
package org.openapitools.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import javax.validation.constraints.*; import javax.validation.Valid; /** * <API key> */ @JsonPropertyOrder({ <API key>.JSON_PROPERTY_ADMIN, <API key>.JSON_PROPERTY_PUSH, <API key>.JSON_PROPERTY_PULL, <API key>.<API key> }) @javax.annotation.Generated(value = "org.openapitools.codegen.languages.<API key>", date = "2022-02-13T02:21:04.175010Z[Etc/UTC]") public class <API key> { public static final String JSON_PROPERTY_ADMIN = "admin"; @JsonProperty(JSON_PROPERTY_ADMIN) private Boolean admin; public static final String JSON_PROPERTY_PUSH = "push"; @JsonProperty(JSON_PROPERTY_PUSH) private Boolean push; public static final String JSON_PROPERTY_PULL = "pull"; @JsonProperty(JSON_PROPERTY_PULL) private Boolean pull; public static final String <API key> = "_class"; @JsonProperty(<API key>) private String propertyClass; public <API key> admin(Boolean admin) { this.admin = admin; return this; } /** * Get admin * @return admin **/ @JsonProperty(value = "admin") @ApiModelProperty(value = "") public Boolean getAdmin() { return admin; } public void setAdmin(Boolean admin) { this.admin = admin; } public <API key> push(Boolean push) { this.push = push; return this; } /** * Get push * @return push **/ @JsonProperty(value = "push") @ApiModelProperty(value = "") public Boolean getPush() { return push; } public void setPush(Boolean push) { this.push = push; } public <API key> pull(Boolean pull) { this.pull = pull; return this; } /** * Get pull * @return pull **/ @JsonProperty(value = "pull") @ApiModelProperty(value = "") public Boolean getPull() { return pull; } public void setPull(Boolean pull) { this.pull = pull; } public <API key> propertyClass(String propertyClass) { this.propertyClass = propertyClass; return this; } /** * Get propertyClass * @return propertyClass **/ @JsonProperty(value = "_class") @ApiModelProperty(value = "") public String getPropertyClass() { return propertyClass; } public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } <API key> <API key> = (<API key>) o; return Objects.equals(this.admin, <API key>.admin) && Objects.equals(this.push, <API key>.push) && Objects.equals(this.pull, <API key>.pull) && Objects.equals(this.propertyClass, <API key>.propertyClass); } @Override public int hashCode() { return Objects.hash(admin, push, pull, propertyClass); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class <API key> {\n"); sb.append(" admin: ").append(toIndentedString(admin)).append("\n"); sb.append(" push: ").append(toIndentedString(push)).append("\n"); sb.append(" pull: ").append(toIndentedString(pull)).append("\n"); sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.nucc.hackwinds.listeners; public interface <API key> { void forecastDataUpdated(); void <API key>(); }
<?php namespace Saft\Sparql\Query; interface Query { /** * @return string */ public function getQuery(); /** * @return array */ public function getQueryParts(); /** * Is instance of AskQuery? * * @return bool */ public function isAskQuery(); /** * Is instance of ConstructQuery? * * @return bool */ public function isConstructQuery(); /** * Is instance of DescribeQuery? * * @return bool */ public function isDescribeQuery(); /** * Is instance of GraphQuery? * * @return bool */ public function isGraphQuery(); /** * Is instance of SelectQuery? * * @return bool */ public function isSelectQuery(); /** * Is instance of UpdateQuery? * * @return bool */ public function isUpdateQuery(); }
# Chat-Project ## Installation and Setup To install make sure a postgres db is running at localhost. Port and db name must be specified in .bashrc or added to the compile.sh Enviroment variables names need to be `$PGPORT` and `$DB_NAME` Create and populate it the database run create_db.sh in `project/sql/scripts/` Make sure all your .csv files are located in your `$PGDATA` path. Start the messaging application by running compile.sh in `project/java/scripts/` ## Special Features * Customized Welcome screen Main menu will display users login name. * Screen clears inbetween selects to improve the User's experience. After most of the menu options the screen is cleared to keep the UI cleaner than if things kept printing to the console. Some menu options had to have a WaitForKey(); integrated into the menu option so the user can still see the output of his option. * Option to connect to an Amazon RDS, the compile.sh has a commented out section for this. The commented sectoin of the compile.sh will set a different hostname, port, user, password and different JDBC library. The different JDBC driver was required as the server is Postgres version 9.14 which is incompatible with the 8.13 one found on well. * Listing contacts includes the phone number Now when you list all of your chats you will also be shown the users phone number for ease of access. * A user cannot message people who have them on their blocked list * When creating a chat we list all of your contacts for easier usage. * Users can edit their status to share with all of their contacts * Several indexes are present to enhance the speed of the database queries\ * the chat id is indexed because it is used in multiple joins * the login name is also indexed because the database scans through the user table hashes for the unique login name * the list id is indexed becuase the list id is constantly being looked for * Hashing is used for indexing because there are no inequality searches (there are only equality searches) ## Usage After running compile.sh you can either create a user or login as an existing user. Once logged in you are personally welcomed to a variety options: Menu option 1-3 These menu items can be used to view and modify your contact list. Your contact list give you an easy way add users when creating a chat Menu option 4-6 These menu items can be used to view and modify your blocked list. Users that are blocked can not add you to their contacts and they cannot send you messages Menu option 7 Will go into a submenu that can be used to view your chats Menu option 8 Will ask for users to add to a new chat. Menu option 9 Will delete all of your accounts information. ## Problems Using postgers on well is very annoying to set up every time, Solutions to this include setting the `$PG_DATA` path to the directory you have your data in. It is also possible to set the static paths in the `load_data.sql` as seen in `load_data_rds.sql`. We ended up trying to use an Amazon RDS to keep all of the data loaded into the database and allow easier usage of concurrent users. The version diffences between the RDS (Postgres 9.14) and Well (Postgre 8.1.23) caused some issues as we developed for RDS and Postgres 9.14, eventually we had to change some of the queries are remove the `RETURN` clause to allow use with Well and the older version of Postgres The UI menu needs to be addressed, and contact list should have a submenu as well as blocked list. The create chat option should be in the submenu for viewing and managing chats. ## Authors Mark Asfour Queries (view blocked list, add to contacts, delete contact and block, add users to chat, delete user account, delete message, add message), edited create_tables.sql, created indexes Mehran Ghamaty UI menus (clear screen, personalized welcome, submenus for specific queries), view chat reply to chat, made lsit chats have status + phonenumber, set up database, RDS ## Bugs Phone number is not validated.
MIT License Copyright (c) 2017 Tim Beaudet 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.
from .base import FunctionalTest class ItemValidationTest(FunctionalTest): def get_error_element(self): return self.browser.<API key>('.has-error') def <API key>(self): # Edith goes to the home page and accidentally tries to submit # an empty list item. She hits Enter on the empty input box self.browser.get(self.server_url) self.get_item_input_box().send_keys('\n') # The home page refreshes, and there is an error message saying # that list items cannot be blank error = self.get_error_element() self.assertEqual(error.text, "You can't have an empty list item") # She tries again with some text for the item, which now works self.get_item_input_box().send_keys('Buy milk\n') self.<API key>('1: Buy milk') # Perversely, she now decides to submit a second blank list item self.get_item_input_box().send_keys('\n') # She receives a similar warning on the list page self.<API key>('1: Buy milk') error = self.get_error_element() self.assertEqual(error.text, "You can't have an empty list item") # And she can correct it by filling some text in self.get_item_input_box().send_keys('Make tea\n') self.<API key>('1: Buy milk') self.<API key>('2: Make tea') def <API key>(self): # Edith goes to the home page and starts a new list self.browser.get(self.server_url) self.get_item_input_box().send_keys('Buy wellies\n') self.<API key>('1: Buy wellies') # She accidentally tries to enter a duplicate item self.get_item_input_box().send_keys('Buy wellies\n') # She sees a helpful error message self.<API key>('1: Buy wellies') error = self.get_error_element() self.assertEqual(error.text, "You've already got this in your list") def <API key>(self): # Edith starts a new list in a way that causes a validation error: self.browser.get(self.server_url) self.get_item_input_box().send_keys('\n') error = self.get_error_element() self.assertTrue(error.is_displayed()) # She starts typing in the input box to clear the error self.get_item_input_box().send_keys('a') # She is pleased to see that the error message disappears error = self.get_error_element() self.assertFalse(error.is_displayed())
75.3 ServletFilterListener `Servlet``Filter``<API key>`Servletlistener - [75.3.1 Spring beanServletFilterListener](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#<API key>) - [75.3.2 ServletFilterListener](https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/htmlsingle/#<API key>)
using System; using System.Collections.Generic; using System.Text; namespace Arebis.Types { <summary> A delegate to translate a given object into a string. </summary> public delegate string ToStringDelegate(object obj); <summary> Wraps an object and provides it with a custom mechanism to translate to string. </summary> [Serializable] public class ToStringWrapper<T> { private T value; private string toString; private ToStringDelegate toStringDelegate; <summary> Constructs a wrapper for the given object. </summary> public ToStringWrapper(T value) { this.value = value; this.toStringDelegate = ToStringWrapper<T>.<API key>; } <summary> Constructs a wrapper for the given object such that the ToString returns the given string. </summary> public ToStringWrapper(T value, string toString) { this.value = value; this.toString = toString; this.toStringDelegate = this.<API key>; } <summary> Constructs a wrapper for the given object such that the ToString translates to the given ToStringDelegate. </summary> public ToStringWrapper(T value, ToStringDelegate toStringDelegate) { this.value = value; this.toStringDelegate = toStringDelegate; } <summary> The wrapped object. </summary> public virtual T Value { get { return this.value; } set { this.value = value; } } <summary> Returns a customizable string representation of the wrapped object. </summary> public override string ToString() { return this.toStringDelegate(this.value); } private string <API key>(object obj) { return this.toString; } private static string <API key>(object obj) { return obj.ToString(); } } }
#ifndef PMQT_H #define PMQT_H #include <stdint.h> #include <math.h> // Basic configuration of the library, these can be changed to support // different floating point types. typedef double pmqt_float_t; #define PMQT_POS_INFINITY (INFINITY) #define PMQT_NEG_INFINITY (-INFINITY) #define PMQT_EPS (1e-9) #define pmqt_fmin(_x, _y) fmin((_x), (_y)) #define pmqt_fmax(_x, _y) fmax((_x), (_y)) #define pmqt_fabs(_x) fabs((_x)) typedef struct pmqt_point { pmqt_float_t x; pmqt_float_t y; } pmqt_point_t; typedef struct pmqt_edge { pmqt_point_t a; pmqt_point_t b; } pmqt_edge_t; // A simple edge linked-list element. typedef struct pmqt_edge_list { const pmqt_edge_t *edge; struct pmqt_edge_list *next; } pmqt_edge_list_t; // A bounding box with precomputed width/height. typedef struct pmqt_bounds { pmqt_point_t nw; pmqt_point_t se; pmqt_float_t width; pmqt_float_t height; } pmqt_bounds_t; // The type of node in the tree. // White: Empty node with no children. // Grey: A node with children, has no data associated with it. // Black (Point): Contains an edge endpoint, number of connected edges that // intersect with the node. // Black (Edge): Contains a single edge that intersects with the node. typedef enum { PMQT_WHITE = 0, PMQT_GREY, PMQT_BLACK_POINT, PMQT_BLACK_EDGE } pmqt_nodetype_t; typedef struct pmqt_node { // children struct pmqt_node *ne; struct pmqt_node *nw; struct pmqt_node *se; struct pmqt_node *sw; union { struct { pmqt_point_t point; pmqt_edge_list_t *edges; } p; const pmqt_edge_t *edge; } u; pmqt_bounds_t bounds; pmqt_nodetype_t type; } pmqt_node_t; typedef struct pmqt { pmqt_node_t *root; } pmqt_t; #define PMQT_CONTINUE 0 // Callback used when searching a tree. typedef int (*pmqt_search_cb)(const pmqt_node_t *node, const pmqt_edge_t *edge, void *arg); // Callback used when walking a tree. typedef int (*pmqt_walk_cb)(const pmqt_node_t *node, void *arg); // Allocates a new PM Quadtree with the given bounds. pmqt_t * pmqt_new(pmqt_float_t min_x, pmqt_float_t min_y, pmqt_float_t max_x, pmqt_float_t max_y); // Deallocates and frees a tree. void pmqt_free(pmqt_t *tree); // Return codes from pmqt_insert. typedef enum { PMQT_OK = 0, // No error PMQT_ERR_NOMEM = -1, // malloc failed PMQT_ERR_INTRSCT = -2, // An edge that would intersect an existing edge // was attempted to be inserted PMQT_ERR_OOB = -3, // An edge that was outside the bounds of the // tree was attempted to be inserted PMQT_ERR_OTHER = -100 // Unknown error } pmqt_err_t; // Insert an edge into the tree. Note: the edge must exist as long as the // tree does. pmqt_err_t pmqt_insert(pmqt_t *tree, const pmqt_edge_t *edge); // Walk all the children of the tree. int pmqt_walk(const pmqt_node_t *root, pmqt_walk_cb descent, pmqt_walk_cb ascent, void *arg); // Search all nodes of the tree that intersect with the given edge. int pmqt_search(const pmqt_node_t *node, const pmqt_edge_t *edge, pmqt_search_cb process, void *arg); #endif // PMQT_H
<html><body> <h4>Windows 10 x64 (18363.778)</h4><br> <h2><API key></h2> <font face="arial"> <API key> = 0n1<br> <API key> = 0n2<br> <API key> = 0n3<br> <API key> = 0n4<br> <API key> = 0n5<br> <API key> = 0n6<br> FileEaInformation = 0n7<br> <API key> = 0n8<br> FileNameInformation = 0n9<br> <API key> = 0n10<br> FileLinkInformation = 0n11<br> <API key> = 0n12<br> <API key> = 0n13<br> <API key> = 0n14<br> <API key> = 0n15<br> FileModeInformation = 0n16<br> <API key> = 0n17<br> FileAllInformation = 0n18<br> <API key> = 0n19<br> <API key> = 0n20<br> <API key> = 0n21<br> <API key> = 0n22<br> FilePipeInformation = 0n23<br> <API key> = 0n24<br> <API key> = 0n25<br> <API key> = 0n26<br> <API key> = 0n27<br> <API key> = 0n28<br> <API key> = 0n29<br> <API key> = 0n30<br> <API key> = 0n31<br> <API key> = 0n32<br> <API key> = 0n33<br> <API key> = 0n34<br> <API key> = 0n35<br> <API key> = 0n36<br> <API key> = 0n37<br> <API key> = 0n38<br> <API key> = 0n39<br> <API key> = 0n40<br> <API key> = 0n41<br> <API key> = 0n42<br> <API key> = 0n43<br> <API key> = 0n44<br> <API key> = 0n45<br> <API key> = 0n46<br> <API key> = 0n47<br> <API key> = 0n48<br> <API key> = 0n49<br> <API key> = 0n50<br> <API key> = 0n51<br> <API key> = 0n52<br> <API key> = 0n53<br> <API key> = 0n54<br> <API key> = 0n55<br> <API key> = 0n56<br> <API key> = 0n57<br> <API key> = 0n58<br> FileIdInformation = 0n59<br> <API key> = 0n60<br> <API key> = 0n61<br> <API key> = 0n62<br> <API key> = 0n63<br> <API key> = 0n64<br> <API key> = 0n65<br> <API key> = 0n66<br> <API key> = 0n67<br> FileStatInformation = 0n68<br> <API key> = 0n69<br> <API key> = 0n70<br> <API key> = 0n71<br> <API key> = 0n72<br> <API key> = 0n73<br> <API key> = 0n74<br> <API key> = 0n75<br> <API key> = 0n76<br> </font></body></html>