text
stringlengths
2
1.04M
meta
dict
<?php namespace PHPExiftool\Driver\Tag\Casio; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class PreviewImage extends AbstractTag { protected $Id = 8192; protected $Name = 'PreviewImage'; protected $FullName = 'Casio::Type2'; protected $GroupName = 'Casio'; protected $g0 = 'MakerNotes'; protected $g1 = 'Casio'; protected $g2 = 'Camera'; protected $Type = 'undef'; protected $Writable = true; protected $Description = 'Preview Image'; protected $local_g2 = 'Preview'; protected $flag_Permanent = true; }
{ "content_hash": "947f1ad6f369100bdbe579e427afe4aa", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 46, "avg_line_length": 16.1, "alnum_prop": 0.6614906832298136, "repo_name": "bburnichon/PHPExiftool", "id": "bb63930c3a492d456586ae76fd7a64fe302a2506", "size": "868", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/PHPExiftool/Driver/Tag/Casio/PreviewImage.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "22076400" } ], "symlink_target": "" }
package org.betelnut.examples.showcase.demos.cache.memcached; /** * 统一定义Memcached中存储的各种对象的Key前缀和超时时间. * * @see org.springside.examples.showcase.service.AccountService#getInitializedUser(String) * * @author calvin */ public enum MemcachedObjectType { USER("user:", 60 * 60 * 1); private String prefix; private int expiredTime; MemcachedObjectType(String prefix, int expiredTime) { this.prefix = prefix; this.expiredTime = expiredTime; } public String getPrefix() { return prefix; } public int getExpiredTime() { return expiredTime; } }
{ "content_hash": "8fd86d44cf25e08a26a652c3c49f9a61", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 90, "avg_line_length": 18.9, "alnum_prop": 0.7336860670194003, "repo_name": "andyChenHuaYing/betelnut-oa", "id": "964832b3b7394b8dc29af4bda5e5c38d7b03d94c", "size": "888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "applications/showcases/src/main/java/org/betelnut/examples/showcase/demos/cache/memcached/MemcachedObjectType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2148" }, { "name": "Java", "bytes": "414982" }, { "name": "Lua", "bytes": "2132" }, { "name": "Shell", "bytes": "4557" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <feature id="de.fhg.igd.eclipse.ui.util.feature" label="Eclipse UI Utilities" version="1.0.0.qualifier" provider-name="Fraunhofer IGD"> <copyright> Copyright 2014 Fraunhofer IGD </copyright> <license url="http://www.apache.org/licenses"> Apache License 2.0 </license> <plugin id="de.fhg.igd.eclipse.ui.util" download-size="0" install-size="0" version="0.0.0" unpack="false"/> <plugin id="de.fhg.igd.eclipse.ui.util.source" download-size="0" install-size="0" version="0.0.0" unpack="false"/> </feature>
{ "content_hash": "2adae64811ef50632cc6cacbbd9b0566", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 49, "avg_line_length": 23, "alnum_prop": 0.5666666666666667, "repo_name": "igd-geo/eclipse-util", "id": "5643d691a2c7b7a1a214c5ac1104d4a0752d3d8a", "size": "690", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "de.fhg.igd.eclipse.ui.util.feature/feature.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "99941" }, { "name": "Shell", "bytes": "76" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "d496fe70993a4cdaad7c60a952bf05be", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "08216dd05a4add7740ec2c61356d9d0f9fb80ae9", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Helianthocereus/Helianthocereus tarijensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import os import os.path def is_desktop(platform): return platform in ["windows", "macos", "linuxbsd", "uwp", "haiku"] def is_unix_like(platform): return platform in ["macos", "linuxbsd", "android", "haiku", "ios"] def module_supports_tools_on(platform): return is_desktop(platform) def configure(env, env_mono): # is_android = env["platform"] == "android" # is_javascript = env["platform"] == "javascript" # is_ios = env["platform"] == "ios" # is_ios_sim = is_ios and env["arch"] in ["x86", "x86_64"] tools_enabled = env["tools"] if tools_enabled and not module_supports_tools_on(env["platform"]): raise RuntimeError("This module does not currently support building for this platform with tools enabled") if env["tools"]: env_mono.Append(CPPDEFINES=["GD_MONO_HOT_RELOAD"]) app_host_dir = find_dotnet_app_host_dir(env) def check_app_host_file_exists(file): file_path = os.path.join(app_host_dir, file) if not os.path.isfile(file_path): raise RuntimeError("File not found: " + file_path) # TODO: # All libnethost does for us is provide a function to find hostfxr. # If we could handle that logic ourselves we could void linking it. # nethost file names: # static: libnethost.a/lib # shared: libnethost.a/dylib and nethost.dll check_app_host_file_exists("libnethost.lib" if os.name == "nt" else "libnethost.a") check_app_host_file_exists("nethost.h") check_app_host_file_exists("hostfxr.h") check_app_host_file_exists("coreclr_delegates.h") env_mono.Prepend(CPPPATH=app_host_dir) env.Append(LIBPATH=[app_host_dir]) # Only the editor build links nethost, which is needed to find hostfxr. # Exported games don't need this logic as hostfxr is bundled with them. if tools_enabled: libnethost_path = os.path.join(app_host_dir, "libnethost.lib" if os.name == "nt" else "libnethost.a") if env["platform"] == "windows": env_mono.Append(CPPDEFINES=["NETHOST_USE_AS_STATIC"]) if env.msvc: env.Append(LINKFLAGS="libnethost.lib") else: env.Append(LINKFLAGS=["-Wl,-whole-archive", libnethost_path, "-Wl,-no-whole-archive"]) else: is_apple = env["platform"] in ["macos", "ios"] # is_macos = is_apple and not is_ios # if is_ios and not is_ios_sim: # env_mono.Append(CPPDEFINES=["IOS_DEVICE"]) if is_apple: env.Append(LINKFLAGS=["-Wl,-force_load," + libnethost_path]) else: env.Append(LINKFLAGS=["-Wl,-whole-archive", libnethost_path, "-Wl,-no-whole-archive"]) def find_dotnet_app_host_dir(env): dotnet_version = "6.0" dotnet_root = env["dotnet_root"] if not dotnet_root: dotnet_cmd = find_dotnet_executable(env["arch"]) if dotnet_cmd: sdk_path = find_dotnet_sdk(dotnet_cmd, dotnet_version) if sdk_path: dotnet_root = os.path.abspath(os.path.join(sdk_path, os.pardir)) if not dotnet_root: raise RuntimeError("Cannot find .NET Core Sdk") print("Found .NET Core Sdk root directory: " + dotnet_root) dotnet_cmd = os.path.join(dotnet_root, "dotnet.exe" if os.name == "nt" else "dotnet") runtime_identifier = determine_runtime_identifier(env) # TODO: In the future, if it can't be found this way, we want to obtain it # from the runtime.{runtime_identifier}.Microsoft.NETCore.DotNetAppHost NuGet package. app_host_version = find_app_host_version(dotnet_cmd, dotnet_version) if not app_host_version: raise RuntimeError("Cannot find .NET app host for version: " + dotnet_version) def get_runtime_path(): return os.path.join( dotnet_root, "packs", "Microsoft.NETCore.App.Host." + runtime_identifier, app_host_version, "runtimes", runtime_identifier, "native", ) app_host_dir = get_runtime_path() # Some Linux distros use their distro name as the RID in these paths. # If the initial generic path doesn't exist, try to get the RID from `dotnet --info`. # The generic RID should still be the first choice. Some platforms like Windows 10 # define the RID as `win10-x64` but still use the generic `win-x64` for directory names. if not app_host_dir or not os.path.isdir(app_host_dir): runtime_identifier = find_dotnet_cli_rid(dotnet_cmd) app_host_dir = get_runtime_path() return app_host_dir def determine_runtime_identifier(env): names_map = { "windows": "win", "macos": "osx", "linuxbsd": "linux", } # .NET RID architectures: x86, x64, arm, or arm64 platform = env["platform"] if is_desktop(platform): if env["arch"] in ["arm", "arm32"]: rid = "arm" elif env["arch"] == "arm64": rid = "arm64" else: bits = env["bits"] bit_arch_map = {"64": "x64", "32": "x86"} rid = bit_arch_map[bits] return "%s-%s" % (names_map[platform], rid) else: raise NotImplementedError() def find_app_host_version(dotnet_cmd, search_version_str): import subprocess from distutils.version import LooseVersion search_version = LooseVersion(search_version_str) try: env = dict(os.environ, DOTNET_CLI_UI_LANGUAGE="en-US") lines = subprocess.check_output([dotnet_cmd, "--list-runtimes"], env=env).splitlines() for line_bytes in lines: line = line_bytes.decode("utf-8") if not line.startswith("Microsoft.NETCore.App "): continue parts = line.split(" ", 2) if len(parts) < 3: continue version_str = parts[1] version = LooseVersion(version_str) if version >= search_version: return version_str except (subprocess.CalledProcessError, OSError) as e: import sys print(e, file=sys.stderr) return "" def find_dotnet_arch(dotnet_cmd): import subprocess try: env = dict(os.environ, DOTNET_CLI_UI_LANGUAGE="en-US") lines = subprocess.check_output([dotnet_cmd, "--info"], env=env).splitlines() for line_bytes in lines: line = line_bytes.decode("utf-8") parts = line.split(":", 1) if len(parts) < 2: continue arch_str = parts[0].strip() if arch_str != "Architecture": continue arch_value = parts[1].strip() arch_map = {"x64": "x86_64", "x86": "x86_32", "arm64": "arm64", "arm32": "arm32"} return arch_map[arch_value] except (subprocess.CalledProcessError, OSError) as e: import sys print(e, file=sys.stderr) return "" def find_dotnet_sdk(dotnet_cmd, search_version_str): import subprocess from distutils.version import LooseVersion search_version = LooseVersion(search_version_str) try: env = dict(os.environ, DOTNET_CLI_UI_LANGUAGE="en-US") lines = subprocess.check_output([dotnet_cmd, "--list-sdks"], env=env).splitlines() for line_bytes in lines: line = line_bytes.decode("utf-8") parts = line.split(" ", 1) if len(parts) < 2: continue version_str = parts[0] version = LooseVersion(version_str) if version < search_version: continue path_part = parts[1] return path_part[1 : path_part.find("]")] except (subprocess.CalledProcessError, OSError) as e: import sys print(e, file=sys.stderr) return "" def find_dotnet_cli_rid(dotnet_cmd): import subprocess try: env = dict(os.environ, DOTNET_CLI_UI_LANGUAGE="en-US") lines = subprocess.check_output([dotnet_cmd, "--info"], env=env).splitlines() for line_bytes in lines: line = line_bytes.decode("utf-8") if not line.startswith(" RID:"): continue parts = line.split() if len(parts) < 2: continue return parts[1] except (subprocess.CalledProcessError, OSError) as e: import sys print(e, file=sys.stderr) return "" ENV_PATH_SEP = ";" if os.name == "nt" else ":" def find_dotnet_executable(arch): is_windows = os.name == "nt" windows_exts = os.environ["PATHEXT"].split(ENV_PATH_SEP) if is_windows else None path_dirs = os.environ["PATH"].split(ENV_PATH_SEP) search_dirs = path_dirs + [os.getcwd()] # cwd is last in the list for dir in path_dirs: search_dirs += [ os.path.join(dir, "x64"), os.path.join(dir, "x86"), os.path.join(dir, "arm64"), os.path.join(dir, "arm32"), ] # search subfolders for cross compiling for dir in search_dirs: path = os.path.join(dir, "dotnet") if is_windows: for extension in windows_exts: path_with_ext = path + extension if os.path.isfile(path_with_ext) and os.access(path_with_ext, os.X_OK): sdk_arch = find_dotnet_arch(path_with_ext) if sdk_arch == arch or arch == "": return path_with_ext else: if os.path.isfile(path) and os.access(path, os.X_OK): sdk_arch = find_dotnet_arch(path) if sdk_arch == arch or arch == "": return path return ""
{ "content_hash": "55709bac389a9559fe25596a8d16ac5e", "timestamp": "", "source": "github", "line_count": 311, "max_line_length": 114, "avg_line_length": 31.234726688102892, "alnum_prop": 0.5825612518015236, "repo_name": "akien-mga/godot", "id": "c819ef5b3022d64454cbeae9684a475ddf7e7278", "size": "9714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/mono/build_scripts/mono_configure.py", "mode": "33188", "license": "mit", "language": [ { "name": "AIDL", "bytes": "1633" }, { "name": "C", "bytes": "1045182" }, { "name": "C#", "bytes": "1578818" }, { "name": "C++", "bytes": "38595824" }, { "name": "CMake", "bytes": "606" }, { "name": "GAP", "bytes": "62" }, { "name": "GDScript", "bytes": "66177" }, { "name": "GLSL", "bytes": "836566" }, { "name": "Java", "bytes": "596743" }, { "name": "JavaScript", "bytes": "188454" }, { "name": "Kotlin", "bytes": "84152" }, { "name": "Makefile", "bytes": "1421" }, { "name": "Objective-C", "bytes": "20550" }, { "name": "Objective-C++", "bytes": "371842" }, { "name": "PowerShell", "bytes": "2713" }, { "name": "Python", "bytes": "464605" }, { "name": "Shell", "bytes": "31057" } ], "symlink_target": "" }
module Azure end module Azure::Mysql end module Azure::Mysql::Mgmt end
{ "content_hash": "a024d2711adb8ee6254de9275bac9714", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 29, "avg_line_length": 23.666666666666668, "alnum_prop": 0.7887323943661971, "repo_name": "Azure/azure-sdk-for-ruby", "id": "3eb71dcae44e332973cfa19bdfccb5f22aaaf43b", "size": "245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "management/azure_mgmt_mysql/lib/module_definition.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "345216400" }, { "name": "Shell", "bytes": "305" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/certificatemanager/v1/certificate_issuance_config.proto package com.google.cloud.certificatemanager.v1; public interface CertificateIssuanceConfigOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.certificatemanager.v1.CertificateIssuanceConfig) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * A user-defined name of the certificate issuance config. * CertificateIssuanceConfig names must be unique globally and match pattern * `projects/&#42;&#47;locations/&#42;&#47;certificateIssuanceConfigs/&#42;`. * </pre> * * <code>string name = 1;</code> * * @return The name. */ java.lang.String getName(); /** * * * <pre> * A user-defined name of the certificate issuance config. * CertificateIssuanceConfig names must be unique globally and match pattern * `projects/&#42;&#47;locations/&#42;&#47;certificateIssuanceConfigs/&#42;`. * </pre> * * <code>string name = 1;</code> * * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * * * <pre> * Output only. The creation timestamp of a CertificateIssuanceConfig. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the createTime field is set. */ boolean hasCreateTime(); /** * * * <pre> * Output only. The creation timestamp of a CertificateIssuanceConfig. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The createTime. */ com.google.protobuf.Timestamp getCreateTime(); /** * * * <pre> * Output only. The creation timestamp of a CertificateIssuanceConfig. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder(); /** * * * <pre> * Output only. The last update timestamp of a CertificateIssuanceConfig. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the updateTime field is set. */ boolean hasUpdateTime(); /** * * * <pre> * Output only. The last update timestamp of a CertificateIssuanceConfig. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The updateTime. */ com.google.protobuf.Timestamp getUpdateTime(); /** * * * <pre> * Output only. The last update timestamp of a CertificateIssuanceConfig. * </pre> * * <code>.google.protobuf.Timestamp update_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder(); /** * * * <pre> * Set of labels associated with a CertificateIssuanceConfig. * </pre> * * <code>map&lt;string, string&gt; labels = 4;</code> */ int getLabelsCount(); /** * * * <pre> * Set of labels associated with a CertificateIssuanceConfig. * </pre> * * <code>map&lt;string, string&gt; labels = 4;</code> */ boolean containsLabels(java.lang.String key); /** Use {@link #getLabelsMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, java.lang.String> getLabels(); /** * * * <pre> * Set of labels associated with a CertificateIssuanceConfig. * </pre> * * <code>map&lt;string, string&gt; labels = 4;</code> */ java.util.Map<java.lang.String, java.lang.String> getLabelsMap(); /** * * * <pre> * Set of labels associated with a CertificateIssuanceConfig. * </pre> * * <code>map&lt;string, string&gt; labels = 4;</code> */ /* nullable */ java.lang.String getLabelsOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue); /** * * * <pre> * Set of labels associated with a CertificateIssuanceConfig. * </pre> * * <code>map&lt;string, string&gt; labels = 4;</code> */ java.lang.String getLabelsOrThrow(java.lang.String key); /** * * * <pre> * One or more paragraphs of text description of a CertificateIssuanceConfig. * </pre> * * <code>string description = 5;</code> * * @return The description. */ java.lang.String getDescription(); /** * * * <pre> * One or more paragraphs of text description of a CertificateIssuanceConfig. * </pre> * * <code>string description = 5;</code> * * @return The bytes for description. */ com.google.protobuf.ByteString getDescriptionBytes(); /** * * * <pre> * Required. The CA that issues the workload certificate. It includes the CA * address, type, authentication to CA service, etc. * </pre> * * <code> * .google.cloud.certificatemanager.v1.CertificateIssuanceConfig.CertificateAuthorityConfig certificate_authority_config = 6 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the certificateAuthorityConfig field is set. */ boolean hasCertificateAuthorityConfig(); /** * * * <pre> * Required. The CA that issues the workload certificate. It includes the CA * address, type, authentication to CA service, etc. * </pre> * * <code> * .google.cloud.certificatemanager.v1.CertificateIssuanceConfig.CertificateAuthorityConfig certificate_authority_config = 6 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The certificateAuthorityConfig. */ com.google.cloud.certificatemanager.v1.CertificateIssuanceConfig.CertificateAuthorityConfig getCertificateAuthorityConfig(); /** * * * <pre> * Required. The CA that issues the workload certificate. It includes the CA * address, type, authentication to CA service, etc. * </pre> * * <code> * .google.cloud.certificatemanager.v1.CertificateIssuanceConfig.CertificateAuthorityConfig certificate_authority_config = 6 [(.google.api.field_behavior) = REQUIRED]; * </code> */ com.google.cloud.certificatemanager.v1.CertificateIssuanceConfig .CertificateAuthorityConfigOrBuilder getCertificateAuthorityConfigOrBuilder(); /** * * * <pre> * Required. Workload certificate lifetime requested. * </pre> * * <code>.google.protobuf.Duration lifetime = 7 [(.google.api.field_behavior) = REQUIRED];</code> * * @return Whether the lifetime field is set. */ boolean hasLifetime(); /** * * * <pre> * Required. Workload certificate lifetime requested. * </pre> * * <code>.google.protobuf.Duration lifetime = 7 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The lifetime. */ com.google.protobuf.Duration getLifetime(); /** * * * <pre> * Required. Workload certificate lifetime requested. * </pre> * * <code>.google.protobuf.Duration lifetime = 7 [(.google.api.field_behavior) = REQUIRED];</code> */ com.google.protobuf.DurationOrBuilder getLifetimeOrBuilder(); /** * * * <pre> * Required. Specifies the percentage of elapsed time of the certificate * lifetime to wait before renewing the certificate. Must be a number between * 1-99, inclusive. * </pre> * * <code>int32 rotation_window_percentage = 8 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The rotationWindowPercentage. */ int getRotationWindowPercentage(); /** * * * <pre> * Required. The key algorithm to use when generating the private key. * </pre> * * <code> * .google.cloud.certificatemanager.v1.CertificateIssuanceConfig.KeyAlgorithm key_algorithm = 9 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for keyAlgorithm. */ int getKeyAlgorithmValue(); /** * * * <pre> * Required. The key algorithm to use when generating the private key. * </pre> * * <code> * .google.cloud.certificatemanager.v1.CertificateIssuanceConfig.KeyAlgorithm key_algorithm = 9 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The keyAlgorithm. */ com.google.cloud.certificatemanager.v1.CertificateIssuanceConfig.KeyAlgorithm getKeyAlgorithm(); }
{ "content_hash": "63945cfa298f75fc6c1d334891173ab0", "timestamp": "", "source": "github", "line_count": 326, "max_line_length": 169, "avg_line_length": 26.282208588957054, "alnum_prop": 0.6462418300653595, "repo_name": "googleapis/java-certificate-manager", "id": "59caec2731ac03f53d1bb4c34051c8de911fe487", "size": "9162", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "proto-google-cloud-certificate-manager-v1/src/main/java/com/google/cloud/certificatemanager/v1/CertificateIssuanceConfigOrBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "3110284" }, { "name": "Python", "bytes": "787" }, { "name": "Shell", "bytes": "20480" } ], "symlink_target": "" }
**Version 3.3.0**, synced to [MPAndroidChart #f6a398b](https://github.com/PhilJay/MPAndroidChart/commit/f6a398b) ![alt tag](https://raw.github.com/danielgindi/Charts/master/Assets/feature_graphic.png) ![Supported Platforms](https://img.shields.io/cocoapods/p/Charts.svg) [![Releases](https://img.shields.io/github/release/danielgindi/Charts.svg)](https://github.com/danielgindi/Charts/releases) [![Latest pod release](https://img.shields.io/cocoapods/v/Charts.svg)](http://cocoapods.org/pods/charts) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Build Status](https://travis-ci.org/danielgindi/Charts.svg?branch=master)](https://travis-ci.org/danielgindi/Charts) [![codecov](https://codecov.io/gh/danielgindi/Charts/branch/master/graph/badge.svg)](https://codecov.io/gh/danielgindi/Charts) [![Join the chat at https://gitter.im/danielgindi/Charts](https://badges.gitter.im/danielgindi/Charts.svg)](https://gitter.im/danielgindi/Charts?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) ### Just a heads up: Charts 3.0 has some breaking changes. Please read [the release/migration notes](https://github.com/danielgindi/Charts/releases/tag/v3.0.0). ### Another heads up: ChartsRealm is now in a [separate repo](https://github.com/danielgindi/ChartsRealm). Pods is also now `Charts` and `ChartsRealm`, instead of ~`Charts/Core`~ and ~`Charts/Realm`~ ### One more heads up: As Swift evolves, if you are not using the latest Swift compiler, you shouldn't check out the master branch. Instead, you should go to the release page and pick up whatever suits you. * Xcode 10.2 / Swift 5.0 (master branch) * iOS >= 8.0 (Use as an **Embedded** Framework) * tvOS >= 9.0 * macOS >= 10.11 Okay so there's this beautiful library called [MPAndroidChart](https://github.com/PhilJay/MPAndroidChart) by [Philipp Jahoda](https://www.linkedin.com/in/philippjahoda) which has become very popular amongst Android developers, but there was no decent solution to create charts for iOS. I've chosen to write it in `Swift` as it can be highly optimized by the compiler, and can be used in both `Swift` and `ObjC` project. The demo project is written in `ObjC` to demonstrate how it works. **An amazing feature** of this library now, for Android, iOS, tvOS and macOS, is the time it saves you when developing for both platforms, as the learning curve is singleton- it happens only once, and the code stays very similar so developers don't have to go around and re-invent the app to produce the same output with a different library. (And that's not even considering the fact that there's not really another good choice out there currently...) ## Having trouble running the demo? * `ChartsDemo/ChartsDemo.xcodeproj` is the demo project for iOS/tvOS * `ChartsDemo-OSX/ChartsDemo-OSX.xcodeproj` is the demo project for macOS * Make sure you are running a supported version of Xcode. * Usually it is specified here a few lines above. * In most cases it will be the latest Xcode version. * Make sure that your project supports Swift 5.0 * Optional: Run `carthage checkout` in the project folder, to fetch dependencies (i.e testing dependencies). * If you don't have Carthage - you can get it [here](https://github.com/Carthage/Carthage/releases). ## Usage In order to correctly compile: 1. Drag the `Charts.xcodeproj` to your project 2. Go to your target's settings, hit the "+" under the "Embedded Binaries" section, and select the Charts.framework 3. `@import Charts` 4. When using Swift in an ObjC project: - You need to import your Bridging Header. Usually it is "*YourProject-Swift.h*", so in ChartsDemo it's "*ChartsDemo-Swift.h*". Do not try to actually include "*ChartsDemo-Swift.h*" in your project :-) - (Xcode 8.1 and earlier) Under "Build Options", mark "Embedded Content Contains Swift Code" - (Xcode 8.2+) Under "Build Options", mark "Always Embed Swift Standard Libraries" 5. When using [Realm.io](https://realm.io/): - Note that the Realm framework is not linked with Charts - it is only there for *optional* bindings. Which means that you need to have the framework in your project, and in a compatible version to whatever is compiled with Charts. We will do our best to always compile against the latest version. - You'll need to add `ChartsRealm` as a dependency too. ## 3rd party tutorials * [Using Realm and Charts with Swift 3 in iOS 10 (Sami Korpela)](https://medium.com/@skoli/using-realm-and-charts-with-swift-3-in-ios-10-40c42e3838c0#.2gyymwfh8) * [Creating a Line Chart in Swift 3 and iOS 10 (Osian Smith)](https://medium.com/@OsianSmith/creating-a-line-chart-in-swift-3-and-ios-10-2f647c95392e) * [Beginning Set-up and Example Using Charts with Swift 3](https://github.com/annalizhaz/ChartsForSwiftBasic) * Want your tutorial to show here? Create a PR! ## Troubleshooting #### Can't compile? * Please note the difference between installing a compiled framework from CocoaPods or Carthage, and copying the source code. * Please read the **Usage** section again. * Search in the issues * Try to politely ask in the issues section #### Other problems / feature requests * Search in the issues * Try to politely ask in the issues section ## CocoaPods Install Add `pod 'Charts'` to your Podfile. "Charts" is the name of the library. For [Realm](https://realm.io/) support, please add `pod 'ChartsRealm'` too. **Note:** ~~`pod 'ios-charts'`~~ is not the correct library, and refers to a different project by someone else. ## Carthage Install Charts now include Carthage prebuilt binaries. ```carthage github "danielgindi/Charts" == 3.3.0 github "danielgindi/Charts" ~> 3.3.0 ``` In order to build the binaries for a new release, use `carthage build --no-skip-current && carthage archive Charts`. ## 3rd party bindings Xamarin (by @Flash3001): *iOS* - [GitHub](https://github.com/Flash3001/iOSCharts.Xamarin)/[NuGet](https://www.nuget.org/packages/iOSCharts/). *Android* - [GitHub](https://github.com/Flash3001/MPAndroidChart.Xamarin)/[NuGet](https://www.nuget.org/packages/MPAndroidChart/). ## Help If you like what you see here, and want to support the work being done in this repository, you could: * Contribute code, issues and pull requests * Let people know this library exists (:fire: spread the word :fire:) * [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=68UL6Y8KUPS96) (You can buy me a beer, or you can buy me dinner :-) **Note:** The author of [MPAndroidChart](https://github.com/PhilJay/MPAndroidChart) is the reason that this library exists, and is accepting [donations](https://github.com/PhilJay/MPAndroidChart#donations) on his page. He deserves them! Questions & Issues ----- If you are having questions or problems, you should: - Make sure you are using the latest version of the library. Check the [**release-section**](https://github.com/danielgindi/Charts/releases). - Study the Android version's [**Documentation-Wiki**](https://github.com/PhilJay/MPAndroidChart/wiki) - Study the (Still incomplete [![Doc-Percent](https://img.shields.io/cocoapods/metrics/doc-percent/Charts.svg)](http://cocoadocs.org/docsets/Charts/)) [**Pod-Documentation**](http://cocoadocs.org/docsets/Charts/) - Search or open questions on [**stackoverflow**](http://stackoverflow.com/questions/tagged/ios-charts) with the `ios-charts` tag - Search [**known issues**](https://github.com/danielgindi/Charts/issues) for your problem (open and closed) - Create new issues (please :fire: **search known issues before** :fire:, do not create duplicate issues) Features ======= **Core features:** - 8 different chart types - Scaling on both axes (with touch-gesture, axes separately or pinch-zoom) - Dragging / Panning (with touch-gesture) - Combined-Charts (line-, bar-, scatter-, candle-stick-, bubble-) - Dual (separate) Axes - Customizable Axes (both x- and y-axis) - Highlighting values (with customizable popup-views) - Save chart to camera-roll / export to PNG/JPEG - Predefined color templates - Legends (generated automatically, customizable) - Animations (build up animations, on both x- and y-axis) - Limit lines (providing additional information, maximums, ...) - Fully customizable (paints, typefaces, legends, colors, background, gestures, dashed lines, ...) - Plotting data directly from [**Realm.io**](https://realm.io) mobile database ([here](https://github.com/danielgindi/ChartsRealm)) **Chart types:** *Screenshots are currently taken from the original repository, as they render exactly the same :-)* - **LineChart (with legend, simple design)** ![alt tag](https://raw.github.com/PhilJay/MPChart/master/screenshots/simpledesign_linechart4.png) - **LineChart (with legend, simple design)** ![alt tag](https://raw.github.com/PhilJay/MPChart/master/screenshots/simpledesign_linechart3.png) - **LineChart (cubic lines)** ![alt tag](https://raw.github.com/PhilJay/MPChart/master/screenshots/cubiclinechart.png) - **LineChart (gradient fill)** ![alt tag](https://raw.github.com/PhilJay/MPAndroidChart/master/screenshots/line_chart_gradient.png) - **Combined-Chart (bar- and linechart in this case)** ![alt tag](https://raw.github.com/PhilJay/MPChart/master/screenshots/combined_chart.png) - **BarChart (with legend, simple design)** ![alt tag](https://raw.github.com/PhilJay/MPChart/master/screenshots/simpledesign_barchart3.png) - **BarChart (grouped DataSets)** ![alt tag](https://raw.github.com/PhilJay/MPChart/master/screenshots/groupedbarchart.png) - **Horizontal-BarChart** ![alt tag](https://raw.github.com/PhilJay/MPChart/master/screenshots/horizontal_barchart.png) - **PieChart (with selection, ...)** ![alt tag](https://raw.github.com/PhilJay/MPAndroidChart/master/screenshots/simpledesign_piechart1.png) - **ScatterChart** (with squares, triangles, circles, ... and more) ![alt tag](https://raw.github.com/PhilJay/MPAndroidChart/master/screenshots/scatterchart.png) - **CandleStickChart** (for financial data) ![alt tag](https://raw.github.com/PhilJay/MPAndroidChart/master/screenshots/candlestickchart.png) - **BubbleChart** (area covered by bubbles indicates the value) ![alt tag](https://raw.github.com/PhilJay/MPAndroidChart/master/screenshots/bubblechart.png) - **RadarChart** (spider web chart) ![alt tag](https://raw.github.com/PhilJay/MPAndroidChart/master/screenshots/radarchart.png) Documentation ======= Currently there's no need for documentation for the iOS/tvOS/macOS version, as the API is **95% the same** as on Android. You can read the official [MPAndroidChart](https://github.com/PhilJay/MPAndroidChart) documentation here: [**Wiki**](https://github.com/PhilJay/MPAndroidChart/wiki) Or you can see the Charts Demo project in both Objective-C and Swift ([**ChartsDemo-iOS**](https://github.com/danielgindi/Charts/tree/master/ChartsDemo-iOS), as well as macOS [**ChartsDemo-macOS**](https://github.com/danielgindi/Charts/tree/master/ChartsDemo-macOS)) and learn the how-tos from it. Special Thanks ======= Goes to [@liuxuan30](https://github.com/liuxuan30), [@petester42](https://github.com/petester42) and [@AlBirdie](https://github.com/AlBirdie) for new features, bugfixes, and lots and lots of involvement in our open-sourced community! You guys are a huge help to all of those coming here with questions and issues, and I couldn't respond to all of those without you. License ======= Copyright 2016 Daniel Cohen Gindi & Philipp Jahoda Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
{ "content_hash": "5119bcebe62f9fd5f18d213add166692", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 682, "avg_line_length": 56.691588785046726, "alnum_prop": 0.7507418397626113, "repo_name": "MAARK/Charts", "id": "91c8f8a34ce78f264cf057f7cf895db3537d24da", "size": "12132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "104" }, { "name": "Objective-C", "bytes": "196728" }, { "name": "Ruby", "bytes": "7593" }, { "name": "Shell", "bytes": "1302" }, { "name": "Swift", "bytes": "1079837" } ], "symlink_target": "" }
namespace policy { TEST(BrowserPolicyConnectorTest, IsNonEnterpriseUser) { // List of example emails that are not enterprise users. static const char* kNonEnterpriseUsers[] = { "fizz@aol.com", "foo@gmail.com", "bar@googlemail.com", "baz@hotmail.it", "baz@hotmail.co.uk", "baz@hotmail.com.tw", "user@msn.com", "another_user@live.com", "foo@qq.com", "i_love@yahoo.com", "i_love@yahoo.com.tw", "i_love@yahoo.jp", "i_love@yahoo.co.uk", "user@yandex.ru" }; // List of example emails that are potential enterprise users. static const char* kEnterpriseUsers[] = { "foo@google.com", "chrome_rules@chromium.org", "user@hotmail.enterprise.com", }; for (unsigned int i = 0; i < base::size(kNonEnterpriseUsers); ++i) { std::string username(kNonEnterpriseUsers[i]); EXPECT_TRUE(BrowserPolicyConnector::IsNonEnterpriseUser(username)) << "IsNonEnterpriseUser returned false for " << username; } for (unsigned int i = 0; i < base::size(kEnterpriseUsers); ++i) { std::string username(kEnterpriseUsers[i]); EXPECT_FALSE(BrowserPolicyConnector::IsNonEnterpriseUser(username)) << "IsNonEnterpriseUser returned true for " << username; } } } // namespace policy
{ "content_hash": "0299b4a5c3a27fa6e01ead36e8365392", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 74, "avg_line_length": 30.853658536585368, "alnum_prop": 0.6624505928853754, "repo_name": "ric2b/Vivaldi-browser", "id": "2f50ae0bcbca40f64b0bb21f1be62e3aefc94513", "size": "1582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chromium/components/policy/core/browser/browser_policy_connector_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
module MmoStarterKit module Config module Actions class Index < MmoStarterKit::Config::Actions::Base MmoStarterKit::Config::Actions.register(self) register_instance_option :collection do true end register_instance_option :http_methods do [:get, :post] end register_instance_option :route_fragment do '' end register_instance_option :breadcrumb_parent do parent_model = bindings[:abstract_model].try(:config).try(:parent) if am = parent_model && RailsAdmin.config(parent_model).try(:abstract_model) [:index, am] else [:dashboard] end end register_instance_option :controller do proc do @objects ||= list_entries unless @model_config.list.scopes.empty? if params[:scope].blank? unless @model_config.list.scopes.first.nil? @objects = @objects.send(@model_config.list.scopes.first) end elsif @model_config.list.scopes.collect(&:to_s).include?(params[:scope]) @objects = @objects.send(params[:scope].to_sym) end end respond_to do |format| format.html do render @action.template_name, status: (flash[:error].present? ? :not_found : 200) end format.json do output = if params[:compact] primary_key_method = @association ? @association.associated_primary_key : @model_config.abstract_model.primary_key label_method = @model_config.object_label_method @objects.collect { |o| {id: o.send(primary_key_method).to_s, label: o.send(label_method).to_s} } else @objects.to_json(@schema) end if params[:send_data] send_data output, filename: "#{params[:model_name]}_#{DateTime.now.strftime("%Y-%m-%d_%Hh%Mm%S")}.json" else render json: output, root: false end end format.xml do output = @objects.to_xml(@schema) if params[:send_data] send_data output, filename: "#{params[:model_name]}_#{DateTime.now.strftime("%Y-%m-%d_%Hh%Mm%S")}.xml" else render xml: output end end format.csv do header, encoding, output = CSVConverter.new(@objects, @schema).to_csv(params[:csv_options]) if params[:send_data] send_data output, type: "text/csv; charset=#{encoding}; #{"header=present" if header}", disposition: "attachment; filename=#{params[:model_name]}_#{DateTime.now.strftime("%Y-%m-%d_%Hh%Mm%S")}.csv" else render text: output end end end end end register_instance_option :link_icon do 'icon-th-list' end end end end end
{ "content_hash": "242f16d1a5031e13b93243ed72b6b6b3", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 136, "avg_line_length": 34.234042553191486, "alnum_prop": 0.5083903045369795, "repo_name": "SeaDragonGit/mmostarterkit", "id": "13fab4ac42581c89272e4ce4fd002d82f805be7a", "size": "3218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/mmo_starter_kit/config/actions/index.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "230935" }, { "name": "CoffeeScript", "bytes": "15127" }, { "name": "JavaScript", "bytes": "76173" }, { "name": "Ruby", "bytes": "558578" } ], "symlink_target": "" }
package com.pineone.icbms.so.resources.vo.location; import com.pineone.icbms.so.resources.domain.AGenericDomain; /** * Generic location.<BR/> * Created by Melvin on 2015. 12. 7.. */ abstract class AGenericLocation extends AGenericDomain implements IGenericLocation { protected String uri; @Override public String getUri() { return uri; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(super.toString()); sb.append("uri: ").append(uri); return sb.toString(); } }
{ "content_hash": "c07575445159297cc5494625d2fac0b5", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 82, "avg_line_length": 22.26923076923077, "alnum_prop": 0.6545768566493955, "repo_name": "pahnjy/PineoneIoTProject", "id": "7c49b561ffac748c9aeba29f5349164ebb069663", "size": "579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "so-resources/src/main/java/com/pineone/icbms/so/resources/vo/location/AGenericLocation.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "57587" } ], "symlink_target": "" }
package Paws::S3::ListObjects; use Moose; has Bucket => (is => 'ro', isa => 'Str', uri_name => 'Bucket', traits => ['ParamInURI'], required => 1); has Delimiter => (is => 'ro', isa => 'Str', query_name => 'delimiter', traits => ['ParamInQuery']); has EncodingType => (is => 'ro', isa => 'Str', query_name => 'encoding-type', traits => ['ParamInQuery']); has Marker => (is => 'ro', isa => 'Str', query_name => 'marker', traits => ['ParamInQuery']); has MaxKeys => (is => 'ro', isa => 'Int', query_name => 'max-keys', traits => ['ParamInQuery']); has Prefix => (is => 'ro', isa => 'Str', query_name => 'prefix', traits => ['ParamInQuery']); has RequestPayer => (is => 'ro', isa => 'Str', header_name => 'x-amz-request-payer', traits => ['ParamInHeader']); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'ListObjects'); class_has _api_uri => (isa => 'Str', is => 'ro', default => '/{Bucket}'); class_has _api_method => (isa => 'Str', is => 'ro', default => 'GET'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::S3::ListObjectsOutput'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::S3::ListObjects - Arguments for method ListObjects on Paws::S3 =head1 DESCRIPTION This class represents the parameters used for calling the method ListObjects on the Amazon Simple Storage Service service. Use the attributes of this class as arguments to method ListObjects. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ListObjects. As an example: $service_obj->ListObjects(Att1 => $value1, Att2 => $value2, ...); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. =head1 ATTRIBUTES =head2 B<REQUIRED> Bucket => Str =head2 Delimiter => Str A delimiter is a character you use to group keys. =head2 EncodingType => Str Valid values are: C<"url"> =head2 Marker => Str Specifies the key to start with when listing objects in a bucket. =head2 MaxKeys => Int Sets the maximum number of keys returned in the response. The response might contain fewer keys but will never contain more. =head2 Prefix => Str Limits the response to keys that begin with the specified prefix. =head2 RequestPayer => Str Confirms that the requester knows that she or he will be charged for the list objects request. Bucket owners need not specify this parameter in their requests. Valid values are: C<"requester"> =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method ListObjects in L<Paws::S3> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
{ "content_hash": "4bbfd3015aa5ecded91f947c624fe20d", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 249, "avg_line_length": 29.91089108910891, "alnum_prop": 0.6789142667990732, "repo_name": "ioanrogers/aws-sdk-perl", "id": "825c119dd62cf55c0c3430b042f689a334c668fe", "size": "3022", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "auto-lib/Paws/S3/ListObjects.pm", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1292" }, { "name": "Perl", "bytes": "20360380" }, { "name": "Perl 6", "bytes": "99393" }, { "name": "Shell", "bytes": "445" } ], "symlink_target": "" }
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // This file contains the exception classes used in the configuration // classes. //////////////////////////////////////////////////////////////////////////////// #ifndef Pegasus_ConfigExceptions_h #define Pegasus_ConfigExceptions_h #include <Pegasus/Common/Exception.h> #include <Pegasus/Config/Linkage.h> #include <Pegasus/Common/MessageLoader.h> PEGASUS_NAMESPACE_BEGIN /** MissingCommandLineOptionArgument Exception class */ class PEGASUS_CONFIG_LINKAGE MissingCommandLineOptionArgument : public Exception { public: MissingCommandLineOptionArgument(const String& optionName) : Exception(MessageLoaderParms( "Config.ConfigExceptions.MISSING_CMDLINE_OPTION", "Missing command line option argument: $0", optionName)) { } }; /** UnrecognizedCommandLineOption Exception class */ class PEGASUS_CONFIG_LINKAGE UnrecognizedCommandLineOption : public Exception { public: UnrecognizedCommandLineOption() : Exception(MessageLoaderParms( "Config.ConfigExceptions.UNRECOGNIZED_CMDLINE_OPTION", "Unrecognized command line option. ")) { } }; /** InvalidPropertyValue Exception class */ class PEGASUS_CONFIG_LINKAGE InvalidPropertyValue : public Exception { public: InvalidPropertyValue(const String& name, const String& value) : Exception(MessageLoaderParms( "Config.ConfigExceptions.INVALID_PROPERTY_VALUE", "Invalid property value: $0=$1", name, value)) { } protected: InvalidPropertyValue(const MessageLoaderParms& theMessage) : Exception(theMessage) { } }; /** InvalidDirectoryPropertyValue Exception class */ class PEGASUS_CONFIG_LINKAGE InvalidDirectoryPropertyValue : public InvalidPropertyValue { public: InvalidDirectoryPropertyValue(const String& name, const String& value) : InvalidPropertyValue(MessageLoaderParms( "Config.ConfigExceptions.INVALID_DIRECTORY_PROPERTY_VALUE", "For property $0 specified value $1 is not a directory or " "the directory is not writeable.", name, value)) { } }; /** DuplicateOption Exception class */ class PEGASUS_CONFIG_LINKAGE DuplicateOption : public Exception { public: DuplicateOption(const String& name) : Exception(MessageLoaderParms( "Config.ConfigExceptions.DUPLICATE_OPTION", "Duplicate option: $0", name)) { } }; /** ConfigFileSyntaxError Exception class */ class PEGASUS_CONFIG_LINKAGE ConfigFileSyntaxError : public Exception { public: ConfigFileSyntaxError(const String& file, Uint32 line) : Exception(_formatMessage(file, line)) { } static String _formatMessage(const String& file, Uint32 line); }; /** UnrecognizedConfigFileOption Exception class */ class PEGASUS_CONFIG_LINKAGE UnrecognizedConfigFileOption : public Exception { public: UnrecognizedConfigFileOption(const String& name) : Exception(MessageLoaderParms( "Config.ConfigExceptions.UNRECOGNIZED_CONFIG_FILE_OPTION", "Unrecognized config file option: $0", name)) { } }; /** MissingRequiredOptionValue Exception class */ class PEGASUS_CONFIG_LINKAGE MissingRequiredOptionValue : public Exception { public: MissingRequiredOptionValue(const String& name) : Exception(MessageLoaderParms( "Config.ConfigExceptions.MISSING_REQUIRED_OPTION", "Missing required option value: $0", name)) { } }; /** UnrecognizedConfigProperty Exception class */ class PEGASUS_CONFIG_LINKAGE UnrecognizedConfigProperty : public Exception { public: UnrecognizedConfigProperty(const String& name) : Exception(MessageLoaderParms( "Config.ConfigExceptions.UNRECOGNIZED_CONFIG_PROPERTY", "Unrecognized config property: $0", name)) { } }; /** NonDynamicConfigProperty Exception class */ class PEGASUS_CONFIG_LINKAGE NonDynamicConfigProperty : public Exception { public: NonDynamicConfigProperty(const String& name) : Exception(MessageLoaderParms( "Config.ConfigExceptions.NONDYNAMIC_CONFIG_PROPERTY", "NonDynamic config property: $0", name)) { } }; /** FailedSaveProperties Exception class */ class PEGASUS_CONFIG_LINKAGE FailedSaveProperties : public Exception { public: FailedSaveProperties(const String& reason) : Exception(MessageLoaderParms( "Config.ConfigExceptions.FAILED_SAVE_PROPERTIES", "Failed to save configuration properties to file: $0. " "Configuration property not set.", reason)) { } }; PEGASUS_NAMESPACE_END #endif /* Pegasus_ConfigExceptions_h */
{ "content_hash": "de39f905d5e55e257339ae78d8d2a0e3", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 80, "avg_line_length": 29.231441048034934, "alnum_prop": 0.655661786674634, "repo_name": "xenserver/openpegasus", "id": "9088a3daafccb3d71d739505052a74609ddebe62", "size": "6694", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pegasus/src/Pegasus/Config/ConfigExceptions.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "16927" }, { "name": "Awk", "bytes": "8389" }, { "name": "C", "bytes": "4288026" }, { "name": "C++", "bytes": "21497005" }, { "name": "Erlang", "bytes": "58804" }, { "name": "Java", "bytes": "883396" }, { "name": "Objective-C", "bytes": "223991" }, { "name": "Perl", "bytes": "113006" }, { "name": "Scala", "bytes": "255" }, { "name": "Shell", "bytes": "87052" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Montagnella reicheana Henn. ### Remarks null
{ "content_hash": "d1915e134292098be9127b1f6ffa0053", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 27, "avg_line_length": 10.153846153846153, "alnum_prop": 0.7121212121212122, "repo_name": "mdoering/backbone", "id": "726da41cf16efe5a3aaa5f3ebc5801a3dfd8a1f7", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Montagnella/Montagnella reicheana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Todoist.Net.Models; namespace Todoist.Net.Services { /// <summary> /// Contains operations for reminders management. /// </summary> public interface IRemindersService : IRemindersCommandService { /// <summary> /// Gets all reminders. /// </summary> /// <returns>The filters.</returns> /// <exception cref="HttpRequestException">API exception.</exception> Task<IEnumerable<Reminder>> GetAsync(); /// <summary> /// Gets a reminder info by ID. /// </summary> /// <param name="id">The ID of the reminder.</param> /// <returns> /// The reminder info. /// </returns> /// <exception cref="HttpRequestException">API exception.</exception> Task<ReminderInfo> GetAsync(ComplexId id); } }
{ "content_hash": "ff88103fef598e00a52aefbdf93cd4dc", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 77, "avg_line_length": 29.64516129032258, "alnum_prop": 0.6050054406964092, "repo_name": "olsh/todoist-net", "id": "f68548262bf512ba818581a4950ad0b7f7e49257", "size": "921", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Todoist.Net/Services/IReminersService.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "360354" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Fri Nov 14 18:25:18 PST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.apache.hadoop.hbase.protobuf.generated.FilterProtos.MultipleColumnPrefixFilter.Builder (HBase 0.98.8-hadoop2 API)</title> <meta name="date" content="2014-11-14"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.hbase.protobuf.generated.FilterProtos.MultipleColumnPrefixFilter.Builder (HBase 0.98.8-hadoop2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/class-use/FilterProtos.MultipleColumnPrefixFilter.Builder.html" target="_top">Frames</a></li> <li><a href="FilterProtos.MultipleColumnPrefixFilter.Builder.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.hadoop.hbase.protobuf.generated.FilterProtos.MultipleColumnPrefixFilter.Builder" class="title">Uses of Class<br>org.apache.hadoop.hbase.protobuf.generated.FilterProtos.MultipleColumnPrefixFilter.Builder</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.hadoop.hbase.protobuf.generated">org.apache.hadoop.hbase.protobuf.generated</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.hadoop.hbase.protobuf.generated"> <!-- --> </a> <h3>Uses of <a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a> in <a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/package-summary.html">org.apache.hadoop.hbase.protobuf.generated</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/package-summary.html">org.apache.hadoop.hbase.protobuf.generated</a> that return <a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.Builder.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html#addAllSortedPrefixes(java.lang.Iterable)">addAllSortedPrefixes</a></strong>(<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Iterable.html?is-external=true" title="class or interface in java.lang">Iterable</a>&lt;? extends com.google.protobuf.ByteString&gt;&nbsp;values)</code> <div class="block"><code>repeated bytes sorted_prefixes = 1;</code></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.Builder.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html#addSortedPrefixes(com.google.protobuf.ByteString)">addSortedPrefixes</a></strong>(com.google.protobuf.ByteString&nbsp;value)</code> <div class="block"><code>repeated bytes sorted_prefixes = 1;</code></div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.Builder.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html#clear()">clear</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.Builder.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html#clearSortedPrefixes()">clearSortedPrefixes</a></strong>()</code> <div class="block"><code>repeated bytes sorted_prefixes = 1;</code></div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.Builder.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html#clone()">clone</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.Builder.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html#mergeFrom(com.google.protobuf.CodedInputStream,%20com.google.protobuf.ExtensionRegistryLite)">mergeFrom</a></strong>(com.google.protobuf.CodedInputStream&nbsp;input, com.google.protobuf.ExtensionRegistryLite&nbsp;extensionRegistry)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.Builder.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html#mergeFrom(org.apache.hadoop.hbase.protobuf.generated.FilterProtos.MultipleColumnPrefixFilter)">mergeFrom</a></strong>(<a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter</a>&nbsp;other)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.Builder.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html#mergeFrom(com.google.protobuf.Message)">mergeFrom</a></strong>(com.google.protobuf.Message&nbsp;other)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.html#newBuilder()">newBuilder</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.html#newBuilder(org.apache.hadoop.hbase.protobuf.generated.FilterProtos.MultipleColumnPrefixFilter)">newBuilder</a></strong>(<a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter</a>&nbsp;prototype)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.html#newBuilderForType()">newBuilderForType</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.html#newBuilderForType(com.google.protobuf.GeneratedMessage.BuilderParent)">newBuilderForType</a></strong>(com.google.protobuf.GeneratedMessage.BuilderParent&nbsp;parent)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.Builder.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html#setSortedPrefixes(int,%20com.google.protobuf.ByteString)">setSortedPrefixes</a></strong>(int&nbsp;index, com.google.protobuf.ByteString&nbsp;value)</code> <div class="block"><code>repeated bytes sorted_prefixes = 1;</code></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">FilterProtos.MultipleColumnPrefixFilter.Builder</a></code></td> <td class="colLast"><span class="strong">FilterProtos.MultipleColumnPrefixFilter.</span><code><strong><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.html#toBuilder()">toBuilder</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/hadoop/hbase/protobuf/generated/FilterProtos.MultipleColumnPrefixFilter.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/class-use/FilterProtos.MultipleColumnPrefixFilter.Builder.html" target="_top">Frames</a></li> <li><a href="FilterProtos.MultipleColumnPrefixFilter.Builder.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "d95c8a7e128fcf71883880374c26a209", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 606, "avg_line_length": 78.44748858447488, "alnum_prop": 0.7143189755529685, "repo_name": "devansh2015/hbase-0.98.8", "id": "1a1a1583fbdaa891a9d6426e8a76f00a5caa7a08", "size": "17180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/devapidocs/org/apache/hadoop/hbase/protobuf/generated/class-use/FilterProtos.MultipleColumnPrefixFilter.Builder.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "23219" }, { "name": "CSS", "bytes": "1216" }, { "name": "Groff", "bytes": "5218" }, { "name": "HTML", "bytes": "3492" }, { "name": "JavaScript", "bytes": "1347" }, { "name": "Ruby", "bytes": "265714" }, { "name": "Shell", "bytes": "70300" } ], "symlink_target": "" }
TEST(QRCodeGenerator, Generate) { // Without a QR decoder implementation, there's a limit to how much we can // test the QR encoder. Therefore this test just runs a generation to ensure // that no DCHECKs are hit and that the output has the correct structure. When // run under ASan, this will also check that every byte of the output has been // written to. constexpr size_t kMaxInputLen = 210; uint8_t input[kMaxInputLen]; QRCodeGenerator qr; absl::optional<int> smallest_size; absl::optional<int> largest_size; for (const bool use_alphanum : {false, true}) { SCOPED_TRACE(use_alphanum); // 'A' is in the alphanumeric set, but 'a' is not. memset(input, use_alphanum ? 'A' : 'a', sizeof(input)); for (size_t input_len = 30; input_len < kMaxInputLen; input_len += 10) { SCOPED_TRACE(input_len); absl::optional<QRCodeGenerator::GeneratedCode> qr_code = qr.Generate(base::span<const uint8_t>(input, input_len)); ASSERT_NE(qr_code, absl::nullopt); auto& qr_data = qr_code->data; if (!smallest_size || qr_code->qr_size < *smallest_size) { smallest_size = qr_code->qr_size; } if (!largest_size || qr_code->qr_size > *largest_size) { largest_size = qr_code->qr_size; } int index = 0; for (int y = 0; y < qr_code->qr_size; y++) { for (int x = 0; x < qr_code->qr_size; x++) { ASSERT_EQ(0, qr_data[index++] & 0b11111100); } } } } // The generator should generate a variety of QR sizes. ASSERT_TRUE(smallest_size); ASSERT_TRUE(largest_size); ASSERT_LT(*smallest_size, *largest_size); } TEST(QRCodeGenerator, ManySizes) { // Generate larger and larger QR codes until there's a clean failure. Ensures // that there are no edge cases like crbug.com/1177437. QRCodeGenerator qr; std::string input = "!"; std::map<int, size_t> max_input_length_for_qr_size; for (size_t i = input.size();; i++) { absl::optional<QRCodeGenerator::GeneratedCode> code = qr.Generate(base::span<const uint8_t>( reinterpret_cast<const uint8_t*>(input.data()), input.size())); if (!code) { break; } max_input_length_for_qr_size[code->qr_size] = input.size(); input.push_back('!'); } ASSERT_GT(input.size(), 200u); // Capacities taken from https://www.qrcode.com/en/about/version.html ASSERT_EQ(max_input_length_for_qr_size[25], 32u); // 2-L ASSERT_EQ(max_input_length_for_qr_size[37], 84u); // 5-M ASSERT_EQ(max_input_length_for_qr_size[45], 122u); // 7-M ASSERT_EQ(max_input_length_for_qr_size[53], 180u); // 9-M ASSERT_EQ(max_input_length_for_qr_size[65], 287u); // 12-M } TEST(QRCodeGenerator, Segmentation) { struct Test { QRCodeGenerator::VersionClass vclass; const char* input; std::vector<std::pair<QRCodeGenerator::SegmentType, const char*>> segments; }; const auto SMALL = QRCodeGenerator::VersionClass::SMALL; const auto LARGE = QRCodeGenerator::VersionClass::LARGE; const auto D = QRCodeGenerator::SegmentType::DIGIT; const auto A = QRCodeGenerator::SegmentType::ALPHANUM; const auto B = QRCodeGenerator::SegmentType::BINARY; static const std::vector<Test> kTests = { {SMALL, "", {}}, {LARGE, "", {}}, // Runs of the same class should be a single segment. {SMALL, "01234", {{D, "01234"}}}, {LARGE, "01234", {{D, "01234"}}}, {SMALL, "abcdef", {{B, "abcdef"}}}, {LARGE, "abcdef", {{B, "abcdef"}}}, {SMALL, "ABC", {{A, "ABC"}}}, {LARGE, "ABC", {{A, "ABC"}}}, // Where cheaper, different classes should be merged into the wider // class. {SMALL, "01w", {{B, "01w"}}}, {SMALL, "w01", {{B, "w01"}}}, // But merging should only happen when cheaper. The merged version here is // 60 bits so the following should be split because that costs only 51 // bits. {SMALL, "01234w", {{D, "01234"}, {B, "w"}}}, {SMALL, "w01234", {{B, "w"}, {D, "01234"}}}, // The '0' should be merged into either of the binary blocks and then // the binary blocks should be unified together. {SMALL, "abcdef0abcdef", {{B, "abcdef0abcdef"}}}, // Segments should always be merged into the lesser class. // 1. First establish that six A/a are enough to justify their own // segment. {SMALL, "AAAAAAaaaaaa", {{A, "AAAAAA"}, {B, "aaaaaa"}}}, // 2. The digit should merge into the ALPHANUM block because it's // cheaper there. {SMALL, "AAAAAA0aaaaaa", {{A, "AAAAAA0"}, {B, "aaaaaa"}}}, // 3. That should happen even with things flipped. {SMALL, "aaaaaa0AAAAAA", {{B, "aaaaaa"}, {A, "0AAAAAA"}}}, // Check that a QR input that we might use is segmented as expected. {SMALL, "FIDO:/123412341234", {{A, "FIDO:/"}, {D, "123412341234"}}}, }; for (const auto& test : kTests) { const std::string input = test.input; const std::vector<QRCodeGenerator::Segment> segments = QRCodeGenerator::SegmentInput( test.vclass, base::span<const uint8_t>( reinterpret_cast<const uint8_t*>(test.input), strlen(test.input))); bool match = segments.size() == test.segments.size(); if (match) { size_t offset = 0; for (size_t i = 0; i < segments.size(); i++) { if (segments[i].type != test.segments[i].first || input.substr(offset, segments[i].length) != test.segments[i].second) { match = false; break; } offset += segments[i].length; } } if (!match) { auto type_to_char = [](QRCodeGenerator::SegmentType segment_type) -> char { switch (segment_type) { case QRCodeGenerator::SegmentType::DIGIT: return 'D'; case QRCodeGenerator::SegmentType::ALPHANUM: return 'A'; case QRCodeGenerator::SegmentType::BINARY: return 'B'; } }; std::string got = ""; size_t offset = 0; for (const auto& segment : segments) { if (!got.empty()) { got += " "; } got += type_to_char(segment.type); got += input.substr(offset, segment.length); offset += segment.length; } std::string want = ""; for (const auto& segment : test.segments) { if (!want.empty()) { want += " "; } want += type_to_char(segment.first); want += segment.second; } ADD_FAILURE() << "got: " << got << "\nwant: " << want; return; } } } TEST(QRCodeGenerator, SegmentationValid) { // The segmentation must always be valid: i.e. must assign each input byte // to a segment that can express it, and the segments must span the whole // input. for (int i = 0; i < 10000; i++) { const size_t len = base::RandInt(1, 64); std::vector<uint8_t> input(len); for (size_t j = 0; j < len; j++) { input[j] = base::RandInt(32, 126); } const std::vector<QRCodeGenerator::Segment> segments = QRCodeGenerator::SegmentInput( i & 1 ? QRCodeGenerator::VersionClass::SMALL : QRCodeGenerator::VersionClass::LARGE, input); ASSERT_TRUE(QRCodeGenerator::IsValidSegmentation(segments, input)); ASSERT_TRUE(QRCodeGenerator::NoSuperfluousSegments(segments)); } }
{ "content_hash": "25f0b7ce7fa3babb70245bec3aaba3cb", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 80, "avg_line_length": 35.312796208530806, "alnum_prop": 0.5890484498725004, "repo_name": "scheib/chromium", "id": "c60c4cf7a8ecc6737fda8d0f379801cb17015ce5", "size": "7780", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "components/qr_code_generator/qr_code_generator_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
namespace base { ProcessId GetParentProcessId(ProcessHandle process) { struct kinfo_proc info; size_t length; int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process }; if (sysctl(mib, base::size(mib), &info, &length, NULL, 0) < 0) return -1; return info.ki_ppid; } FilePath GetProcessExecutablePath(ProcessHandle process) { char pathname[PATH_MAX]; size_t length; int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, process }; length = sizeof(pathname); if (sysctl(mib, base::size(mib), pathname, &length, NULL, 0) < 0 || length == 0) { return FilePath(); } return FilePath(std::string(pathname)); } } // namespace base
{ "content_hash": "9b6fd0352b61827a514b21ef7b5a3642", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 69, "avg_line_length": 23.20689655172414, "alnum_prop": 0.6582466567607727, "repo_name": "ric2b/Vivaldi-browser", "id": "6cea2333b3e2ca37588de2756cdcc3714490090d", "size": "1050", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chromium/base/process/process_handle_freebsd.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
if [ $# -lt 1 ]; then echo "Usage: $0 path_to_binaries" echo "e.g. $0 ../../src" exit 1 fi set -f BITMARKD=${1}/pfennigd CLI=${1}/pfennig-cli DIR="${BASH_SOURCE%/*}" SENDANDWAIT="${DIR}/send.sh" if [[ ! -d "$DIR" ]]; then DIR="$PWD"; fi . "$DIR/util.sh" D=$(mktemp -d test.XXXXX) # Two nodes; one will play the part of merchant, the # other an evil transaction-mutating miner. D1=${D}/node1 CreateDataDir $D1 port=11000 rpcport=11001 B1ARGS="-datadir=$D1 -debug=mempool" $BITMARKD $B1ARGS & B1PID=$! D2=${D}/node2 CreateDataDir $D2 port=11010 rpcport=11011 B2ARGS="-datadir=$D2 -debug=mempool" $BITMARKD $B2ARGS & B2PID=$! # Wait until all four nodes are at the same block number function WaitBlocks { while : do sleep 1 declare -i BLOCKS1=$( GetBlocks $B1ARGS ) declare -i BLOCKS2=$( GetBlocks $B2ARGS ) if (( BLOCKS1 == BLOCKS2 )) then break fi done } # Wait until node has $N peers function WaitPeers { while : do declare -i PEERS=$( $CLI $1 getconnectioncount ) if (( PEERS == "$2" )) then break fi sleep 1 done } echo "Generating test blockchain..." # Start with B2 connected to B1: $CLI $B2ARGS addnode 127.0.0.1:11000 onetry WaitPeers "$B1ARGS" 1 # 2 block, 50 XBT each == 100 XBT # These will be transactions "A" and "B" $CLI $B1ARGS setgenerate true 2 WaitBlocks # 100 blocks, 0 mature == 0 XBT $CLI $B2ARGS setgenerate true 100 WaitBlocks CheckBalance "$B1ARGS" 100 CheckBalance "$B2ARGS" 0 # restart B2 with no connection $CLI $B2ARGS stop > /dev/null 2>&1 wait $B2PID $BITMARKD $B2ARGS & B2PID=$! B1ADDRESS=$( $CLI $B1ARGS getnewaddress ) B2ADDRESS=$( $CLI $B2ARGS getnewaddress ) # Transaction C: send-to-self, spend A TXID_C=$( $CLI $B1ARGS sendtoaddress $B1ADDRESS 50.0) # Transaction D: spends B and C TXID_D=$( $CLI $B1ARGS sendtoaddress $B2ADDRESS 100.0) CheckBalance "$B1ARGS" 0 # Mutate TXID_C and add it to B2's memory pool: RAWTX_C=$( $CLI $B1ARGS getrawtransaction $TXID_C ) # ... mutate C to create C' L=${RAWTX_C:82:2} NEWLEN=$( printf "%x" $(( 16#$L + 1 )) ) MUTATEDTX_C=${RAWTX_C:0:82}${NEWLEN}4c${RAWTX_C:84} # ... give mutated tx1 to B2: MUTATEDTXID=$( $CLI $B2ARGS sendrawtransaction $MUTATEDTX_C ) echo "TXID_C: " $TXID_C echo "Mutated: " $MUTATEDTXID # Re-connect nodes, and have both nodes mine some blocks: $CLI $B2ARGS addnode 127.0.0.1:11000 onetry WaitPeers "$B1ARGS" 1 # Having B2 mine the next block puts the mutated # transaction C in the chain: $CLI $B2ARGS setgenerate true 1 WaitBlocks # B1 should still be able to spend 100, because D is conflicted # so does not count as a spend of B CheckBalance "$B1ARGS" 100 $CLI $B2ARGS stop > /dev/null 2>&1 wait $B2PID $CLI $B1ARGS stop > /dev/null 2>&1 wait $B1PID echo "Tests successful, cleaning up" rm -rf $D exit 0
{ "content_hash": "fd09e29a8f68f945b89bcf5fc04ac1fd", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 63, "avg_line_length": 22.410852713178294, "alnum_prop": 0.6554825319958492, "repo_name": "project-bitmark/pfennig", "id": "dc8a0bdbaa490ed136d81755d0f45d2b1b5afcd2", "size": "3372", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "qa/rpc-tests/conflictedbalance.sh", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "50884" }, { "name": "C++", "bytes": "3077947" }, { "name": "CSS", "bytes": "1127" }, { "name": "Makefile", "bytes": "8009" }, { "name": "Objective-C", "bytes": "1125" }, { "name": "Objective-C++", "bytes": "6466" }, { "name": "Python", "bytes": "110376" }, { "name": "Shell", "bytes": "45389" } ], "symlink_target": "" }
package process import ( "bufio" "fmt" "io/ioutil" "os" "path" "strings" ) const ( pageSize = 4 << 10 // standard setting, applicable for most systems procPath = "/proc" ) type statsReader struct { ProcPath string Command string } // Stats returns a process resource stats reader for current process func Stats() statsReader { return statsReader{ ProcPath: procPath, Command: path.Base(os.Args[0]), } } // Memory returns memory stats for current process func (rdr statsReader) Memory() (MemStats, error) { fd, err := os.Open(rdr.ProcPath + "/self/statm") if err != nil { return MemStats{}, nil } defer fd.Close() var total, rss, shared int // The fields come in order described in `/proc/[pid]/statm` section // of https://man7.org/linux/man-pages/man5/proc.5.html if _, err := fmt.Fscanf(fd, "%d %d %d", &total, // size &rss, // resident &shared, // shared // ... the rest of the fields are not used and thus omitted ); err != nil { return MemStats{}, fmt.Errorf("failed to parse %s: %s", fd.Name(), err) } return MemStats{ Total: total * pageSize, Rss: rss * pageSize, Shared: shared * pageSize, }, nil } // CPU returns CPU stats for current process and the CPU tick they were taken on func (rdr statsReader) CPU() (CPUStats, int, error) { fd, err := os.Open(rdr.ProcPath + "/self/stat") if err != nil { return CPUStats{}, 0, nil } defer fd.Close() var ( stats CPUStats skipInt int skipCh byte ) // The command in `/proc/self/stat` output is truncated to 15 bytes (16 including the terminating null byte) comm := rdr.Command if len(comm) > 15 { comm = comm[:15] } // The fields come in order described in `/proc/[pid]/stat` section // of https://man7.org/linux/man-pages/man5/proc.5.html. We skip parsing // the `comm` field since it may contain space characters that break fmt.Fscanf format. if _, err := fmt.Fscanf(fd, "%d ("+comm+") %c %d %d %d %d %d %d %d %d %d %d %d %d", &skipInt, // pid &skipCh, // state &skipInt, // ppid &skipInt, // pgrp &skipInt, // session &skipInt, // tty_nr &skipInt, // tpgid &skipInt, // flags &skipInt, // minflt &skipInt, // cminflt &skipInt, // majflt &skipInt, // cmajflt &stats.User, // utime &stats.System, // stime // ... the rest of the fields are not used and thus omitted ); err != nil { return stats, 0, fmt.Errorf("failed to parse %s: %s", fd.Name(), err) } tick, err := rdr.currentTick() if err != nil { return stats, 0, fmt.Errorf("failed to get current CPU tick: %s", err) } return stats, tick, nil } // currentTick parses /proc/stat, sums up the total number of ticks spent on each CPU and averages them // by the number of CPUs func (rdr statsReader) currentTick() (int, error) { fd, err := os.Open(rdr.ProcPath + "/stat") if err != nil { return 0, nil } defer fd.Close() sc := bufio.NewScanner(fd) sc.Split(bufio.ScanLines) var ( ticks, cpuCount int user, nice, sys, idle, iowait, irq, softIRQ, steal int skipStr string ) for sc.Scan() { s := sc.Text() if !strings.HasPrefix(s, "cpu") { continue } if strings.HasPrefix(s, "cpu ") { // skip total CPU line continue } // The fields come in order described in `/proc/stat` section // of https://man7.org/linux/man-pages/man5/proc.5.html if _, err := fmt.Sscanf(s, "%s %d %d %d %d %d %d %d %d", &skipStr, // CPU label &user, &nice, &sys, &idle, &iowait, &irq, &softIRQ, &steal, // ... the rest of the fields are not used and thus omitted ); err != nil { return 0, fmt.Errorf("failed to parse %s: %s", fd.Name(), err) } ticks += user + nice + sys + idle + iowait + irq + softIRQ + steal cpuCount++ } if err := sc.Err(); err != nil { return 0, fmt.Errorf("failed to read %s: %s", fd.Name(), err) } if cpuCount < 2 { return ticks, nil } return ticks / cpuCount, nil } // Limits returns resource limits configured for current process func (rdr statsReader) Limits() (ResourceLimits, error) { fd, err := os.Open(rdr.ProcPath + "/self/limits") if err != nil { return ResourceLimits{}, nil } defer fd.Close() sc := bufio.NewScanner(fd) sc.Split(bufio.ScanLines) var limits ResourceLimits for sc.Scan() { s := sc.Text() if !strings.HasPrefix(s, "Max open files") { continue } s = strings.TrimLeft(s[14:], " \t") // trim the "max open files" prefix along with trailing space if !strings.HasPrefix(s, "unlimited") { if _, err := fmt.Sscanf(s, "%d", &limits.OpenFiles.Max); err != nil { return limits, fmt.Errorf("unexpected %s format: %s", fd.Name(), err) } } break } if err := sc.Err(); err != nil { return limits, fmt.Errorf("failed to read %s: %s", fd.Name(), err) } fdNum, err := rdr.currentOpenFiles() if err != nil { return limits, fmt.Errorf("failed to get the number of open files: %s", err) } limits.OpenFiles.Current = fdNum return limits, nil } func (rdr statsReader) currentOpenFiles() (int, error) { fds, err := ioutil.ReadDir(rdr.ProcPath + "/self/fd/") if err != nil { return 0, fmt.Errorf("failed to list %s: %s", rdr.ProcPath+"/fd/", err) } return len(fds), nil }
{ "content_hash": "d229ca99518d8e5050e0d7f2cdf3ded1", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 109, "avg_line_length": 24.269406392694062, "alnum_prop": 0.6154280338664158, "repo_name": "instana/golang-sensor", "id": "43229a6bb2098f9540710c79d2c933f6cf11c12b", "size": "5400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "process/stats_reader_linux.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "74604" }, { "name": "JavaScript", "bytes": "394" } ], "symlink_target": "" }
/* * Routines for testing only. Not really industrial strength. * * Author: Wietse Venema, Eindhoven University of Technology, The Netherlands. * * $FreeBSD$ */ #ifndef lint static char sccs_id[] = "@(#) scaffold.c 1.6 97/03/21 19:27:24"; #endif /* System libraries. */ #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <syslog.h> #include <setjmp.h> #include <string.h> #ifndef INADDR_NONE #define INADDR_NONE (-1) /* XXX should be 0xffffffff */ #endif #ifndef INET6 extern char *malloc(); #endif /* Application-specific. */ #include "tcpd.h" #include "scaffold.h" /* * These are referenced by the options module and by rfc931.c. */ int allow_severity = SEVERITY; int deny_severity = LOG_WARNING; int rfc931_timeout = RFC931_TIMEOUT; #ifndef INET6 /* dup_hostent - create hostent in one memory block */ static struct hostent *dup_hostent(hp) struct hostent *hp; { struct hostent_block { struct hostent host; char *addr_list[1]; }; struct hostent_block *hb; int count; char *data; char *addr; for (count = 0; hp->h_addr_list[count] != 0; count++) /* void */ ; if ((hb = (struct hostent_block *) malloc(sizeof(struct hostent_block) + (hp->h_length + sizeof(char *)) * count)) == 0) { fprintf(stderr, "Sorry, out of memory\n"); exit(1); } memset((char *) &hb->host, 0, sizeof(hb->host)); hb->host.h_length = hp->h_length; hb->host.h_addr_list = hb->addr_list; hb->host.h_addr_list[count] = 0; data = (char *) (hb->host.h_addr_list + count + 1); for (count = 0; (addr = hp->h_addr_list[count]) != 0; count++) { hb->host.h_addr_list[count] = data + hp->h_length * count; memcpy(hb->host.h_addr_list[count], addr, hp->h_length); } return (&hb->host); } #endif /* find_inet_addr - find all addresses for this host, result to free() */ #ifdef INET6 struct addrinfo *find_inet_addr(host) char *host; { struct addrinfo hints, *res; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; if (getaddrinfo(host, NULL, &hints, &res) == 0) return (res); memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE | AI_CANONNAME; if (getaddrinfo(host, NULL, &hints, &res) != 0) { tcpd_warn("%s: host not found", host); return (0); } if (res->ai_family != AF_INET6 && res->ai_family != AF_INET) { tcpd_warn("%d: not an internet host", res->ai_family); freeaddrinfo(res); return (0); } if (!res->ai_canonname) { tcpd_warn("%s: hostname alias", host); tcpd_warn("(cannot obtain official name)", res->ai_canonname); } else if (STR_NE(host, res->ai_canonname)) { tcpd_warn("%s: hostname alias", host); tcpd_warn("(official name: %.*s)", STRING_LENGTH, res->ai_canonname); } return (res); } #else struct hostent *find_inet_addr(host) char *host; { struct in_addr addr; struct hostent *hp; static struct hostent h; static char *addr_list[2]; /* * Host address: translate it to internal form. */ if ((addr.s_addr = dot_quad_addr(host)) != INADDR_NONE) { h.h_addr_list = addr_list; h.h_addr_list[0] = (char *) &addr; h.h_length = sizeof(addr); return (dup_hostent(&h)); } /* * Map host name to a series of addresses. Watch out for non-internet * forms or aliases. The NOT_INADDR() is here in case gethostbyname() has * been "enhanced" to accept numeric addresses. Make a copy of the * address list so that later gethostbyXXX() calls will not clobber it. */ if (NOT_INADDR(host) == 0) { tcpd_warn("%s: not an internet address", host); return (0); } if ((hp = gethostbyname(host)) == 0) { tcpd_warn("%s: host not found", host); return (0); } if (hp->h_addrtype != AF_INET) { tcpd_warn("%d: not an internet host", hp->h_addrtype); return (0); } if (STR_NE(host, hp->h_name)) { tcpd_warn("%s: hostname alias", host); tcpd_warn("(official name: %.*s)", STRING_LENGTH, hp->h_name); } return (dup_hostent(hp)); } #endif /* check_dns - give each address thorough workout, return address count */ int check_dns(host) char *host; { struct request_info request; #ifdef INET6 struct sockaddr_storage sin; struct addrinfo *hp, *res; #else struct sockaddr_in sin; struct hostent *hp; #endif int count; char *addr; if ((hp = find_inet_addr(host)) == 0) return (0); request_init(&request, RQ_CLIENT_SIN, &sin, 0); sock_methods(&request); #ifndef INET6 memset((char *) &sin, 0, sizeof(sin)); sin.sin_family = AF_INET; #endif #ifdef INET6 for (res = hp, count = 0; res; res = res->ai_next, count++) { memcpy(&sin, res->ai_addr, res->ai_addrlen); #else for (count = 0; (addr = hp->h_addr_list[count]) != 0; count++) { memcpy((char *) &sin.sin_addr, addr, sizeof(sin.sin_addr)); #endif /* * Force host name and address conversions. Use the request structure * as a cache. Detect hostname lookup problems. Any name/name or * name/address conflicts will be reported while eval_hostname() does * its job. */ request_set(&request, RQ_CLIENT_ADDR, "", RQ_CLIENT_NAME, "", 0); if (STR_EQ(eval_hostname(request.client), unknown)) tcpd_warn("host address %s->name lookup failed", eval_hostaddr(request.client)); } #ifdef INET6 freeaddrinfo(hp); #else free((char *) hp); #endif return (count); } /* dummy function to intercept the real shell_cmd() */ /* ARGSUSED */ void shell_cmd(command) char *command; { if (hosts_access_verbose) printf("command: %s", command); } /* dummy function to intercept the real clean_exit() */ /* ARGSUSED */ void clean_exit(request) struct request_info *request; { exit(0); } /* dummy function to intercept the real rfc931() */ /* ARGSUSED */ void rfc931(request) struct request_info *request; { strcpy(request->user, unknown); } /* check_path - examine accessibility */ int check_path(path, st) char *path; struct stat *st; { struct stat stbuf; char buf[BUFSIZ]; if (stat(path, st) < 0) return (-1); #ifdef notdef if (st->st_uid != 0) tcpd_warn("%s: not owned by root", path); if (st->st_mode & 020) tcpd_warn("%s: group writable", path); #endif if (st->st_mode & 002) tcpd_warn("%s: world writable", path); if (path[0] == '/' && path[1] != 0) { strrchr(strcpy(buf, path), '/')[0] = 0; (void) check_path(buf[0] ? buf : "/", &stbuf); } return (0); }
{ "content_hash": "14366a9865eb1205e4d3cb0abb87a0be", "timestamp": "", "source": "github", "line_count": 272, "max_line_length": 79, "avg_line_length": 24.783088235294116, "alnum_prop": 0.6183058893339267, "repo_name": "jhbsz/OSI-OS", "id": "8da9df0c686111289f621afb33f420cbb13fdce2", "size": "6741", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "contrib/tcp_wrappers/scaffold.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
var __reflect = (this && this.__reflect) || function (p, c, t) { p.__class__ = c, t ? t.push(c) : t = [c], p.__types__ = p.__types__ ? t.concat(p.__types__) : t; }; var __extends = this && this.__extends || function __extends(t, e) { function r() { this.constructor = t; } for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i]); r.prototype = e.prototype, t.prototype = new r(); }; /** * 事件 */ var SocketEvent = (function (_super) { __extends(SocketEvent, _super); function SocketEvent(type, data) { var _this = _super.call(this, type) || this; _this.data = data; return _this; } SocketEvent.prototype.getByKey = function (key) { return (this.data ? this.data[key] : null); }; return SocketEvent; }(egret.Event)); __reflect(SocketEvent.prototype, "SocketEvent"); //# sourceMappingURL=SocketEvent.js.map
{ "content_hash": "7db6326a78f7230eab2bb938f3acd6ca", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 100, "avg_line_length": 32.111111111111114, "alnum_prop": 0.580161476355248, "repo_name": "xiashu/egret-code", "id": "906aa7e3c478a483bfda83969ee14aef0dd6200d", "size": "871", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "网络篇/URLLoader/bin-debug/SocketEvent.js", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "3795" }, { "name": "AngelScript", "bytes": "2719" }, { "name": "HTML", "bytes": "157878" }, { "name": "JavaScript", "bytes": "73439757" }, { "name": "PHP", "bytes": "951" }, { "name": "TypeScript", "bytes": "672105" } ], "symlink_target": "" }
"use strict"; const FormInstance = require('../../formApi/formInstance'); /** * Example form to demonstrate the FileApi. * @class * @extends Defiant.Plugin.FormApi.FormInstance * @memberOf Defiant.Plugin.Example */ class ExampleFileUploadForm extends FormInstance { /** * When this function is finished, then the form should be ready to * be rendered as a string. * @function * @async * @param {Object} [data={}] * The initialization data. */ async init(data={}) { const FormApi = this.context.engine.pluginRegistry.get('FormApi'); const File = FormApi.getElement('File'); const Button = FormApi.getElement('Button'); const GenericRenderable = FormApi.getElement('GenericRenderable'); let files = []; // Get a list of files to display. // TODO: Convert to View. let Orm = this.context.engine.pluginRegistry.get('Orm'); let sql = this.context.engine.sql; let ExampleFileUpload = Orm.entityRegistry.get('exampleFileUpload') let exampleUploadTable = sql.define(ExampleFileUpload.schema()); let fileTable = sql.define(Orm.entityRegistry.get('file').schema()); let query = exampleUploadTable.select( exampleUploadTable.id, exampleUploadTable.fileId, fileTable.uuid, fileTable.created, fileTable.size, fileTable.originalName) .from(exampleUploadTable .leftJoin(fileTable) .on(exampleUploadTable.fileId.equals(fileTable.id))) .toQuery(); let db = this.context.engine.database; // Execute the query. let rows = await new Promise((accept) => { db.all(query.text, ...query.values, (err, rows) => { if (rows) { return accept(rows); } return accept(err); }); }); for (let index in rows) { rows[index].url = await ExampleFileUpload.getUrl(rows[index]); files.push(rows[index]); } // Build the form. this .addInstance(File.newInstance(this.context, { name: 'fileUpload', multiple: true, data: { label: 'File', description: 'Choose a file to upload.', }, })) .addInstance(Button.newInstance(this.context, { name: 'submit', data: { value: 'submit', content: 'Submit', } })) .addInstance(GenericRenderable.newInstance(this.context, { name: 'fileUploadListRenderable', renderable: this.context.theme.getRenderable('FileUploadListRenderable'), renderableSetup: { data: { files: files, }, }, })); await super.init(); } /** * Perform the form submission. * @function * @async */ async submit() { let Orm = this.context.engine.pluginRegistry.get('Orm'); let exampleFileUpload = Orm.entityRegistry.get('exampleFileUpload'); let fileUploadEntity = Orm.entityRegistry.get('fileUpload'); let fileEntity = Orm.entityRegistry.get('file'); let post = this.context.post[this.name]; await super.submit(); // Loop through the uploaded files. for (let key in post['fileUpload[files]']) { let file = post['fileUpload[files]'][key]; // Load the uploaded file data. let upload = {id: file.id} await fileUploadEntity.load(upload); // Create a new File entity. let entity = {}; ['uuid', 'accountId', 'size', 'originalName', 'path', 'created'].map(key => entity[key] = upload[key]); entity.usageCount = 1; entity.type = 'exampleFileUpload'; await fileEntity.save(entity); // Create exampleFileUpload table record. let record = {fileId: entity.id}; await exampleFileUpload.save(record); // Delete the old record. await fileUploadEntity.purge({id: upload.id}); // Remove the entry from fileUpload[data]. delete post['fileUpload[files]'][key]; } } } module.exports = ExampleFileUploadForm;
{ "content_hash": "b7051e75e9e44a94fd581e5bfbf14954", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 109, "avg_line_length": 29.781954887218046, "alnum_prop": 0.6213077505680383, "repo_name": "coreyp1/defiant", "id": "816b29ef1851d9be01c4b82d7a6520543c687642", "size": "3961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/plugin/example/form/exampleFileUploadFormInstance.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "801" }, { "name": "HTML", "bytes": "3383" }, { "name": "JavaScript", "bytes": "316101" } ], "symlink_target": "" }
#ifndef AVRO_H #define AVRO_H /** @file avro.h @brief AVRO API */ #include <stdarg.h> #include <stdint.h> #include <sys/types.h> #include <apr_pools.h> #include <apr_file_io.h> #include <apr_network_io.h> #ifdef __cplusplus extern "C" { #endif /** @defgroup AVRO Avro C API @{ */ /** * @defgroup Handle_Routines AVRO Handles * @ingroup AVRO * @{ */ /** Avro operation enum. Enum for discriminating whether an Avro handle is for encoding or decoding data. */ enum avro_op { AVRO_ENCODE = 0, /**< Marks a handle as encoding Avro data */ AVRO_DECODE = 1 /**< Marks a handle as decoding Avro data */ }; typedef enum avro_op avro_op; /** Avro status enum. Enum used by Avro functions to return state. @todo expand the number of states */ enum avro_status_t { AVRO_OK = 0, /**< Function success */ AVRO_FAILURE = 1 /**< Function failure */ }; typedef enum avro_status_t avro_status_t; #define CHECK_ERROR(__status) if(__status != AVRO_OK){ return __status; } /** Avro handle. Opaque handle for encoding/decoding data to memory, file or network. @warning Never operate on an Avro handle directly. Use the AVRO Handle routines instead. */ struct AVRO { enum avro_op a_op; /**< Hold the type of operation the handle is performing */ struct avro_ops { /** * Function for getting bytes from the underlying media */ avro_status_t (*a_getbytes) (struct AVRO * avro, caddr_t addr, int64_t len); /** * Function for sending bytes to the backing store */ avro_status_t (*a_putbytes) (struct AVRO * avro, const char *addr, const int64_t len); } *a_ops; apr_pool_t *pool; /**< Pool used for allocating memory for dynamic data structures */ unsigned char *schema; /**< Current AVRO schema for processing data */ apr_file_t *file; /**< Used by the file-backed handle */ apr_socket_t *socket; /**< Used by the socket-backed handle */ caddr_t addr; /**< Used by the memory-backed handle */ int64_t len; /**< Used by the memory-backed handle */ int64_t used; /**< Used by the memory-backed handle */ }; typedef struct AVRO AVRO; #define AVRO_GETBYTES(avro, addr, len) \ (*(avro)->a_ops->a_getbytes)(avro, addr, len) #define AVRO_PUTBYTES(avro, addr, len) \ (*(avro)->a_ops->a_putbytes)(avro, addr, len) /** Initialize the AVRO library @return The Avro status */ avro_status_t avro_initialize(void); /** Create a memory-backed Avro handle @param avro Pointer to handle that will be initialized @param pool Pool used for allocating dynamic data structures. @param addr Address of the memory location for manipulating data @param len Size of the memory to use @param op Expressing the operation the handle should perform (e.g. encode, decode) @return The Avro status */ avro_status_t avro_create_memory (AVRO * avro, apr_pool_t * pool, caddr_t addr, int64_t len, avro_op op); /** Create a file-backed Avro handle @param avro Pointer to the handle that will be initialized @param pool Pool used for allocating dynamic data structures @param file The file to read(decode) or write(encode) from @param op Expresses the operation the handle should perform (e.g. encode, decode) @return The Avro status */ avro_status_t avro_create_file (AVRO * avro, apr_pool_t * pool, apr_file_t * file, avro_op op); /** Create a socket-backed Avro handle @param avro Pointer to the handle that will be initialized @param pool Pool used for allocating dynamic data structures @param socket The socket to read(decode) or write(encode) from @param op Expresses the operation the handle should perform (e.g. encode, decode) @return The Avro status */ avro_status_t avro_create_socket (AVRO * avro, apr_pool_t * pool, apr_socket_t * socket, avro_op op); /** @} */ typedef avro_status_t (*avroproc_t) (AVRO *, void *, ...); typedef int bool_t; /** * @defgroup Primitives AVRO Primitive Type Serialization * @ingroup AVRO * @{ */ /** avro_null() will not read or write any data */ avro_status_t avro_null (void); /** avro_int64() is called to read/write a 64-bit signed integer @param avro The Avro handle @param lp Pointer to the 64-bit integer @return The Avro status */ avro_status_t avro_int64 (AVRO * avro, int64_t * lp); /** avro_string() is called to read/write a string @param avro The Avro handle @param str Pointer to the string @param maxlen The maximum length of the string to read/write @return The Avro status */ avro_status_t avro_string (AVRO * avro, char **str, int64_t maxlen); /** avro_bytes() is called to read/write opaque bytes @param avro The Avro handle @param bytes The pointer to the bytes to read/write @param len Pointer to an integer which either (1) expresses the number of bytes you wish to encode or (2) is set on return to give the number of bytes decoded @param maxlen The maximum number of bytes to read/write @return The Avro status */ avro_status_t avro_bytes (AVRO * avro, char **bytes, int64_t * len, int64_t maxlen); /** avro_bool() is called to read/write a boolean value @param avro The Avro handle @param bp Pointer to the boolean pointer @return The Avro status */ avro_status_t avro_bool (AVRO * avro, bool_t * bp); /** avro_float() is called to read/write a float @param avro The Avro handle @param fp Pointer to the float @return The Avro status */ avro_status_t avro_float (AVRO * avro, float *fp); /** avro_double() is called to read/write a double @param avro The Avro handle @param dp Pointer to the double @return The Avro status */ avro_status_t avro_double (AVRO * avro, double *dp); /** @} */ /** * @defgroup Compound AVRO Compound Type Serialization * @ingroup AVRO * @{ */ /** avro_array() encodes/decodes an array of avro elements @param avro The Avro handle @param addrp Pointer to the array @param sizep Pointer to the number of elements @param maxsize The maximum number of Avro elements @param elsize The size in bytes of each element @param elproc The Avro routine to handle each element @return The Avro status */ avro_status_t avro_array (AVRO * avro, caddr_t * addrp, uint32_t * sizep, uint32_t maxsize, uint32_t elsize, avroproc_t elproc); /** @} */ /* Useful for debugging */ void avro_dump_memory (AVRO * avro, FILE * fp); avro_status_t avro_getint32_raw (AVRO * avro, int32_t * value); avro_status_t avro_putint32_raw (AVRO * avro, const int32_t value); avro_status_t avro_getint64_raw (AVRO * avro, int64_t * value); avro_status_t avro_putint64_raw (AVRO * avro, const int64_t value); /** @} */ #ifdef __cplusplus } #endif #endif /* ifdef AVRO_H */
{ "content_hash": "298aac0bd14e518a683a413fec23de15", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 89, "avg_line_length": 28.25974025974026, "alnum_prop": 0.7020526960784313, "repo_name": "philz/avro", "id": "043fd1e484c54da11d7d14e6575d93876f372ad5", "size": "7286", "binary": false, "copies": "1", "ref": "refs/heads/working", "path": "src/c/avro.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294754" }, { "name": "C++", "bytes": "52285" }, { "name": "Java", "bytes": "524343" }, { "name": "JavaScript", "bytes": "45" }, { "name": "Python", "bytes": "197655" }, { "name": "Shell", "bytes": "4000" } ], "symlink_target": "" }
//===--- CodeCompletion.cpp - Code completion implementation --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/IDE/CodeCompletion.h" #include "CodeCompletionResultBuilder.h" #include "swift/AST/ASTPrinter.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/Comment.h" #include "swift/AST/Initializer.h" #include "swift/AST/GenericSignature.h" #include "swift/AST/LazyResolver.h" #include "swift/AST/NameLookup.h" #include "swift/AST/ParameterList.h" #include "swift/AST/ProtocolConformance.h" #include "swift/AST/SubstitutionMap.h" #include "swift/AST/USRGeneration.h" #include "swift/Basic/Defer.h" #include "swift/Basic/LLVM.h" #include "swift/ClangImporter/ClangImporter.h" #include "swift/ClangImporter/ClangModule.h" #include "swift/IDE/CodeCompletionCache.h" #include "swift/IDE/Utils.h" #include "swift/Parse/CodeCompletionCallbacks.h" #include "swift/Sema/IDETypeChecking.h" #include "swift/Subsystems.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/AST/Comment.h" #include "clang/AST/CommentVisitor.h" #include "clang/AST/Decl.h" #include "clang/Basic/Module.h" #include "clang/Index/USRGeneration.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SaveAndRestore.h" #include <algorithm> #include <string> using namespace swift; using namespace ide; using CommandWordsPairs = std::vector<std::pair<StringRef, StringRef>>; enum CodeCompletionCommandKind { none, keyword, recommended, recommendedover, mutatingvariant, nonmutatingvariant, }; CodeCompletionCommandKind getCommandKind(StringRef Command) { #define CHECK_CASE(KIND) \ if (Command == #KIND) \ return CodeCompletionCommandKind::KIND; CHECK_CASE(keyword); CHECK_CASE(recommended); CHECK_CASE(recommendedover); CHECK_CASE(mutatingvariant); CHECK_CASE(nonmutatingvariant); #undef CHECK_CASE return CodeCompletionCommandKind::none; } StringRef getCommandName(CodeCompletionCommandKind Kind) { #define CHECK_CASE(KIND) \ if (CodeCompletionCommandKind::KIND == Kind) { \ static std::string Name(#KIND); \ return Name; \ } CHECK_CASE(keyword) CHECK_CASE(recommended) CHECK_CASE(recommendedover) CHECK_CASE(mutatingvariant); CHECK_CASE(nonmutatingvariant); #undef CHECK_CASE llvm_unreachable("Cannot handle this Kind."); } bool containsInterestedWords(StringRef Content, StringRef Splitter, bool AllowWhitespace) { do { Content = Content.split(Splitter).second; Content = AllowWhitespace ? Content.trim() : Content; #define CHECK_CASE(KIND) \ if (Content.startswith(#KIND)) \ return true; CHECK_CASE(keyword) CHECK_CASE(recommended) CHECK_CASE(recommendedover) CHECK_CASE(mutatingvariant); CHECK_CASE(nonmutatingvariant); #undef CHECK_CASE } while (!Content.empty()); return false; } void splitTextByComma(StringRef Text, std::vector<StringRef>& Subs) { do { auto Pair = Text.split(','); auto Key = Pair.first.trim(); if (!Key.empty()) Subs.push_back(Key); Text = Pair.second; } while (!Text.empty()); } namespace clang { namespace comments { class WordPairsArrangedViewer { ArrayRef<std::pair<StringRef, StringRef>> Content; std::vector<StringRef> ViewedText; std::vector<StringRef> Words; StringRef Key; bool isKeyViewed(StringRef K) { return std::find(ViewedText.begin(), ViewedText.end(), K) != ViewedText.end(); } public: WordPairsArrangedViewer(ArrayRef<std::pair<StringRef, StringRef>> Content): Content(Content) {} bool hasNext() { Words.clear(); bool Found = false; for (auto P : Content) { if (!Found && !isKeyViewed(P.first)) { Key = P.first; Found = true; } if (Found && P.first == Key) Words.push_back(P.second); } return Found; } std::pair<StringRef, ArrayRef<StringRef>> next() { bool HasNext = hasNext(); (void) HasNext; assert(HasNext && "Have no more data."); ViewedText.push_back(Key); return std::make_pair(Key, llvm::makeArrayRef(Words)); } }; class ClangCommentExtractor : public ConstCommentVisitor<ClangCommentExtractor> { CommandWordsPairs &Words; const CommandTraits &Traits; std::vector<const Comment *> Parents; void visitChildren(const Comment* C) { Parents.push_back(C); for (auto It = C->child_begin(); It != C->child_end(); ++ It) visit(*It); Parents.pop_back(); } public: ClangCommentExtractor(CommandWordsPairs &Words, const CommandTraits &Traits) : Words(Words), Traits(Traits) {} #define CHILD_VISIT(NAME) \ void visit##NAME(const NAME *C) {\ visitChildren(C);\ } CHILD_VISIT(FullComment) CHILD_VISIT(ParagraphComment) #undef CHILD_VISIT void visitInlineCommandComment(const InlineCommandComment *C) { auto Command = C->getCommandName(Traits); auto CommandKind = getCommandKind(Command); if (CommandKind == CodeCompletionCommandKind::none) return; auto &Parent = Parents.back(); for (auto CIT = std::find(Parent->child_begin(), Parent->child_end(), C) + 1; CIT != Parent->child_end(); CIT++) { if (auto TC = dyn_cast<TextComment>(*CIT)) { auto Text = TC->getText(); std::vector<StringRef> Subs; splitTextByComma(Text, Subs); auto Kind = getCommandName(CommandKind); for (auto S : Subs) Words.push_back(std::make_pair(Kind, S)); } else break; } } }; void getClangDocKeyword(ClangImporter &Importer, const Decl *D, CommandWordsPairs &Words) { ClangCommentExtractor Extractor(Words, Importer.getClangASTContext(). getCommentCommandTraits()); if (auto RC = Importer.getClangASTContext().getRawCommentForAnyRedecl(D)) { auto RT = RC->getRawText(Importer.getClangASTContext().getSourceManager()); if (containsInterestedWords(RT, "@", /*AllowWhitespace*/false)) { FullComment* Comment = Importer.getClangASTContext(). getLocalCommentForDeclUncached(D); Extractor.visit(Comment); } } } } // end namespace comments } // end namespace clang namespace swift { namespace markup { class SwiftDocWordExtractor : public MarkupASTWalker { CommandWordsPairs &Pairs; CodeCompletionCommandKind Kind; public: SwiftDocWordExtractor(CommandWordsPairs &Pairs) : Pairs(Pairs), Kind(CodeCompletionCommandKind::none) {} void visitKeywordField(const KeywordField *Field) override { Kind = CodeCompletionCommandKind::keyword; } void visitRecommendedField(const RecommendedField *Field) override { Kind = CodeCompletionCommandKind::recommended; } void visitRecommendedoverField(const RecommendedoverField *Field) override { Kind = CodeCompletionCommandKind::recommendedover; } void visitMutatingvariantField(const MutatingvariantField *Field) override { Kind = CodeCompletionCommandKind::mutatingvariant; } void visitNonmutatingvariantField(const NonmutatingvariantField *Field) override { Kind = CodeCompletionCommandKind::nonmutatingvariant; } void visitText(const Text *Text) override { if (Kind == CodeCompletionCommandKind::none) return; StringRef CommandName = getCommandName(Kind); std::vector<StringRef> Subs; splitTextByComma(Text->str(), Subs); for (auto S : Subs) Pairs.push_back(std::make_pair(CommandName, S)); } }; void getSwiftDocKeyword(const Decl* D, CommandWordsPairs &Words) { auto Interested = false; for (auto C : D->getRawComment().Comments) { if (containsInterestedWords(C.RawText, "-", /*AllowWhitespace*/true)) { Interested = true; break; } } if (!Interested) return; static swift::markup::MarkupContext MC; auto DC = getSingleDocComment(MC, D); if (!DC.hasValue()) return; SwiftDocWordExtractor Extractor(Words); for (auto Part : DC.getValue()->getBodyNodes()) { switch (Part->getKind()) { case ASTNodeKind::KeywordField: case ASTNodeKind::RecommendedField: case ASTNodeKind::RecommendedoverField: case ASTNodeKind::MutatingvariantField: case ASTNodeKind::NonmutatingvariantField: Extractor.walk(Part); break; default: break; } } } } // end namespace markup } // end namespace swift static bool shouldHideDeclFromCompletionResults(const ValueDecl *D) { // Hide private stdlib declarations. if (D->isPrivateStdlibDecl(/*treatNonBuiltinProtocolsAsPublic*/false) || // ShowInInterfaceAttr is for decls to show in interface as exception but // they are not intended to be used directly. D->getAttrs().hasAttribute<ShowInInterfaceAttr>()) return true; if (AvailableAttr::isUnavailable(D)) return true; if (auto *ClangD = D->getClangDecl()) { if (ClangD->hasAttr<clang::SwiftPrivateAttr>()) return true; } // Hide editor placeholders. if (D->getBaseName().isEditorPlaceholder()) return true; if (!D->isUserAccessible()) return true; return false; } using DeclFilter = std::function<bool(ValueDecl *, DeclVisibilityKind)>; static bool DefaultFilter(ValueDecl* VD, DeclVisibilityKind Kind) { return true; } static bool KeyPathFilter(ValueDecl* decl, DeclVisibilityKind) { return isa<TypeDecl>(decl) || (isa<VarDecl>(decl) && decl->getDeclContext()->isTypeContext()); } static bool SwiftKeyPathFilter(ValueDecl* decl, DeclVisibilityKind) { switch(decl->getKind()){ case DeclKind::Var: case DeclKind::Subscript: return true; default: return false; } } std::string swift::ide::removeCodeCompletionTokens( StringRef Input, StringRef TokenName, unsigned *CompletionOffset) { assert(TokenName.size() >= 1); *CompletionOffset = ~0U; std::string CleanFile; CleanFile.reserve(Input.size()); const std::string Token = std::string("#^") + TokenName.str() + "^#"; for (const char *Ptr = Input.begin(), *End = Input.end(); Ptr != End; ++Ptr) { const char C = *Ptr; if (C == '#' && Ptr <= End - Token.size() && StringRef(Ptr, Token.size()) == Token) { Ptr += Token.size() - 1; *CompletionOffset = CleanFile.size(); CleanFile += '\0'; continue; } if (C == '#' && Ptr <= End - 2 && Ptr[1] == '^') { do { Ptr++; } while (Ptr < End && *Ptr != '#'); if (Ptr == End) break; continue; } CleanFile += C; } return CleanFile; } namespace { class StmtFinder : public ASTWalker { SourceManager &SM; SourceLoc Loc; StmtKind Kind; Stmt *Found = nullptr; public: StmtFinder(SourceManager &SM, SourceLoc Loc, StmtKind Kind) : SM(SM), Loc(Loc), Kind(Kind) {} std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override { return { SM.rangeContainsTokenLoc(S->getSourceRange(), Loc), S }; } Stmt *walkToStmtPost(Stmt *S) override { if (S->getKind() == Kind) { Found = S; return nullptr; } return S; } Stmt *getFoundStmt() const { return Found; } }; } // end anonymous namespace static Stmt *findNearestStmt(const AbstractFunctionDecl *AFD, SourceLoc Loc, StmtKind Kind) { auto &SM = AFD->getASTContext().SourceMgr; assert(SM.rangeContainsTokenLoc(AFD->getSourceRange(), Loc)); StmtFinder Finder(SM, Loc, Kind); // FIXME(thread-safety): the walker is mutating the AST. const_cast<AbstractFunctionDecl *>(AFD)->walk(Finder); return Finder.getFoundStmt(); } /// Prepare the given expression for type-checking again, prinicipally by /// erasing any ErrorType types on the given expression, allowing later /// type-checking to make progress. /// /// FIXME: this is fundamentally a workaround for the fact that we may end up /// typechecking parts of an expression more than once - first for checking /// the context, and later for checking more-specific things like unresolved /// members. We should restructure code-completion type-checking so that we /// never typecheck more than once (or find a more principled way to do it). static void prepareForRetypechecking(Expr *E) { assert(E); struct Eraser : public ASTWalker { std::pair<bool, Expr *> walkToExprPre(Expr *expr) override { if (expr && expr->getType() && expr->getType()->hasError()) expr->setType(Type()); if (auto *ACE = dyn_cast_or_null<AutoClosureExpr>(expr)) { return { true, ACE->getSingleExpressionBody() }; } return { true, expr }; } bool walkToTypeLocPre(TypeLoc &TL) override { if (TL.getType() && TL.getType()->hasError()) TL.setType(Type(), /*was validated*/false); return true; } std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override { if (P && P->hasType() && P->getType()->hasError()) { P->setType(Type()); } return { true, P }; } std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override { return { false, S }; } }; E->walk(Eraser()); } CodeCompletionString::CodeCompletionString(ArrayRef<Chunk> Chunks) { std::uninitialized_copy(Chunks.begin(), Chunks.end(), getTrailingObjects<Chunk>()); NumChunks = Chunks.size(); } CodeCompletionString *CodeCompletionString::create(llvm::BumpPtrAllocator &Allocator, ArrayRef<Chunk> Chunks) { void *CCSMem = Allocator.Allocate(totalSizeToAlloc<Chunk>(Chunks.size()), alignof(CodeCompletionString)); return new (CCSMem) CodeCompletionString(Chunks); } void CodeCompletionString::print(raw_ostream &OS) const { unsigned PrevNestingLevel = 0; for (auto C : getChunks()) { bool AnnotatedTextChunk = false; if (C.getNestingLevel() < PrevNestingLevel) { OS << "#}"; } switch (C.getKind()) { using ChunkKind = Chunk::ChunkKind; case ChunkKind::AccessControlKeyword: case ChunkKind::DeclAttrKeyword: case ChunkKind::DeclAttrParamKeyword: case ChunkKind::OverrideKeyword: case ChunkKind::ThrowsKeyword: case ChunkKind::RethrowsKeyword: case ChunkKind::DeclIntroducer: case ChunkKind::Text: case ChunkKind::LeftParen: case ChunkKind::RightParen: case ChunkKind::LeftBracket: case ChunkKind::RightBracket: case ChunkKind::LeftAngle: case ChunkKind::RightAngle: case ChunkKind::Dot: case ChunkKind::Ellipsis: case ChunkKind::Comma: case ChunkKind::ExclamationMark: case ChunkKind::QuestionMark: case ChunkKind::Ampersand: case ChunkKind::Equal: case ChunkKind::Whitespace: AnnotatedTextChunk = C.isAnnotation(); LLVM_FALLTHROUGH; case ChunkKind::CallParameterName: case ChunkKind::CallParameterInternalName: case ChunkKind::CallParameterColon: case ChunkKind::DeclAttrParamColon: case ChunkKind::CallParameterType: case ChunkKind::CallParameterClosureType: case ChunkKind::GenericParameterName: if (AnnotatedTextChunk) OS << "['"; else if (C.getKind() == ChunkKind::CallParameterInternalName) OS << "("; else if (C.getKind() == ChunkKind::CallParameterClosureType) OS << "##"; for (char Ch : C.getText()) { if (Ch == '\n') OS << "\\n"; else OS << Ch; } if (AnnotatedTextChunk) OS << "']"; else if (C.getKind() == ChunkKind::CallParameterInternalName) OS << ")"; break; case ChunkKind::OptionalBegin: case ChunkKind::CallParameterBegin: case ChunkKind::GenericParameterBegin: OS << "{#"; break; case ChunkKind::DynamicLookupMethodCallTail: case ChunkKind::OptionalMethodCallTail: OS << C.getText(); break; case ChunkKind::TypeAnnotation: OS << "[#"; OS << C.getText(); OS << "#]"; break; case ChunkKind::BraceStmtWithCursor: OS << " {|}"; break; } PrevNestingLevel = C.getNestingLevel(); } while (PrevNestingLevel > 0) { OS << "#}"; PrevNestingLevel--; } } void CodeCompletionString::dump() const { print(llvm::errs()); } CodeCompletionDeclKind CodeCompletionResult::getCodeCompletionDeclKind(const Decl *D) { switch (D->getKind()) { case DeclKind::Import: case DeclKind::Extension: case DeclKind::PatternBinding: case DeclKind::EnumCase: case DeclKind::TopLevelCode: case DeclKind::IfConfig: case DeclKind::PoundDiagnostic: case DeclKind::MissingMember: llvm_unreachable("not expecting such a declaration result"); case DeclKind::Module: return CodeCompletionDeclKind::Module; case DeclKind::TypeAlias: return CodeCompletionDeclKind::TypeAlias; case DeclKind::AssociatedType: return CodeCompletionDeclKind::AssociatedType; case DeclKind::GenericTypeParam: return CodeCompletionDeclKind::GenericTypeParam; case DeclKind::Enum: return CodeCompletionDeclKind::Enum; case DeclKind::Struct: return CodeCompletionDeclKind::Struct; case DeclKind::Class: return CodeCompletionDeclKind::Class; case DeclKind::Protocol: return CodeCompletionDeclKind::Protocol; case DeclKind::Var: case DeclKind::Param: { auto DC = D->getDeclContext(); if (DC->isTypeContext()) { if (cast<VarDecl>(D)->isStatic()) return CodeCompletionDeclKind::StaticVar; else return CodeCompletionDeclKind::InstanceVar; } if (DC->isLocalContext()) return CodeCompletionDeclKind::LocalVar; return CodeCompletionDeclKind::GlobalVar; } case DeclKind::Constructor: return CodeCompletionDeclKind::Constructor; case DeclKind::Destructor: return CodeCompletionDeclKind::Destructor; case DeclKind::Accessor: case DeclKind::Func: { auto DC = D->getDeclContext(); auto FD = cast<FuncDecl>(D); if (DC->isTypeContext()) { if (FD->isStatic()) return CodeCompletionDeclKind::StaticMethod; return CodeCompletionDeclKind::InstanceMethod; } if (FD->isOperator()) { if (auto op = FD->getOperatorDecl()) { switch (op->getKind()) { case DeclKind::PrefixOperator: return CodeCompletionDeclKind::PrefixOperatorFunction; case DeclKind::PostfixOperator: return CodeCompletionDeclKind::PostfixOperatorFunction; case DeclKind::InfixOperator: return CodeCompletionDeclKind::InfixOperatorFunction; default: llvm_unreachable("unexpected operator kind"); } } else { return CodeCompletionDeclKind::InfixOperatorFunction; } } return CodeCompletionDeclKind::FreeFunction; } case DeclKind::InfixOperator: return CodeCompletionDeclKind::InfixOperatorFunction; case DeclKind::PrefixOperator: return CodeCompletionDeclKind::PrefixOperatorFunction; case DeclKind::PostfixOperator: return CodeCompletionDeclKind::PostfixOperatorFunction; case DeclKind::PrecedenceGroup: return CodeCompletionDeclKind::PrecedenceGroup; case DeclKind::EnumElement: return CodeCompletionDeclKind::EnumElement; case DeclKind::Subscript: return CodeCompletionDeclKind::Subscript; } llvm_unreachable("invalid DeclKind"); } void CodeCompletionResult::print(raw_ostream &OS) const { llvm::SmallString<64> Prefix; switch (getKind()) { case ResultKind::Declaration: Prefix.append("Decl"); switch (getAssociatedDeclKind()) { case CodeCompletionDeclKind::Class: Prefix.append("[Class]"); break; case CodeCompletionDeclKind::Struct: Prefix.append("[Struct]"); break; case CodeCompletionDeclKind::Enum: Prefix.append("[Enum]"); break; case CodeCompletionDeclKind::EnumElement: Prefix.append("[EnumElement]"); break; case CodeCompletionDeclKind::Protocol: Prefix.append("[Protocol]"); break; case CodeCompletionDeclKind::TypeAlias: Prefix.append("[TypeAlias]"); break; case CodeCompletionDeclKind::AssociatedType: Prefix.append("[AssociatedType]"); break; case CodeCompletionDeclKind::GenericTypeParam: Prefix.append("[GenericTypeParam]"); break; case CodeCompletionDeclKind::Constructor: Prefix.append("[Constructor]"); break; case CodeCompletionDeclKind::Destructor: Prefix.append("[Destructor]"); break; case CodeCompletionDeclKind::Subscript: Prefix.append("[Subscript]"); break; case CodeCompletionDeclKind::StaticMethod: Prefix.append("[StaticMethod]"); break; case CodeCompletionDeclKind::InstanceMethod: Prefix.append("[InstanceMethod]"); break; case CodeCompletionDeclKind::PrefixOperatorFunction: Prefix.append("[PrefixOperatorFunction]"); break; case CodeCompletionDeclKind::PostfixOperatorFunction: Prefix.append("[PostfixOperatorFunction]"); break; case CodeCompletionDeclKind::InfixOperatorFunction: Prefix.append("[InfixOperatorFunction]"); break; case CodeCompletionDeclKind::FreeFunction: Prefix.append("[FreeFunction]"); break; case CodeCompletionDeclKind::StaticVar: Prefix.append("[StaticVar]"); break; case CodeCompletionDeclKind::InstanceVar: Prefix.append("[InstanceVar]"); break; case CodeCompletionDeclKind::LocalVar: Prefix.append("[LocalVar]"); break; case CodeCompletionDeclKind::GlobalVar: Prefix.append("[GlobalVar]"); break; case CodeCompletionDeclKind::Module: Prefix.append("[Module]"); break; case CodeCompletionDeclKind::PrecedenceGroup: Prefix.append("[PrecedenceGroup]"); break; } break; case ResultKind::Keyword: Prefix.append("Keyword"); switch (getKeywordKind()) { case CodeCompletionKeywordKind::None: break; #define KEYWORD(X) case CodeCompletionKeywordKind::kw_##X: \ Prefix.append("[" #X "]"); \ break; #define POUND_KEYWORD(X) case CodeCompletionKeywordKind::pound_##X: \ Prefix.append("[#" #X "]"); \ break; #include "swift/Syntax/TokenKinds.def" } break; case ResultKind::Pattern: Prefix.append("Pattern"); break; case ResultKind::Literal: Prefix.append("Literal"); switch (getLiteralKind()) { case CodeCompletionLiteralKind::ArrayLiteral: Prefix.append("[Array]"); break; case CodeCompletionLiteralKind::BooleanLiteral: Prefix.append("[Boolean]"); break; case CodeCompletionLiteralKind::ColorLiteral: Prefix.append("[_Color]"); break; case CodeCompletionLiteralKind::ImageLiteral: Prefix.append("[_Image]"); break; case CodeCompletionLiteralKind::DictionaryLiteral: Prefix.append("[Dictionary]"); break; case CodeCompletionLiteralKind::IntegerLiteral: Prefix.append("[Integer]"); break; case CodeCompletionLiteralKind::NilLiteral: Prefix.append("[Nil]"); break; case CodeCompletionLiteralKind::StringLiteral: Prefix.append("[String]"); break; case CodeCompletionLiteralKind::Tuple: Prefix.append("[Tuple]"); break; } break; case ResultKind::BuiltinOperator: Prefix.append("BuiltinOperator"); break; } Prefix.append("/"); switch (getSemanticContext()) { case SemanticContextKind::None: Prefix.append("None"); break; case SemanticContextKind::ExpressionSpecific: Prefix.append("ExprSpecific"); break; case SemanticContextKind::Local: Prefix.append("Local"); break; case SemanticContextKind::CurrentNominal: Prefix.append("CurrNominal"); break; case SemanticContextKind::Super: Prefix.append("Super"); break; case SemanticContextKind::OutsideNominal: Prefix.append("OutNominal"); break; case SemanticContextKind::CurrentModule: Prefix.append("CurrModule"); break; case SemanticContextKind::OtherModule: Prefix.append("OtherModule"); if (!ModuleName.empty()) Prefix.append((Twine("[") + ModuleName + "]").str()); break; } if (NotRecommended) Prefix.append("/NotRecommended"); if (NumBytesToErase != 0) { Prefix.append("/Erase["); Prefix.append(Twine(NumBytesToErase).str()); Prefix.append("]"); } switch (TypeDistance) { case ExpectedTypeRelation::Invalid: Prefix.append("/TypeRelation[Invalid]"); break; case ExpectedTypeRelation::Identical: Prefix.append("/TypeRelation[Identical]"); break; case ExpectedTypeRelation::Convertible: Prefix.append("/TypeRelation[Convertible]"); break; case ExpectedTypeRelation::Unrelated: break; } for (clang::comments::WordPairsArrangedViewer Viewer(DocWords); Viewer.hasNext();) { auto Pair = Viewer.next(); Prefix.append("/"); Prefix.append(Pair.first); Prefix.append("["); StringRef Sep = ", "; for (auto KW : Pair.second) { Prefix.append(KW); Prefix.append(Sep); } for (unsigned I = 0, N = Sep.size(); I < N; ++I) Prefix.pop_back(); Prefix.append("]"); } Prefix.append(": "); while (Prefix.size() < 36) { Prefix.append(" "); } OS << Prefix; CompletionString->print(OS); } void CodeCompletionResult::dump() const { print(llvm::errs()); } static StringRef copyString(llvm::BumpPtrAllocator &Allocator, StringRef Str) { char *Mem = Allocator.Allocate<char>(Str.size()); std::copy(Str.begin(), Str.end(), Mem); return StringRef(Mem, Str.size()); } static ArrayRef<StringRef> copyStringArray(llvm::BumpPtrAllocator &Allocator, ArrayRef<StringRef> Arr) { StringRef *Buff = Allocator.Allocate<StringRef>(Arr.size()); std::copy(Arr.begin(), Arr.end(), Buff); return llvm::makeArrayRef(Buff, Arr.size()); } static ArrayRef<std::pair<StringRef, StringRef>> copyStringPairArray( llvm::BumpPtrAllocator &Allocator, ArrayRef<std::pair<StringRef, StringRef>> Arr) { std::pair<StringRef, StringRef> *Buff = Allocator.Allocate<std::pair<StringRef, StringRef>>(Arr.size()); std::copy(Arr.begin(), Arr.end(), Buff); return llvm::makeArrayRef(Buff, Arr.size()); } void CodeCompletionResultBuilder::addChunkWithText( CodeCompletionString::Chunk::ChunkKind Kind, StringRef Text) { addChunkWithTextNoCopy(Kind, copyString(*Sink.Allocator, Text)); } void CodeCompletionResultBuilder::setAssociatedDecl(const Decl *D) { assert(Kind == CodeCompletionResult::ResultKind::Declaration); AssociatedDecl = D; if (auto *ClangD = D->getClangDecl()) CurrentModule = ClangD->getImportedOwningModule(); // FIXME: macros // FIXME: imported header module if (!CurrentModule) CurrentModule = D->getModuleContext(); if (D->getAttrs().getDeprecated(D->getASTContext())) setNotRecommended(CodeCompletionResult::Deprecated); } StringRef CodeCompletionContext::copyString(StringRef Str) { return ::copyString(*CurrentResults.Allocator, Str); } bool shouldCopyAssociatedUSRForDecl(const ValueDecl *VD) { // Avoid trying to generate a USR for some declaration types. if (isa<AbstractTypeParamDecl>(VD) && !isa<AssociatedTypeDecl>(VD)) return false; if (isa<ParamDecl>(VD)) return false; if (isa<ModuleDecl>(VD)) return false; if (VD->hasClangNode() && !VD->getClangDecl()) return false; return true; } template <typename FnTy> static void walkValueDeclAndOverriddenDecls(const Decl *D, const FnTy &Fn) { if (auto *VD = dyn_cast<ValueDecl>(D)) { Fn(VD); walkOverriddenDecls(VD, Fn); } } ArrayRef<StringRef> copyAssociatedUSRs(llvm::BumpPtrAllocator &Allocator, const Decl *D) { llvm::SmallVector<StringRef, 4> USRs; walkValueDeclAndOverriddenDecls(D, [&](llvm::PointerUnion<const ValueDecl*, const clang::NamedDecl*> OD) { llvm::SmallString<128> SS; bool Ignored = true; if (auto *OVD = OD.dyn_cast<const ValueDecl*>()) { if (shouldCopyAssociatedUSRForDecl(OVD)) { llvm::raw_svector_ostream OS(SS); Ignored = printDeclUSR(OVD, OS); } } else if (auto *OND = OD.dyn_cast<const clang::NamedDecl*>()) { Ignored = clang::index::generateUSRForDecl(OND, SS); } if (!Ignored) USRs.push_back(copyString(Allocator, SS)); }); if (!USRs.empty()) return copyStringArray(Allocator, USRs); return ArrayRef<StringRef>(); } static CodeCompletionResult::ExpectedTypeRelation calculateTypeRelation( Type Ty, Type ExpectedTy, DeclContext *DC) { if (Ty.isNull() || ExpectedTy.isNull() || Ty->is<ErrorType>() || ExpectedTy->is<ErrorType>()) return CodeCompletionResult::ExpectedTypeRelation::Unrelated; // Equality/Conversion of GenericTypeParameterType won't account for // requirements – ignore them if (!Ty->hasTypeParameter() && !ExpectedTy->hasTypeParameter()) { if (Ty->isEqual(ExpectedTy)) return CodeCompletionResult::ExpectedTypeRelation::Identical; if (isConvertibleTo(Ty, ExpectedTy, *DC)) return CodeCompletionResult::ExpectedTypeRelation::Convertible; } if (auto FT = Ty->getAs<AnyFunctionType>()) { if (FT->getResult()->isVoid()) return CodeCompletionResult::ExpectedTypeRelation::Invalid; } return CodeCompletionResult::ExpectedTypeRelation::Unrelated; } static CodeCompletionResult::ExpectedTypeRelation calculateTypeRelationForDecl(const Decl *D, Type ExpectedType, bool IsImplicitlyCurriedInstanceMethod, bool UseFuncResultType = true) { auto VD = dyn_cast<ValueDecl>(D); auto DC = D->getDeclContext(); if (!VD) return CodeCompletionResult::ExpectedTypeRelation::Unrelated; if (auto FD = dyn_cast<AbstractFunctionDecl>(VD)) { auto funcType = FD->getInterfaceType()->getAs<AnyFunctionType>(); if (DC->isTypeContext() && funcType && funcType->is<AnyFunctionType>() && !IsImplicitlyCurriedInstanceMethod) funcType = funcType->getResult()->getAs<AnyFunctionType>(); if (funcType) { auto relation = calculateTypeRelation(funcType, ExpectedType, DC); if (UseFuncResultType) relation = std::max(relation, calculateTypeRelation(funcType->getResult(), ExpectedType, DC)); return relation; } } if (auto NTD = dyn_cast<NominalTypeDecl>(VD)) { return std::max( calculateTypeRelation(NTD->getInterfaceType(), ExpectedType, DC), calculateTypeRelation(NTD->getDeclaredInterfaceType(), ExpectedType, DC)); } return calculateTypeRelation(VD->getInterfaceType(), ExpectedType, DC); } static CodeCompletionResult::ExpectedTypeRelation calculateMaxTypeRelationForDecl( const Decl *D, ArrayRef<Type> ExpectedTypes, bool IsImplicitlyCurriedInstanceMethod = false) { auto Result = CodeCompletionResult::ExpectedTypeRelation::Unrelated; for (auto Type : ExpectedTypes) { Result = std::max(Result, calculateTypeRelationForDecl( D, Type, IsImplicitlyCurriedInstanceMethod)); } return Result; } CodeCompletionOperatorKind CodeCompletionResult::getCodeCompletionOperatorKind(StringRef name) { using CCOK = CodeCompletionOperatorKind; using OpPair = std::pair<StringRef, CCOK>; // This list must be kept in alphabetical order. static OpPair ops[] = { std::make_pair("!", CCOK::Bang), std::make_pair("!=", CCOK::NotEq), std::make_pair("!==", CCOK::NotEqEq), std::make_pair("%", CCOK::Modulo), std::make_pair("%=", CCOK::ModuloEq), std::make_pair("&", CCOK::Amp), std::make_pair("&&", CCOK::AmpAmp), std::make_pair("&*", CCOK::AmpStar), std::make_pair("&+", CCOK::AmpPlus), std::make_pair("&-", CCOK::AmpMinus), std::make_pair("&=", CCOK::AmpEq), std::make_pair("(", CCOK::LParen), std::make_pair("*", CCOK::Star), std::make_pair("*=", CCOK::StarEq), std::make_pair("+", CCOK::Plus), std::make_pair("+=", CCOK::PlusEq), std::make_pair("-", CCOK::Minus), std::make_pair("-=", CCOK::MinusEq), std::make_pair(".", CCOK::Dot), std::make_pair("...", CCOK::DotDotDot), std::make_pair("..<", CCOK::DotDotLess), std::make_pair("/", CCOK::Slash), std::make_pair("/=", CCOK::SlashEq), std::make_pair("<", CCOK::Less), std::make_pair("<<", CCOK::LessLess), std::make_pair("<<=", CCOK::LessLessEq), std::make_pair("<=", CCOK::LessEq), std::make_pair("=", CCOK::Eq), std::make_pair("==", CCOK::EqEq), std::make_pair("===", CCOK::EqEqEq), std::make_pair(">", CCOK::Greater), std::make_pair(">=", CCOK::GreaterEq), std::make_pair(">>", CCOK::GreaterGreater), std::make_pair(">>=", CCOK::GreaterGreaterEq), std::make_pair("?.", CCOK::QuestionDot), std::make_pair("^", CCOK::Caret), std::make_pair("^=", CCOK::CaretEq), std::make_pair("|", CCOK::Pipe), std::make_pair("|=", CCOK::PipeEq), std::make_pair("||", CCOK::PipePipe), std::make_pair("~=", CCOK::TildeEq), }; static auto opsSize = sizeof(ops) / sizeof(ops[0]); auto I = std::lower_bound( ops, &ops[opsSize], std::make_pair(name, CCOK::None), [](const OpPair &a, const OpPair &b) { return a.first < b.first; }); if (I == &ops[opsSize] || I->first != name) return CCOK::Unknown; return I->second; } static StringRef getOperatorName(CodeCompletionString *str) { return str->getFirstTextChunk(/*includeLeadingPunctuation=*/true); } CodeCompletionOperatorKind CodeCompletionResult::getCodeCompletionOperatorKind(CodeCompletionString *str) { return getCodeCompletionOperatorKind(getOperatorName(str)); } CodeCompletionResult *CodeCompletionResultBuilder::takeResult() { auto *CCS = CodeCompletionString::create(*Sink.Allocator, Chunks); switch (Kind) { case CodeCompletionResult::ResultKind::Declaration: { StringRef BriefComment; auto MaybeClangNode = AssociatedDecl->getClangNode(); if (MaybeClangNode) { if (auto *D = MaybeClangNode.getAsDecl()) { const auto &ClangContext = D->getASTContext(); if (const clang::RawComment *RC = ClangContext.getRawCommentForAnyRedecl(D)) BriefComment = RC->getBriefText(ClangContext); } } else { BriefComment = AssociatedDecl->getBriefComment(); } StringRef ModuleName; if (CurrentModule) { if (Sink.LastModule.first == CurrentModule.getOpaqueValue()) { ModuleName = Sink.LastModule.second; } else { if (auto *C = CurrentModule.dyn_cast<const clang::Module *>()) { ModuleName = copyString(*Sink.Allocator, C->getFullModuleName()); } else { ModuleName = copyString( *Sink.Allocator, CurrentModule.get<const swift::ModuleDecl *>()->getName().str()); } Sink.LastModule.first = CurrentModule.getOpaqueValue(); Sink.LastModule.second = ModuleName; } } auto typeRelation = ExpectedTypeRelation; if (typeRelation == CodeCompletionResult::Unrelated) typeRelation = calculateMaxTypeRelationForDecl(AssociatedDecl, ExpectedDeclTypes); if (typeRelation == CodeCompletionResult::Invalid) { IsNotRecommended = true; NotRecReason = CodeCompletionResult::NotRecommendedReason::TypeMismatch; } return new (*Sink.Allocator) CodeCompletionResult( SemanticContext, NumBytesToErase, CCS, AssociatedDecl, ModuleName, /*NotRecommended=*/IsNotRecommended, NotRecReason, copyString(*Sink.Allocator, BriefComment), copyAssociatedUSRs(*Sink.Allocator, AssociatedDecl), copyStringPairArray(*Sink.Allocator, CommentWords), typeRelation); } case CodeCompletionResult::ResultKind::Keyword: return new (*Sink.Allocator) CodeCompletionResult(KeywordKind, SemanticContext, NumBytesToErase, CCS, ExpectedTypeRelation); case CodeCompletionResult::ResultKind::BuiltinOperator: case CodeCompletionResult::ResultKind::Pattern: return new (*Sink.Allocator) CodeCompletionResult( Kind, SemanticContext, NumBytesToErase, CCS, ExpectedTypeRelation); case CodeCompletionResult::ResultKind::Literal: assert(LiteralKind.hasValue()); return new (*Sink.Allocator) CodeCompletionResult(*LiteralKind, SemanticContext, NumBytesToErase, CCS, ExpectedTypeRelation); } llvm_unreachable("Unhandled CodeCompletionResult in switch."); } void CodeCompletionResultBuilder::finishResult() { if (!Cancelled) Sink.Results.push_back(takeResult()); } MutableArrayRef<CodeCompletionResult *> CodeCompletionContext::takeResults() { // Copy pointers to the results. const size_t Count = CurrentResults.Results.size(); CodeCompletionResult **Results = CurrentResults.Allocator->Allocate<CodeCompletionResult *>(Count); std::copy(CurrentResults.Results.begin(), CurrentResults.Results.end(), Results); CurrentResults.Results.clear(); return MutableArrayRef<CodeCompletionResult *>(Results, Count); } Optional<unsigned> CodeCompletionString::getFirstTextChunkIndex( bool includeLeadingPunctuation) const { for (auto i : indices(getChunks())) { auto &C = getChunks()[i]; switch (C.getKind()) { using ChunkKind = Chunk::ChunkKind; case ChunkKind::Text: case ChunkKind::CallParameterName: case ChunkKind::CallParameterInternalName: case ChunkKind::GenericParameterName: case ChunkKind::LeftParen: case ChunkKind::LeftBracket: case ChunkKind::Equal: case ChunkKind::DeclAttrParamKeyword: case ChunkKind::DeclAttrKeyword: return i; case ChunkKind::Dot: case ChunkKind::ExclamationMark: case ChunkKind::QuestionMark: if (includeLeadingPunctuation) return i; continue; case ChunkKind::RightParen: case ChunkKind::RightBracket: case ChunkKind::LeftAngle: case ChunkKind::RightAngle: case ChunkKind::Ellipsis: case ChunkKind::Comma: case ChunkKind::Ampersand: case ChunkKind::Whitespace: case ChunkKind::AccessControlKeyword: case ChunkKind::OverrideKeyword: case ChunkKind::ThrowsKeyword: case ChunkKind::RethrowsKeyword: case ChunkKind::DeclIntroducer: case ChunkKind::CallParameterColon: case ChunkKind::DeclAttrParamColon: case ChunkKind::CallParameterType: case ChunkKind::CallParameterClosureType: case ChunkKind::OptionalBegin: case ChunkKind::CallParameterBegin: case ChunkKind::GenericParameterBegin: case ChunkKind::DynamicLookupMethodCallTail: case ChunkKind::OptionalMethodCallTail: case ChunkKind::TypeAnnotation: continue; case ChunkKind::BraceStmtWithCursor: llvm_unreachable("should have already extracted the text"); } } return None; } StringRef CodeCompletionString::getFirstTextChunk(bool includeLeadingPunctuation) const { Optional<unsigned> Idx = getFirstTextChunkIndex(includeLeadingPunctuation); if (Idx.hasValue()) return getChunks()[*Idx].getText(); return StringRef(); } void CodeCompletionString::getName(raw_ostream &OS) const { auto FirstTextChunk = getFirstTextChunkIndex(); int TextSize = 0; if (FirstTextChunk.hasValue()) { for (auto C : getChunks().slice(*FirstTextChunk)) { using ChunkKind = Chunk::ChunkKind; bool shouldPrint = !C.isAnnotation(); switch (C.getKind()) { case ChunkKind::TypeAnnotation: case ChunkKind::CallParameterClosureType: case ChunkKind::DeclAttrParamColon: case ChunkKind::OptionalMethodCallTail: continue; case ChunkKind::ThrowsKeyword: case ChunkKind::RethrowsKeyword: shouldPrint = true; // Even when they're annotations. break; default: break; } if (C.hasText() && shouldPrint) { TextSize += C.getText().size(); OS << C.getText(); } } } assert((TextSize > 0) && "code completion string should have non-empty name!"); } void CodeCompletionContext::sortCompletionResults( MutableArrayRef<CodeCompletionResult *> Results) { struct ResultAndName { CodeCompletionResult *result; std::string name; }; // Caching the name of each field is important to avoid unnecessary calls to // CodeCompletionString::getName(). std::vector<ResultAndName> nameCache(Results.size()); for (unsigned i = 0, n = Results.size(); i < n; ++i) { auto *result = Results[i]; nameCache[i].result = result; llvm::raw_string_ostream OS(nameCache[i].name); result->getCompletionString()->getName(OS); OS.flush(); } // Sort nameCache, and then transform Results to return the pointers in order. std::sort(nameCache.begin(), nameCache.end(), [](const ResultAndName &LHS, const ResultAndName &RHS) { int Result = StringRef(LHS.name).compare_lower(RHS.name); // If the case insensitive comparison is equal, then secondary sort order // should be case sensitive. if (Result == 0) Result = LHS.name.compare(RHS.name); return Result < 0; }); std::transform(nameCache.begin(), nameCache.end(), Results.begin(), [](const ResultAndName &entry) { return entry.result; }); } namespace { class CodeCompletionCallbacksImpl : public CodeCompletionCallbacks { CodeCompletionContext &CompletionContext; std::vector<RequestedCachedModule> RequestedModules; CodeCompletionConsumer &Consumer; CodeCompletionExpr *CodeCompleteTokenExpr = nullptr; AssignExpr *AssignmentExpr; CallExpr *FuncCallExpr; UnresolvedMemberExpr *UnresolvedExpr; bool UnresolvedExprInReturn; std::vector<std::string> TokensBeforeUnresolvedExpr; CompletionKind Kind = CompletionKind::None; Expr *ParsedExpr = nullptr; SourceLoc DotLoc; TypeLoc ParsedTypeLoc; DeclContext *CurDeclContext = nullptr; DeclAttrKind AttrKind; int AttrParamIndex; bool IsInSil; bool HasSpace = false; bool ShouldCompleteCallPatternAfterParen = true; bool PreferFunctionReferencesToCalls = false; Optional<DeclKind> AttTargetDK; SmallVector<StringRef, 3> ParsedKeywords; std::vector<std::pair<std::string, bool>> SubModuleNameVisibilityPairs; StmtKind ParentStmtKind; void addSuperKeyword(CodeCompletionResultSink &Sink) { auto *DC = CurDeclContext->getInnermostTypeContext(); if (!DC) return; auto *CD = DC->getAsClassOrClassExtensionContext(); if (!CD) return; Type ST = CD->getSuperclass(); if (ST.isNull() || ST->is<ErrorType>()) return; CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::CurrentNominal, {}); Builder.setKeywordKind(CodeCompletionKeywordKind::kw_super); Builder.addTextChunk("super"); Builder.addTypeAnnotation(ST.getString()); } /// \brief Set to true when we have delivered code completion results /// to the \c Consumer. bool DeliveredResults = false; bool typecheckContext(DeclContext *DC) { // Nothing to type check in module context. if (DC->isModuleScopeContext()) return true; // Type check the parent context. if (!typecheckContext(DC->getParent())) return false; // Type-check this context. switch (DC->getContextKind()) { case DeclContextKind::AbstractClosureExpr: case DeclContextKind::Initializer: case DeclContextKind::Module: case DeclContextKind::SerializedLocal: // Nothing to do for these. return true; case DeclContextKind::AbstractFunctionDecl: return typeCheckAbstractFunctionBodyUntil( cast<AbstractFunctionDecl>(DC), P.Context.SourceMgr.getCodeCompletionLoc()); case DeclContextKind::ExtensionDecl: return typeCheckCompletionDecl(cast<ExtensionDecl>(DC)); case DeclContextKind::GenericTypeDecl: return typeCheckCompletionDecl(cast<GenericTypeDecl>(DC)); case DeclContextKind::FileUnit: llvm_unreachable("module scope context handled above"); case DeclContextKind::SubscriptDecl: // FIXME: what do we need to check here? return true; case DeclContextKind::TopLevelCodeDecl: return typeCheckTopLevelCodeDecl(cast<TopLevelCodeDecl>(DC)); } llvm_unreachable("Unhandled DeclContextKind in switch."); } Optional<std::pair<Type, ConcreteDeclRef>> typeCheckParsedExpr() { assert(ParsedExpr && "should have an expression"); // Figure out the kind of type-check we'll be performing. auto CheckKind = CompletionTypeCheckKind::Normal; if (Kind == CompletionKind::KeyPathExpr || Kind == CompletionKind::KeyPathExprDot) CheckKind = CompletionTypeCheckKind::KeyPath; // If we've already successfully type-checked the expression for some // reason, just return the type. // FIXME: if it's ErrorType but we've already typechecked we shouldn't // typecheck again. rdar://21466394 if (CheckKind == CompletionTypeCheckKind::Normal && ParsedExpr->getType() && !ParsedExpr->getType()->is<ErrorType>()) return std::make_pair(ParsedExpr->getType(), ParsedExpr->getReferencedDecl()); prepareForRetypechecking(ParsedExpr); ConcreteDeclRef ReferencedDecl = nullptr; Expr *ModifiedExpr = ParsedExpr; if (auto T = getTypeOfCompletionContextExpr(P.Context, CurDeclContext, CheckKind, ModifiedExpr, ReferencedDecl)) { // FIXME: even though we don't apply the solution, the type checker may // modify the original expression. We should understand what effect that // may have on code completion. ParsedExpr = ModifiedExpr; return std::make_pair(*T, ReferencedDecl); } return None; } /// \returns true on success, false on failure. bool typecheckParsedType() { assert(ParsedTypeLoc.getTypeRepr() && "should have a TypeRepr"); return !performTypeLocChecking(P.Context, ParsedTypeLoc, CurDeclContext, false); } public: CodeCompletionCallbacksImpl(Parser &P, CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CodeCompletionCallbacks(P), CompletionContext(CompletionContext), Consumer(Consumer) { } void completeExpr() override; void completeDotExpr(Expr *E, SourceLoc DotLoc) override; void completeStmtOrExpr() override; void completePostfixExprBeginning(CodeCompletionExpr *E) override; void completeForEachSequenceBeginning(CodeCompletionExpr *E) override; void completePostfixExpr(Expr *E, bool hasSpace) override; void completePostfixExprParen(Expr *E, Expr *CodeCompletionE) override; void completeExprSuper(SuperRefExpr *SRE) override; void completeExprSuperDot(SuperRefExpr *SRE) override; void completeExprKeyPath(KeyPathExpr *KPE, bool HasDot) override; void completeTypeSimpleBeginning() override; void completeTypeIdentifierWithDot(IdentTypeRepr *ITR) override; void completeTypeIdentifierWithoutDot(IdentTypeRepr *ITR) override; void completeCaseStmtBeginning() override; void completeCaseStmtDotPrefix() override; void completeDeclAttrKeyword(Decl *D, bool Sil, bool Param) override; void completeDeclAttrParam(DeclAttrKind DK, int Index) override; void completeNominalMemberBeginning( SmallVectorImpl<StringRef> &Keywords) override; void completePoundAvailablePlatform() override; void completeImportDecl(std::vector<std::pair<Identifier, SourceLoc>> &Path) override; void completeUnresolvedMember(UnresolvedMemberExpr *E, ArrayRef<StringRef> Identifiers, bool HasReturn) override; void completeAssignmentRHS(AssignExpr *E) override; void completeCallArg(CallExpr *E) override; void completeReturnStmt(CodeCompletionExpr *E) override; void completeAfterPound(CodeCompletionExpr *E, StmtKind ParentKind) override; void completeGenericParams(TypeLoc TL) override; void addKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody); void doneParsing() override; void deliverCompletionResults(); }; } // end anonymous namespace void CodeCompletionCallbacksImpl::completeExpr() { if (DeliveredResults) return; Parser::ParserPositionRAII RestorePosition(P); P.restoreParserPosition(ExprBeginPosition); // FIXME: implement fallback code completion. deliverCompletionResults(); } namespace { static bool isTopLevelContext(const DeclContext *DC) { for (; DC && DC->isLocalContext(); DC = DC->getParent()) { switch (DC->getContextKind()) { case DeclContextKind::TopLevelCodeDecl: return true; case DeclContextKind::AbstractFunctionDecl: case DeclContextKind::SubscriptDecl: return false; default: continue; } } return false; } static Type getReturnTypeFromContext(const DeclContext *DC) { if (auto FD = dyn_cast<AbstractFunctionDecl>(DC)) { if (FD->hasInterfaceType()) { if (auto FT = FD->getInterfaceType()->getAs<FunctionType>()) { return FT->getResult(); } } } else if (auto CE = dyn_cast<AbstractClosureExpr>(DC)) { if (CE->getType()) { return CE->getResultType(); } } return Type(); } static KnownProtocolKind protocolForLiteralKind(CodeCompletionLiteralKind kind) { switch (kind) { case CodeCompletionLiteralKind::ArrayLiteral: return KnownProtocolKind::ExpressibleByArrayLiteral; case CodeCompletionLiteralKind::BooleanLiteral: return KnownProtocolKind::ExpressibleByBooleanLiteral; case CodeCompletionLiteralKind::ColorLiteral: return KnownProtocolKind::ExpressibleByColorLiteral; case CodeCompletionLiteralKind::ImageLiteral: return KnownProtocolKind::ExpressibleByImageLiteral; case CodeCompletionLiteralKind::DictionaryLiteral: return KnownProtocolKind::ExpressibleByDictionaryLiteral; case CodeCompletionLiteralKind::IntegerLiteral: return KnownProtocolKind::ExpressibleByIntegerLiteral; case CodeCompletionLiteralKind::NilLiteral: return KnownProtocolKind::ExpressibleByNilLiteral; case CodeCompletionLiteralKind::StringLiteral: return KnownProtocolKind::ExpressibleByUnicodeScalarLiteral; case CodeCompletionLiteralKind::Tuple: llvm_unreachable("no such protocol kind"); } llvm_unreachable("Unhandled CodeCompletionLiteralKind in switch."); } /// Whether funcType has a single argument (not including defaulted arguments) /// that is of type () -> (). static bool hasTrivialTrailingClosure(const FuncDecl *FD, AnyFunctionType *funcType) { llvm::SmallBitVector defaultMap = computeDefaultMap(funcType->getParams(), FD, /*level*/ FD->isInstanceMember() ? 1 : 0); if (defaultMap.size() - defaultMap.count() == 1) { auto param = funcType->getParams().back(); if (!param.isAutoClosure()) { if (auto Fn = param.getType()->getAs<AnyFunctionType>()) { return Fn->getInput()->isVoid() && Fn->getResult()->isVoid(); } } } return false; } /// Build completions by doing visible decl lookup from a context. class CompletionLookup final : public swift::VisibleDeclConsumer { CodeCompletionResultSink &Sink; ASTContext &Ctx; OwnedResolver TypeResolver; const DeclContext *CurrDeclContext; ClangImporter *Importer; CodeCompletionContext *CompletionContext; enum class LookupKind { ValueExpr, ValueInDeclContext, EnumElement, Type, TypeInDeclContext, ImportFromModule }; LookupKind Kind; /// Type of the user-provided expression for LookupKind::ValueExpr /// completions. Type ExprType; /// Whether the expr is of statically inferred metatype. bool IsStaticMetatype; /// User-provided base type for LookupKind::Type completions. Type BaseType; /// Expected types of the code completion expression. std::vector<Type> ExpectedTypes; bool HaveDot = false; bool IsUnwrappedOptional = false; SourceLoc DotLoc; bool NeedLeadingDot = false; bool NeedOptionalUnwrap = false; unsigned NumBytesToEraseForOptionalUnwrap = 0; bool HaveLParen = false; bool IsSuperRefExpr = false; bool IsSelfRefExpr = false; bool IsKeyPathExpr = false; bool IsSwiftKeyPathExpr = false; bool IsDynamicLookup = false; bool PreferFunctionReferencesToCalls = false; bool HaveLeadingSpace = false; bool IncludeInstanceMembers = false; /// \brief True if we are code completing inside a static method. bool InsideStaticMethod = false; /// \brief Innermost method that the code completion point is in. const AbstractFunctionDecl *CurrentMethod = nullptr; Optional<SemanticContextKind> ForcedSemanticContext = None; bool IsUnresolvedMember = false; public: bool FoundFunctionCalls = false; bool FoundFunctionsWithoutFirstKeyword = false; private: void foundFunction(const AbstractFunctionDecl *AFD) { FoundFunctionCalls = true; DeclName Name = AFD->getFullName(); auto ArgNames = Name.getArgumentNames(); if (ArgNames.empty()) return; if (ArgNames[0].empty()) FoundFunctionsWithoutFirstKeyword = true; } void foundFunction(const AnyFunctionType *AFT) { FoundFunctionCalls = true; Type In = AFT->getInput(); if (!In) return; if (In->hasParenSugar()) { FoundFunctionsWithoutFirstKeyword = true; return; } TupleType *InTuple = In->getAs<TupleType>(); if (!InTuple) return; auto Elements = InTuple->getElements(); if (Elements.empty()) return; if (!Elements[0].hasName()) FoundFunctionsWithoutFirstKeyword = true; } void setClangDeclKeywords(const ValueDecl *VD, CommandWordsPairs &Pairs, CodeCompletionResultBuilder &Builder) { if (auto *CD = VD->getClangDecl()) { clang::comments::getClangDocKeyword(*Importer, CD, Pairs); } else { swift::markup::getSwiftDocKeyword(VD, Pairs); } Builder.addDeclDocCommentWords(llvm::makeArrayRef(Pairs)); } bool shouldUseFunctionReference(AbstractFunctionDecl *D) { if (PreferFunctionReferencesToCalls) return true; bool isImplicitlyCurriedIM = isImplicitlyCurriedInstanceMethod(D); for (auto expectedType : ExpectedTypes) { if (expectedType && expectedType->lookThroughAllOptionalTypes() ->is<AnyFunctionType>() && calculateTypeRelationForDecl(D, expectedType, isImplicitlyCurriedIM, /*UseFuncResultType=*/false) >= CodeCompletionResult::ExpectedTypeRelation::Convertible) { return true; } } return false; } public: struct RequestedResultsTy { const ModuleDecl *TheModule; bool OnlyTypes; bool NeedLeadingDot; static RequestedResultsTy fromModule(const ModuleDecl *TheModule) { return { TheModule, false, false }; } RequestedResultsTy onlyTypes() const { return { TheModule, true, NeedLeadingDot }; } RequestedResultsTy needLeadingDot(bool NeedDot) const { return { TheModule, OnlyTypes, NeedDot }; } static RequestedResultsTy toplevelResults() { return { nullptr, false, false }; } }; Optional<RequestedResultsTy> RequestedCachedResults; public: CompletionLookup(CodeCompletionResultSink &Sink, ASTContext &Ctx, const DeclContext *CurrDeclContext, CodeCompletionContext *CompletionContext = nullptr) : Sink(Sink), Ctx(Ctx), TypeResolver(createLazyResolver(Ctx)), CurrDeclContext(CurrDeclContext), Importer(static_cast<ClangImporter *>(CurrDeclContext->getASTContext(). getClangModuleLoader())), CompletionContext(CompletionContext) { // Determine if we are doing code completion inside a static method. if (CurrDeclContext) { CurrentMethod = CurrDeclContext->getInnermostMethodContext(); if (auto *FD = dyn_cast_or_null<FuncDecl>(CurrentMethod)) InsideStaticMethod = FD->isStatic(); } } void discardTypeResolver() { TypeResolver.reset(); } void setHaveDot(SourceLoc DotLoc) { HaveDot = true; this->DotLoc = DotLoc; } void setIsUnwrappedOptional(bool value) { IsUnwrappedOptional = value; } void setIsStaticMetatype(bool value) { IsStaticMetatype = value; } void setExpectedTypes(ArrayRef<Type> Types) { ExpectedTypes.reserve(Types.size()); for (auto T : Types) if (T) ExpectedTypes.push_back(T); } bool hasExpectedTypes() const { return !ExpectedTypes.empty(); } bool needDot() const { return NeedLeadingDot; } void setHaveLParen(bool Value) { HaveLParen = Value; } void setIsSuperRefExpr() { IsSuperRefExpr = true; } void setIsSelfRefExpr(bool value) { IsSelfRefExpr = value; } void setIsKeyPathExpr() { IsKeyPathExpr = true; } void setIsSwiftKeyPathExpr() { IsSwiftKeyPathExpr = true; } void setIsDynamicLookup() { IsDynamicLookup = true; } void setPreferFunctionReferencesToCalls() { PreferFunctionReferencesToCalls = true; } void setHaveLeadingSpace(bool value) { HaveLeadingSpace = value; } void includeInstanceMembers() { IncludeInstanceMembers = true; } void addSubModuleNames(std::vector<std::pair<std::string, bool>> &SubModuleNameVisibilityPairs) { for (auto &Pair : SubModuleNameVisibilityPairs) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind:: Declaration, SemanticContextKind::OtherModule, ExpectedTypes); auto MD = ModuleDecl::create(Ctx.getIdentifier(Pair.first), Ctx); Builder.setAssociatedDecl(MD); Builder.addTextChunk(MD->getNameStr()); Builder.addTypeAnnotation("Module"); if (Pair.second) Builder.setNotRecommended(CodeCompletionResult::NotRecommendedReason:: Redundant); } } void collectImportedModules(llvm::StringSet<> &ImportedModules) { SmallVector<ModuleDecl::ImportedModule, 16> Imported; SmallVector<ModuleDecl::ImportedModule, 16> FurtherImported; CurrDeclContext->getParentSourceFile()->getImportedModules(Imported, ModuleDecl::ImportFilter::All); while (!Imported.empty()) { ModuleDecl *MD = Imported.back().second; Imported.pop_back(); if (!ImportedModules.insert(MD->getNameStr()).second) continue; FurtherImported.clear(); MD->getImportedModules(FurtherImported, ModuleDecl::ImportFilter::Public); Imported.append(FurtherImported.begin(), FurtherImported.end()); for (auto SubMod : FurtherImported) { Imported.push_back(SubMod); } } } void addImportModuleNames() { // FIXME: Add user-defined swift modules SmallVector<StringRef, 20> ModuleNames; // Collect clang module names. { SmallVector<clang::Module*, 20> ClangModules; Ctx.getVisibleTopLevelClangModules(ClangModules); for (auto *M : ClangModules) { if (!M->isAvailable()) continue; if (M->getTopLevelModuleName().startswith("_")) continue; if (M->getTopLevelModuleName() == Ctx.SwiftShimsModuleName.str()) continue; ModuleNames.push_back(M->getTopLevelModuleName()); } } std::sort(ModuleNames.begin(), ModuleNames.end(), [](StringRef LHS, StringRef RHS) { return LHS.compare_lower(RHS) < 0; }); llvm::StringSet<> ImportedModules; collectImportedModules(ImportedModules); for (auto ModuleName : ModuleNames) { auto MD = ModuleDecl::create(Ctx.getIdentifier(ModuleName), Ctx); CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::OtherModule, ExpectedTypes); Builder.setAssociatedDecl(MD); Builder.addTextChunk(MD->getNameStr()); Builder.addTypeAnnotation("Module"); // Imported modules are not recommended. if (ImportedModules.count(MD->getNameStr()) != 0) Builder.setNotRecommended( CodeCompletionResult::NotRecommendedReason::Redundant); } } SemanticContextKind getSemanticContext(const Decl *D, DeclVisibilityKind Reason) { if (ForcedSemanticContext) return *ForcedSemanticContext; if (IsUnresolvedMember) { if (isa<EnumElementDecl>(D)) { return SemanticContextKind::ExpressionSpecific; } } switch (Reason) { case DeclVisibilityKind::LocalVariable: case DeclVisibilityKind::FunctionParameter: case DeclVisibilityKind::GenericParameter: return SemanticContextKind::Local; case DeclVisibilityKind::MemberOfCurrentNominal: if (IsSuperRefExpr && CurrentMethod && CurrentMethod->getOverriddenDecl() == D) return SemanticContextKind::ExpressionSpecific; return SemanticContextKind::CurrentNominal; case DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal: case DeclVisibilityKind::MemberOfSuper: return SemanticContextKind::Super; case DeclVisibilityKind::MemberOfOutsideNominal: return SemanticContextKind::OutsideNominal; case DeclVisibilityKind::VisibleAtTopLevel: if (CurrDeclContext && D->getModuleContext() == CurrDeclContext->getParentModule()) { // Treat global variables from the same source file as local when // completing at top-level. if (isa<VarDecl>(D) && isTopLevelContext(CurrDeclContext) && D->getDeclContext()->getParentSourceFile() == CurrDeclContext->getParentSourceFile()) { return SemanticContextKind::Local; } else { return SemanticContextKind::CurrentModule; } } else { return SemanticContextKind::OtherModule; } case DeclVisibilityKind::DynamicLookup: // AnyObject results can come from different modules, including the // current module, but we always assign them the OtherModule semantic // context. These declarations are uniqued by signature, so it is // totally random (determined by the hash function) which of the // equivalent declarations (across multiple modules) we will get. return SemanticContextKind::OtherModule; } llvm_unreachable("unhandled kind"); } void addLeadingDot(CodeCompletionResultBuilder &Builder) { if (NeedOptionalUnwrap) { Builder.setNumBytesToErase(NumBytesToEraseForOptionalUnwrap); Builder.addQuestionMark(); Builder.addLeadingDot(); return; } if (needDot()) Builder.addLeadingDot(); } void addTypeAnnotation(CodeCompletionResultBuilder &Builder, Type T) { T = T->getReferenceStorageReferent(); if (T->isVoid()) Builder.addTypeAnnotation("Void"); else Builder.addTypeAnnotation(T.getString()); } void addTypeAnnotationForImplicitlyUnwrappedOptional( CodeCompletionResultBuilder &Builder, Type T, bool dynamicOrOptional = false) { std::string suffix; // FIXME: This retains previous behavior, but in reality the type of dynamic // lookups is IUO, not Optional as it is for the @optional attribute. if (dynamicOrOptional) { T = T->getOptionalObjectType(); suffix = "!?"; } else { suffix = "!"; } Type ObjectType = T->getReferenceStorageReferent()->getOptionalObjectType(); if (ObjectType->isVoid()) Builder.addTypeAnnotation("Void" + suffix); else Builder.addTypeAnnotation(ObjectType.getStringAsComponent() + suffix); } /// For printing in code completion results, replace archetypes with /// protocol compositions. /// /// FIXME: Perhaps this should be an option in PrintOptions instead. Type eraseArchetypes(ModuleDecl *M, Type type, GenericSignature *genericSig) { auto buildProtocolComposition = [&](ArrayRef<ProtocolDecl *> protos) -> Type { SmallVector<Type, 2> types; for (auto proto : protos) types.push_back(proto->getDeclaredInterfaceType()); return ProtocolCompositionType::get(M->getASTContext(), types, /*HasExplicitAnyObject=*/false); }; if (auto *genericFuncType = type->getAs<GenericFunctionType>()) { return GenericFunctionType::get(genericSig, eraseArchetypes(M, genericFuncType->getInput(), genericSig), eraseArchetypes(M, genericFuncType->getResult(), genericSig), genericFuncType->getExtInfo()); } return type.transform([&](Type t) -> Type { // FIXME: Code completion should only deal with one or the other, // and not both. if (auto *archetypeType = t->getAs<ArchetypeType>()) { auto protos = archetypeType->getConformsTo(); if (!protos.empty()) return buildProtocolComposition(protos); } if (t->isTypeParameter()) { auto protos = genericSig->getConformsTo(t); if (!protos.empty()) return buildProtocolComposition(protos); } return t; }); } Type getTypeOfMember(const ValueDecl *VD, Optional<Type> ExprType = None) { if (!ExprType) ExprType = this->ExprType; auto *M = CurrDeclContext->getParentModule(); auto *GenericSig = VD->getInnermostDeclContext() ->getGenericSignatureOfContext(); Type T = VD->getInterfaceType(); if (*ExprType) { Type ContextTy = VD->getDeclContext()->getDeclaredInterfaceType(); if (ContextTy) { // Look through lvalue types and metatypes Type MaybeNominalType = (*ExprType)->getRValueType(); if (auto Metatype = MaybeNominalType->getAs<MetatypeType>()) MaybeNominalType = Metatype->getInstanceType(); if (auto SelfType = MaybeNominalType->getAs<DynamicSelfType>()) MaybeNominalType = SelfType->getSelfType(); // For optional protocol requirements and dynamic dispatch, // strip off optionality from the base type, but only if // we're not actually completing a member of Optional. if (!ContextTy->getOptionalObjectType() && MaybeNominalType->getOptionalObjectType()) MaybeNominalType = MaybeNominalType->getOptionalObjectType(); // For dynamic lookup don't substitute in the base type. if (MaybeNominalType->isAnyObject()) return T; // FIXME: Sometimes ExprType is the type of the member here, // and not the type of the base. That is inconsistent and // should be cleaned up. if (!MaybeNominalType->mayHaveMembers()) return T; // For everything else, substitute in the base type. auto Subs = MaybeNominalType->getMemberSubstitutionMap(M, VD); // Pass in DesugarMemberTypes so that we see the actual // concrete type witnesses instead of type alias types. T = T.subst(Subs, (SubstFlags::DesugarMemberTypes | SubstFlags::UseErrorType)); } } return eraseArchetypes(M, T, GenericSig); } Type getAssociatedTypeType(const AssociatedTypeDecl *ATD) { Type BaseTy = BaseType; if (!BaseTy) BaseTy = ExprType; if (!BaseTy && CurrDeclContext) BaseTy = CurrDeclContext->getInnermostTypeContext() ->getDeclaredTypeInContext(); if (BaseTy) { BaseTy = BaseTy->getRValueInstanceType(); if (auto NTD = BaseTy->getAnyNominal()) { auto *Module = NTD->getParentModule(); auto Conformance = Module->lookupConformance( BaseTy, ATD->getProtocol()); if (Conformance && Conformance->isConcrete()) { return Conformance->getConcrete() ->getTypeWitness(const_cast<AssociatedTypeDecl *>(ATD), TypeResolver.get()); } } } return Type(); } void addVarDeclRef(const VarDecl *VD, DeclVisibilityKind Reason) { if (!VD->hasName() || (VD->hasAccess() && !VD->isAccessibleFrom(CurrDeclContext)) || shouldHideDeclFromCompletionResults(VD)) return; StringRef Name = VD->getName().get(); assert(!Name.empty() && "name should not be empty"); CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(VD, Reason), ExpectedTypes); Builder.setAssociatedDecl(VD); addLeadingDot(Builder); Builder.addTextChunk(Name); setClangDeclKeywords(VD, Pairs, Builder); // Add a type annotation. Type VarType = getTypeOfMember(VD); if (VD->getName() == Ctx.Id_self) { // Strip inout from 'self'. It is useful to show inout for function // parameters. But for 'self' it is just noise. VarType = VarType->getInOutObjectType(); } auto DynamicOrOptional = IsDynamicLookup || VD->getAttrs().hasAttribute<OptionalAttr>(); if (DynamicOrOptional) { // Values of properties that were found on a AnyObject have // Optional<T> type. Same applies to optional members. VarType = OptionalType::get(VarType); } if (VD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>()) addTypeAnnotationForImplicitlyUnwrappedOptional(Builder, VarType, DynamicOrOptional); else addTypeAnnotation(Builder, VarType); } void addParameters(CodeCompletionResultBuilder &Builder, const ParameterList *params) { bool NeedComma = false; for (auto &param : *params) { if (NeedComma) Builder.addComma(); NeedComma = true; Type type = param->getInterfaceType(); if (param->isVariadic()) type = ParamDecl::getVarargBaseTy(type); auto isIUO = param->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>(); Builder.addCallParameter(param->getArgumentName(), type, param->isVariadic(), /*Outermost*/ true, param->isInOut(), isIUO); } } void addPatternFromTypeImpl(CodeCompletionResultBuilder &Builder, Type T, Identifier Label, bool IsTopLevel, bool IsVarArg) { if (auto *TT = T->getAs<TupleType>()) { if (!Label.empty()) { Builder.addTextChunk(Label.str()); Builder.addTextChunk(": "); } if (!IsTopLevel || !HaveLParen) Builder.addLeftParen(); else Builder.addAnnotatedLeftParen(); bool NeedComma = false; for (auto TupleElt : TT->getElements()) { if (NeedComma) Builder.addComma(); Type EltT = TupleElt.isVararg() ? TupleElt.getVarargBaseTy() : TupleElt.getType(); addPatternFromTypeImpl(Builder, EltT, TupleElt.getName(), false, TupleElt.isVararg()); NeedComma = true; } Builder.addRightParen(); return; } if (auto *PT = dyn_cast<ParenType>(T.getPointer())) { if (IsTopLevel && !HaveLParen) Builder.addLeftParen(); else if (IsTopLevel) Builder.addAnnotatedLeftParen(); Builder.addCallParameter(Identifier(), PT->getUnderlyingType(), /*IsVarArg*/ false, IsTopLevel, PT->getParameterFlags().isInOut(), /*isIUO*/ false); if (IsTopLevel) Builder.addRightParen(); return; } if (IsTopLevel && !HaveLParen) Builder.addLeftParen(); else if (IsTopLevel) Builder.addAnnotatedLeftParen(); Builder.addCallParameter(Label, T, IsVarArg, IsTopLevel, /*isInOut*/ false, /*isIUO*/ false); if (IsTopLevel) Builder.addRightParen(); } void addPatternFromType(CodeCompletionResultBuilder &Builder, Type T) { addPatternFromTypeImpl(Builder, T, Identifier(), true, /*isVarArg*/false); } static bool hasInterestingDefaultValues(const AbstractFunctionDecl *func) { if (!func) return false; bool isMemberOfType = func->getDeclContext()->isTypeContext(); for (auto param : *func->getParameterList(isMemberOfType ? 1 : 0)) { switch (param->getDefaultArgumentKind()) { case DefaultArgumentKind::Normal: case DefaultArgumentKind::Inherited: // FIXME: include this? return true; default: break; } } return false; } // Returns true if any content was added to Builder. bool addParamPatternFromFunction(CodeCompletionResultBuilder &Builder, const AnyFunctionType *AFT, const AbstractFunctionDecl *AFD, bool includeDefaultArgs = true) { const ParameterList *BodyParams = nullptr; if (AFD) { BodyParams = AFD->getParameterList(AFD->getImplicitSelfDecl() ? 1 : 0); // FIXME: Hack because we don't know which parameter list we're // actually working with. unsigned expectedNumParams; if (auto *TT = dyn_cast<TupleType>(AFT->getInput().getPointer())) expectedNumParams = TT->getNumElements(); else expectedNumParams = 1; if (expectedNumParams != BodyParams->size()) { // Adjust to the "self" list if that is present, otherwise give up. if (expectedNumParams == 1 && AFD->getImplicitSelfDecl()) BodyParams = AFD->getParameterList(0); else BodyParams = nullptr; } } bool modifiedBuilder = false; // Determine whether we should skip this argument because it is defaulted. auto shouldSkipArg = [&](unsigned i) -> bool { if (!BodyParams || i >= BodyParams->size()) return false; switch (BodyParams->get(i)->getDefaultArgumentKind()) { case DefaultArgumentKind::None: return false; case DefaultArgumentKind::Normal: case DefaultArgumentKind::Inherited: case DefaultArgumentKind::NilLiteral: case DefaultArgumentKind::EmptyArray: case DefaultArgumentKind::EmptyDictionary: return !includeDefaultArgs; case DefaultArgumentKind::File: case DefaultArgumentKind::Line: case DefaultArgumentKind::Column: case DefaultArgumentKind::Function: case DefaultArgumentKind::DSOHandle: // Skip parameters that are defaulted to source location or other // caller context information. Users typically don't want to specify // these parameters. return true; } llvm_unreachable("Unhandled DefaultArgumentKind in switch."); }; // Do not desugar AFT->getInput(), as we want to treat (_: (a,b)) distinctly // from (a,b) for code-completion. if (auto *TT = dyn_cast<TupleType>(AFT->getInput().getPointer())) { bool NeedComma = false; // Iterate over the tuple type fields, corresponding to each parameter. for (unsigned i = 0, e = TT->getNumElements(); i != e; ++i) { // If we should skip this argument, do so. if (shouldSkipArg(i)) continue; const auto &TupleElt = TT->getElement(i); auto ParamType = TupleElt.isVararg() ? TupleElt.getVarargBaseTy() : TupleElt.getType(); auto Name = TupleElt.getName(); if (NeedComma) Builder.addComma(); if (BodyParams) { auto *PD = BodyParams->get(i); // If we have a local name for the parameter, pass in that as well. auto argName = PD->getArgumentName(); auto bodyName = PD->getName(); auto isIUO = PD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>(); Builder.addCallParameter(argName, bodyName, ParamType, TupleElt.isVararg(), true, TupleElt.isInOut(), isIUO); } else { Builder.addCallParameter(Name, ParamType, TupleElt.isVararg(), /*TopLevel*/ true, TupleElt.isInOut(), /*isIUO*/ false); } modifiedBuilder = true; NeedComma = true; } } else if (!shouldSkipArg(0)) { // If it's not a tuple, it could be a unary function. Type T = AFT->getInput(); bool isInOut = false; if (auto *PT = dyn_cast<ParenType>(T.getPointer())) { // Only unwrap the paren sugar, if it exists. T = PT->getUnderlyingType(); isInOut = PT->getParameterFlags().isInOut(); } modifiedBuilder = true; if (BodyParams) { auto *PD = BodyParams->get(0); auto argName = PD->getArgumentName(); auto bodyName = PD->getName(); auto isIUO = PD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>(); Builder.addCallParameter(argName, bodyName, T, /*IsVarArg*/ false, /*Toplevel*/ true, isInOut, isIUO); } else Builder.addCallParameter(Identifier(), T, /*IsVarArg*/ false, /*TopLevel*/ true, isInOut, /*isIUO*/ false); } return modifiedBuilder; } static void addThrows(CodeCompletionResultBuilder &Builder, const AnyFunctionType *AFT, const AbstractFunctionDecl *AFD) { if (AFD && AFD->getAttrs().hasAttribute<RethrowsAttr>()) Builder.addAnnotatedRethrows(); else if (AFT->throws()) Builder.addAnnotatedThrows(); } void addPoundAvailable(StmtKind ParentKind) { if (ParentKind != StmtKind::If && ParentKind != StmtKind::Guard) return; CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::ExpressionSpecific, ExpectedTypes); Builder.addTextChunk("available"); Builder.addLeftParen(); Builder.addSimpleTypedParameter("Platform", /*IsVarArg=*/true); Builder.addComma(); Builder.addTextChunk("*"); Builder.addRightParen(); } void addPoundSelector(bool needPound) { // #selector is only available when the Objective-C runtime is. if (!Ctx.LangOpts.EnableObjCInterop) return; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::ExpressionSpecific, ExpectedTypes); if (needPound) Builder.addTextChunk("#selector"); else Builder.addTextChunk("selector"); Builder.addLeftParen(); Builder.addSimpleTypedParameter("@objc method", /*IsVarArg=*/false); Builder.addRightParen(); } void addPoundKeyPath(bool needPound) { // #keyPath is only available when the Objective-C runtime is. if (!Ctx.LangOpts.EnableObjCInterop) return; // After #, this is a very likely result. When just in a String context, // it's not. auto semanticContext = needPound ? SemanticContextKind::None : SemanticContextKind::ExpressionSpecific; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, semanticContext, ExpectedTypes); if (needPound) Builder.addTextChunk("#keyPath"); else Builder.addTextChunk("keyPath"); Builder.addLeftParen(); Builder.addSimpleTypedParameter("@objc property sequence", /*IsVarArg=*/false); Builder.addRightParen(); } void addFunctionCallPattern(const AnyFunctionType *AFT, const AbstractFunctionDecl *AFD = nullptr) { if (AFD) foundFunction(AFD); else foundFunction(AFT); // Add the pattern, possibly including any default arguments. auto addPattern = [&](bool includeDefaultArgs = true) { // FIXME: to get the corect semantic context we need to know how lookup // would have found the declaration AFD. For now, just choose a reasonable // default, it's most likely to be CurrentModule or CurrentNominal. CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Pattern, SemanticContextKind::CurrentModule, ExpectedTypes); if (!HaveLParen) Builder.addLeftParen(); else Builder.addAnnotatedLeftParen(); bool anyParam = addParamPatternFromFunction(Builder, AFT, AFD, includeDefaultArgs); if (HaveLParen && !anyParam) { // Empty result, don't add it. Builder.cancel(); return; } // The rparen matches the lparen here so that we insert both or neither. if (!HaveLParen) Builder.addRightParen(); else Builder.addAnnotatedRightParen(); addThrows(Builder, AFT, AFD); if (AFD && AFD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>()) addTypeAnnotationForImplicitlyUnwrappedOptional(Builder, AFT->getResult()); else addTypeAnnotation(Builder, AFT->getResult()); }; if (hasInterestingDefaultValues(AFD)) addPattern(/*includeDefaultArgs*/ false); addPattern(); } bool isImplicitlyCurriedInstanceMethod(const AbstractFunctionDecl *FD) { switch (Kind) { case LookupKind::ValueExpr: return ExprType->is<AnyMetatypeType>() && !FD->isStatic(); case LookupKind::ValueInDeclContext: if (InsideStaticMethod && FD->getDeclContext() == CurrentMethod->getDeclContext() && !FD->isStatic()) return true; if (auto Init = dyn_cast<Initializer>(CurrDeclContext)) return FD->getDeclContext() == Init->getParent() && !FD->isStatic(); return false; case LookupKind::EnumElement: case LookupKind::Type: case LookupKind::TypeInDeclContext: llvm_unreachable("cannot have a method call while doing a " "type completion"); case LookupKind::ImportFromModule: return false; } llvm_unreachable("Unhandled LookupKind in switch."); } void addMethodCall(const FuncDecl *FD, DeclVisibilityKind Reason) { if (FD->getName().empty()) return; foundFunction(FD); bool IsImplicitlyCurriedInstanceMethod = isImplicitlyCurriedInstanceMethod(FD); StringRef Name = FD->getName().get(); assert(!Name.empty() && "name should not be empty"); unsigned FirstIndex = 0; if (!IsImplicitlyCurriedInstanceMethod && FD->getImplicitSelfDecl()) FirstIndex = 1; Type FunctionType = getTypeOfMember(FD); assert(FunctionType); if (FirstIndex != 0 && FunctionType->is<AnyFunctionType>()) FunctionType = FunctionType->castTo<AnyFunctionType>()->getResult(); bool trivialTrailingClosure = false; if (!IsImplicitlyCurriedInstanceMethod && FunctionType->is<AnyFunctionType>()) { trivialTrailingClosure = hasTrivialTrailingClosure( FD, FunctionType->castTo<AnyFunctionType>()); } // Add the method, possibly including any default arguments. auto addMethodImpl = [&](bool includeDefaultArgs = true, bool trivialTrailingClosure = false) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(FD, Reason), ExpectedTypes); setClangDeclKeywords(FD, Pairs, Builder); Builder.setAssociatedDecl(FD); addLeadingDot(Builder); Builder.addTextChunk(Name); if (IsDynamicLookup) Builder.addDynamicLookupMethodCallTail(); else if (FD->getAttrs().hasAttribute<OptionalAttr>()) Builder.addOptionalMethodCallTail(); llvm::SmallString<32> TypeStr; if (!FunctionType->is<AnyFunctionType>()) { llvm::raw_svector_ostream OS(TypeStr); FunctionType.print(OS); Builder.addTypeAnnotation(OS.str()); return; } Type FirstInputType = FunctionType->castTo<AnyFunctionType>()->getInput(); if (IsImplicitlyCurriedInstanceMethod) { bool isInOut = false; if (auto PT = dyn_cast<ParenType>(FirstInputType.getPointer())) { FirstInputType = PT->getUnderlyingType(); isInOut = PT->getParameterFlags().isInOut(); } Builder.addLeftParen(); Builder.addCallParameter(Ctx.Id_self, FirstInputType, /*IsVarArg*/ false, /*TopLevel*/ true, isInOut, /*isIUO*/ false); Builder.addRightParen(); } else if (trivialTrailingClosure) { Builder.addBraceStmtWithCursor(" { code }"); } else { Builder.addLeftParen(); auto AFT = FunctionType->castTo<AnyFunctionType>(); addParamPatternFromFunction(Builder, AFT, FD, includeDefaultArgs); Builder.addRightParen(); addThrows(Builder, AFT, FD); } Type ResultType = FunctionType->castTo<AnyFunctionType>()->getResult(); // Build type annotation. { llvm::raw_svector_ostream OS(TypeStr); for (unsigned i = FirstIndex + 1, e = FD->getParameterLists().size(); i != e; ++i) { ResultType->castTo<AnyFunctionType>()->getInput()->print(OS); ResultType = ResultType->castTo<AnyFunctionType>()->getResult(); OS << " -> "; } // What's left is the result type. if (ResultType->isVoid()) { OS << "Void"; } else if (!IsImplicitlyCurriedInstanceMethod && FD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>()) { // As we did with parameters in addParamPatternFromFunction, // for regular methods we'll print '!' after implicitly // unwrapped optional results. auto ObjectType = ResultType->getOptionalObjectType(); OS << ObjectType->getStringAsComponent(); OS << "!"; } else { ResultType.print(OS); } } Builder.addTypeAnnotation(TypeStr); }; if (FunctionType->is<AnyFunctionType>() && hasInterestingDefaultValues(FD)) { addMethodImpl(/*includeDefaultArgs*/ false); } if (trivialTrailingClosure) { addMethodImpl(/*includeDefaultArgs=*/false, /*trivialTrailingClosure=*/true); } addMethodImpl(); } void addConstructorCall(const ConstructorDecl *CD, DeclVisibilityKind Reason, Optional<Type> BaseType, Optional<Type> Result, bool IsOnType = true, Identifier addName = Identifier()) { foundFunction(CD); Type MemberType = getTypeOfMember(CD, BaseType); AnyFunctionType *ConstructorType = nullptr; if (auto MemberFuncType = MemberType->getAs<AnyFunctionType>()) ConstructorType = MemberFuncType->getResult() ->castTo<AnyFunctionType>(); bool needInit = false; if (!IsOnType) { assert(addName.empty()); needInit = true; } else if (addName.empty() && HaveDot) { needInit = true; } // If we won't be able to provide a result, bail out. if (MemberType->hasError() && addName.empty() && !needInit) return; // Add the constructor, possibly including any default arguments. auto addConstructorImpl = [&](bool includeDefaultArgs = true) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(CD, Reason), ExpectedTypes); setClangDeclKeywords(CD, Pairs, Builder); Builder.setAssociatedDecl(CD); if (needInit) { assert(addName.empty()); addLeadingDot(Builder); Builder.addTextChunk("init"); } else if (!addName.empty()) { Builder.addTextChunk(addName.str()); } else { assert(!MemberType->hasError() && "will insert empty result"); } if (!ConstructorType) { addTypeAnnotation(Builder, MemberType); return; } if (!HaveLParen) Builder.addLeftParen(); else Builder.addAnnotatedLeftParen(); bool anyParam = addParamPatternFromFunction(Builder, ConstructorType, CD, includeDefaultArgs); if (HaveLParen && !anyParam) { // Empty result, don't add it. Builder.cancel(); return; } // The rparen matches the lparen here so that we insert both or neither. if (!HaveLParen) Builder.addRightParen(); else Builder.addAnnotatedRightParen(); addThrows(Builder, ConstructorType, CD); if (CD->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>()) { addTypeAnnotationForImplicitlyUnwrappedOptional( Builder, Result.hasValue() ? Result.getValue() : ConstructorType->getResult()); } else { addTypeAnnotation(Builder, Result.hasValue() ? Result.getValue() : ConstructorType->getResult()); } }; if (ConstructorType && hasInterestingDefaultValues(CD)) addConstructorImpl(/*includeDefaultArgs*/ false); addConstructorImpl(); } void addConstructorCallsForType(Type type, Identifier name, DeclVisibilityKind Reason) { if (!Ctx.LangOpts.CodeCompleteInitsInPostfixExpr) return; assert(CurrDeclContext); SmallVector<ValueDecl *, 16> initializers; if (CurrDeclContext->lookupQualified(type, DeclBaseName::createConstructor(), NL_QualifiedDefault, TypeResolver.get(), initializers)) { for (auto *init : initializers) { if (shouldHideDeclFromCompletionResults(init)) continue; addConstructorCall(cast<ConstructorDecl>(init), Reason, type, None, /*IsOnType=*/true, name); } } } bool shouldAddSubscriptCall() { if (IsSwiftKeyPathExpr) return true; return !HaveDot; } void addSubscriptCall(const SubscriptDecl *SD, DeclVisibilityKind Reason) { assert(shouldAddSubscriptCall() && "cannot add a subscript after a dot"); CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(SD, Reason), ExpectedTypes); Builder.setAssociatedDecl(SD); setClangDeclKeywords(SD, Pairs, Builder); Builder.addLeftBracket(); addParameters(Builder, SD->getIndices()); Builder.addRightBracket(); // Add a type annotation. Type T = SD->getElementInterfaceType(); if (IsDynamicLookup) { // Values of properties that were found on a AnyObject have // Optional<T> type. T = OptionalType::get(T); } addTypeAnnotation(Builder, T); } void addNominalTypeRef(const NominalTypeDecl *NTD, DeclVisibilityKind Reason) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(NTD, Reason), ExpectedTypes); Builder.setAssociatedDecl(NTD); setClangDeclKeywords(NTD, Pairs, Builder); addLeadingDot(Builder); Builder.addTextChunk(NTD->getName().str()); addTypeAnnotation(Builder, NTD->getDeclaredType()); } void addTypeAliasRef(const TypeAliasDecl *TAD, DeclVisibilityKind Reason) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(TAD, Reason), ExpectedTypes); Builder.setAssociatedDecl(TAD); setClangDeclKeywords(TAD, Pairs, Builder); addLeadingDot(Builder); Builder.addTextChunk(TAD->getName().str()); if (TAD->hasInterfaceType()) { auto underlyingType = TAD->getUnderlyingTypeLoc().getType(); if (underlyingType->hasError()) { Type parentType; if (auto nominal = TAD->getDeclContext() ->getAsNominalTypeOrNominalTypeExtensionContext()) { parentType = nominal->getDeclaredInterfaceType(); } addTypeAnnotation( Builder, NameAliasType::get(const_cast<TypeAliasDecl *>(TAD), parentType, SubstitutionMap(), underlyingType)); } else { addTypeAnnotation(Builder, underlyingType); } } } void addGenericTypeParamRef(const GenericTypeParamDecl *GP, DeclVisibilityKind Reason) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(GP, Reason), ExpectedTypes); setClangDeclKeywords(GP, Pairs, Builder); Builder.setAssociatedDecl(GP); addLeadingDot(Builder); Builder.addTextChunk(GP->getName().str()); addTypeAnnotation(Builder, GP->getDeclaredInterfaceType()); } void addAssociatedTypeRef(const AssociatedTypeDecl *AT, DeclVisibilityKind Reason) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(AT, Reason), ExpectedTypes); setClangDeclKeywords(AT, Pairs, Builder); Builder.setAssociatedDecl(AT); addLeadingDot(Builder); Builder.addTextChunk(AT->getName().str()); if (Type T = getAssociatedTypeType(AT)) addTypeAnnotation(Builder, T); } void addEnumElementRef(const EnumElementDecl *EED, DeclVisibilityKind Reason, bool HasTypeContext) { if (!EED->hasName() || (EED->hasAccess() && !EED->isAccessibleFrom(CurrDeclContext)) || shouldHideDeclFromCompletionResults(EED)) return; CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, HasTypeContext ? SemanticContextKind::ExpressionSpecific : getSemanticContext(EED, Reason), ExpectedTypes); Builder.setAssociatedDecl(EED); setClangDeclKeywords(EED, Pairs, Builder); addLeadingDot(Builder); Builder.addTextChunk(EED->getName().str()); if (auto *params = EED->getParameterList()) { Builder.addLeftParen(); addParameters(Builder, params); Builder.addRightParen(); } // Enum element is of function type such as EnumName.type -> Int -> // EnumName; however we should show Int -> EnumName as the type Type EnumType; if (EED->hasInterfaceType()) { EnumType = EED->getInterfaceType(); if (auto FuncType = EnumType->getAs<AnyFunctionType>()) { EnumType = FuncType->getResult(); } } if (EnumType) addTypeAnnotation(Builder, EnumType); } void addKeyword(StringRef Name, Type TypeAnnotation, SemanticContextKind SK = SemanticContextKind::None, CodeCompletionKeywordKind KeyKind = CodeCompletionKeywordKind::None) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SK, ExpectedTypes); addLeadingDot(Builder); Builder.addTextChunk(Name); Builder.setKeywordKind(KeyKind); if (!TypeAnnotation.isNull()) addTypeAnnotation(Builder, TypeAnnotation); } void addKeyword(StringRef Name, StringRef TypeAnnotation, CodeCompletionKeywordKind KeyKind = CodeCompletionKeywordKind::None) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, ExpectedTypes); addLeadingDot(Builder); Builder.addTextChunk(Name); Builder.setKeywordKind(KeyKind); if (!TypeAnnotation.empty()) Builder.addTypeAnnotation(TypeAnnotation); } void addDeclAttrParamKeyword(StringRef Name, StringRef Annotation, bool NeedSpecify) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, ExpectedTypes); Builder.addDeclAttrParamKeyword(Name, Annotation, NeedSpecify); } void addDeclAttrKeyword(StringRef Name, StringRef Annotation) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, ExpectedTypes); Builder.addDeclAttrKeyword(Name, Annotation); } /// Add the compound function name for the given function. void addCompoundFunctionName(AbstractFunctionDecl *AFD, DeclVisibilityKind Reason) { CommandWordsPairs Pairs; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, getSemanticContext(AFD, Reason), ExpectedTypes); setClangDeclKeywords(AFD, Pairs, Builder); Builder.setAssociatedDecl(AFD); // Base name addLeadingDot(Builder); Builder.addTextChunk(AFD->getBaseName().userFacingName()); // Add the argument labels. auto ArgLabels = AFD->getFullName().getArgumentNames(); if (!ArgLabels.empty()) { if (!HaveLParen) Builder.addLeftParen(); else Builder.addAnnotatedLeftParen(); for (auto ArgLabel : ArgLabels) { if (ArgLabel.empty()) Builder.addTextChunk("_"); else Builder.addTextChunk(ArgLabel.str()); Builder.addTextChunk(":"); } Builder.addRightParen(); } } // Implement swift::VisibleDeclConsumer. void foundDecl(ValueDecl *D, DeclVisibilityKind Reason) override { if (shouldHideDeclFromCompletionResults(D)) return; if (IsKeyPathExpr && !KeyPathFilter(D, Reason)) return; if (IsSwiftKeyPathExpr && !SwiftKeyPathFilter(D, Reason)) return; if (!D->hasInterfaceType()) TypeResolver->resolveDeclSignature(D); else if (isa<TypeAliasDecl>(D)) { // A TypeAliasDecl might have type set, but not the underlying type. TypeResolver->resolveDeclSignature(D); } switch (Kind) { case LookupKind::ValueExpr: if (auto *CD = dyn_cast<ConstructorDecl>(D)) { // Do we want compound function names here? if (shouldUseFunctionReference(CD)) { addCompoundFunctionName(CD, Reason); return; } if (auto MT = ExprType->getAs<AnyMetatypeType>()) { Type Ty = MT->getInstanceType(); assert(Ty && "Cannot find instance type."); // If instance type is type alias, show users that the constructed // type is the typealias instead of the underlying type of the alias. Optional<Type> Result = None; if (!CD->getInterfaceType()->is<ErrorType>() && isa<NameAliasType>(Ty.getPointer()) && Ty->getDesugaredType() == CD->getResultInterfaceType().getPointer()) { Result = Ty; } // If the expression type is not a static metatype or an archetype, the base // is not a type. Direct call syntax is illegal on values, so we only add // initializer completions if we do not have a left parenthesis and either // the initializer is required, the base type's instance type is not a class, // or this is a 'self' or 'super' reference. if (IsStaticMetatype || Ty->is<ArchetypeType>()) addConstructorCall(CD, Reason, None, Result, /*isOnType*/true); else if ((IsSelfRefExpr || IsSuperRefExpr || !Ty->is<ClassType>() || CD->isRequired()) && !HaveLParen) addConstructorCall(CD, Reason, None, Result, /*isOnType*/false); return; } if (!HaveLParen) { auto CDC = dyn_cast<ConstructorDecl>(CurrDeclContext); if (!CDC) return; // We do not want 'init' completions for 'self' in non-convenience // initializers and for 'super' in convenience initializers. if ((IsSelfRefExpr && CDC->isConvenienceInit()) || ((IsSuperRefExpr && !CDC->isConvenienceInit()))) addConstructorCall(CD, Reason, None, None, /*IsOnType=*/false); } return; } if (HaveLParen) return; if (auto *VD = dyn_cast<VarDecl>(D)) { addVarDeclRef(VD, Reason); return; } if (auto *FD = dyn_cast<FuncDecl>(D)) { // We cannot call operators with a postfix parenthesis syntax. if (FD->isBinaryOperator() || FD->isUnaryOperator()) return; // We cannot call accessors. We use VarDecls and SubscriptDecls to // produce completions that refer to getters and setters. if (isa<AccessorDecl>(FD)) return; // Do we want compound function names here? if (shouldUseFunctionReference(FD)) { addCompoundFunctionName(FD, Reason); return; } addMethodCall(FD, Reason); return; } if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) { addNominalTypeRef(NTD, Reason); addConstructorCallsForType(NTD->getDeclaredInterfaceType(), NTD->getName(), Reason); return; } if (auto *TAD = dyn_cast<TypeAliasDecl>(D)) { addTypeAliasRef(TAD, Reason); auto type = TAD->mapTypeIntoContext(TAD->getUnderlyingTypeLoc().getType()); if (type->mayHaveMembers()) addConstructorCallsForType(type, TAD->getName(), Reason); return; } if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) { addGenericTypeParamRef(GP, Reason); for (auto *protocol : GP->getConformingProtocols()) addConstructorCallsForType(protocol->getDeclaredInterfaceType(), GP->getName(), Reason); return; } if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) { addAssociatedTypeRef(AT, Reason); return; } if (auto *EED = dyn_cast<EnumElementDecl>(D)) { addEnumElementRef(EED, Reason, /*HasTypeContext=*/false); } // Swift key path allows .[0] if (shouldAddSubscriptCall()) { if (auto *SD = dyn_cast<SubscriptDecl>(D)) { if (ExprType->is<AnyMetatypeType>()) return; addSubscriptCall(SD, Reason); } } return; case LookupKind::ValueInDeclContext: case LookupKind::ImportFromModule: if (auto *VD = dyn_cast<VarDecl>(D)) { addVarDeclRef(VD, Reason); return; } if (auto *FD = dyn_cast<FuncDecl>(D)) { // We cannot call operators with a postfix parenthesis syntax. if (FD->isBinaryOperator() || FD->isUnaryOperator()) return; // We cannot call accessors. We use VarDecls and SubscriptDecls to // produce completions that refer to getters and setters. if (isa<AccessorDecl>(FD)) return; // Do we want compound function names here? if (shouldUseFunctionReference(FD)) { addCompoundFunctionName(FD, Reason); return; } addMethodCall(FD, Reason); return; } if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) { addNominalTypeRef(NTD, Reason); addConstructorCallsForType(NTD->getDeclaredInterfaceType(), NTD->getName(), Reason); return; } if (auto *TAD = dyn_cast<TypeAliasDecl>(D)) { addTypeAliasRef(TAD, Reason); auto type = TAD->mapTypeIntoContext(TAD->getDeclaredInterfaceType()); if (type->mayHaveMembers()) addConstructorCallsForType(type, TAD->getName(), Reason); return; } if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) { addGenericTypeParamRef(GP, Reason); for (auto *protocol : GP->getConformingProtocols()) addConstructorCallsForType(protocol->getDeclaredInterfaceType(), GP->getName(), Reason); return; } if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) { addAssociatedTypeRef(AT, Reason); return; } return; case LookupKind::EnumElement: handleEnumElement(D, Reason); return; case LookupKind::Type: case LookupKind::TypeInDeclContext: if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) { addNominalTypeRef(NTD, Reason); return; } if (auto *TAD = dyn_cast<TypeAliasDecl>(D)) { addTypeAliasRef(TAD, Reason); return; } if (auto *GP = dyn_cast<GenericTypeParamDecl>(D)) { addGenericTypeParamRef(GP, Reason); return; } if (auto *AT = dyn_cast<AssociatedTypeDecl>(D)) { addAssociatedTypeRef(AT, Reason); return; } return; } } bool handleEnumElement(ValueDecl *D, DeclVisibilityKind Reason) { if (!D->hasInterfaceType()) TypeResolver->resolveDeclSignature(D); if (auto *EED = dyn_cast<EnumElementDecl>(D)) { addEnumElementRef(EED, Reason, /*HasTypeContext=*/true); return true; } else if (auto *ED = dyn_cast<EnumDecl>(D)) { llvm::DenseSet<EnumElementDecl *> Elements; ED->getAllElements(Elements); for (auto *Ele : Elements) { if (!Ele->hasInterfaceType()) TypeResolver->resolveDeclSignature(Ele); addEnumElementRef(Ele, Reason, /*HasTypeContext=*/true); } return true; } return false; } bool tryTupleExprCompletions(Type ExprType) { auto *TT = ExprType->getAs<TupleType>(); if (!TT) return false; unsigned Index = 0; for (auto TupleElt : TT->getElements()) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Pattern, SemanticContextKind::CurrentNominal, ExpectedTypes); addLeadingDot(Builder); if (TupleElt.hasName()) { Builder.addTextChunk(TupleElt.getName().str()); } else { llvm::SmallString<4> IndexStr; { llvm::raw_svector_ostream OS(IndexStr); OS << Index; } Builder.addTextChunk(IndexStr.str()); } addTypeAnnotation(Builder, TupleElt.getType()); Index++; } return true; } bool tryFunctionCallCompletions(Type ExprType, const ValueDecl *VD) { ExprType = ExprType->getRValueType(); if (auto AFT = ExprType->getAs<AnyFunctionType>()) { if (auto *AFD = dyn_cast_or_null<AbstractFunctionDecl>(VD)) { addFunctionCallPattern(AFT, AFD); } else { addFunctionCallPattern(AFT); } return true; } return false; } bool tryModuleCompletions(Type ExprType) { if (auto MT = ExprType->getAs<ModuleType>()) { ModuleDecl *M = MT->getModule(); if (CurrDeclContext->getParentModule() != M) { // Only use the cache if it is not the current module. RequestedCachedResults = RequestedResultsTy::fromModule(M) .needLeadingDot(needDot()); return true; } } return false; } /// If the given ExprType is optional, this adds completions for the unwrapped /// type. /// /// \return true if the given type was Optional . bool tryUnwrappedCompletions(Type ExprType, bool isIUO) { // FIXME: consider types convertible to T?. ExprType = ExprType->getRValueType(); // FIXME: We don't always pass down whether a type is from an // unforced IUO. if (isIUO) { if (Type Unwrapped = ExprType->getOptionalObjectType()) { lookupVisibleMemberDecls(*this, Unwrapped, CurrDeclContext, TypeResolver.get(), IncludeInstanceMembers); return true; } assert(IsUnwrappedOptional && "IUOs should be optional if not bound/forced"); return false; } if (Type Unwrapped = ExprType->getOptionalObjectType()) { llvm::SaveAndRestore<bool> ChangeNeedOptionalUnwrap(NeedOptionalUnwrap, true); if (DotLoc.isValid()) { NumBytesToEraseForOptionalUnwrap = Ctx.SourceMgr.getByteDistance( DotLoc, Ctx.SourceMgr.getCodeCompletionLoc()); } else { NumBytesToEraseForOptionalUnwrap = 0; } if (NumBytesToEraseForOptionalUnwrap <= CodeCompletionResult::MaxNumBytesToErase) { if (!tryTupleExprCompletions(Unwrapped)) { lookupVisibleMemberDecls(*this, Unwrapped, CurrDeclContext, TypeResolver.get(), IncludeInstanceMembers); } } return true; } return false; } void getValueExprCompletions(Type ExprType, ValueDecl *VD = nullptr) { Kind = LookupKind::ValueExpr; NeedLeadingDot = !HaveDot; // This is horrible ExprType = ExprType->getRValueType(); this->ExprType = ExprType; if (ExprType->hasTypeParameter()) { DeclContext *DC = nullptr; if (VD) DC = VD->getInnermostDeclContext(); else if (auto NTD = ExprType->getRValueInstanceType()->getAnyNominal()) DC = NTD; if (DC) ExprType = DC->mapTypeIntoContext(ExprType); } // Handle special cases bool isIUO = VD && VD->getAttrs() .hasAttribute<ImplicitlyUnwrappedOptionalAttr>(); if (tryFunctionCallCompletions(ExprType, VD)) return; if (tryModuleCompletions(ExprType)) return; if (tryTupleExprCompletions(ExprType)) return; // Don't check/return so we still add the members of Optional itself below tryUnwrappedCompletions(ExprType, isIUO); lookupVisibleMemberDecls(*this, ExprType, CurrDeclContext, TypeResolver.get(), IncludeInstanceMembers); } template <typename T> void collectOperatorsFromMap(SourceFile::OperatorMap<T> &map, bool includePrivate, std::vector<OperatorDecl *> &results) { for (auto &pair : map) { if (pair.second.getPointer() && (pair.second.getInt() || includePrivate)) { results.push_back(pair.second.getPointer()); } } } void collectOperatorsFrom(SourceFile *SF, std::vector<OperatorDecl *> &results) { bool includePrivate = CurrDeclContext->getParentSourceFile() == SF; collectOperatorsFromMap(SF->PrefixOperators, includePrivate, results); collectOperatorsFromMap(SF->PostfixOperators, includePrivate, results); collectOperatorsFromMap(SF->InfixOperators, includePrivate, results); } void collectOperatorsFrom(LoadedFile *F, std::vector<OperatorDecl *> &results) { SmallVector<Decl *, 64> topLevelDecls; F->getTopLevelDecls(topLevelDecls); for (auto D : topLevelDecls) { if (auto op = dyn_cast<OperatorDecl>(D)) results.push_back(op); } } std::vector<OperatorDecl *> collectOperators() { std::vector<OperatorDecl *> results; assert(CurrDeclContext); CurrDeclContext->getParentSourceFile()->forAllVisibleModules( [&](ModuleDecl::ImportedModule import) { for (auto fileUnit : import.second->getFiles()) { switch (fileUnit->getKind()) { case FileUnitKind::Builtin: case FileUnitKind::Derived: case FileUnitKind::ClangModule: continue; case FileUnitKind::Source: collectOperatorsFrom(cast<SourceFile>(fileUnit), results); break; case FileUnitKind::SerializedAST: collectOperatorsFrom(cast<LoadedFile>(fileUnit), results); break; } } }); return results; } void addPostfixBang(Type resultType) { CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::BuiltinOperator, SemanticContextKind::None, {}); // FIXME: we can't use the exclamation mark chunk kind, or it isn't // included in the completion name. builder.addTextChunk("!"); assert(resultType); addTypeAnnotation(builder, resultType); } void addPostfixOperatorCompletion(OperatorDecl *op, Type resultType) { // FIXME: we should get the semantic context of the function, not the // operator decl. auto semanticContext = getSemanticContext(op, DeclVisibilityKind::VisibleAtTopLevel); CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::Declaration, semanticContext, {}); // FIXME: handle variable amounts of space. if (HaveLeadingSpace) builder.setNumBytesToErase(1); builder.setAssociatedDecl(op); builder.addTextChunk(op->getName().str()); assert(resultType); addTypeAnnotation(builder, resultType); } void tryPostfixOperator(Expr *expr, PostfixOperatorDecl *op) { if (!expr->getType()) return; // We allocate these expressions on the stack because we know they can't // escape and there isn't a better way to allocate scratch Expr nodes. UnresolvedDeclRefExpr UDRE(op->getName(), DeclRefKind::PostfixOperator, DeclNameLoc(expr->getSourceRange().End)); PostfixUnaryExpr opExpr(&UDRE, expr); Expr *tempExpr = &opExpr; ConcreteDeclRef referencedDecl; if (auto T = getTypeOfCompletionContextExpr( CurrDeclContext->getASTContext(), const_cast<DeclContext *>(CurrDeclContext), CompletionTypeCheckKind::Normal, tempExpr, referencedDecl)) addPostfixOperatorCompletion(op, *T); } void addAssignmentOperator(Type RHSType, Type resultType) { CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::BuiltinOperator, SemanticContextKind::None, {}); if (HaveLeadingSpace) builder.addAnnotatedWhitespace(" "); else builder.addWhitespace(" "); builder.addEqual(); builder.addWhitespace(" "); assert(RHSType && resultType); builder.addCallParameter(Identifier(), Identifier(), RHSType, /*IsVarArg*/ false, /*TopLevel*/ true, /*IsInOut*/ false, /*isIUO*/ false); addTypeAnnotation(builder, resultType); } void addInfixOperatorCompletion(OperatorDecl *op, Type resultType, Type RHSType) { // FIXME: we should get the semantic context of the function, not the // operator decl. auto semanticContext = getSemanticContext(op, DeclVisibilityKind::VisibleAtTopLevel); CodeCompletionResultBuilder builder( Sink, CodeCompletionResult::ResultKind::Declaration, semanticContext, {}); builder.setAssociatedDecl(op); if (HaveLeadingSpace) builder.addAnnotatedWhitespace(" "); else builder.addWhitespace(" "); builder.addTextChunk(op->getName().str()); builder.addWhitespace(" "); if (RHSType) builder.addCallParameter(Identifier(), Identifier(), RHSType, false, true, /*IsInOut*/ false, /*isIUO*/ false); if (resultType) addTypeAnnotation(builder, resultType); } void tryInfixOperatorCompletion(InfixOperatorDecl *op, SequenceExpr *SE) { if (op->getName().str() == "~>") return; MutableArrayRef<Expr *> sequence = SE->getElements(); assert(sequence.size() >= 3 && !sequence.back() && !sequence.drop_back(1).back() && "sequence not cleaned up"); assert((sequence.size() & 1) && "sequence expr ending with operator"); // FIXME: these checks should apply to the LHS of the operator, not the // immediately left expression. Move under the type-checking. Expr *LHS = sequence.drop_back(2).back(); if (LHS->getType() && (LHS->getType()->is<MetatypeType>() || LHS->getType()->is<AnyFunctionType>())) return; // We allocate these expressions on the stack because we know they can't // escape and there isn't a better way to allocate scratch Expr nodes. UnresolvedDeclRefExpr UDRE(op->getName(), DeclRefKind::BinaryOperator, DeclNameLoc(LHS->getEndLoc())); sequence.drop_back(1).back() = &UDRE; CodeCompletionExpr CCE(LHS->getSourceRange()); sequence.back() = &CCE; SWIFT_DEFER { // Reset sequence. SE->setElement(SE->getNumElements() - 1, nullptr); SE->setElement(SE->getNumElements() - 2, nullptr); prepareForRetypechecking(SE); // Reset any references to operators in types, so they are properly // handled as operators by sequence folding. // // FIXME: Would be better to have some kind of 'OperatorRefExpr'? for (auto &element : sequence.drop_back(2)) { if (auto operatorRef = element->getMemberOperatorRef()) { operatorRef->setType(nullptr); element = operatorRef; } } }; Expr *expr = SE; if (!typeCheckCompletionSequence(const_cast<DeclContext *>(CurrDeclContext), expr)) { if (!LHS->getType()->getRValueType()->getOptionalObjectType()) { // Don't complete optional operators on non-optional types. // FIXME: can we get the type-checker to disallow these for us? if (op->getName().str() == "??") return; if (auto NT = CCE.getType()->getNominalOrBoundGenericNominal()) { if (NT->getName() == CurrDeclContext->getASTContext().Id_OptionalNilComparisonType) return; } } // If the right-hand side and result type are both type parameters, we're // not providing a useful completion. if (expr->getType()->isTypeParameter() && CCE.getType()->isTypeParameter()) return; addInfixOperatorCompletion(op, expr->getType(), CCE.getType()); } } void flattenBinaryExpr(BinaryExpr *expr, SmallVectorImpl<Expr *> &sequence) { auto LHS = expr->getArg()->getElement(0); if (auto binexpr = dyn_cast<BinaryExpr>(LHS)) flattenBinaryExpr(binexpr, sequence); else sequence.push_back(LHS); sequence.push_back(expr->getFn()); auto RHS = expr->getArg()->getElement(1); if (auto binexpr = dyn_cast<BinaryExpr>(RHS)) flattenBinaryExpr(binexpr, sequence); else sequence.push_back(RHS); } void typeCheckLeadingSequence(SmallVectorImpl<Expr *> &sequence) { Expr *expr = SequenceExpr::create(CurrDeclContext->getASTContext(), sequence); prepareForRetypechecking(expr); // Take advantage of the fact the type-checker leaves the types on the AST. if (!typeCheckExpression(const_cast<DeclContext *>(CurrDeclContext), expr)) { if (auto binexpr = dyn_cast<BinaryExpr>(expr)) { // Rebuild the sequence from the type-checked version. sequence.clear(); flattenBinaryExpr(binexpr, sequence); return; } } // Fall back to just using the immediate LHS. auto LHS = sequence.back(); sequence.clear(); sequence.push_back(LHS); } void getOperatorCompletions(Expr *LHS, ArrayRef<Expr *> leadingSequence) { std::vector<OperatorDecl *> operators = collectOperators(); // FIXME: this always chooses the first operator with the given name. llvm::DenseSet<Identifier> seenPostfixOperators; llvm::DenseSet<Identifier> seenInfixOperators; SmallVector<Expr *, 3> sequence(leadingSequence.begin(), leadingSequence.end()); sequence.push_back(LHS); assert((sequence.size() & 1) && "sequence expr ending with operator"); if (sequence.size() > 1) typeCheckLeadingSequence(sequence); // Create a single sequence expression, which we will modify for each // operator, filling in the operator and dummy right-hand side. sequence.push_back(nullptr); // operator sequence.push_back(nullptr); // RHS auto *SE = SequenceExpr::create(CurrDeclContext->getASTContext(), sequence); prepareForRetypechecking(SE); for (auto op : operators) { switch (op->getKind()) { case DeclKind::PrefixOperator: // Don't insert prefix operators in postfix position. // FIXME: where should these get completed? break; case DeclKind::PostfixOperator: if (seenPostfixOperators.insert(op->getName()).second) tryPostfixOperator(LHS, cast<PostfixOperatorDecl>(op)); break; case DeclKind::InfixOperator: if (seenInfixOperators.insert(op->getName()).second) tryInfixOperatorCompletion(cast<InfixOperatorDecl>(op), SE); break; default: llvm_unreachable("unexpected operator kind"); } } if (leadingSequence.empty() && LHS->getType() && LHS->getType()->hasLValueType()) { addAssignmentOperator(LHS->getType()->getRValueType(), CurrDeclContext->getASTContext().TheEmptyTupleType); } // FIXME: unify this with the ?.member completions. if (auto T = LHS->getType()) if (auto ValueT = T->getRValueType()->getOptionalObjectType()) addPostfixBang(ValueT); } void addValueLiteralCompletions() { auto &context = CurrDeclContext->getASTContext(); auto *module = CurrDeclContext->getParentModule(); auto addFromProto = [&]( CodeCompletionLiteralKind kind, StringRef defaultTypeName, llvm::function_ref<void(CodeCompletionResultBuilder &)> consumer, bool isKeyword = false) { CodeCompletionResultBuilder builder(Sink, CodeCompletionResult::Literal, SemanticContextKind::None, {}); builder.setLiteralKind(kind); consumer(builder); // Check for matching ExpectedTypes. auto *P = context.getProtocol(protocolForLiteralKind(kind)); bool foundConformance = false; for (auto T : ExpectedTypes) { if (!T) continue; auto typeRelation = CodeCompletionResult::Identical; // Convert through optional types unless we're looking for a protocol // that Optional itself conforms to. if (kind != CodeCompletionLiteralKind::NilLiteral) { if (auto optionalObjT = T->getOptionalObjectType()) { T = optionalObjT; typeRelation = CodeCompletionResult::Convertible; } } // Check for conformance to the literal protocol. if (auto *NTD = T->getAnyNominal()) { SmallVector<ProtocolConformance *, 2> conformances; if (NTD->lookupConformance(module, P, conformances)) { foundConformance = true; addTypeAnnotation(builder, T); builder.setExpectedTypeRelation(typeRelation); } } } // Fallback to showing the default type. if (!foundConformance && !defaultTypeName.empty()) builder.addTypeAnnotation(defaultTypeName); }; // FIXME: the pedantically correct way is to resolve Swift.*LiteralType. using LK = CodeCompletionLiteralKind; using Builder = CodeCompletionResultBuilder; // Add literal completions that conform to specific protocols. addFromProto(LK::IntegerLiteral, "Int", [](Builder &builder) { builder.addTextChunk("0"); }); addFromProto(LK::BooleanLiteral, "Bool", [](Builder &builder) { builder.addTextChunk("true"); }, /*isKeyword=*/true); addFromProto(LK::BooleanLiteral, "Bool", [](Builder &builder) { builder.addTextChunk("false"); }, /*isKeyword=*/true); addFromProto(LK::NilLiteral, "", [](Builder &builder) { builder.addTextChunk("nil"); }, /*isKeyword=*/true); addFromProto(LK::StringLiteral, "String", [&](Builder &builder) { builder.addTextChunk("\""); builder.addSimpleNamedParameter("abc"); builder.addTextChunk("\""); }); addFromProto(LK::ArrayLiteral, "Array", [&](Builder &builder) { builder.addLeftBracket(); builder.addSimpleNamedParameter("values"); builder.addRightBracket(); }); addFromProto(LK::DictionaryLiteral, "Dictionary", [&](Builder &builder) { builder.addLeftBracket(); builder.addSimpleNamedParameter("key"); builder.addTextChunk(": "); builder.addSimpleNamedParameter("value"); builder.addRightBracket(); }); auto floatType = context.getFloatDecl()->getDeclaredType(); addFromProto(LK::ColorLiteral, "", [&](Builder &builder) { builder.addTextChunk("#colorLiteral"); builder.addLeftParen(); builder.addCallParameter(context.getIdentifier("red"), floatType, false, true, /*IsInOut*/ false, /*isIUO*/ false); builder.addComma(); builder.addCallParameter(context.getIdentifier("green"), floatType, false, true, /*IsInOut*/ false, /*isIUO*/ false); builder.addComma(); builder.addCallParameter(context.getIdentifier("blue"), floatType, false, true, /*IsInOut*/ false, /*isIUO*/ false); builder.addComma(); builder.addCallParameter(context.getIdentifier("alpha"), floatType, false, true, /*IsInOut*/ false, /*isIUO*/ false); builder.addRightParen(); }); auto stringType = context.getStringDecl()->getDeclaredType(); addFromProto(LK::ImageLiteral, "", [&](Builder &builder) { builder.addTextChunk("#imageLiteral"); builder.addLeftParen(); builder.addCallParameter(context.getIdentifier("resourceName"), stringType, false, true, /*IsInOut*/ false, /*isIUO*/ false); builder.addRightParen(); }); // Add tuple completion (item, item). { CodeCompletionResultBuilder builder(Sink, CodeCompletionResult::Literal, SemanticContextKind::None, {}); builder.setLiteralKind(LK::Tuple); builder.addLeftParen(); builder.addSimpleNamedParameter("values"); builder.addRightParen(); for (auto T : ExpectedTypes) { if (!T) continue; if (T->is<TupleType>()) { addTypeAnnotation(builder, T); builder.setExpectedTypeRelation(CodeCompletionResult::Identical); break; } } } } struct FilteredDeclConsumer : public swift::VisibleDeclConsumer { swift::VisibleDeclConsumer &Consumer; DeclFilter Filter; FilteredDeclConsumer(swift::VisibleDeclConsumer &Consumer, DeclFilter Filter) : Consumer(Consumer), Filter(Filter) {} void foundDecl(ValueDecl *VD, DeclVisibilityKind Kind) override { if (Filter(VD, Kind)) Consumer.foundDecl(VD, Kind); } }; void getValueCompletionsInDeclContext(SourceLoc Loc, DeclFilter Filter = DefaultFilter, bool IncludeTopLevel = false, bool RequestCache = true, bool LiteralCompletions = true) { ExprType = Type(); Kind = LookupKind::ValueInDeclContext; NeedLeadingDot = false; FilteredDeclConsumer Consumer(*this, Filter); lookupVisibleDecls(Consumer, CurrDeclContext, TypeResolver.get(), /*IncludeTopLevel=*/IncludeTopLevel, Loc); if (RequestCache) RequestedCachedResults = RequestedResultsTy::toplevelResults(); // Manually add any expected nominal types from imported modules so that // they get their expected type relation. Don't include protocols, since // they can't be initialized from the type name. // FIXME: this does not include types that conform to an expected protocol. // FIXME: this creates duplicate results. for (auto T : ExpectedTypes) { if (auto NT = T->getAs<NominalType>()) { if (auto NTD = NT->getDecl()) { if (!isa<ProtocolDecl>(NTD) && NTD->getModuleContext() != CurrDeclContext->getParentModule()) { addNominalTypeRef(NT->getDecl(), DeclVisibilityKind::VisibleAtTopLevel); } } } } if (CompletionContext) { // FIXME: this is an awful simplification that says all and only enums can // use implicit member syntax (leading dot). Computing the accurate answer // using lookup (e.g. getUnresolvedMemberCompletions) is too expensive, // and for some clients this approximation is good enough. CompletionContext->MayUseImplicitMemberExpr = std::any_of(ExpectedTypes.begin(), ExpectedTypes.end(), [](Type T) { if (auto *NTD = T->getAnyNominal()) return isa<EnumDecl>(NTD); return false; }); } if (LiteralCompletions) addValueLiteralCompletions(); // If the expected type is ObjectiveC.Selector, add #selector. If // it's String, add #keyPath. if (Ctx.LangOpts.EnableObjCInterop) { bool addedSelector = false; bool addedKeyPath = false; for (auto T : ExpectedTypes) { T = T->lookThroughAllOptionalTypes(); if (auto structDecl = T->getStructOrBoundGenericStruct()) { if (!addedSelector && structDecl->getName() == Ctx.Id_Selector && structDecl->getParentModule()->getName() == Ctx.Id_ObjectiveC) { addPoundSelector(/*needPound=*/true); if (addedKeyPath) break; addedSelector = true; continue; } } if (!addedKeyPath && T->getAnyNominal() == Ctx.getStringDecl()) { addPoundKeyPath(/*needPound=*/true); if (addedSelector) break; addedKeyPath = true; continue; } } } } struct LookupByName : public swift::VisibleDeclConsumer { CompletionLookup &Lookup; std::vector<std::string> &SortedNames; llvm::SmallPtrSet<Decl*, 3> HandledDecls; bool isNameHit(StringRef Name) { return std::binary_search(SortedNames.begin(), SortedNames.end(), Name); } void unboxType(Type T) { if (T->hasParenSugar()) { unboxType(T->getDesugaredType()); } else if (T->is<TupleType>()) { for (auto Ele : T->getAs<TupleType>()->getElements()) { unboxType(Ele.getType()); } } else if (auto FT = T->getAs<FunctionType>()) { unboxType(FT->getInput()); unboxType(FT->getResult()); } else if (auto NTD = T->getNominalOrBoundGenericNominal()){ if (HandledDecls.insert(NTD).second) Lookup.getUnresolvedMemberCompletions(T); } } LookupByName(CompletionLookup &Lookup, std::vector<std::string> &SortedNames) : Lookup(Lookup), SortedNames(SortedNames) { std::sort(SortedNames.begin(), SortedNames.end()); } void handleDeclRange(const DeclRange &Members, DeclVisibilityKind Reason) { for (auto M : Members) { if (auto VD = dyn_cast<ValueDecl>(M)) { foundDecl(VD, Reason); } } } void foundDecl(ValueDecl *VD, DeclVisibilityKind Reason) override { if (auto NTD = dyn_cast<NominalTypeDecl>(VD)) { if (isNameHit(NTD->getNameStr())) { unboxType(NTD->getDeclaredType()); } handleDeclRange(NTD->getMembers(), Reason); for (auto Ex : NTD->getExtensions()) { handleDeclRange(Ex->getMembers(), Reason); } } else if (!VD->getBaseName().isSpecial() && isNameHit(VD->getBaseName().getIdentifier().str())) { if (VD->hasInterfaceType()) unboxType(VD->getInterfaceType()); } } }; void getUnresolvedMemberCompletions(ArrayRef<Type> Types) { NeedLeadingDot = !HaveDot; for (auto T : Types) { if (T && T->getNominalOrBoundGenericNominal()) { // We can only say .foo where foo is a static member of the contextual // type and has the same type (or if the member is a function, then the // same result type) as the contextual type. FilteredDeclConsumer consumer(*this, [=](ValueDecl *VD, DeclVisibilityKind reason) { if (!VD->hasInterfaceType()) { TypeResolver->resolveDeclSignature(VD); if (!VD->hasInterfaceType()) return false; } auto declTy = VD->getInterfaceType(); while (auto FT = declTy->getAs<AnyFunctionType>()) declTy = FT->getResult(); return declTy->isEqual(T); }); auto baseType = MetatypeType::get(T); llvm::SaveAndRestore<LookupKind> SaveLook(Kind, LookupKind::ValueExpr); llvm::SaveAndRestore<Type> SaveType(ExprType, baseType); llvm::SaveAndRestore<bool> SaveUnresolved(IsUnresolvedMember, true); lookupVisibleMemberDecls(consumer, baseType, CurrDeclContext, TypeResolver.get(), /*includeInstanceMembers=*/false); } } } void getUnresolvedMemberCompletions(std::vector<std::string> &FuncNames, bool HasReturn) { NeedLeadingDot = !HaveDot; LookupByName Lookup(*this, FuncNames); lookupVisibleDecls(Lookup, CurrDeclContext, TypeResolver.get(), true); if (HasReturn) if (auto ReturnType = getReturnTypeFromContext(CurrDeclContext)) Lookup.unboxType(ReturnType); } static bool getPositionInTupleExpr(DeclContext &DC, Expr *Target, TupleExpr *Tuple, unsigned &Pos, bool &HasName) { auto &SM = DC.getASTContext().SourceMgr; Pos = 0; for (auto E : Tuple->getElements()) { if (SM.isBeforeInBuffer(E->getEndLoc(), Target->getStartLoc())) { Pos ++; continue; } HasName = !Tuple->getElementName(Pos).empty(); return true; } return false; } void addArgNameCompletionResults(ArrayRef<StringRef> Names) { for (auto Name : Names) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::ExpressionSpecific, {}); Builder.addTextChunk(Name); Builder.addCallParameterColon(); Builder.addTypeAnnotation("Argument name"); } } static void collectArgumentExpectation(unsigned Position, bool HasName, ArrayRef<Type> Types, SourceLoc Loc, std::vector<Type> &ExpectedTypes, std::vector<StringRef> &ExpectedNames) { SmallPtrSet<TypeBase *, 4> seenTypes; SmallPtrSet<const char *, 4> seenNames; for (auto Type : Types) { if (auto TT = Type->getAs<TupleType>()) { if (Position >= TT->getElements().size()) { continue; } auto Ele = TT->getElement(Position); if (Ele.hasName() && !HasName) { if (seenNames.insert(Ele.getName().get()).second) ExpectedNames.push_back(Ele.getName().str()); } else { if (seenTypes.insert(Ele.getType().getPointer()).second) ExpectedTypes.push_back(Ele.getType()); } } else if (Position == 0) { // The only param. TypeBase *T = Type->getDesugaredType(); if (seenTypes.insert(T).second) ExpectedTypes.push_back(T); } } } bool lookupArgCompletionsAtPosition(unsigned Position, bool HasName, ArrayRef<Type> Types, SourceLoc Loc) { std::vector<Type> ExpectedTypes; std::vector<StringRef> ExpectedNames; collectArgumentExpectation(Position, HasName, Types, Loc, ExpectedTypes, ExpectedNames); addArgNameCompletionResults(ExpectedNames); if (!ExpectedTypes.empty()) { setExpectedTypes(ExpectedTypes); getValueCompletionsInDeclContext(Loc, DefaultFilter); } return true; } static bool isPotentialSignatureMatch(ArrayRef<Type> TupleEles, ArrayRef<Type> ExprTypes, DeclContext *DC) { // Not likely to be a match if users provide more arguments than expected. if (ExprTypes.size() >= TupleEles.size()) return false; for (unsigned I = 0; I < ExprTypes.size(); ++ I) { auto Ty = ExprTypes[I]; if (Ty && !Ty->is<ErrorType>()) { if (!isConvertibleTo(Ty, TupleEles[I], *DC)) { return false; } } } return true; } static void removeUnlikelyOverloads(SmallVectorImpl<Type> &PossibleArgTypes, ArrayRef<Type> TupleEleTypes, DeclContext *DC) { for (auto It = PossibleArgTypes.begin(); It != PossibleArgTypes.end(); ) { llvm::SmallVector<Type, 3> ExpectedTypes; if (isa<TupleType>((*It).getPointer())) { auto Elements = (*It)->getAs<TupleType>()->getElements(); for (auto Ele : Elements) ExpectedTypes.push_back(Ele.getType()); } else { ExpectedTypes.push_back(*It); } if (isPotentialSignatureMatch(ExpectedTypes, TupleEleTypes, DC)) { ++ It; } else { PossibleArgTypes.erase(It); } } } static bool collectionInputTypes(DeclContext &DC, CallExpr *callExpr, SmallVectorImpl<Type> &possibleTypes) { auto *fnExpr = callExpr->getFn(); if (auto type = fnExpr->getType()) { if (auto *funcType = type->getAs<AnyFunctionType>()) possibleTypes.push_back(funcType->getInput()); } else if (auto *DRE = dyn_cast<DeclRefExpr>(fnExpr)) { if (auto *decl = DRE->getDecl()) { auto declType = decl->getInterfaceType(); if (auto *funcType = declType->getAs<AnyFunctionType>()) possibleTypes.push_back(funcType->getInput()); } } else if (auto *OSRE = dyn_cast<OverloadSetRefExpr>(fnExpr)) { for (auto *decl : OSRE->getDecls()) { auto declType = decl->getInterfaceType(); if (auto *funcType = declType->getAs<AnyFunctionType>()) possibleTypes.push_back(funcType->getInput()); } } else { ConcreteDeclRef ref = nullptr; auto fnType = getTypeOfCompletionContextExpr(DC.getASTContext(), &DC, CompletionTypeCheckKind::Normal, fnExpr, ref); if (!fnType) return false; if (auto *AFT = (*fnType)->getAs<AnyFunctionType>()) possibleTypes.push_back(AFT->getInput()); } return !possibleTypes.empty(); } static bool collectPossibleArgTypes(DeclContext &DC, CallExpr *CallE, Expr *CCExpr, SmallVectorImpl<Type> &PossibleTypes, unsigned &Position, bool &HasName) { if (!collectionInputTypes(DC, CallE, PossibleTypes)) return false; if (auto *tuple = dyn_cast<TupleExpr>(CallE->getArg())) { for (unsigned i = 0, n = tuple->getNumElements(); i != n; ++i) { if (isa<CodeCompletionExpr>(tuple->getElement(i))) { HasName = !tuple->getElementName(i).empty(); Position = i; return true; } } return getPositionInTupleExpr(DC, CCExpr, tuple, Position, HasName); } else if (isa<ParenExpr>(CallE->getArg())) { HasName = false; Position = 0; return true; } return false; } static bool collectArgumentExpectation(DeclContext &DC, CallExpr *CallE, Expr *CCExpr, std::vector<Type> &ExpectedTypes, std::vector<StringRef> &ExpectedNames) { SmallVector<Type, 2> PossibleTypes; unsigned Position; bool HasName; if (collectPossibleArgTypes(DC, CallE, CCExpr, PossibleTypes, Position, HasName)) { collectArgumentExpectation(Position, HasName, PossibleTypes, CCExpr->getStartLoc(), ExpectedTypes, ExpectedNames); return !ExpectedTypes.empty() || !ExpectedNames.empty(); } return false; } bool getCallArgCompletions(DeclContext &DC, CallExpr *CallE, Expr *CCExpr) { SmallVector<Type, 2> PossibleTypes; unsigned Position; bool HasName; bool hasPossibleArgTypes = collectPossibleArgTypes(DC, CallE, CCExpr, PossibleTypes, Position, HasName); bool hasCompletions = lookupArgCompletionsAtPosition(Position, HasName, PossibleTypes, CCExpr->getStartLoc()); return hasPossibleArgTypes && hasCompletions; } void getTypeContextEnumElementCompletions(SourceLoc Loc) { llvm::SaveAndRestore<LookupKind> ChangeLookupKind( Kind, LookupKind::EnumElement); NeedLeadingDot = !HaveDot; const DeclContext *FunctionDC = CurrDeclContext; const AbstractFunctionDecl *CurrentFunction = nullptr; while (FunctionDC->isLocalContext()) { if (auto *AFD = dyn_cast<AbstractFunctionDecl>(FunctionDC)) { CurrentFunction = AFD; break; } FunctionDC = FunctionDC->getParent(); } if (!CurrentFunction) return; auto *Switch = cast_or_null<SwitchStmt>( findNearestStmt(CurrentFunction, Loc, StmtKind::Switch)); if (!Switch) return; auto Ty = Switch->getSubjectExpr()->getType(); if (!Ty) return; auto *TheEnumDecl = dyn_cast_or_null<EnumDecl>(Ty->getAnyNominal()); if (!TheEnumDecl) return; for (auto Element : TheEnumDecl->getAllElements()) { foundDecl(Element, DeclVisibilityKind::MemberOfCurrentNominal); } } void getTypeCompletions(Type BaseType) { Kind = LookupKind::Type; this->BaseType = BaseType; NeedLeadingDot = !HaveDot; Type MetaBase = MetatypeType::get(BaseType); lookupVisibleMemberDecls(*this, MetaBase, CurrDeclContext, TypeResolver.get(), IncludeInstanceMembers); addKeyword("Type", MetaBase); } static bool canUseAttributeOnDecl(DeclAttrKind DAK, bool IsInSil, Optional<DeclKind> DK) { if (DeclAttribute::isUserInaccessible(DAK)) return false; if (DeclAttribute::isDeclModifier(DAK)) return false; if (DeclAttribute::shouldBeRejectedByParser(DAK)) return false; if (!IsInSil && DeclAttribute::isSilOnly(DAK)) return false; if (!DK.hasValue()) return true; return DeclAttribute::canAttributeAppearOnDeclKind(DAK, DK.getValue()); } void getAttributeDeclCompletions(bool IsInSil, Optional<DeclKind> DK) { // FIXME: also include user-defined attribute keywords StringRef TargetName = "Declaration"; if (DK.hasValue()) { switch (DK.getValue()) { #define DECL(Id, ...) \ case DeclKind::Id: \ TargetName = #Id; \ break; #include "swift/AST/DeclNodes.def" } } std::string Description = TargetName.str() + " Attribute"; #define DECL_ATTR(KEYWORD, NAME, ...) \ if (canUseAttributeOnDecl(DAK_##NAME, IsInSil, DK)) \ addDeclAttrKeyword(#KEYWORD, Description); #include "swift/AST/Attr.def" } void getAttributeDeclParamCompletions(DeclAttrKind AttrKind, int ParamIndex) { if (AttrKind == DAK_Available) { if (ParamIndex == 0) { addDeclAttrParamKeyword("*", "Platform", false); #define AVAILABILITY_PLATFORM(X, PrettyName) \ addDeclAttrParamKeyword(#X, "Platform", false); #include "swift/AST/PlatformKinds.def" } else { addDeclAttrParamKeyword("unavailable", "", false); addDeclAttrParamKeyword("message", "Specify message", true); addDeclAttrParamKeyword("renamed", "Specify replacing name", true); addDeclAttrParamKeyword("introduced", "Specify version number", true); addDeclAttrParamKeyword("deprecated", "Specify version number", true); } } } void getPoundAvailablePlatformCompletions() { // The platform names should be identical to those in @available. getAttributeDeclParamCompletions(DAK_Available, 0); } void getTypeCompletionsInDeclContext(SourceLoc Loc) { Kind = LookupKind::TypeInDeclContext; lookupVisibleDecls(*this, CurrDeclContext, TypeResolver.get(), /*IncludeTopLevel=*/false, Loc); RequestedCachedResults = RequestedResultsTy::toplevelResults().onlyTypes(); } void getToplevelCompletions(bool OnlyTypes) { Kind = OnlyTypes ? LookupKind::TypeInDeclContext : LookupKind::ValueInDeclContext; NeedLeadingDot = false; ModuleDecl *M = CurrDeclContext->getParentModule(); AccessFilteringDeclConsumer FilteringConsumer(CurrDeclContext, *this, TypeResolver.get()); M->lookupVisibleDecls({}, FilteringConsumer, NLKind::UnqualifiedLookup); } void getVisibleDeclsOfModule(const ModuleDecl *TheModule, ArrayRef<std::string> AccessPath, bool ResultsHaveLeadingDot) { Kind = LookupKind::ImportFromModule; NeedLeadingDot = ResultsHaveLeadingDot; llvm::SmallVector<std::pair<Identifier, SourceLoc>, 1> LookupAccessPath; for (auto Piece : AccessPath) { LookupAccessPath.push_back( std::make_pair(Ctx.getIdentifier(Piece), SourceLoc())); } AccessFilteringDeclConsumer FilteringConsumer(CurrDeclContext, *this, TypeResolver.get()); TheModule->lookupVisibleDecls(LookupAccessPath, FilteringConsumer, NLKind::UnqualifiedLookup); } }; class CompletionOverrideLookup : public swift::VisibleDeclConsumer { CodeCompletionResultSink &Sink; OwnedResolver TypeResolver; const DeclContext *CurrDeclContext; SmallVectorImpl<StringRef> &ParsedKeywords; bool hasFuncIntroducer = false; bool hasVarIntroducer = false; bool hasTypealiasIntroducer = false; bool hasInitializerModifier = false; bool hasAccessModifier = false; bool hasOverride = false; bool hasOverridabilityModifier = false; public: CompletionOverrideLookup(CodeCompletionResultSink &Sink, ASTContext &Ctx, const DeclContext *CurrDeclContext, SmallVectorImpl<StringRef> &ParsedKeywords) : Sink(Sink), TypeResolver(createLazyResolver(Ctx)), CurrDeclContext(CurrDeclContext), ParsedKeywords(ParsedKeywords) { hasFuncIntroducer = isKeywordSpecified("func"); hasVarIntroducer = isKeywordSpecified("var") || isKeywordSpecified("let"); hasTypealiasIntroducer = isKeywordSpecified("typealias"); hasInitializerModifier = isKeywordSpecified("required") || isKeywordSpecified("convenience"); hasAccessModifier = isKeywordSpecified("private") || isKeywordSpecified("fileprivate") || isKeywordSpecified("internal") || isKeywordSpecified("public") || isKeywordSpecified("open"); hasOverride = isKeywordSpecified("override"); hasOverridabilityModifier = isKeywordSpecified("final") || isKeywordSpecified("open"); } bool isKeywordSpecified(StringRef Word) { return std::find(ParsedKeywords.begin(), ParsedKeywords.end(), Word) != ParsedKeywords.end(); } bool missingOverride(DeclVisibilityKind Reason) { return !hasOverride && Reason == DeclVisibilityKind::MemberOfSuper && !CurrDeclContext->getAsProtocolOrProtocolExtensionContext(); } void addAccessControl(const ValueDecl *VD, CodeCompletionResultBuilder &Builder) { assert(CurrDeclContext->getAsNominalTypeOrNominalTypeExtensionContext()); auto AccessOfContext = CurrDeclContext->getAsNominalTypeOrNominalTypeExtensionContext() ->getFormalAccess(); auto Access = std::min(VD->getFormalAccess(), AccessOfContext); // Only emit 'public', not needed otherwise. if (Access >= AccessLevel::Public) Builder.addAccessControlKeyword(Access); } void addValueOverride(const ValueDecl *VD, DeclVisibilityKind Reason, CodeCompletionResultBuilder &Builder, bool hasDeclIntroducer) { class DeclNameOffsetLocatorPrinter : public StreamPrinter { public: using StreamPrinter::StreamPrinter; Optional<unsigned> NameOffset; void printDeclLoc(const Decl *D) override { if (!NameOffset.hasValue()) NameOffset = OS.tell(); } }; llvm::SmallString<256> DeclStr; unsigned NameOffset = 0; { llvm::raw_svector_ostream OS(DeclStr); DeclNameOffsetLocatorPrinter Printer(OS); PrintOptions Options; if (auto transformType = CurrDeclContext->getDeclaredTypeInContext()) Options.setBaseType(transformType); Options.PrintDefaultParameterPlaceholder = false; Options.PrintImplicitAttrs = false; Options.ExclusiveAttrList.push_back(TAK_escaping); Options.PrintOverrideKeyword = false; Options.PrintPropertyAccessors = false; VD->print(Printer, Options); NameOffset = Printer.NameOffset.getValue(); } if (!hasDeclIntroducer && !hasAccessModifier) addAccessControl(VD, Builder); // FIXME: if we're missing 'override', but have the decl introducer we // should delete it and re-add both in the correct order. if (!hasDeclIntroducer && missingOverride(Reason)) Builder.addOverrideKeyword(); if (!hasDeclIntroducer) Builder.addDeclIntroducer(DeclStr.str().substr(0, NameOffset)); Builder.addTextChunk(DeclStr.str().substr(NameOffset)); } void addMethodOverride(const FuncDecl *FD, DeclVisibilityKind Reason) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::Super, {}); Builder.setAssociatedDecl(FD); addValueOverride(FD, Reason, Builder, hasFuncIntroducer); Builder.addBraceStmtWithCursor(); } void addVarOverride(const VarDecl *VD, DeclVisibilityKind Reason) { // Overrides cannot use 'let', but if the 'override' keyword is specified // then the intention is clear, so provide the results anyway. The compiler // can then provide an error telling you to use 'var' instead. // If we don't need override then it's a protocol requirement, so show it. if (missingOverride(Reason) && hasVarIntroducer && isKeywordSpecified("let")) return; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::Super, {}); Builder.setAssociatedDecl(VD); addValueOverride(VD, Reason, Builder, hasVarIntroducer); } void addTypeAlias(const AssociatedTypeDecl *ATD, DeclVisibilityKind Reason) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::Super, {}); Builder.setAssociatedDecl(ATD); if (!hasTypealiasIntroducer && !hasAccessModifier) addAccessControl(ATD, Builder); if (!hasTypealiasIntroducer) Builder.addDeclIntroducer("typealias "); Builder.addTextChunk(ATD->getName().str()); Builder.addTextChunk(" = "); Builder.addSimpleNamedParameter("Type"); } void addConstructor(const ConstructorDecl *CD, DeclVisibilityKind Reason) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Declaration, SemanticContextKind::Super, {}); Builder.setAssociatedDecl(CD); if (!hasAccessModifier) addAccessControl(CD, Builder); if (missingOverride(Reason) && CD->isDesignatedInit() && !CD->isRequired()) Builder.addOverrideKeyword(); // Emit 'required' if we're in class context, 'required' is not specified, // and 1) this is a protocol conformance and the class is not final, or 2) // this is subclass and the initializer is marked as required. bool needRequired = false; auto C = CurrDeclContext->getAsClassOrClassExtensionContext(); if (C && !isKeywordSpecified("required")) { if (Reason == DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal && !C->isFinal()) needRequired = true; else if (Reason == DeclVisibilityKind::MemberOfSuper && CD->isRequired()) needRequired = true; } llvm::SmallString<256> DeclStr; if (needRequired) DeclStr += "required "; { llvm::raw_svector_ostream OS(DeclStr); PrintOptions Options; Options.PrintImplicitAttrs = false; Options.SkipAttributes = true; Options.PrintDefaultParameterPlaceholder = false; CD->print(OS, Options); } Builder.addTextChunk(DeclStr); Builder.addBraceStmtWithCursor(); } // Implement swift::VisibleDeclConsumer. void foundDecl(ValueDecl *D, DeclVisibilityKind Reason) override { if (Reason == DeclVisibilityKind::MemberOfCurrentNominal) return; if (shouldHideDeclFromCompletionResults(D)) return; if (D->getAttrs().hasAttribute<FinalAttr>()) return; if (!D->hasInterfaceType()) TypeResolver->resolveDeclSignature(D); bool hasIntroducer = hasFuncIntroducer || hasVarIntroducer || hasTypealiasIntroducer; if (auto *FD = dyn_cast<FuncDecl>(D)) { // We cannot override operators as members. if (FD->isBinaryOperator() || FD->isUnaryOperator()) return; // We cannot override individual accessors. if (isa<AccessorDecl>(FD)) return; if (hasFuncIntroducer || (!hasIntroducer && !hasInitializerModifier)) addMethodOverride(FD, Reason); return; } if (auto *VD = dyn_cast<VarDecl>(D)) { if (hasVarIntroducer || (!hasIntroducer && !hasInitializerModifier)) addVarOverride(VD, Reason); return; } if (auto *CD = dyn_cast<ConstructorDecl>(D)) { if (!isa<ProtocolDecl>(CD->getDeclContext())) return; if (hasIntroducer || hasOverride || hasOverridabilityModifier) return; if (CD->isRequired() || CD->isDesignatedInit()) addConstructor(CD, Reason); return; } } void addDesignatedInitializers(Type CurrTy) { if (hasFuncIntroducer || hasVarIntroducer || hasTypealiasIntroducer || hasOverridabilityModifier) return; assert(CurrTy); const auto *CD = dyn_cast_or_null<ClassDecl>(CurrTy->getAnyNominal()); if (!CD) return; if (!CD->getSuperclass()) return; CD = CD->getSuperclass()->getClassOrBoundGenericClass(); for (const auto *Member : CD->getMembers()) { const auto *Constructor = dyn_cast<ConstructorDecl>(Member); if (!Constructor) continue; if (Constructor->hasStubImplementation()) continue; if (Constructor->isDesignatedInit()) addConstructor(Constructor, DeclVisibilityKind::MemberOfSuper); } } void addAssociatedTypes(Type CurrTy) { if (!hasTypealiasIntroducer && (hasFuncIntroducer || hasVarIntroducer || hasInitializerModifier || hasOverride || hasOverridabilityModifier)) return; NominalTypeDecl *NTD = CurrTy->getAnyNominal(); for (auto Conformance : NTD->getAllConformances()) { auto Proto = Conformance->getProtocol(); if (!Proto->isAccessibleFrom(CurrDeclContext)) continue; auto NormalConformance = Conformance->getRootNormalConformance(); for (auto Member : Proto->getMembers()) { auto *ATD = dyn_cast<AssociatedTypeDecl>(Member); if (!ATD) continue; // FIXME: Also exclude the type alias that has already been specified. if (!NormalConformance->hasTypeWitness(ATD) || !ATD->getDefaultDefinitionLoc().isNull()) continue; addTypeAlias(ATD, DeclVisibilityKind::MemberOfProtocolImplementedByCurrentNominal); } } } void getOverrideCompletions(SourceLoc Loc) { if (!CurrDeclContext->getAsNominalTypeOrNominalTypeExtensionContext()) return; if (isa<ProtocolDecl>(CurrDeclContext)) return; Type CurrTy = CurrDeclContext->getDeclaredTypeInContext(); if (CurrTy && !CurrTy->is<ErrorType>()) { lookupVisibleMemberDecls(*this, CurrTy, CurrDeclContext, TypeResolver.get(), /*includeInstanceMembers=*/false); addDesignatedInitializers(CurrTy); addAssociatedTypes(CurrTy); } } }; } // end anonymous namespace static void addSelectorModifierKeywords(CodeCompletionResultSink &sink) { auto addKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) { CodeCompletionResultBuilder Builder( sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); Builder.setKeywordKind(Kind); Builder.addTextChunk(Name); Builder.addCallParameterColon(); Builder.addSimpleTypedParameter("@objc property", /*IsVarArg=*/false); }; addKeyword("getter", CodeCompletionKeywordKind::None); addKeyword("setter", CodeCompletionKeywordKind::None); } void CodeCompletionCallbacksImpl::completeDotExpr(Expr *E, SourceLoc DotLoc) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::DotExpr; if (E->getKind() == ExprKind::KeyPath) Kind = CompletionKind::SwiftKeyPath; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; } ParsedExpr = E; this->DotLoc = DotLoc; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeStmtOrExpr() { assert(P.Tok.is(tok::code_complete)); Kind = CompletionKind::StmtOrExpr; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completePostfixExprBeginning(CodeCompletionExpr *E) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::PostfixExprBeginning; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; if (CompleteExprSelectorContext == ObjCSelectorContext::MethodSelector) { addSelectorModifierKeywords(CompletionContext.getResultSink()); } } CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completeForEachSequenceBeginning( CodeCompletionExpr *E) { assert(P.Tok.is(tok::code_complete)); Kind = CompletionKind::ForEachSequence; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completePostfixExpr(Expr *E, bool hasSpace) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; HasSpace = hasSpace; Kind = CompletionKind::PostfixExpr; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; } ParsedExpr = E; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completePostfixExprParen(Expr *E, Expr *CodeCompletionE) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::PostfixExprParen; ParsedExpr = E; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = static_cast<CodeCompletionExpr*>(CodeCompletionE); ShouldCompleteCallPatternAfterParen = true; if (Context.LangOpts.CodeCompleteCallPatternHeuristics) { // Lookahead one token to decide what kind of call completions to provide. // When it appears that there is already code for the call present, just // complete values and/or argument labels. Otherwise give the entire call // pattern. Token next = P.peekToken(); if (!next.isAtStartOfLine() && !next.is(tok::eof) && !next.is(tok::r_paren)) { ShouldCompleteCallPatternAfterParen = false; } } } void CodeCompletionCallbacksImpl::completeExprSuper(SuperRefExpr *SRE) { // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::SuperExpr; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; } ParsedExpr = SRE; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeExprSuperDot(SuperRefExpr *SRE) { // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::SuperExprDot; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; } ParsedExpr = SRE; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeExprKeyPath(KeyPathExpr *KPE, bool HasDot) { Kind = HasDot ? CompletionKind::KeyPathExprDot : CompletionKind::KeyPathExpr; ParsedExpr = KPE; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completePoundAvailablePlatform() { Kind = CompletionKind::PoundAvailablePlatform; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeSimpleBeginning() { Kind = CompletionKind::TypeSimpleBeginning; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeDeclAttrParam(DeclAttrKind DK, int Index) { Kind = CompletionKind::AttributeDeclParen; AttrKind = DK; AttrParamIndex = Index; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeDeclAttrKeyword(Decl *D, bool Sil, bool Param) { Kind = CompletionKind::AttributeBegin; IsInSil = Sil; if (Param) { AttTargetDK = DeclKind::Param; } else if (D) { AttTargetDK = D->getKind(); } CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeIdentifierWithDot( IdentTypeRepr *ITR) { if (!ITR) { completeTypeSimpleBeginning(); return; } Kind = CompletionKind::TypeIdentifierWithDot; ParsedTypeLoc = TypeLoc(ITR); CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeIdentifierWithoutDot( IdentTypeRepr *ITR) { assert(ITR); Kind = CompletionKind::TypeIdentifierWithoutDot; ParsedTypeLoc = TypeLoc(ITR); CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeCaseStmtBeginning() { assert(!InEnumElementRawValue); Kind = CompletionKind::CaseStmtBeginning; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeCaseStmtDotPrefix() { assert(!InEnumElementRawValue); Kind = CompletionKind::CaseStmtDotPrefix; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeImportDecl( std::vector<std::pair<Identifier, SourceLoc>> &Path) { Kind = CompletionKind::Import; CurDeclContext = P.CurDeclContext; DotLoc = Path.empty() ? SourceLoc() : Path.back().second; if (DotLoc.isInvalid()) return; auto Importer = static_cast<ClangImporter *>(CurDeclContext->getASTContext(). getClangModuleLoader()); std::vector<std::string> SubNames; Importer->collectSubModuleNames(Path, SubNames); ASTContext &Ctx = CurDeclContext->getASTContext(); for (StringRef Sub : SubNames) { Path.push_back(std::make_pair(Ctx.getIdentifier(Sub), SourceLoc())); SubModuleNameVisibilityPairs.push_back( std::make_pair(Sub.str(), Ctx.getLoadedModule(Path))); Path.pop_back(); } } void CodeCompletionCallbacksImpl::completeUnresolvedMember(UnresolvedMemberExpr *E, ArrayRef<StringRef> Identifiers, bool HasReturn) { Kind = CompletionKind::UnresolvedMember; CurDeclContext = P.CurDeclContext; UnresolvedExpr = E; UnresolvedExprInReturn = HasReturn; for (auto Id : Identifiers) { TokensBeforeUnresolvedExpr.push_back(Id); } } void CodeCompletionCallbacksImpl::completeAssignmentRHS(AssignExpr *E) { AssignmentExpr = E; ParsedExpr = E->getDest(); CurDeclContext = P.CurDeclContext; Kind = CompletionKind::AssignmentRHS; } void CodeCompletionCallbacksImpl::completeCallArg(CallExpr *E) { if (Kind == CompletionKind::PostfixExprBeginning || Kind == CompletionKind::None) { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::CallArg; FuncCallExpr = E; ParsedExpr = E; } } void CodeCompletionCallbacksImpl::completeReturnStmt(CodeCompletionExpr *E) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::ReturnStmtExpr; } void CodeCompletionCallbacksImpl::completeAfterPound(CodeCompletionExpr *E, StmtKind ParentKind) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::AfterPound; ParentStmtKind = ParentKind; } void CodeCompletionCallbacksImpl::completeGenericParams(TypeLoc TL) { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::GenericParams; ParsedTypeLoc = TL; } void CodeCompletionCallbacksImpl::completeNominalMemberBeginning( SmallVectorImpl<StringRef> &Keywords) { assert(!InEnumElementRawValue); ParsedKeywords.clear(); ParsedKeywords.append(Keywords.begin(), Keywords.end()); Kind = CompletionKind::NominalMemberBeginning; CurDeclContext = P.CurDeclContext; } static bool isDynamicLookup(Type T) { return T->getRValueType()->isAnyObject(); } static bool isClangSubModule(ModuleDecl *TheModule) { if (auto ClangMod = TheModule->findUnderlyingClangModule()) return ClangMod->isSubModule(); return false; } static void addDeclKeywords(CodeCompletionResultSink &Sink) { auto AddKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) { if (Name == "let" || Name == "var") { // Treat keywords that could be the start of a pattern specially. return; } // FIXME: __consuming should not appear in CodeCompletion until it is // finalized in a language proposal. if (Name == "__consuming") return; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); Builder.setKeywordKind(Kind); Builder.addTextChunk(Name); }; #define DECL_KEYWORD(kw) AddKeyword(#kw, CodeCompletionKeywordKind::kw_##kw); #include "swift/Syntax/TokenKinds.def" // Context-sensitive keywords. auto AddCSKeyword = [&](StringRef Name) { AddKeyword(Name, CodeCompletionKeywordKind::None); }; #define CONTEXTUAL_CASE(KW) AddCSKeyword(#KW); #define CONTEXTUAL_DECL_ATTR(KW, ...) CONTEXTUAL_CASE(KW) #define CONTEXTUAL_DECL_ATTR_ALIAS(KW, ...) CONTEXTUAL_CASE(KW) #define CONTEXTUAL_SIMPLE_DECL_ATTR(KW, ...) CONTEXTUAL_CASE(KW) #include <swift/AST/Attr.def> #undef CONTEXTUAL_CASE } static void addStmtKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody) { auto AddKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) { if (!MaybeFuncBody && Kind == CodeCompletionKeywordKind::kw_return) return; CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); Builder.setKeywordKind(Kind); Builder.addTextChunk(Name); }; #define STMT_KEYWORD(kw) AddKeyword(#kw, CodeCompletionKeywordKind::kw_##kw); #include "swift/Syntax/TokenKinds.def" // Throw is not marked as a STMT_KEYWORD. AddKeyword("throw", CodeCompletionKeywordKind::kw_throw); } static void addLetVarKeywords(CodeCompletionResultSink &Sink) { auto AddKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); Builder.setKeywordKind(Kind); Builder.addTextChunk(Name); }; AddKeyword("let", CodeCompletionKeywordKind::kw_let); AddKeyword("var", CodeCompletionKeywordKind::kw_var); } static void addExprKeywords(CodeCompletionResultSink &Sink) { auto AddKeyword = [&](StringRef Name, StringRef TypeAnnotation, CodeCompletionKeywordKind Kind) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); Builder.setKeywordKind(Kind); Builder.addTextChunk(Name); if (!TypeAnnotation.empty()) Builder.addTypeAnnotation(TypeAnnotation); }; // Expr keywords. AddKeyword("try", StringRef(), CodeCompletionKeywordKind::kw_try); AddKeyword("try!", StringRef(), CodeCompletionKeywordKind::kw_try); AddKeyword("try?", StringRef(), CodeCompletionKeywordKind::kw_try); // FIXME: The pedantically correct way to find the type is to resolve the // Swift.StringLiteralType type. AddKeyword("#function", "String", CodeCompletionKeywordKind::pound_function); AddKeyword("#file", "String", CodeCompletionKeywordKind::pound_file); // Same: Swift.IntegerLiteralType. AddKeyword("#line", "Int", CodeCompletionKeywordKind::pound_line); AddKeyword("#column", "Int", CodeCompletionKeywordKind::pound_column); AddKeyword("#dsohandle", "UnsafeMutableRawPointer", CodeCompletionKeywordKind::pound_dsohandle); } static void addAnyTypeKeyword(CodeCompletionResultSink &Sink) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResult::ResultKind::Keyword, SemanticContextKind::None, {}); Builder.setKeywordKind(CodeCompletionKeywordKind::None); Builder.addTextChunk("Any"); Builder.addTypeAnnotation("Any"); } void CodeCompletionCallbacksImpl::addKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody) { switch (Kind) { case CompletionKind::None: case CompletionKind::DotExpr: case CompletionKind::AttributeDeclParen: case CompletionKind::AttributeBegin: case CompletionKind::PoundAvailablePlatform: case CompletionKind::Import: case CompletionKind::UnresolvedMember: case CompletionKind::CallArg: case CompletionKind::AfterPound: case CompletionKind::GenericParams: case CompletionKind::KeyPathExpr: case CompletionKind::KeyPathExprDot: case CompletionKind::SwiftKeyPath: break; case CompletionKind::StmtOrExpr: addDeclKeywords(Sink); addStmtKeywords(Sink, MaybeFuncBody); LLVM_FALLTHROUGH; case CompletionKind::AssignmentRHS: case CompletionKind::ReturnStmtExpr: case CompletionKind::PostfixExprBeginning: case CompletionKind::ForEachSequence: addSuperKeyword(Sink); addLetVarKeywords(Sink); addExprKeywords(Sink); addAnyTypeKeyword(Sink); break; case CompletionKind::PostfixExpr: case CompletionKind::PostfixExprParen: case CompletionKind::SuperExpr: case CompletionKind::SuperExprDot: case CompletionKind::CaseStmtBeginning: case CompletionKind::CaseStmtDotPrefix: case CompletionKind::TypeIdentifierWithDot: case CompletionKind::TypeIdentifierWithoutDot: break; case CompletionKind::TypeSimpleBeginning: addAnyTypeKeyword(Sink); break; case CompletionKind::NominalMemberBeginning: addDeclKeywords(Sink); addLetVarKeywords(Sink); break; } } namespace { class ExprParentFinder : public ASTWalker { friend class CodeCompletionTypeContextAnalyzer; Expr *ChildExpr; llvm::function_ref<bool(ASTNode)> Predicate; bool arePositionsSame(Expr *E1, Expr *E2) { return E1->getSourceRange().Start == E2->getSourceRange().Start && E1->getSourceRange().End == E2->getSourceRange().End; } public: llvm::SmallVector<ASTNode, 5> Ancestors; ASTNode ParentClosest; ASTNode ParentFarthest; ExprParentFinder(Expr* ChildExpr, llvm::function_ref<bool(ASTNode)> Predicate) : ChildExpr(ChildExpr), Predicate(Predicate) {} std::pair<bool, Expr *> walkToExprPre(Expr *E) override { if (E == ChildExpr || arePositionsSame(E, ChildExpr)) { if (!Ancestors.empty()) { ParentClosest = Ancestors.back(); ParentFarthest = Ancestors.front(); } return {false, nullptr}; } if (Predicate(E)) Ancestors.push_back(E); return { true, E }; } Expr *walkToExprPost(Expr *E) override { if (Predicate(E)) Ancestors.pop_back(); return E; } std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override { if (Predicate(S)) Ancestors.push_back(S); return { true, S }; } Stmt *walkToStmtPost(Stmt *S) override { if (Predicate(S)) Ancestors.pop_back(); return S; } bool walkToDeclPre(Decl *D) override { if (Predicate(D)) Ancestors.push_back(D); return true; } bool walkToDeclPost(Decl *D) override { if (Predicate(D)) Ancestors.pop_back(); return true; } }; } // end anonymous namespace /// Given an expression and its context, the analyzer tries to figure out the /// expected type of the expression by analyzing its context. class CodeCompletionTypeContextAnalyzer { DeclContext *DC; Expr *ParsedExpr; SourceManager &SM; ASTContext &Context; ExprParentFinder Finder; public: CodeCompletionTypeContextAnalyzer(DeclContext *DC, Expr *ParsedExpr) : DC(DC), ParsedExpr(ParsedExpr), SM(DC->getASTContext().SourceMgr), Context(DC->getASTContext()), Finder(ParsedExpr, [](ASTNode Node) { if (auto E = Node.dyn_cast<Expr *>()) { switch(E->getKind()) { case ExprKind::Call: case ExprKind::Assign: return true; default: return false; } } else if (auto S = Node.dyn_cast<Stmt *>()) { switch (S->getKind()) { case StmtKind::Return: case StmtKind::ForEach: case StmtKind::RepeatWhile: case StmtKind::If: case StmtKind::While: case StmtKind::Guard: return true; default: return false; } } else if (auto D = Node.dyn_cast<Decl *>()) { switch (D->getKind()) { case DeclKind::PatternBinding: return true; default: return false; } } else return false; }) {} void analyzeExpr(Expr *Parent, llvm::function_ref<void(Type)> Callback, SmallVectorImpl<StringRef> &PossibleNames) { switch (Parent->getKind()) { case ExprKind::Call: { std::vector<Type> PotentialTypes; std::vector<StringRef> ExpectedNames; CompletionLookup::collectArgumentExpectation( *DC, cast<CallExpr>(Parent), ParsedExpr, PotentialTypes, ExpectedNames); for (Type Ty : PotentialTypes) Callback(Ty); for (auto name : ExpectedNames) PossibleNames.push_back(name); break; } case ExprKind::Assign: { auto &SM = DC->getASTContext().SourceMgr; auto *AE = cast<AssignExpr>(Parent); // Make sure code completion is on the right hand side. if (SM.isBeforeInBuffer(AE->getEqualLoc(), ParsedExpr->getStartLoc())) { // The destination is of the expected type. auto *destExpr = AE->getDest(); if (auto type = destExpr->getType()) { Callback(type); } else if (auto *DRE = dyn_cast<DeclRefExpr>(destExpr)) { if (auto *decl = DRE->getDecl()) Callback(decl->getInterfaceType()); } } break; } default: llvm_unreachable("Unhandled expression kinds."); } } void analyzeStmt(Stmt *Parent, llvm::function_ref<void(Type)> Callback) { switch (Parent->getKind()) { case StmtKind::Return: Callback(getReturnTypeFromContext(DC)); break; case StmtKind::ForEach: if (auto SEQ = cast<ForEachStmt>(Parent)->getSequence()) { if (containsTarget(SEQ)) { Callback(Context.getSequenceDecl()->getDeclaredInterfaceType()); } } break; case StmtKind::RepeatWhile: case StmtKind::If: case StmtKind::While: case StmtKind::Guard: if (isBoolConditionOf(Parent)) { Callback(Context.getBoolDecl()->getDeclaredInterfaceType()); } break; default: llvm_unreachable("Unhandled statement kinds."); } } bool isBoolConditionOf(Stmt *parent) { if (auto *repeat = dyn_cast<RepeatWhileStmt>(parent)) { return repeat->getCond() && containsTarget(repeat->getCond()); } if (auto *conditional = dyn_cast<LabeledConditionalStmt>(parent)) { for (StmtConditionElement cond : conditional->getCond()) { if (auto *E = cond.getBooleanOrNull()) { if (containsTarget(E)) { return true; } } } } return false; } bool containsTarget(Expr *E) { assert(E && "expected parent expression"); return SM.rangeContains(E->getSourceRange(), ParsedExpr->getSourceRange()); } void analyzeDecl(Decl *D, llvm::function_ref<void(Type)> Callback) { switch (D->getKind()) { case DeclKind::PatternBinding: { auto PBD = cast<PatternBindingDecl>(D); for (unsigned I = 0; I < PBD->getNumPatternEntries(); ++ I) { if (auto Init = PBD->getInit(I)) { if (containsTarget(Init)) { if (PBD->getPattern(I)->hasType()) { Callback(PBD->getPattern(I)->getType()); break; } } } } break; } default: llvm_unreachable("Unhandled decl kinds."); } } bool Analyze(llvm::SmallVectorImpl<Type> &PossibleTypes) { SmallVector<StringRef, 1> PossibleNames; return Analyze(PossibleTypes, PossibleNames) && !PossibleTypes.empty(); } bool Analyze(SmallVectorImpl<Type> &PossibleTypes, SmallVectorImpl<StringRef> &PossibleNames) { // We cannot analyze without target. if (!ParsedExpr) return false; DC->walkContext(Finder); auto Callback = [&] (Type Result) { if (Result && Result->getKind() != TypeKind::Error) PossibleTypes.push_back(Result->getRValueType()); }; for (auto It = Finder.Ancestors.rbegin(); It != Finder.Ancestors.rend(); ++ It) { if (auto Parent = It->dyn_cast<Expr *>()) { analyzeExpr(Parent, Callback, PossibleNames); } else if (auto Parent = It->dyn_cast<Stmt *>()) { analyzeStmt(Parent, Callback); } else if (auto Parent = It->dyn_cast<Decl *>()) { analyzeDecl(Parent, Callback); } if (!PossibleTypes.empty() || !PossibleNames.empty()) return true; } return false; } }; void CodeCompletionCallbacksImpl::doneParsing() { CompletionContext.CodeCompletionKind = Kind; if (Kind == CompletionKind::None) { return; } bool MaybeFuncBody = true; if (CurDeclContext) { auto *CD = CurDeclContext->getLocalContext(); if (!CD || CD->getContextKind() == DeclContextKind::Initializer || CD->getContextKind() == DeclContextKind::TopLevelCodeDecl) MaybeFuncBody = false; } // Add keywords even if type checking fails completely. addKeywords(CompletionContext.getResultSink(), MaybeFuncBody); if (auto *DC = dyn_cast_or_null<DeclContext>(ParsedDecl)) { if (DC->isChildContextOf(CurDeclContext)) CurDeclContext = DC; } if (!typecheckContext(CurDeclContext)) return; Optional<Type> ExprType; ConcreteDeclRef ReferencedDecl = nullptr; if (ParsedExpr) { if (auto typechecked = typeCheckParsedExpr()) { ExprType = typechecked->first; ReferencedDecl = typechecked->second; ParsedExpr->setType(*ExprType); } if (!ExprType && Kind != CompletionKind::PostfixExprParen && Kind != CompletionKind::CallArg && Kind != CompletionKind::KeyPathExpr && Kind != CompletionKind::KeyPathExprDot) return; } if (!ParsedTypeLoc.isNull() && !typecheckParsedType()) return; CompletionLookup Lookup(CompletionContext.getResultSink(), P.Context, CurDeclContext, &CompletionContext); if (ExprType) { Lookup.setIsStaticMetatype(ParsedExpr->isStaticallyDerivedMetatype()); } if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(ParsedExpr)) { Lookup.setIsSelfRefExpr(DRE->getDecl()->getFullName() == Context.Id_self); } if (isInsideObjCSelector()) Lookup.includeInstanceMembers(); if (PreferFunctionReferencesToCalls) Lookup.setPreferFunctionReferencesToCalls(); auto DoPostfixExprBeginning = [&] (){ SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getValueCompletionsInDeclContext(Loc); }; switch (Kind) { case CompletionKind::None: llvm_unreachable("should be already handled"); return; case CompletionKind::DotExpr: { Lookup.setHaveDot(DotLoc); if (isDynamicLookup(*ExprType)) Lookup.setIsDynamicLookup(); if (!ExprType.getValue()->getAs<ModuleType>()) Lookup.addKeyword("self", (*ExprType)->getRValueType(), SemanticContextKind::CurrentNominal, CodeCompletionKeywordKind::kw_self); if (isa<BindOptionalExpr>(ParsedExpr) || isa<ForceValueExpr>(ParsedExpr)) Lookup.setIsUnwrappedOptional(true); ::CodeCompletionTypeContextAnalyzer TypeAnalyzer(CurDeclContext, ParsedExpr); llvm::SmallVector<Type, 2> PossibleTypes; if (TypeAnalyzer.Analyze(PossibleTypes)) { Lookup.setExpectedTypes(PossibleTypes); } Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); break; } case CompletionKind::SwiftKeyPath: { Lookup.setHaveDot(DotLoc); Lookup.setIsSwiftKeyPathExpr(); if (auto BGT = (*ExprType)->getAs<BoundGenericType>()) { auto AllArgs = BGT->getGenericArgs(); if (AllArgs.size() == 2) { // The second generic type argument of KeyPath<Root, Value> should be // the value we pull code completion results from. Lookup.getValueExprCompletions(AllArgs[1]); } } break; } case CompletionKind::StmtOrExpr: DoPostfixExprBeginning(); break; case CompletionKind::ForEachSequence: case CompletionKind::PostfixExprBeginning: { ::CodeCompletionTypeContextAnalyzer Analyzer(CurDeclContext, CodeCompleteTokenExpr); llvm::SmallVector<Type, 1> Types; if (Analyzer.Analyze(Types)) { Lookup.setExpectedTypes(Types); } DoPostfixExprBeginning(); break; } case CompletionKind::PostfixExpr: { Lookup.setHaveLeadingSpace(HasSpace); if (isDynamicLookup(*ExprType)) Lookup.setIsDynamicLookup(); Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); Lookup.getOperatorCompletions(ParsedExpr, leadingSequenceExprs); if (!ExprType.getValue()->getAs<ModuleType>()) Lookup.addKeyword("self", (*ExprType)->getRValueType(), SemanticContextKind::CurrentNominal, CodeCompletionKeywordKind::kw_self); break; } case CompletionKind::PostfixExprParen: { Lookup.setHaveLParen(true); ::CodeCompletionTypeContextAnalyzer TypeAnalyzer(CurDeclContext, CodeCompleteTokenExpr); SmallVector<Type, 2> PossibleTypes; SmallVector<StringRef, 2> PossibleNames; if (TypeAnalyzer.Analyze(PossibleTypes, PossibleNames)) { Lookup.setExpectedTypes(PossibleTypes); } if (ExprType) { if (ShouldCompleteCallPatternAfterParen) { Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); } else { // Add argument labels, then fallthrough to get values. Lookup.addArgNameCompletionResults(PossibleNames); } } if (!Lookup.FoundFunctionCalls || (Lookup.FoundFunctionCalls && Lookup.FoundFunctionsWithoutFirstKeyword)) { Lookup.setHaveLParen(false); DoPostfixExprBeginning(); } break; } case CompletionKind::SuperExpr: { Lookup.setIsSuperRefExpr(); Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); break; } case CompletionKind::SuperExprDot: { Lookup.setIsSuperRefExpr(); Lookup.setHaveDot(SourceLoc()); Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); break; } case CompletionKind::KeyPathExprDot: Lookup.setHaveDot(SourceLoc()); LLVM_FALLTHROUGH; case CompletionKind::KeyPathExpr: { Lookup.setIsKeyPathExpr(); Lookup.includeInstanceMembers(); if (ExprType) { if (isDynamicLookup(*ExprType)) Lookup.setIsDynamicLookup(); Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); } else { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getValueCompletionsInDeclContext(Loc, KeyPathFilter, false, true, false); } break; } case CompletionKind::TypeSimpleBeginning: { Lookup.getTypeCompletionsInDeclContext( P.Context.SourceMgr.getCodeCompletionLoc()); break; } case CompletionKind::TypeIdentifierWithDot: { Lookup.setHaveDot(SourceLoc()); Lookup.getTypeCompletions(ParsedTypeLoc.getType()); break; } case CompletionKind::TypeIdentifierWithoutDot: { Lookup.getTypeCompletions(ParsedTypeLoc.getType()); break; } case CompletionKind::CaseStmtBeginning: { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getValueCompletionsInDeclContext(Loc); Lookup.getTypeContextEnumElementCompletions(Loc); break; } case CompletionKind::CaseStmtDotPrefix: { Lookup.setHaveDot(SourceLoc()); SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getTypeContextEnumElementCompletions(Loc); break; } case CompletionKind::NominalMemberBeginning: { Lookup.discardTypeResolver(); CompletionOverrideLookup OverrideLookup(CompletionContext.getResultSink(), P.Context, CurDeclContext, ParsedKeywords); OverrideLookup.getOverrideCompletions(SourceLoc()); break; } case CompletionKind::AttributeBegin: { Lookup.getAttributeDeclCompletions(IsInSil, AttTargetDK); break; } case CompletionKind::AttributeDeclParen: { Lookup.getAttributeDeclParamCompletions(AttrKind, AttrParamIndex); break; } case CompletionKind::PoundAvailablePlatform: { Lookup.getPoundAvailablePlatformCompletions(); break; } case CompletionKind::Import: { if (DotLoc.isValid()) Lookup.addSubModuleNames(SubModuleNameVisibilityPairs); else Lookup.addImportModuleNames(); break; } case CompletionKind::UnresolvedMember : { Lookup.setHaveDot(SourceLoc()); SmallVector<Type, 1> PossibleTypes; ExprParentFinder Walker(UnresolvedExpr, [&](ASTNode Node) { return Node.is<Expr *>(); }); CurDeclContext->walkContext(Walker); bool Success = false; if (auto PE = Walker.ParentFarthest.get<Expr *>()) { prepareForRetypechecking(PE); Success = typeCheckUnresolvedExpr(*CurDeclContext, UnresolvedExpr, PE, PossibleTypes); Lookup.getUnresolvedMemberCompletions(PossibleTypes); } if (!Success) { Lookup.getUnresolvedMemberCompletions( TokensBeforeUnresolvedExpr, UnresolvedExprInReturn); } break; } case CompletionKind::AssignmentRHS : { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); if (auto destType = ParsedExpr->getType()) Lookup.setExpectedTypes(destType->getRValueType()); Lookup.getValueCompletionsInDeclContext(Loc, DefaultFilter); break; } case CompletionKind::CallArg : { if (!CodeCompleteTokenExpr || !Lookup.getCallArgCompletions(*CurDeclContext, FuncCallExpr, CodeCompleteTokenExpr)) DoPostfixExprBeginning(); break; } case CompletionKind::ReturnStmtExpr : { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); if (auto FD = dyn_cast<AbstractFunctionDecl>(CurDeclContext)) { if (auto FT = FD->getInterfaceType()->getAs<FunctionType>()) { Lookup.setExpectedTypes(FT->getResult()); } } Lookup.getValueCompletionsInDeclContext(Loc); break; } case CompletionKind::AfterPound: { Lookup.addPoundAvailable(ParentStmtKind); Lookup.addPoundSelector(/*needPound=*/false); Lookup.addPoundKeyPath(/*needPound=*/false); break; } case CompletionKind::GenericParams: if (auto GT = ParsedTypeLoc.getType()->getAnyGeneric()) { if (auto Params = GT->getGenericParams()) { for (auto GP : Params->getParams()) { Lookup.addGenericTypeParamRef(GP, DeclVisibilityKind::GenericParameter); } } } break; } if (Lookup.RequestedCachedResults) { // Use the current SourceFile as the DeclContext so that we can use it to // perform qualified lookup, and to get the correct visibility for // @testable imports. const SourceFile &SF = P.SF; auto &Request = Lookup.RequestedCachedResults.getValue(); llvm::DenseSet<CodeCompletionCache::Key> ImportsSeen; auto handleImport = [&](ModuleDecl::ImportedModule Import) { ModuleDecl *TheModule = Import.second; ModuleDecl::AccessPathTy Path = Import.first; if (TheModule->getFiles().empty()) return; // Clang submodules are ignored and there's no lookup cost involved, // so just ignore them and don't put the empty results in the cache // because putting a lot of objects in the cache will push out // other lookups. if (isClangSubModule(TheModule)) return; std::vector<std::string> AccessPath; for (auto Piece : Path) { AccessPath.push_back(Piece.first.str()); } StringRef ModuleFilename = TheModule->getModuleFilename(); // ModuleFilename can be empty if something strange happened during // module loading, for example, the module file is corrupted. if (!ModuleFilename.empty()) { auto &Ctx = TheModule->getASTContext(); CodeCompletionCache::Key K{ModuleFilename, TheModule->getName().str(), AccessPath, Request.NeedLeadingDot, SF.hasTestableImport(TheModule), Ctx.LangOpts.CodeCompleteInitsInPostfixExpr}; using PairType = llvm::DenseSet<swift::ide::CodeCompletionCache::Key, llvm::DenseMapInfo<CodeCompletionCache::Key>>::iterator; std::pair<PairType, bool> Result = ImportsSeen.insert(K); if (!Result.second) return; // already handled. RequestedModules.push_back( {std::move(K), TheModule, Request.OnlyTypes}); } }; if (Request.TheModule) { Lookup.discardTypeResolver(); // FIXME: actually check imports. const_cast<ModuleDecl*>(Request.TheModule) ->forAllVisibleModules({}, handleImport); } else { // Add results from current module. Lookup.getToplevelCompletions(Request.OnlyTypes); Lookup.discardTypeResolver(); // Add results for all imported modules. SmallVector<ModuleDecl::ImportedModule, 4> Imports; auto *SF = CurDeclContext->getParentSourceFile(); SF->getImportedModules(Imports, ModuleDecl::ImportFilter::All); for (auto Imported : Imports) { ModuleDecl *TheModule = Imported.second; ModuleDecl::AccessPathTy AccessPath = Imported.first; TheModule->forAllVisibleModules(AccessPath, handleImport); } } Lookup.RequestedCachedResults.reset(); } CompletionContext.HasExpectedTypeRelation = Lookup.hasExpectedTypes(); deliverCompletionResults(); } void CodeCompletionCallbacksImpl::deliverCompletionResults() { // Use the current SourceFile as the DeclContext so that we can use it to // perform qualified lookup, and to get the correct visibility for // @testable imports. DeclContext *DCForModules = &P.SF; Consumer.handleResultsAndModules(CompletionContext, RequestedModules, DCForModules); RequestedModules.clear(); DeliveredResults = true; } void PrintingCodeCompletionConsumer::handleResults( MutableArrayRef<CodeCompletionResult *> Results) { unsigned NumResults = 0; for (auto Result : Results) { if (!IncludeKeywords && Result->getKind() == CodeCompletionResult::Keyword) continue; NumResults++; } if (NumResults == 0) return; OS << "Begin completions, " << NumResults << " items\n"; for (auto Result : Results) { if (!IncludeKeywords && Result->getKind() == CodeCompletionResult::Keyword) continue; Result->print(OS); llvm::SmallString<64> Name; llvm::raw_svector_ostream NameOs(Name); Result->getCompletionString()->getName(NameOs); OS << "; name=" << Name; StringRef comment = Result->getBriefDocComment(); if (IncludeComments && !comment.empty()) { OS << "; comment=" << comment; } OS << "\n"; } OS << "End completions\n"; } namespace { class CodeCompletionCallbacksFactoryImpl : public CodeCompletionCallbacksFactory { CodeCompletionContext &CompletionContext; CodeCompletionConsumer &Consumer; public: CodeCompletionCallbacksFactoryImpl(CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CompletionContext(CompletionContext), Consumer(Consumer) {} CodeCompletionCallbacks *createCodeCompletionCallbacks(Parser &P) override { return new CodeCompletionCallbacksImpl(P, CompletionContext, Consumer); } }; } // end anonymous namespace CodeCompletionCallbacksFactory * swift::ide::makeCodeCompletionCallbacksFactory( CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) { return new CodeCompletionCallbacksFactoryImpl(CompletionContext, Consumer); } void swift::ide::lookupCodeCompletionResultsFromModule( CodeCompletionResultSink &targetSink, const ModuleDecl *module, ArrayRef<std::string> accessPath, bool needLeadingDot, const DeclContext *currDeclContext) { CompletionLookup Lookup(targetSink, module->getASTContext(), currDeclContext); Lookup.getVisibleDeclsOfModule(module, accessPath, needLeadingDot); } void swift::ide::copyCodeCompletionResults(CodeCompletionResultSink &targetSink, CodeCompletionResultSink &sourceSink, bool onlyTypes) { // We will be adding foreign results (from another sink) into TargetSink. // TargetSink should have an owning pointer to the allocator that keeps the // results alive. targetSink.ForeignAllocators.push_back(sourceSink.Allocator); if (onlyTypes) { std::copy_if(sourceSink.Results.begin(), sourceSink.Results.end(), std::back_inserter(targetSink.Results), [](CodeCompletionResult *R) -> bool { if (R->getKind() != CodeCompletionResult::Declaration) return false; switch(R->getAssociatedDeclKind()) { case CodeCompletionDeclKind::PrecedenceGroup: case CodeCompletionDeclKind::Module: case CodeCompletionDeclKind::Class: case CodeCompletionDeclKind::Struct: case CodeCompletionDeclKind::Enum: case CodeCompletionDeclKind::Protocol: case CodeCompletionDeclKind::TypeAlias: case CodeCompletionDeclKind::AssociatedType: case CodeCompletionDeclKind::GenericTypeParam: return true; case CodeCompletionDeclKind::EnumElement: case CodeCompletionDeclKind::Constructor: case CodeCompletionDeclKind::Destructor: case CodeCompletionDeclKind::Subscript: case CodeCompletionDeclKind::StaticMethod: case CodeCompletionDeclKind::InstanceMethod: case CodeCompletionDeclKind::PrefixOperatorFunction: case CodeCompletionDeclKind::PostfixOperatorFunction: case CodeCompletionDeclKind::InfixOperatorFunction: case CodeCompletionDeclKind::FreeFunction: case CodeCompletionDeclKind::StaticVar: case CodeCompletionDeclKind::InstanceVar: case CodeCompletionDeclKind::LocalVar: case CodeCompletionDeclKind::GlobalVar: return false; } llvm_unreachable("Unhandled CodeCompletionDeclKind in switch."); }); } else { targetSink.Results.insert(targetSink.Results.end(), sourceSink.Results.begin(), sourceSink.Results.end()); } } void SimpleCachingCodeCompletionConsumer::handleResultsAndModules( CodeCompletionContext &context, ArrayRef<RequestedCachedModule> requestedModules, DeclContext *DCForModules) { for (auto &R : requestedModules) { // FIXME(thread-safety): lock the whole AST context. We might load a // module. llvm::Optional<CodeCompletionCache::ValueRefCntPtr> V = context.Cache.get(R.Key); if (!V.hasValue()) { // No cached results found. Fill the cache. V = context.Cache.createValue(); lookupCodeCompletionResultsFromModule( (*V)->Sink, R.TheModule, R.Key.AccessPath, R.Key.ResultsHaveLeadingDot, DCForModules); context.Cache.set(R.Key, *V); } assert(V.hasValue()); copyCodeCompletionResults(context.getResultSink(), (*V)->Sink, R.OnlyTypes); } handleResults(context.takeResults()); }
{ "content_hash": "89f797ce880566ec689a78588fbf38f7", "timestamp": "", "source": "github", "line_count": 5791, "max_line_length": 99, "avg_line_length": 34.80452426178553, "alnum_prop": 0.6479883703045849, "repo_name": "huonw/swift", "id": "60ddc8ed95c9030092eb91b05df668b66ef3817c", "size": "201555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/IDE/CodeCompletion.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "34" }, { "name": "C", "bytes": "200369" }, { "name": "C++", "bytes": "29277385" }, { "name": "CMake", "bytes": "462532" }, { "name": "D", "bytes": "1107" }, { "name": "DTrace", "bytes": "2438" }, { "name": "Emacs Lisp", "bytes": "57358" }, { "name": "LLVM", "bytes": "67650" }, { "name": "Makefile", "bytes": "1841" }, { "name": "Objective-C", "bytes": "369708" }, { "name": "Objective-C++", "bytes": "232830" }, { "name": "Perl", "bytes": "2211" }, { "name": "Python", "bytes": "1180644" }, { "name": "Ruby", "bytes": "2091" }, { "name": "Shell", "bytes": "206022" }, { "name": "Swift", "bytes": "24216920" }, { "name": "Vim script", "bytes": "15654" } ], "symlink_target": "" }
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving, DeriveDataTypeable, DeriveFunctor, DeriveTraversable, DeriveFoldable, MultiParamTypeClasses, TypeFamilies #-} -- | -- Defines two variants of @(,)@ with lifted instances for the standard type classes. -- -- The 'Functor', 'Applicative' and 'Comonad' instances are the standard instances. The -- 'Monad' instances are not in base (but should argubly be there). All of these instances -- are equivalent to 'Writer' in transformers. -- -- 'Applicative' is used to lift 'Monoid' and the standard numeric classes. -- -- The only difference between 'Twain' and 'Couple' is the handling of 'Eq' and 'Ord': -- 'Twain' compares only the second value, while 'Couple' compares both. Thus 'Couple' needs -- an extra @Ord b@ constraint for all sub-classes of 'Ord'. -- module Data.Functor.Couple (Twain(..), Couple(..)) where import Data.Bifunctor import Data.Functor.Product import Data.Functor.Identity import Data.Foldable import Data.Traversable import Data.Functor.Adjunction (unzipR) import Data.Semigroup import Data.Typeable import Control.Applicative import Control.Comonad import Data.PairMonad () import Control.Lens (Wrapped(..), Rewrapped(..), iso) -- | -- A variant of pair/writer with lifted instances for the numeric classes, using 'Applicative'. -- newtype Twain b a = Twain { getTwain :: (b, a) } deriving (Show, Functor, Traversable, Foldable, Typeable, Applicative, Monad, Comonad, Semigroup, Monoid) instance Wrapped (Twain b a) where type Unwrapped (Twain b a) = (b, a) _Wrapped' = iso getTwain Twain instance Rewrapped (Twain c a) (Twain c b) instance (Monoid b, Num a) => Num (Twain b a) where (+) = liftA2 (+) (*) = liftA2 (*) (-) = liftA2 (-) abs = fmap abs signum = fmap signum fromInteger = pure . fromInteger instance (Monoid b, Fractional a) => Fractional (Twain b a) where recip = fmap recip fromRational = pure . fromRational instance (Monoid b, Floating a) => Floating (Twain b a) where pi = pure pi sqrt = fmap sqrt exp = fmap exp log = fmap log sin = fmap sin cos = fmap cos asin = fmap asin atan = fmap atan acos = fmap acos sinh = fmap sinh cosh = fmap cosh asinh = fmap asinh atanh = fmap atanh acosh = fmap acos instance (Monoid b, Enum a) => Enum (Twain b a) where toEnum = pure . toEnum fromEnum = fromEnum . extract instance (Monoid b, Bounded a) => Bounded (Twain b a) where minBound = pure minBound maxBound = pure maxBound -- -- Eq, Ord and their subclasses -- -- If comparison takes both values into account, we must add and (Ord b) -- constraint to all of the following instances. Instead, follow the -- spirit of the Num et al instances to compare just the second argument. -- instance Eq a => Eq (Twain b a) where Twain (b,a) == Twain (b',a') = a == a' instance Ord a => Ord (Twain b a) where Twain (b,a) < Twain (b',a') = a < a' instance (Monoid b, Real a, Enum a, Integral a) => Integral (Twain b a) where quot = liftA2 quot rem = liftA2 rem quotRem = fmap (fmap unzipR) (liftA2 quotRem) toInteger = toInteger . extract instance (Monoid b, Real a) => Real (Twain b a) where toRational = toRational . extract instance (Monoid b, RealFrac a) => RealFrac (Twain b a) where properFraction = first extract . unzipR . fmap properFraction -- | -- A variant of pair/writer with lifted instances for the numeric classes, using 'Applicative'. -- newtype Couple b a = Couple { getCouple :: (b, a) } deriving (Show, Functor, Foldable, Traversable, Typeable, Applicative, Monad, Comonad, Semigroup, Monoid) instance Wrapped (Couple b a) where type Unwrapped (Couple b a) = (b, a) _Wrapped' = iso getCouple Couple instance Rewrapped (Couple c a) (Couple c b) instance (Monoid b, Num a) => Num (Couple b a) where (+) = liftA2 (+) (*) = liftA2 (*) (-) = liftA2 (-) abs = fmap abs signum = fmap signum fromInteger = pure . fromInteger instance (Monoid b, Fractional a) => Fractional (Couple b a) where recip = fmap recip fromRational = pure . fromRational instance (Monoid b, Floating a) => Floating (Couple b a) where pi = pure pi sqrt = fmap sqrt exp = fmap exp log = fmap log sin = fmap sin cos = fmap cos asin = fmap asin atan = fmap atan acos = fmap acos sinh = fmap sinh cosh = fmap cosh asinh = fmap asinh atanh = fmap atanh acosh = fmap acos instance (Monoid b, Enum a) => Enum (Couple b a) where toEnum = pure . toEnum fromEnum = fromEnum . extract instance (Monoid b, Bounded a) => Bounded (Couple b a) where minBound = pure minBound maxBound = pure maxBound instance (Eq b, Eq a) => Eq (Couple b a) where Couple ((b,a)) == Couple (b',a') = (b,a) == (b',a') instance (Ord b, Ord a) => Ord (Couple b a) where Couple (b,a) < Couple (b',a') = (b,a) < (b',a') instance (Monoid b, Ord b, Real a, Enum a, Integral a) => Integral (Couple b a) where quot = liftA2 quot rem = liftA2 rem quotRem = fmap (fmap unzipR) (liftA2 quotRem) toInteger = toInteger . extract instance (Monoid b, Ord b, Real a) => Real (Couple b a) where toRational = toRational . extract instance (Monoid b, Ord b, RealFrac a) => RealFrac (Couple b a) where properFraction = first extract . unzipR . fmap properFraction
{ "content_hash": "8769d4643b358ba45abf2ea6a678433e", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 107, "avg_line_length": 30.353932584269664, "alnum_prop": 0.665741254858412, "repo_name": "FranklinChen/music-score", "id": "6ce3546857eae26e6e420f5571479318c16fb8e4", "size": "5405", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Data/Functor/Couple.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "769337" }, { "name": "LilyPond", "bytes": "687" } ], "symlink_target": "" }
package com.amazonaws.services.ecrpublic.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ecr-public-2020-10-30/TagResource" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class TagResourceRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The Amazon Resource Name (ARN) of the resource to which to add tags. Currently, the supported resource is an * Amazon ECR Public repository. * </p> */ private String resourceArn; /** * <p> * The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum character * length of 128 characters, and tag values can have a maximum length of 256 characters. * </p> */ private java.util.List<Tag> tags; /** * <p> * The Amazon Resource Name (ARN) of the resource to which to add tags. Currently, the supported resource is an * Amazon ECR Public repository. * </p> * * @param resourceArn * The Amazon Resource Name (ARN) of the resource to which to add tags. Currently, the supported resource is * an Amazon ECR Public repository. */ public void setResourceArn(String resourceArn) { this.resourceArn = resourceArn; } /** * <p> * The Amazon Resource Name (ARN) of the resource to which to add tags. Currently, the supported resource is an * Amazon ECR Public repository. * </p> * * @return The Amazon Resource Name (ARN) of the resource to which to add tags. Currently, the supported resource is * an Amazon ECR Public repository. */ public String getResourceArn() { return this.resourceArn; } /** * <p> * The Amazon Resource Name (ARN) of the resource to which to add tags. Currently, the supported resource is an * Amazon ECR Public repository. * </p> * * @param resourceArn * The Amazon Resource Name (ARN) of the resource to which to add tags. Currently, the supported resource is * an Amazon ECR Public repository. * @return Returns a reference to this object so that method calls can be chained together. */ public TagResourceRequest withResourceArn(String resourceArn) { setResourceArn(resourceArn); return this; } /** * <p> * The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum character * length of 128 characters, and tag values can have a maximum length of 256 characters. * </p> * * @return The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum * character length of 128 characters, and tag values can have a maximum length of 256 characters. */ public java.util.List<Tag> getTags() { return tags; } /** * <p> * The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum character * length of 128 characters, and tag values can have a maximum length of 256 characters. * </p> * * @param tags * The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum * character length of 128 characters, and tag values can have a maximum length of 256 characters. */ public void setTags(java.util.Collection<Tag> tags) { if (tags == null) { this.tags = null; return; } this.tags = new java.util.ArrayList<Tag>(tags); } /** * <p> * The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum character * length of 128 characters, and tag values can have a maximum length of 256 characters. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the * existing values. * </p> * * @param tags * The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum * character length of 128 characters, and tag values can have a maximum length of 256 characters. * @return Returns a reference to this object so that method calls can be chained together. */ public TagResourceRequest withTags(Tag... tags) { if (this.tags == null) { setTags(new java.util.ArrayList<Tag>(tags.length)); } for (Tag ele : tags) { this.tags.add(ele); } return this; } /** * <p> * The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum character * length of 128 characters, and tag values can have a maximum length of 256 characters. * </p> * * @param tags * The tags to add to the resource. A tag is an array of key-value pairs. Tag keys can have a maximum * character length of 128 characters, and tag values can have a maximum length of 256 characters. * @return Returns a reference to this object so that method calls can be chained together. */ public TagResourceRequest withTags(java.util.Collection<Tag> tags) { setTags(tags); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getResourceArn() != null) sb.append("ResourceArn: ").append(getResourceArn()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof TagResourceRequest == false) return false; TagResourceRequest other = (TagResourceRequest) obj; if (other.getResourceArn() == null ^ this.getResourceArn() == null) return false; if (other.getResourceArn() != null && other.getResourceArn().equals(this.getResourceArn()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getResourceArn() == null) ? 0 : getResourceArn().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public TagResourceRequest clone() { return (TagResourceRequest) super.clone(); } }
{ "content_hash": "605d797b9b8a5bec2d901b4169ab0d6a", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 120, "avg_line_length": 35.514150943396224, "alnum_prop": 0.6198698366316908, "repo_name": "aws/aws-sdk-java", "id": "ad8daee1a47f1324c575ffa589baff3cdcea81a7", "size": "8109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-ecrpublic/src/main/java/com/amazonaws/services/ecrpublic/model/TagResourceRequest.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
.container { display: grid; grid-gap: 5px; grid-template-columns: [main-start] 1fr [content-start] 5fr [content-end main-end]; grid-template-rows: [main-start] 40px [content-start] auto [content-end] 40px [main-end]; } .header { grid-column: main; } .menu { } .content { grid-column: content; } .footer { grid-column: main; }
{ "content_hash": "2b874c0466ae0d6de37bf9c22ea74f78", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 91, "avg_line_length": 15.772727272727273, "alnum_prop": 0.654178674351585, "repo_name": "mertnuhoglu/study", "id": "46dd5d6eec72f804281f41aa70dcb9c7897e27e7", "size": "349", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/cssgrid_01/cssgrid22.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1346" }, { "name": "Batchfile", "bytes": "2299" }, { "name": "C", "bytes": "174" }, { "name": "CSS", "bytes": "236474" }, { "name": "Clojure", "bytes": "629884" }, { "name": "Dockerfile", "bytes": "979" }, { "name": "Emacs Lisp", "bytes": "1702" }, { "name": "HTML", "bytes": "23846866" }, { "name": "Java", "bytes": "69706" }, { "name": "JavaScript", "bytes": "11626914" }, { "name": "Jupyter Notebook", "bytes": "372344" }, { "name": "Lua", "bytes": "31206" }, { "name": "Mermaid", "bytes": "55" }, { "name": "PLpgSQL", "bytes": "41904" }, { "name": "Procfile", "bytes": "293" }, { "name": "Python", "bytes": "8861" }, { "name": "R", "bytes": "168361" }, { "name": "Ruby", "bytes": "453" }, { "name": "Sass", "bytes": "1120" }, { "name": "Scala", "bytes": "837" }, { "name": "Shell", "bytes": "81225" }, { "name": "TeX", "bytes": "453" }, { "name": "TypeScript", "bytes": "465092" }, { "name": "Vim Script", "bytes": "4860" }, { "name": "sed", "bytes": "3" } ], "symlink_target": "" }
<html lang="en"> <head> <title>Print Settings - Debugging with GDB</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Debugging with GDB"> <meta name="generator" content="makeinfo 4.8"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Data.html#Data" title="Data"> <link rel="prev" href="Auto-Display.html#Auto-Display" title="Auto Display"> <link rel="next" href="Pretty-Printing.html#Pretty-Printing" title="Pretty Printing"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988-2017 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Free Software'' and ``Free Software Needs Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: ``You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.'' --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="Print-Settings"></a> Next:&nbsp;<a rel="next" accesskey="n" href="Pretty-Printing.html#Pretty-Printing">Pretty Printing</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="Auto-Display.html#Auto-Display">Auto Display</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Data.html#Data">Data</a> <hr> </div> <h3 class="section">10.8 Print Settings</h3> <p><a name="index-format-options-641"></a><a name="index-print-settings-642"></a><span class="sc">gdb</span> provides the following ways to control how arrays, structures, and symbols are printed. <p class="noindent">These settings are useful for debugging programs in any language: <a name="index-set-print-643"></a> <dl><dt><code>set print address</code><dt><code>set print address on</code><dd><a name="index-print_002fdon_0027t-print-memory-addresses-644"></a><span class="sc">gdb</span> prints memory addresses showing the location of stack traces, structure values, pointer values, breakpoints, and so forth, even when it also displays the contents of those addresses. The default is <code>on</code>. For example, this is what a stack frame display looks like with <code>set print address on</code>: <pre class="smallexample"> (gdb) f #0 set_quotes (lq=0x34c78 "&lt;&lt;", rq=0x34c88 "&gt;&gt;") at input.c:530 530 if (lquote != def_lquote) </pre> <br><dt><code>set print address off</code><dd>Do not print addresses when displaying their contents. For example, this is the same stack frame displayed with <code>set print address off</code>: <pre class="smallexample"> (gdb) set print addr off (gdb) f #0 set_quotes (lq="&lt;&lt;", rq="&gt;&gt;") at input.c:530 530 if (lquote != def_lquote) </pre> <p>You can use `<samp><span class="samp">set print address off</span></samp>' to eliminate all machine dependent displays from the <span class="sc">gdb</span> interface. For example, with <code>print address off</code>, you should get the same text for backtraces on all machines&mdash;whether or not they involve pointer arguments. <p><a name="index-show-print-645"></a><br><dt><code>show print address</code><dd>Show whether or not addresses are to be printed. </dl> <p>When <span class="sc">gdb</span> prints a symbolic address, it normally prints the closest earlier symbol plus an offset. If that symbol does not uniquely identify the address (for example, it is a name whose scope is a single source file), you may need to clarify. One way to do this is with <code>info line</code>, for example `<samp><span class="samp">info line *0x4537</span></samp>'. Alternately, you can set <span class="sc">gdb</span> to print the source file and line number when it prints a symbolic address: <dl> <dt><code>set print symbol-filename on</code><dd><a name="index-source-file-and-line-of-a-symbol-646"></a><a name="index-symbol_002c-source-file-and-line-647"></a>Tell <span class="sc">gdb</span> to print the source file name and line number of a symbol in the symbolic form of an address. <br><dt><code>set print symbol-filename off</code><dd>Do not print source file name and line number of a symbol. This is the default. <br><dt><code>show print symbol-filename</code><dd>Show whether or not <span class="sc">gdb</span> will print the source file name and line number of a symbol in the symbolic form of an address. </dl> <p>Another situation where it is helpful to show symbol filenames and line numbers is when disassembling code; <span class="sc">gdb</span> shows you the line number and source file that corresponds to each instruction. <p>Also, you may wish to see the symbolic form only if the address being printed is reasonably close to the closest earlier symbol: <dl> <dt><code>set print max-symbolic-offset </code><var>max-offset</var><dt><code>set print max-symbolic-offset unlimited</code><dd><a name="index-maximum-value-for-offset-of-closest-symbol-648"></a>Tell <span class="sc">gdb</span> to only display the symbolic form of an address if the offset between the closest earlier symbol and the address is less than <var>max-offset</var>. The default is <code>unlimited</code>, which tells <span class="sc">gdb</span> to always print the symbolic form of an address if any symbol precedes it. Zero is equivalent to <code>unlimited</code>. <br><dt><code>show print max-symbolic-offset</code><dd>Ask how large the maximum offset is that <span class="sc">gdb</span> prints in a symbolic address. </dl> <p><a name="index-wild-pointer_002c-interpreting-649"></a><a name="index-pointer_002c-finding-referent-650"></a>If you have a pointer and you are not sure where it points, try `<samp><span class="samp">set print symbol-filename on</span></samp>'. Then you can determine the name and source file location of the variable where it points, using `<samp><span class="samp">p/a </span><var>pointer</var></samp>'. This interprets the address in symbolic form. For example, here <span class="sc">gdb</span> shows that a variable <code>ptt</code> points at another variable <code>t</code>, defined in <samp><span class="file">hi2.c</span></samp>: <pre class="smallexample"> (gdb) set print symbol-filename on (gdb) p/a ptt $4 = 0xe008 &lt;t in hi2.c&gt; </pre> <blockquote> <em>Warning:</em> For pointers that point to a local variable, `<samp><span class="samp">p/a</span></samp>' does not show the symbol name and filename of the referent, even with the appropriate <code>set print</code> options turned on. </blockquote> <p>You can also enable `<samp><span class="samp">/a</span></samp>'-like formatting all the time using `<samp><span class="samp">set print symbol on</span></samp>': <dl> <dt><code>set print symbol on</code><dd>Tell <span class="sc">gdb</span> to print the symbol corresponding to an address, if one exists. <br><dt><code>set print symbol off</code><dd>Tell <span class="sc">gdb</span> not to print the symbol corresponding to an address. In this mode, <span class="sc">gdb</span> will still print the symbol corresponding to pointers to functions. This is the default. <br><dt><code>show print symbol</code><dd>Show whether <span class="sc">gdb</span> will display the symbol corresponding to an address. </dl> <p>Other settings control how different kinds of objects are printed: <dl> <dt><code>set print array</code><dt><code>set print array on</code><dd><a name="index-pretty-print-arrays-651"></a>Pretty print arrays. This format is more convenient to read, but uses more space. The default is off. <br><dt><code>set print array off</code><dd>Return to compressed format for arrays. <br><dt><code>show print array</code><dd>Show whether compressed or pretty format is selected for displaying arrays. <p><a name="index-print-array-indexes-652"></a><br><dt><code>set print array-indexes</code><dt><code>set print array-indexes on</code><dd>Print the index of each element when displaying arrays. May be more convenient to locate a given element in the array or quickly find the index of a given element in that printed array. The default is off. <br><dt><code>set print array-indexes off</code><dd>Stop printing element indexes when displaying arrays. <br><dt><code>show print array-indexes</code><dd>Show whether the index of each element is printed when displaying arrays. <br><dt><code>set print elements </code><var>number-of-elements</var><dt><code>set print elements unlimited</code><dd><a name="index-number-of-array-elements-to-print-653"></a><a name="index-limit-on-number-of-printed-array-elements-654"></a>Set a limit on how many elements of an array <span class="sc">gdb</span> will print. If <span class="sc">gdb</span> is printing a large array, it stops printing after it has printed the number of elements set by the <code>set print elements</code> command. This limit also applies to the display of strings. When <span class="sc">gdb</span> starts, this limit is set to 200. Setting <var>number-of-elements</var> to <code>unlimited</code> or zero means that the number of elements to print is unlimited. <br><dt><code>show print elements</code><dd>Display the number of elements of a large array that <span class="sc">gdb</span> will print. If the number is 0, then the printing is unlimited. <br><dt><code>set print frame-arguments </code><var>value</var><dd><a name="index-set-print-frame_002darguments-655"></a><a name="index-printing-frame-argument-values-656"></a><a name="index-print-all-frame-argument-values-657"></a><a name="index-print-frame-argument-values-for-scalars-only-658"></a><a name="index-do-not-print-frame-argument-values-659"></a>This command allows to control how the values of arguments are printed when the debugger prints a frame (see <a href="Frames.html#Frames">Frames</a>). The possible values are: <dl> <dt><code>all</code><dd>The values of all arguments are printed. <br><dt><code>scalars</code><dd>Print the value of an argument only if it is a scalar. The value of more complex arguments such as arrays, structures, unions, etc, is replaced by <code>...</code>. This is the default. Here is an example where only scalar arguments are shown: <pre class="smallexample"> #1 0x08048361 in call_me (i=3, s=..., ss=0xbf8d508c, u=..., e=green) at frame-args.c:23 </pre> <br><dt><code>none</code><dd>None of the argument values are printed. Instead, the value of each argument is replaced by <code>...</code>. In this case, the example above now becomes: <pre class="smallexample"> #1 0x08048361 in call_me (i=..., s=..., ss=..., u=..., e=...) at frame-args.c:23 </pre> </dl> <p>By default, only scalar arguments are printed. This command can be used to configure the debugger to print the value of all arguments, regardless of their type. However, it is often advantageous to not print the value of more complex parameters. For instance, it reduces the amount of information printed in each frame, making the backtrace more readable. Also, it improves performance when displaying Ada frames, because the computation of large arguments can sometimes be CPU-intensive, especially in large applications. Setting <code>print frame-arguments</code> to <code>scalars</code> (the default) or <code>none</code> avoids this computation, thus speeding up the display of each Ada frame. <br><dt><code>show print frame-arguments</code><dd>Show how the value of arguments should be displayed when printing a frame. <br><dt><code>set print raw frame-arguments on</code><dd>Print frame arguments in raw, non pretty-printed, form. <br><dt><code>set print raw frame-arguments off</code><dd>Print frame arguments in pretty-printed form, if there is a pretty-printer for the value (see <a href="Pretty-Printing.html#Pretty-Printing">Pretty Printing</a>), otherwise print the value in raw form. This is the default. <br><dt><code>show print raw frame-arguments</code><dd>Show whether to print frame arguments in raw form. <p><a name="set-print-entry_002dvalues"></a> <br><dt><code>set print entry-values </code><var>value</var><dd><a name="index-set-print-entry_002dvalues-660"></a>Set printing of frame argument values at function entry. In some cases <span class="sc">gdb</span> can determine the value of function argument which was passed by the function caller, even if the value was modified inside the called function and therefore is different. With optimized code, the current value could be unavailable, but the entry value may still be known. <p>The default value is <code>default</code> (see below for its description). Older <span class="sc">gdb</span> behaved as with the setting <code>no</code>. Compilers not supporting this feature will behave in the <code>default</code> setting the same way as with the <code>no</code> setting. <p>This functionality is currently supported only by DWARF 2 debugging format and the compiler has to produce `<samp><span class="samp">DW_TAG_GNU_call_site</span></samp>' tags. With <span class="sc">gcc</span>, you need to specify <samp><span class="option">-O -g</span></samp> during compilation, to get this information. <p>The <var>value</var> parameter can be one of the following: <dl> <dt><code>no</code><dd>Print only actual parameter values, never print values from function entry point. <pre class="smallexample"> #0 equal (val=5) #0 different (val=6) #0 lost (val=&lt;optimized out&gt;) #0 born (val=10) #0 invalid (val=&lt;optimized out&gt;) </pre> <br><dt><code>only</code><dd>Print only parameter values from function entry point. The actual parameter values are never printed. <pre class="smallexample"> #0 equal (val@entry=5) #0 different (val@entry=5) #0 lost (val@entry=5) #0 born (val@entry=&lt;optimized out&gt;) #0 invalid (val@entry=&lt;optimized out&gt;) </pre> <br><dt><code>preferred</code><dd>Print only parameter values from function entry point. If value from function entry point is not known while the actual value is known, print the actual value for such parameter. <pre class="smallexample"> #0 equal (val@entry=5) #0 different (val@entry=5) #0 lost (val@entry=5) #0 born (val=10) #0 invalid (val@entry=&lt;optimized out&gt;) </pre> <br><dt><code>if-needed</code><dd>Print actual parameter values. If actual parameter value is not known while value from function entry point is known, print the entry point value for such parameter. <pre class="smallexample"> #0 equal (val=5) #0 different (val=6) #0 lost (val@entry=5) #0 born (val=10) #0 invalid (val=&lt;optimized out&gt;) </pre> <br><dt><code>both</code><dd>Always print both the actual parameter value and its value from function entry point, even if values of one or both are not available due to compiler optimizations. <pre class="smallexample"> #0 equal (val=5, val@entry=5) #0 different (val=6, val@entry=5) #0 lost (val=&lt;optimized out&gt;, val@entry=5) #0 born (val=10, val@entry=&lt;optimized out&gt;) #0 invalid (val=&lt;optimized out&gt;, val@entry=&lt;optimized out&gt;) </pre> <br><dt><code>compact</code><dd>Print the actual parameter value if it is known and also its value from function entry point if it is known. If neither is known, print for the actual value <code>&lt;optimized out&gt;</code>. If not in MI mode (see <a href="GDB_002fMI.html#GDB_002fMI">GDB/MI</a>) and if both values are known and identical, print the shortened <code>param=param@entry=VALUE</code> notation. <pre class="smallexample"> #0 equal (val=val@entry=5) #0 different (val=6, val@entry=5) #0 lost (val@entry=5) #0 born (val=10) #0 invalid (val=&lt;optimized out&gt;) </pre> <br><dt><code>default</code><dd>Always print the actual parameter value. Print also its value from function entry point, but only if it is known. If not in MI mode (see <a href="GDB_002fMI.html#GDB_002fMI">GDB/MI</a>) and if both values are known and identical, print the shortened <code>param=param@entry=VALUE</code> notation. <pre class="smallexample"> #0 equal (val=val@entry=5) #0 different (val=6, val@entry=5) #0 lost (val=&lt;optimized out&gt;, val@entry=5) #0 born (val=10) #0 invalid (val=&lt;optimized out&gt;) </pre> </dl> <p>For analysis messages on possible failures of frame argument values at function entry resolution see <a href="set-debug-entry_002dvalues.html#set-debug-entry_002dvalues">set debug entry-values</a>. <br><dt><code>show print entry-values</code><dd>Show the method being used for printing of frame argument values at function entry. <br><dt><code>set print repeats </code><var>number-of-repeats</var><dt><code>set print repeats unlimited</code><dd><a name="index-repeated-array-elements-661"></a>Set the threshold for suppressing display of repeated array elements. When the number of consecutive identical elements of an array exceeds the threshold, <span class="sc">gdb</span> prints the string <code>"&lt;repeats </code><var>n</var><code> times&gt;"</code>, where <var>n</var> is the number of identical repetitions, instead of displaying the identical elements themselves. Setting the threshold to <code>unlimited</code> or zero will cause all elements to be individually printed. The default threshold is 10. <br><dt><code>show print repeats</code><dd>Display the current threshold for printing repeated identical elements. <br><dt><code>set print null-stop</code><dd><a name="index-g_t_0040sc_007bnull_007d-elements-in-arrays-662"></a>Cause <span class="sc">gdb</span> to stop printing the characters of an array when the first <span class="sc">null</span> is encountered. This is useful when large arrays actually contain only short strings. The default is off. <br><dt><code>show print null-stop</code><dd>Show whether <span class="sc">gdb</span> stops printing an array on the first <span class="sc">null</span> character. <br><dt><code>set print pretty on</code><dd><a name="index-print-structures-in-indented-form-663"></a><a name="index-indentation-in-structure-display-664"></a>Cause <span class="sc">gdb</span> to print structures in an indented format with one member per line, like this: <pre class="smallexample"> $1 = { next = 0x0, flags = { sweet = 1, sour = 1 }, meat = 0x54 "Pork" } </pre> <br><dt><code>set print pretty off</code><dd>Cause <span class="sc">gdb</span> to print structures in a compact format, like this: <pre class="smallexample"> $1 = {next = 0x0, flags = {sweet = 1, sour = 1}, \ meat = 0x54 "Pork"} </pre> <p class="noindent">This is the default format. <br><dt><code>show print pretty</code><dd>Show which format <span class="sc">gdb</span> is using to print structures. <br><dt><code>set print sevenbit-strings on</code><dd><a name="index-eight_002dbit-characters-in-strings-665"></a><a name="index-octal-escapes-in-strings-666"></a>Print using only seven-bit characters; if this option is set, <span class="sc">gdb</span> displays any eight-bit characters (in strings or character values) using the notation <code>\</code><var>nnn</var>. This setting is best if you are working in English (<span class="sc">ascii</span>) and you use the high-order bit of characters as a marker or &ldquo;meta&rdquo; bit. <br><dt><code>set print sevenbit-strings off</code><dd>Print full eight-bit characters. This allows the use of more international character sets, and is the default. <br><dt><code>show print sevenbit-strings</code><dd>Show whether or not <span class="sc">gdb</span> is printing only seven-bit characters. <br><dt><code>set print union on</code><dd><a name="index-unions-in-structures_002c-printing-667"></a>Tell <span class="sc">gdb</span> to print unions which are contained in structures and other unions. This is the default setting. <br><dt><code>set print union off</code><dd>Tell <span class="sc">gdb</span> not to print unions which are contained in structures and other unions. <span class="sc">gdb</span> will print <code>"{...}"</code> instead. <br><dt><code>show print union</code><dd>Ask <span class="sc">gdb</span> whether or not it will print unions which are contained in structures and other unions. <p>For example, given the declarations <pre class="smallexample"> typedef enum {Tree, Bug} Species; typedef enum {Big_tree, Acorn, Seedling} Tree_forms; typedef enum {Caterpillar, Cocoon, Butterfly} Bug_forms; struct thing { Species it; union { Tree_forms tree; Bug_forms bug; } form; }; struct thing foo = {Tree, {Acorn}}; </pre> <p class="noindent">with <code>set print union on</code> in effect `<samp><span class="samp">p foo</span></samp>' would print <pre class="smallexample"> $1 = {it = Tree, form = {tree = Acorn, bug = Cocoon}} </pre> <p class="noindent">and with <code>set print union off</code> in effect it would print <pre class="smallexample"> $1 = {it = Tree, form = {...}} </pre> <p class="noindent"><code>set print union</code> affects programs written in C-like languages and in Pascal. </dl> <p class="noindent">These settings are of interest when debugging C<tt>++</tt> programs: <a name="index-demangling-C_0040t_007b_002b_002b_007d-names-668"></a> <dl><dt><code>set print demangle</code><dt><code>set print demangle on</code><dd>Print C<tt>++</tt> names in their source form rather than in the encoded (&ldquo;mangled&rdquo;) form passed to the assembler and linker for type-safe linkage. The default is on. <br><dt><code>show print demangle</code><dd>Show whether C<tt>++</tt> names are printed in mangled or demangled form. <br><dt><code>set print asm-demangle</code><dt><code>set print asm-demangle on</code><dd>Print C<tt>++</tt> names in their source form rather than their mangled form, even in assembler code printouts such as instruction disassemblies. The default is off. <br><dt><code>show print asm-demangle</code><dd>Show whether C<tt>++</tt> names in assembly listings are printed in mangled or demangled form. <p><a name="index-C_0040t_007b_002b_002b_007d-symbol-decoding-style-669"></a><a name="index-symbol-decoding-style_002c-C_0040t_007b_002b_002b_007d-670"></a><a name="index-set-demangle_002dstyle-671"></a><br><dt><code>set demangle-style </code><var>style</var><dd>Choose among several encoding schemes used by different compilers to represent C<tt>++</tt> names. The choices for <var>style</var> are currently: <dl> <dt><code>auto</code><dd>Allow <span class="sc">gdb</span> to choose a decoding style by inspecting your program. This is the default. <br><dt><code>gnu</code><dd>Decode based on the <span class="sc">gnu</span> C<tt>++</tt> compiler (<code>g++</code>) encoding algorithm. <br><dt><code>hp</code><dd>Decode based on the HP ANSI C<tt>++</tt> (<code>aCC</code>) encoding algorithm. <br><dt><code>lucid</code><dd>Decode based on the Lucid C<tt>++</tt> compiler (<code>lcc</code>) encoding algorithm. <br><dt><code>arm</code><dd>Decode using the algorithm in the <cite>C</cite><tt>++</tt><cite> Annotated Reference Manual</cite>. <strong>Warning:</strong> this setting alone is not sufficient to allow debugging <code>cfront</code>-generated executables. <span class="sc">gdb</span> would require further enhancement to permit that. </dl> If you omit <var>style</var>, you will see a list of possible formats. <br><dt><code>show demangle-style</code><dd>Display the encoding style currently in use for decoding C<tt>++</tt> symbols. <br><dt><code>set print object</code><dt><code>set print object on</code><dd><a name="index-derived-type-of-an-object_002c-printing-672"></a><a name="index-display-derived-types-673"></a>When displaying a pointer to an object, identify the <em>actual</em> (derived) type of the object rather than the <em>declared</em> type, using the virtual function table. Note that the virtual function table is required&mdash;this feature can only work for objects that have run-time type identification; a single virtual method in the object's declared type is sufficient. Note that this setting is also taken into account when working with variable objects via MI (see <a href="GDB_002fMI.html#GDB_002fMI">GDB/MI</a>). <br><dt><code>set print object off</code><dd>Display only the declared type of objects, without reference to the virtual function table. This is the default setting. <br><dt><code>show print object</code><dd>Show whether actual, or declared, object types are displayed. <br><dt><code>set print static-members</code><dt><code>set print static-members on</code><dd><a name="index-static-members-of-C_0040t_007b_002b_002b_007d-objects-674"></a>Print static members when displaying a C<tt>++</tt> object. The default is on. <br><dt><code>set print static-members off</code><dd>Do not print static members when displaying a C<tt>++</tt> object. <br><dt><code>show print static-members</code><dd>Show whether C<tt>++</tt> static members are printed or not. <br><dt><code>set print pascal_static-members</code><dt><code>set print pascal_static-members on</code><dd><a name="index-static-members-of-Pascal-objects-675"></a><a name="index-Pascal-objects_002c-static-members-display-676"></a>Print static members when displaying a Pascal object. The default is on. <br><dt><code>set print pascal_static-members off</code><dd>Do not print static members when displaying a Pascal object. <br><dt><code>show print pascal_static-members</code><dd>Show whether Pascal static members are printed or not. <!-- These don't work with HP ANSI C++ yet. --> <br><dt><code>set print vtbl</code><dt><code>set print vtbl on</code><dd><a name="index-pretty-print-C_0040t_007b_002b_002b_007d-virtual-function-tables-677"></a><a name="index-virtual-functions-_0028C_0040t_007b_002b_002b_007d_0029-display-678"></a><a name="index-VTBL-display-679"></a>Pretty print C<tt>++</tt> virtual function tables. The default is off. (The <code>vtbl</code> commands do not work on programs compiled with the HP ANSI C<tt>++</tt> compiler (<code>aCC</code>).) <br><dt><code>set print vtbl off</code><dd>Do not pretty print C<tt>++</tt> virtual function tables. <br><dt><code>show print vtbl</code><dd>Show whether C<tt>++</tt> virtual function tables are pretty printed, or not. </dl> </body></html>
{ "content_hash": "de93d7f36fd9997b657008cdabd0cd6e", "timestamp": "", "source": "github", "line_count": 489, "max_line_length": 435, "avg_line_length": 58.29447852760736, "alnum_prop": 0.6874342243738161, "repo_name": "ChangsoonKim/STM32F7DiscTutor", "id": "bca435a77ca0ae54621e7e47a3a5ec0e180e1650", "size": "28506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "toolchain/osx/gcc-arm-none-eabi-6-2017-q1-update/share/doc/gcc-arm-none-eabi/html/gdb/Print-Settings.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "4483749" }, { "name": "C", "bytes": "155831052" }, { "name": "C++", "bytes": "14522753" }, { "name": "HTML", "bytes": "22473152" }, { "name": "Logos", "bytes": "9680" }, { "name": "Makefile", "bytes": "25498" }, { "name": "Objective-C", "bytes": "285838" }, { "name": "Python", "bytes": "288546" }, { "name": "Roff", "bytes": "2842557" }, { "name": "Shell", "bytes": "20768" }, { "name": "XC", "bytes": "9187" }, { "name": "XS", "bytes": "9137" } ], "symlink_target": "" }
layout: resume menuorder: 3 menutitle: Resume --- ## Currently Current Position Description ## Education `1990 - 1994` __University Name__ Degree Awarded `1995 - 1997` __University Name__ Degree Awarded ## Awards `2012` Name of Award, Organization ## Publications <!-- A list is also available [online](https://scholar.google.co.uk/citations?user=LTOTl0YAAAAJ) --> ### Journals `1994` Article Title, Journal Title `1994` Article Title, Journal Title ### Books `1994` Book Title, Journal Title `1994` Book Title, Journal Title ## Presentations `1994` Presentation Title, Conference, <a href="https://MyWebsite.tld/presentation1">Link to Presentation</a> ## Occupation `Current` __Current Job Title__, Current Employer - Task - Task `1994-1996` __Current Job Title__, Current Employer - Task - Task <!-- ### Footer Last updated: May 2013 -->
{ "content_hash": "cbcf7afe6e5b9a70f1cdf791a6ac379e", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 102, "avg_line_length": 12.295774647887324, "alnum_prop": 0.699885452462772, "repo_name": "NCSU-Libraries/jekyll-academic", "id": "a61e59eda6c2dd823a7d262cb5e57ea9abf41422", "size": "877", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "resume.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "252362" }, { "name": "HTML", "bytes": "94972" }, { "name": "JavaScript", "bytes": "311789" }, { "name": "Ruby", "bytes": "2397" } ], "symlink_target": "" }
$(function() { $('#show').click(function() { $('.foo').show(); Kwf.callOnContentReady(document.body, { action: 'show' }); }); $('#hide').click(function() { $('.foo').hide(); Kwf.callOnContentReady(document.body, { action: 'hide' }); }); }); Kwf.onJElementShow('.foo', function(el) { $('#log').append('show'); }); Kwf.onJElementHide('.foo', function(el) { $('#log').append('hide'); });
{ "content_hash": "31eb57a08d9c2fb423cd46e060f69ebd", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 66, "avg_line_length": 26, "alnum_prop": 0.5158371040723982, "repo_name": "nsams/koala-framework", "id": "f1efbde6125577858cfbceeca407e0b96de701ed", "size": "442", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/Kwf/Js/OnContentReady/Page2.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ApacheConf", "bytes": "140" }, { "name": "CSS", "bytes": "139170" }, { "name": "HTML", "bytes": "10081" }, { "name": "JavaScript", "bytes": "1152139" }, { "name": "PHP", "bytes": "6951594" }, { "name": "Smarty", "bytes": "200442" } ], "symlink_target": "" }
/** * @file Octahedron Buffer * @author Alexander Rose <alexander.rose@weirdbyte.de> * @private */ import { OctahedronBufferGeometry, Vector3, Matrix4 } from 'three' import { BufferRegistry } from '../globals' import GeometryBuffer from './geometry-buffer' import { BufferData, BufferParameters } from './buffer' const scale = new Vector3() const target = new Vector3() const up = new Vector3() const eye = new Vector3(0, 0, 0) export interface OctahedronBufferData extends BufferData { heightAxis: Float32Array depthAxis: Float32Array size: Float32Array } /** * Octahedron buffer. Draws octahedrons. * * @example * var octahedronBuffer = new OctahedronBuffer({ * position: new Float32Array([ 0, 3, 0, -2, 0, 0 ]), * color: new Float32Array([ 1, 0, 1, 0, 1, 0 ]), * size: new Float32Array([ 2, 1.5 ]), * heightAxis: new Float32Array([ 0, 1, 1, 0, 2, 0 ]), * depthAxis: new Float32Array([ 1, 0, 1, 0, 0, 2 ]) * }) */ class OctahedronBuffer extends GeometryBuffer { updateNormals = true _heightAxis: Float32Array _depthAxis: Float32Array _size: Float32Array constructor (data: OctahedronBufferData, params: Partial<BufferParameters> = {}) { super(data, params, new OctahedronBufferGeometry(1, 0)) this.setAttributes(data, true) } applyPositionTransform (matrix: Matrix4, i: number, i3: number) { target.fromArray(this._heightAxis as any, i3) up.fromArray(this._depthAxis as any, i3) matrix.lookAt(eye, target, up) scale.set(this._size[ i ], up.length(), target.length()) matrix.scale(scale) } setAttributes (data: Partial<OctahedronBufferData> = {}, initNormals?: boolean) { if (data.size) this._size = data.size if (data.heightAxis) this._heightAxis = data.heightAxis if (data.depthAxis) this._depthAxis = data.depthAxis super.setAttributes(data, initNormals) } } BufferRegistry.add('octahedron', OctahedronBuffer) export default OctahedronBuffer
{ "content_hash": "446e5f1f78dd2d8f8c78abdc2b112de0", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 84, "avg_line_length": 28.735294117647058, "alnum_prop": 0.6965199590583419, "repo_name": "fredludlow/ngl", "id": "43e68d53e82697da5f72d23c984a6aeb5b2159d0", "size": "1954", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/buffer/octahedron-buffer.ts", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "64096" }, { "name": "JavaScript", "bytes": "183568" }, { "name": "Python", "bytes": "3110" }, { "name": "Shell", "bytes": "1500" }, { "name": "TypeScript", "bytes": "1783008" } ], "symlink_target": "" }
package org.projectspinoza.concept; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.projectspinoza.concept.models.TagConceptNet; import org.projectspinoza.concept.utils.OntoConceptResultGenerator; /** * author : OrbitSoft * */ public class Main { public static Set<String> tags = new HashSet<String>(); private static Logger log = LogManager.getRootLogger(); public static void main( String[] args ) throws IOException { log.info("Inside Concept Main...."); tags.add("bmw"); tags.add("morning"); tags.add("coffee"); List<TagConceptNet> concepts = new TagConceptMatcher().getConcepts(tags, "AtLocation"); OntoConceptResultGenerator.generatFile("conceptNet_result", concepts); log.info("Done with conceptNet!"); } }
{ "content_hash": "853853ff15231a210d04542f94b7dcb4", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 93, "avg_line_length": 29.25, "alnum_prop": 0.7158119658119658, "repo_name": "project-spinoza/onto-concept", "id": "07edcde04a1b0225fe04015e19acef1f5aa73553", "size": "936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "concept/src/main/java/org/projectspinoza/concept/Main.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "379" }, { "name": "CSS", "bytes": "626" }, { "name": "Java", "bytes": "44118" }, { "name": "Shell", "bytes": "398" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Visualising statistical significance thresholds on EEG data &#8212; MNE 0.18.2 documentation</title> <link rel="stylesheet" href="../../_static/bootstrap-sphinx.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../../_static/gallery.css" /> <link rel="stylesheet" type="text/css" href="../../_static/bootstrap_divs.css" /> <link rel="stylesheet" href="../../_static/reset-syntax.css" type="text/css" /> <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <script type="text/javascript" src="../../_static/language_data.js"></script> <script type="text/javascript" src="../../_static/bootstrap_divs.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../../_static/favicon.ico"/> <link rel="index" title="Index" href="../../genindex.html" /> <link rel="search" title="Search" href="../../search.html" /> <script type="text/javascript" src="../../_static/copybutton.js"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-37225609-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <link rel="stylesheet" href="../../_static/style.css " type="text/css" /> <link rel="stylesheet" href="../../_static/font-awesome.css" type="text/css" /> <link rel="stylesheet" href="../../_static/flag-icon.css" type="text/css" /> <script type="text/javascript"> !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s); js.id=id;js.src="https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); </script> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'> <meta name="apple-mobile-web-app-capable" content="yes"> <script type="text/javascript" src="../../_static/js/jquery-1.11.0.min.js "></script> <script type="text/javascript" src="../../_static/js/jquery-fix.js "></script> <script type="text/javascript" src="../../_static/bootstrap-3.3.7/js/bootstrap.min.js "></script> <script type="text/javascript" src="../../_static/bootstrap-sphinx.js "></script> <link rel="canonical" href="https://mne.tools/stable/index.html" /> </head><body> <div id="navbar" class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <!-- .btn-navbar is used as the toggle for collapsed navbar content --> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../index.html"><span><img src="../../_static/mne_logo_small.png"></span> </a> <span class="navbar-text navbar-version pull-left"><b>0.18.2</b></span> </div> <div class="collapse navbar-collapse nav-collapse"> <ul class="nav navbar-nav"> <li><a href="../../getting_started.html">Install</a></li> <li><a href="../../documentation.html">Documentation</a></li> <li><a href="../../python_reference.html">API</a></li> <li><a href="../../glossary.html">Glossary</a></li> <li><a href="../../auto_examples/index.html">Examples</a></li> <li><a href="../../contributing.html">Contribute</a></li> <li class="dropdown globaltoc-container"> <a role="button" id="dLabelGlobalToc" data-toggle="dropdown" data-target="#" href="../../index.html">Site <b class="caret"></b></a> <ul class="dropdown-menu globaltoc" role="menu" aria-labelledby="dLabelGlobalToc"></ul> </li> <li class="hidden-sm"></li> </ul> <div class="navbar-form navbar-right navbar-btn dropdown btn-group-sm" style="margin-left: 20px; margin-top: 5px; margin-bottom: 5px"> <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown"> v0.18.2 <span class="caret"></span> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li><a href="https://mne-tools.github.io/dev/index.html">Development</a></li> <li><a href="https://mne-tools.github.io/stable/index.html">v0.18 (stable)</a></li> <li><a href="https://mne-tools.github.io/0.17/index.html">v0.17</a></li> <li><a href="https://mne-tools.github.io/0.16/index.html">v0.16</a></li> <li><a href="https://mne-tools.github.io/0.15/index.html">v0.15</a></li> <li><a href="https://mne-tools.github.io/0.14/index.html">v0.14</a></li> <li><a href="https://mne-tools.github.io/0.13/index.html">v0.13</a></li> <li><a href="https://mne-tools.github.io/0.12/index.html">v0.12</a></li> <li><a href="https://mne-tools.github.io/0.11/index.html">v0.11</a></li> </ul> </div> <form class="navbar-form navbar-right" action="../../search.html" method="get"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> </div> <div class="container"> <div class="row"> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <p class="logo"><a href="../../index.html"> <img class="logo" src="../../_static/mne_logo_small.png" alt="Logo"/> </a></p><ul> <li><a class="reference internal" href="#">Visualising statistical significance thresholds on EEG data</a><ul> <li><a class="reference internal" href="#references">References</a></li> </ul> </li> </ul> <form action="../../search.html" method="get"> <div class="form-group"> <input type="text" name="q" class="form-control" placeholder="Search" /> </div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="body col-md-12 content" role="main"> <div class="sphx-glr-download-link-note admonition note"> <p class="admonition-title">Note</p> <p>Click <a class="reference internal" href="#sphx-glr-download-auto-tutorials-stats-sensor-space-plot-stats-cluster-erp-py"><span class="std std-ref">here</span></a> to download the full example code</p> </div> <div class="sphx-glr-example-title section" id="visualising-statistical-significance-thresholds-on-eeg-data"> <span id="sphx-glr-auto-tutorials-stats-sensor-space-plot-stats-cluster-erp-py"></span><h1>Visualising statistical significance thresholds on EEG data<a class="headerlink" href="#visualising-statistical-significance-thresholds-on-eeg-data" title="Permalink to this headline">¶</a></h1> <p>MNE-Python provides a range of tools for statistical hypothesis testing and the visualisation of the results. Here, we show a few options for exploratory and confirmatory tests - e.g., targeted t-tests, cluster-based permutation approaches (here with Threshold-Free Cluster Enhancement); and how to visualise the results.</p> <p>The underlying data comes from <a class="footnote-reference brackets" href="#id3" id="id1">1</a>; we contrast long vs. short words. TFCE is described in <a class="footnote-reference brackets" href="#id4" id="id2">2</a>.</p> <div class="section" id="references"> <h2>References<a class="headerlink" href="#references" title="Permalink to this headline">¶</a></h2> <dl class="footnote brackets"> <dt class="label" id="id3"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt> <dd><p>Dufau, S., Grainger, J., Midgley, KJ., Holcomb, PJ. A thousand words are worth a picture: Snapshots of printed-word processing in an event-related potential megastudy. Psychological Science, 2015</p> </dd> <dt class="label" id="id4"><span class="brackets"><a class="fn-backref" href="#id2">2</a></span></dt> <dd><p>Smith and Nichols 2009, “Threshold-free cluster enhancement: addressing problems of smoothing, threshold dependence, and localisation in cluster inference”, NeuroImage 44 (2009) 83-98.</p> </dd> </dl> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span> <span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span> <span class="kn">from</span> <span class="nn">scipy.stats</span> <span class="k">import</span> <a href="https://scipy.github.io/devdocs/generated/scipy.stats.ttest_ind.html#scipy.stats.ttest_ind" title="View documentation for scipy.stats.ttest_ind"><span class="n">ttest_ind</span></a> <span class="kn">import</span> <span class="nn">mne</span> <span class="kn">from</span> <span class="nn">mne.channels</span> <span class="k">import</span> <a href="../../generated/mne.channels.find_ch_connectivity.html#mne.channels.find_ch_connectivity" title="View documentation for mne.channels.find_ch_connectivity"><span class="n">find_ch_connectivity</span></a><span class="p">,</span> <a href="../../generated/mne.channels.make_1020_channel_selections.html#mne.channels.make_1020_channel_selections" title="View documentation for mne.channels.make_1020_channel_selections"><span class="n">make_1020_channel_selections</span></a> <span class="kn">from</span> <span class="nn">mne.stats</span> <span class="k">import</span> <a href="../../generated/mne.stats.spatio_temporal_cluster_test.html#mne.stats.spatio_temporal_cluster_test" title="View documentation for mne.stats.spatio_temporal_cluster_test"><span class="n">spatio_temporal_cluster_test</span></a> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="c1"># Load the data</span> <span class="n">path</span> <span class="o">=</span> <a href="../../generated/mne.datasets.kiloword.data_path.html#mne.datasets.kiloword.data_path" title="View documentation for mne.datasets.kiloword.data_path"><span class="n">mne</span><span class="o">.</span><span class="n">datasets</span><span class="o">.</span><span class="n">kiloword</span><span class="o">.</span><span class="n">data_path</span></a><span class="p">()</span> <span class="o">+</span> <span class="s1">&#39;/kword_metadata-epo.fif&#39;</span> <span class="n">epochs</span> <span class="o">=</span> <a href="../../generated/mne.read_epochs.html#mne.read_epochs" title="View documentation for mne.read_epochs"><span class="n">mne</span><span class="o">.</span><span class="n">read_epochs</span></a><span class="p">(</span><span class="n">path</span><span class="p">)</span> <span class="n">name</span> <span class="o">=</span> <span class="s2">&quot;NumberOfLetters&quot;</span> <span class="c1"># Split up the data by the median length in letters via the attached metadata</span> <span class="n">median_value</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">epochs</span><span class="o">.</span><span class="n">metadata</span><span class="p">[</span><span class="n">name</span><span class="p">]</span><span class="o">.</span><span class="n">median</span><span class="p">())</span> <span class="n">long_words</span> <span class="o">=</span> <span class="n">epochs</span><span class="p">[</span><span class="n">name</span> <span class="o">+</span> <span class="s2">&quot; &gt; &quot;</span> <span class="o">+</span> <span class="n">median_value</span><span class="p">]</span> <span class="n">short_words</span> <span class="o">=</span> <span class="n">epochs</span><span class="p">[</span><span class="n">name</span> <span class="o">+</span> <span class="s2">&quot; &lt; &quot;</span> <span class="o">+</span> <span class="n">median_value</span><span class="p">]</span> </pre></div> </div> <p class="sphx-glr-script-out">Out:</p> <div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>Reading /home/circleci/mne_data/MNE-kiloword-data/kword_metadata-epo.fif ... Isotrak not found Found the data of interest: t = -100.00 ... 920.00 ms 0 CTF compensation matrices available 960 matching events found No baseline correction applied Adding metadata with 8 columns 0 projection items activated </pre></div> </div> <p>If we have a specific point in space and time we wish to test, it can be convenient to convert the data into Pandas Dataframe format. In this case, the <a class="reference internal" href="../../generated/mne.Epochs.html#mne.Epochs" title="mne.Epochs"><code class="xref py py-class docutils literal notranslate"><span class="pre">mne.Epochs</span></code></a> object has a convenient <a class="reference internal" href="../../generated/mne.Epochs.html#mne.Epochs.to_data_frame" title="mne.Epochs.to_data_frame"><code class="xref py py-meth docutils literal notranslate"><span class="pre">mne.Epochs.to_data_frame()</span></code></a> method, which returns a dataframe. This dataframe can then be queried for specific time windows and sensors. The extracted data can be submitted to standard statistical tests. Here, we conduct t-tests on the difference between long and short words.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">time_windows</span> <span class="o">=</span> <span class="p">((</span><span class="o">.</span><span class="mi">2</span><span class="p">,</span> <span class="o">.</span><span class="mi">25</span><span class="p">),</span> <span class="p">(</span><span class="o">.</span><span class="mi">35</span><span class="p">,</span> <span class="o">.</span><span class="mi">45</span><span class="p">))</span> <span class="n">elecs</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;Fz&quot;</span><span class="p">,</span> <span class="s2">&quot;Cz&quot;</span><span class="p">,</span> <span class="s2">&quot;Pz&quot;</span><span class="p">]</span> <span class="c1"># display the EEG data in Pandas format (first 5 rows)</span> <span class="nb">print</span><span class="p">(</span><span class="n">epochs</span><span class="o">.</span><span class="n">to_data_frame</span><span class="p">()[</span><span class="n">elecs</span><span class="p">]</span><span class="o">.</span><span class="n">head</span><span class="p">())</span> <span class="n">report</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="si">{elec}</span><span class="s2">, time: </span><span class="si">{tmin}</span><span class="s2">-</span><span class="si">{tmax}</span><span class="s2"> s; t(</span><span class="si">{df}</span><span class="s2">)=</span><span class="si">{t_val:.3f}</span><span class="s2">, p=</span><span class="si">{p:.3f}</span><span class="s2">&quot;</span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">Targeted statistical test results:&quot;</span><span class="p">)</span> <span class="k">for</span> <span class="p">(</span><span class="n">tmin</span><span class="p">,</span> <span class="n">tmax</span><span class="p">)</span> <span class="ow">in</span> <span class="n">time_windows</span><span class="p">:</span> <span class="n">long_df</span> <span class="o">=</span> <span class="n">long_words</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span><span class="o">.</span><span class="n">crop</span><span class="p">(</span><span class="n">tmin</span><span class="p">,</span> <span class="n">tmax</span><span class="p">)</span><span class="o">.</span><span class="n">to_data_frame</span><span class="p">()</span> <span class="n">short_df</span> <span class="o">=</span> <span class="n">short_words</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span><span class="o">.</span><span class="n">crop</span><span class="p">(</span><span class="n">tmin</span><span class="p">,</span> <span class="n">tmax</span><span class="p">)</span><span class="o">.</span><span class="n">to_data_frame</span><span class="p">()</span> <span class="k">for</span> <span class="n">elec</span> <span class="ow">in</span> <span class="n">elecs</span><span class="p">:</span> <span class="c1"># extract data</span> <span class="n">A</span> <span class="o">=</span> <span class="n">long_df</span><span class="p">[</span><span class="n">elec</span><span class="p">]</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="s2">&quot;condition&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span> <span class="n">B</span> <span class="o">=</span> <span class="n">short_df</span><span class="p">[</span><span class="n">elec</span><span class="p">]</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="s2">&quot;condition&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span> <span class="c1"># conduct t test</span> <span class="n">t</span><span class="p">,</span> <span class="n">p</span> <span class="o">=</span> <a href="https://scipy.github.io/devdocs/generated/scipy.stats.ttest_ind.html#scipy.stats.ttest_ind" title="View documentation for scipy.stats.ttest_ind"><span class="n">ttest_ind</span></a><span class="p">(</span><span class="n">A</span><span class="p">,</span> <span class="n">B</span><span class="p">)</span> <span class="c1"># display results</span> <span class="n">format_dict</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">elec</span><span class="o">=</span><span class="n">elec</span><span class="p">,</span> <span class="n">tmin</span><span class="o">=</span><span class="n">tmin</span><span class="p">,</span> <span class="n">tmax</span><span class="o">=</span><span class="n">tmax</span><span class="p">,</span> <span class="n">df</span><span class="o">=</span><span class="nb">len</span><span class="p">(</span><span class="n">epochs</span><span class="o">.</span><span class="n">events</span><span class="p">)</span> <span class="o">-</span> <span class="mi">2</span><span class="p">,</span> <span class="n">t_val</span><span class="o">=</span><span class="n">t</span><span class="p">,</span> <span class="n">p</span><span class="o">=</span><span class="n">p</span><span class="p">)</span> <span class="nb">print</span><span class="p">(</span><span class="n">report</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">**</span><span class="n">format_dict</span><span class="p">))</span> </pre></div> </div> <p class="sphx-glr-script-out">Out:</p> <div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>Converting &quot;time&quot; to &quot;&lt;class &#39;numpy.int64&#39;&gt;&quot;... channel Fz ... Pz condition epoch time ... film 0 -100 0.421970 ... 0.398182 -96 0.453939 ... 0.222424 -92 0.465606 ... 0.018485 -88 0.468182 ... -0.173485 -84 0.483485 ... -0.312121 [5 rows x 3 columns] Targeted statistical test results: Converting &quot;time&quot; to &quot;&lt;class &#39;numpy.int64&#39;&gt;&quot;... Converting &quot;time&quot; to &quot;&lt;class &#39;numpy.int64&#39;&gt;&quot;... Fz, time: 0.2-0.25 s; t(958)=-0.572, p=0.568 Cz, time: 0.2-0.25 s; t(958)=-2.836, p=0.005 Pz, time: 0.2-0.25 s; t(958)=-3.938, p=0.000 Converting &quot;time&quot; to &quot;&lt;class &#39;numpy.int64&#39;&gt;&quot;... Converting &quot;time&quot; to &quot;&lt;class &#39;numpy.int64&#39;&gt;&quot;... Fz, time: 0.35-0.45 s; t(958)=5.192, p=0.000 Cz, time: 0.35-0.45 s; t(958)=5.555, p=0.000 Pz, time: 0.35-0.45 s; t(958)=6.353, p=0.000 </pre></div> </div> <p>Absent specific hypotheses, we can also conduct an exploratory mass-univariate analysis at all sensors and time points. This requires correcting for multiple tests. MNE offers various methods for this; amongst them, cluster-based permutation methods allow deriving power from the spatio-temoral correlation structure of the data. Here, we use TFCE.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Calculate statistical thresholds</span> <span class="n">con</span> <span class="o">=</span> <a href="../../generated/mne.channels.find_ch_connectivity.html#mne.channels.find_ch_connectivity" title="View documentation for mne.channels.find_ch_connectivity"><span class="n">find_ch_connectivity</span></a><span class="p">(</span><span class="n">epochs</span><span class="o">.</span><span class="n">info</span><span class="p">,</span> <span class="s2">&quot;eeg&quot;</span><span class="p">)</span> <span class="c1"># Extract data: transpose because the cluster test requires channels to be last</span> <span class="c1"># In this case, inference is done over items. In the same manner, we could</span> <span class="c1"># also conduct the test over, e.g., subjects.</span> <span class="n">X</span> <span class="o">=</span> <span class="p">[</span><span class="n">long_words</span><span class="o">.</span><span class="n">get_data</span><span class="p">()</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="n">short_words</span><span class="o">.</span><span class="n">get_data</span><span class="p">()</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span> <span class="n">tfce</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">start</span><span class="o">=.</span><span class="mi">2</span><span class="p">,</span> <span class="n">step</span><span class="o">=.</span><span class="mi">2</span><span class="p">)</span> <span class="n">t_obs</span><span class="p">,</span> <span class="n">clusters</span><span class="p">,</span> <span class="n">cluster_pv</span><span class="p">,</span> <span class="n">h0</span> <span class="o">=</span> <a href="../../generated/mne.stats.spatio_temporal_cluster_test.html#mne.stats.spatio_temporal_cluster_test" title="View documentation for mne.stats.spatio_temporal_cluster_test"><span class="n">spatio_temporal_cluster_test</span></a><span class="p">(</span> <span class="n">X</span><span class="p">,</span> <span class="n">tfce</span><span class="p">,</span> <span class="n">n_permutations</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span> <span class="c1"># a more standard number would be 1000+</span> <span class="n">significant_points</span> <span class="o">=</span> <span class="n">cluster_pv</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="n">t_obs</span><span class="o">.</span><span class="n">shape</span><span class="p">)</span><span class="o">.</span><span class="n">T</span> <span class="o">&lt;</span> <span class="o">.</span><span class="mi">05</span> <span class="nb">print</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">significant_points</span><span class="o">.</span><span class="n">sum</span><span class="p">())</span> <span class="o">+</span> <span class="s2">&quot; points selected by TFCE ...&quot;</span><span class="p">)</span> </pre></div> </div> <p class="sphx-glr-script-out">Out:</p> <div class="sphx-glr-script-out highlight-none notranslate"><div class="highlight"><pre><span></span>Could not find a connectivity matrix for the data. Computing connectivity based on Delaunay triangulations. -- number of connected vertices : 29 stat_fun(H1): min=0.000000 max=81.298503 Running initial clustering Using 406 thresholds from 0.20 to 81.20 for TFCE computation (h_power=2.00, e_power=0.50) Found 7424 clusters Permuting 99 times... Computing cluster p-values Done. 1461 points selected by TFCE ... </pre></div> </div> <p>The results of these mass univariate analyses can be visualised by plotting <a class="reference internal" href="../../generated/mne.Evoked.html#mne.Evoked" title="mne.Evoked"><code class="xref py py-class docutils literal notranslate"><span class="pre">mne.Evoked</span></code></a> objects as images (via <a class="reference internal" href="../../generated/mne.Evoked.html#mne.Evoked.plot_image" title="mne.Evoked.plot_image"><code class="xref py py-class docutils literal notranslate"><span class="pre">mne.Evoked.plot_image</span></code></a>) and masking points for significance. Here, we group channels by Regions of Interest to facilitate localising effects on the head.</p> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># We need an evoked object to plot the image to be masked</span> <span class="n">evoked</span> <span class="o">=</span> <a href="../../generated/mne.combine_evoked.html#mne.combine_evoked" title="View documentation for mne.combine_evoked"><span class="n">mne</span><span class="o">.</span><span class="n">combine_evoked</span></a><span class="p">([</span><span class="n">long_words</span><span class="o">.</span><span class="n">average</span><span class="p">(),</span> <span class="o">-</span><span class="n">short_words</span><span class="o">.</span><span class="n">average</span><span class="p">()],</span> <span class="n">weights</span><span class="o">=</span><span class="s1">&#39;equal&#39;</span><span class="p">)</span> <span class="c1"># calculate difference wave</span> <span class="n">time_unit</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">time_unit</span><span class="o">=</span><span class="s2">&quot;s&quot;</span><span class="p">)</span> <span class="n">evoked</span><span class="o">.</span><span class="n">plot_joint</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s2">&quot;Long vs. short words&quot;</span><span class="p">,</span> <span class="n">ts_args</span><span class="o">=</span><span class="n">time_unit</span><span class="p">,</span> <span class="n">topomap_args</span><span class="o">=</span><span class="n">time_unit</span><span class="p">)</span> <span class="c1"># show difference wave</span> <span class="c1"># Create ROIs by checking channel labels</span> <span class="n">selections</span> <span class="o">=</span> <a href="../../generated/mne.channels.make_1020_channel_selections.html#mne.channels.make_1020_channel_selections" title="View documentation for mne.channels.make_1020_channel_selections"><span class="n">make_1020_channel_selections</span></a><span class="p">(</span><span class="n">evoked</span><span class="o">.</span><span class="n">info</span><span class="p">,</span> <span class="n">midline</span><span class="o">=</span><span class="s2">&quot;12z&quot;</span><span class="p">)</span> <span class="c1"># Visualize the results</span> <span class="n">fig</span><span class="p">,</span> <span class="n">axes</span> <span class="o">=</span> <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html#matplotlib.pyplot.subplots" title="View documentation for matplotlib.pyplot.subplots"><span class="n">plt</span><span class="o">.</span><span class="n">subplots</span></a><span class="p">(</span><span class="n">nrows</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span> <span class="mi">8</span><span class="p">))</span> <span class="n">axes</span> <span class="o">=</span> <span class="p">{</span><span class="n">sel</span><span class="p">:</span> <span class="n">ax</span> <span class="k">for</span> <span class="n">sel</span><span class="p">,</span> <span class="n">ax</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">selections</span><span class="p">,</span> <span class="n">axes</span><span class="o">.</span><span class="n">ravel</span><span class="p">())}</span> <span class="n">evoked</span><span class="o">.</span><span class="n">plot_image</span><span class="p">(</span><span class="n">axes</span><span class="o">=</span><span class="n">axes</span><span class="p">,</span> <span class="n">group_by</span><span class="o">=</span><span class="n">selections</span><span class="p">,</span> <span class="n">colorbar</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">show</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="n">significant_points</span><span class="p">,</span> <span class="n">show_names</span><span class="o">=</span><span class="s2">&quot;all&quot;</span><span class="p">,</span> <span class="n">titles</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">time_unit</span><span class="p">)</span> <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.colorbar.html#matplotlib.pyplot.colorbar" title="View documentation for matplotlib.pyplot.colorbar"><span class="n">plt</span><span class="o">.</span><span class="n">colorbar</span></a><span class="p">(</span><span class="n">axes</span><span class="p">[</span><span class="s2">&quot;Left&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">images</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">],</span> <span class="n">ax</span><span class="o">=</span><span class="nb">list</span><span class="p">(</span><span class="n">axes</span><span class="o">.</span><span class="n">values</span><span class="p">()),</span> <span class="n">shrink</span><span class="o">=.</span><span class="mi">3</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="s2">&quot;uV&quot;</span><span class="p">)</span> <a href="https://matplotlib.org/api/_as_gen/matplotlib.pyplot.show.html#matplotlib.pyplot.show" title="View documentation for matplotlib.pyplot.show"><span class="n">plt</span><span class="o">.</span><span class="n">show</span></a><span class="p">()</span> </pre></div> </div> <ul class="sphx-glr-horizontal"> <li><img alt="../../_images/sphx_glr_plot_stats_cluster_erp_001.png" class="sphx-glr-multi-img" src="../../_images/sphx_glr_plot_stats_cluster_erp_001.png" /> </li> <li><img alt="../../_images/sphx_glr_plot_stats_cluster_erp_002.png" class="sphx-glr-multi-img" src="../../_images/sphx_glr_plot_stats_cluster_erp_002.png" /> </li> </ul> <p class="sphx-glr-timing"><strong>Total running time of the script:</strong> ( 0 minutes 13.756 seconds)</p> <p><strong>Estimated memory usage:</strong> 63 MB</p> <div class="sphx-glr-footer class sphx-glr-footer-example docutils container" id="sphx-glr-download-auto-tutorials-stats-sensor-space-plot-stats-cluster-erp-py"> <div class="sphx-glr-download docutils container"> <p><a class="reference download internal" download="" href="../../_downloads/5b5106b7dc6abc4ba102db2809560891/plot_stats_cluster_erp.py"><code class="xref download docutils literal notranslate"><span class="pre">Download</span> <span class="pre">Python</span> <span class="pre">source</span> <span class="pre">code:</span> <span class="pre">plot_stats_cluster_erp.py</span></code></a></p> </div> <div class="sphx-glr-download docutils container"> <p><a class="reference download internal" download="" href="../../_downloads/ed4b6d2db0da436bc0c3ccde391d32b1/plot_stats_cluster_erp.ipynb"><code class="xref download docutils literal notranslate"><span class="pre">Download</span> <span class="pre">Jupyter</span> <span class="pre">notebook:</span> <span class="pre">plot_stats_cluster_erp.ipynb</span></code></a></p> </div> </div> <p class="sphx-glr-signature"><a class="reference external" href="https://sphinx-gallery.github.io">Gallery generated by Sphinx-Gallery</a></p> </div> </div> </div> </div> </div> <footer class="footer"> <div class="container institutions"> <a href="https://www.massgeneral.org/"><img class="institution_lg" src="../../_static/institution_logos/MGH.svg" title="Massachusetts General Hospital" alt="Massachusetts General Hospital"/></a> <a href="https://martinos.org/"><img class="institution_lg" src="../../_static/institution_logos/Martinos.png" title="Athinoula A. Martinos Center for Biomedical Imaging" alt="Athinoula A. Martinos Center for Biomedical Imaging"/></a> <a href="https://hms.harvard.edu/"><img class="institution_lg" src="../../_static/institution_logos/Harvard.png" title="Harvard Medical School" alt="Harvard Medical School"/></a> <a href="https://web.mit.edu/"><img class="institution_sm" src="../../_static/institution_logos/MIT.svg" title="Massachusetts Institute of Technology" alt="Massachusetts Institute of Technology"/></a> <a href="https://www.nyu.edu/"><img class="institution_md" src="../../_static/institution_logos/NYU.png" title="New York University" alt="New York University"/></a> <a href="http://www.cea.fr/"><img class="institution_md" src="../../_static/institution_logos/CEA.png" title="Commissariat à l´énergie atomique et aux énergies alternatives" alt="Commissariat à l´énergie atomique et aux énergies alternatives"/></a> <a href="https://sci.aalto.fi/"><img class="institution_md" src="../../_static/institution_logos/Aalto.svg" title="Aalto-yliopiston perustieteiden korkeakoulu" alt="Aalto-yliopiston perustieteiden korkeakoulu"/></a> <a href="https://www.telecom-paris.fr/"><img class="institution_md" src="../../_static/institution_logos/Telecom_Paris_Tech.png" title="Télécom ParisTech" alt="Télécom ParisTech"/></a> <a href="https://www.washington.edu/"><img class="institution_sm" src="../../_static/institution_logos/Washington.png" title="University of Washington" alt="University of Washington"/></a> <a href="https://icm-institute.org/"><img class="institution_lg" src="../../_static/institution_logos/ICM.jpg" title="Institut du Cerveau et de la Moelle épinière" alt="Institut du Cerveau et de la Moelle épinière"/></a> <a href="https://www.bu.edu/"><img class="institution_sm" src="../../_static/institution_logos/BU.svg" title="Boston University" alt="Boston University"/></a> <a href="https://www.inserm.fr/"><img class="institution_xs" src="../../_static/institution_logos/Inserm.svg" title="Institut national de la santé et de la recherche médicale" alt="Institut national de la santé et de la recherche médicale"/></a> <a href="https://www.fz-juelich.de/"><img class="institution_sm" src="../../_static/institution_logos/Julich.svg" title="Forschungszentrum Jülich" alt="Forschungszentrum Jülich"/></a> <a href="https://www.tu-ilmenau.de/"><img class="institution_sm" src="../../_static/institution_logos/Ilmenau.gif" title="Technische Universität Ilmenau" alt="Technische Universität Ilmenau"/></a> <a href="https://bids.berkeley.edu/"><img class="institution_md" src="../../_static/institution_logos/BIDS.png" title="Berkeley Institute for Data Science" alt="Berkeley Institute for Data Science"/></a> <a href="https://www.inria.fr/"><img class="institution_sm" src="../../_static/institution_logos/inria.png" title="Institut national de recherche en informatique et en automatique" alt="Institut national de recherche en informatique et en automatique"/></a> <a href="https://www.au.dk/"><img class="institution_sm" src="../../_static/institution_logos/Aarhus.png" title="Aarhus Universitet" alt="Aarhus Universitet"/></a> <a href="https://www.uni-graz.at/"><img class="institution_md" src="../../_static/institution_logos/Graz.jpg" title="Karl-Franzens-Universität Graz" alt="Karl-Franzens-Universität Graz"/></a> </div> <div class="container"> <ul class="list-inline"> <li><a href="https://github.com/mne-tools/mne-python">GitHub</a></li> <li>·</li> <li><a href="https://mail.nmr.mgh.harvard.edu/mailman/listinfo/mne_analysis">Mailing list</a></li> <li>·</li> <li><a href="https://gitter.im/mne-tools/mne-python">Gitter</a></li> <li>·</li> <li><a href="whats_new.html">What's new</a></li> <li>·</li> <li><a href="faq.html#cite">Cite MNE</a></li> <li class="pull-right"><a href="#">Back to top</a></li> </ul> <p>&copy; Copyright 2012-2019, MNE Developers. Last updated on 2019-07-11.</p> </div> </footer> <script src="https://mne.tools/versionwarning.js"></script> </body> </html>
{ "content_hash": "446726fbebd2bcd3b869a6df6729299a", "timestamp": "", "source": "github", "line_count": 428, "max_line_length": 850, "avg_line_length": 90.9766355140187, "alnum_prop": 0.6576608968103138, "repo_name": "mne-tools/mne-tools.github.io", "id": "2b0a742b8b4be378b970e3299db10d8030324593", "size": "38974", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "0.18/auto_tutorials/stats-sensor-space/plot_stats_cluster_erp.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "708696" }, { "name": "Dockerfile", "bytes": "1820" }, { "name": "HTML", "bytes": "1526247783" }, { "name": "JavaScript", "bytes": "1323087" }, { "name": "Jupyter Notebook", "bytes": "24820047" }, { "name": "Python", "bytes": "18575494" } ], "symlink_target": "" }
// ---------------------------------------------------------------------------------- // // Copyright 2011 Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Samples.WindowsAzure.ServiceManagement { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; #region Configuration Set [DataContract(Namespace = Constants.ServiceManagementNS)] [KnownType(typeof(ProvisioningConfigurationSet))] [KnownType(typeof(LinuxProvisioningConfigurationSet))] [KnownType(typeof(WindowsProvisioningConfigurationSet))] [KnownType(typeof(NetworkConfigurationSet))] public class ConfigurationSet : Mergable<ConfigurationSet> { [DataMember(EmitDefaultValue = false, Order = 0)] public virtual string ConfigurationSetType { get; set; } protected ConfigurationSet() { } public override object ResolveType() { if (this.GetType() != typeof(ConfigurationSet)) { return this; } if (!string.IsNullOrEmpty(this.ConfigurationSetType)) { if (string.Equals(this.ConfigurationSetType, "WindowsProvisioningConfiguration")) { return base.Convert<WindowsProvisioningConfigurationSet>(); } if (string.Equals(this.ConfigurationSetType, "LinuxProvisioningConfiguration")) { return base.Convert<LinuxProvisioningConfigurationSet>(); } if (string.Equals(this.ConfigurationSetType, "NetworkConfiguration")) { return base.Convert<NetworkConfigurationSet>(); } } return this; } } [DataContract(Namespace = Constants.ServiceManagementNS)] public abstract class ProvisioningConfigurationSet : ConfigurationSet { } [DataContract(Namespace = Constants.ServiceManagementNS)] public class WindowsProvisioningConfigurationSet : ProvisioningConfigurationSet { [DataMember(Name = "ComputerName", EmitDefaultValue = false, Order = 1)] public string ComputerName { get { return this.GetValue<string>("ComputerName"); } set { this.SetValue("ComputerName", value); } } [DataMember(Name = "AdminPassword", EmitDefaultValue = false, Order = 2)] public string AdminPassword { get { return this.GetValue<string>("AdminPassword"); } set { this.SetValue("AdminPassword", value); } } [DataMember(Name = "ResetPasswordOnFirstLogon", EmitDefaultValue = false, Order = 4)] private bool? resetPasswordOnFirstLogon { get { return this.GetField<bool>("ResetPasswordOnFirstLogon"); } set { this.SetField("ResetPasswordOnFirstLogon", value); } } public bool ResetPasswordOnFirstLogon { get { return base.GetValue<bool>("ResetPasswordOnFirstLogon"); } set { base.SetValue("ResetPasswordOnFirstLogon", value); } } [DataMember(Name = "EnableAutomaticUpdates", EmitDefaultValue = false, Order = 4)] public bool? EnableAutomaticUpdates { get { return base.GetValue<bool?>("EnableAutomaticUpdates"); } set { base.SetValue("EnableAutomaticUpdates", value); } } [DataMember(Name = "TimeZone", EmitDefaultValue = false, Order = 5)] public string TimeZone { get { return base.GetValue<string>("TimeZone"); } set { base.SetValue("TimeZone", value); } } [DataMember(Name = "DomainJoin", EmitDefaultValue = false, Order = 6)] public DomainJoinSettings DomainJoin { get { return base.GetValue<DomainJoinSettings>("DomainJoin"); } set { base.SetValue("DomainJoin", value); } } [DataMember(Name = "StoredCertificateSettings", EmitDefaultValue = false, Order = 7)] public CertificateSettingList StoredCertificateSettings { get { return base.GetValue<CertificateSettingList>("StoredCertificateSettings"); } set { base.SetValue("StoredCertificateSettings", value); } } public override string ConfigurationSetType { get { return "WindowsProvisioningConfiguration"; } set { base.ConfigurationSetType = value; } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class DomainJoinCredentials { [DataMember(Name = "Domain", EmitDefaultValue = false, Order = 1)] public string Domain { get; set; } [DataMember(Name = "Username", EmitDefaultValue = false, Order = 2)] public string Username { get; set; } [DataMember(Name = "Password", EmitDefaultValue = false, Order = 3)] public string Password { get; set; } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class DomainJoinProvisioning { [DataMember(Name = "AccountData", EmitDefaultValue = false, Order = 1)] public string AccountData { get; set; } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class DomainJoinSettings { [DataMember(Name = "Credentials", EmitDefaultValue = false, Order = 1)] public DomainJoinCredentials Credentials { get; set; } [DataMember(Name = "Provisioning", EmitDefaultValue = false, Order = 2)] public DomainJoinProvisioning Provisioning { get; set; } [DataMember(Name = "JoinDomain", EmitDefaultValue = false, Order = 3)] public string JoinDomain { get; set; } [DataMember(Name = "MachineObjectOU", EmitDefaultValue = false, Order = 4)] public string MachineObjectOU { get; set; } } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class LinuxProvisioningConfigurationSet : ProvisioningConfigurationSet { [DataMember(Name = "HostName", EmitDefaultValue = false, Order = 1)] public string HostName { get { return this.GetValue<string>("HostName"); } set { this.SetValue("HostName", value); } } [DataMember(Name = "UserName", EmitDefaultValue = false, Order = 2)] public string UserName { get { return this.GetValue<string>("UserName"); } set { this.SetValue("UserName", value); } } [DataMember(Name = "UserPassword", EmitDefaultValue = false, Order = 3)] public string UserPassword { get { return this.GetValue<string>("UserPassword"); } set { this.SetValue("UserPassword", value); } } [DataMember(Name = "DisableSshPasswordAuthentication", EmitDefaultValue = false, Order = 4)] public bool? DisableSshPasswordAuthentication { get { return base.GetValue<bool?>("DisableSshPasswordAuthentication"); } set { base.SetValue("DisableSshPasswordAuthentication", value); } } [DataMember(Name = "SSH", EmitDefaultValue = false, Order = 5)] public SSHSettings SSH { get { return base.GetValue<SSHSettings>("SSH"); } set { base.SetValue("SSH", value); } } public override string ConfigurationSetType { get { return "LinuxProvisioningConfiguration"; } set { base.ConfigurationSetType = value; } } [DataContract(Name = "SSHSettings", Namespace = Constants.ServiceManagementNS)] public class SSHSettings { [DataMember(Name = "PublicKeys", EmitDefaultValue = false, Order = 1)] public SSHPublicKeyList PublicKeys { get; set; } [DataMember(Name = "KeyPairs", EmitDefaultValue = false, Order = 2)] public SSHKeyPairList KeyPairs { get; set; } } [CollectionDataContract(Name = "SSHPublicKeyList", ItemName = "PublicKey", Namespace = Constants.ServiceManagementNS)] public class SSHPublicKeyList : List<SSHPublicKey> { } [DataContract(Namespace = Constants.ServiceManagementNS)] public class SSHPublicKey { [DataMember(Name = "Fingerprint", EmitDefaultValue = false, Order = 1)] public string Fingerprint { get; set; } [DataMember(Name = "Path", EmitDefaultValue = false, Order = 2)] public string Path { get; set; } } [CollectionDataContract(Name = "SSHKeyPairList", ItemName = "KeyPair", Namespace = Constants.ServiceManagementNS)] public class SSHKeyPairList : List<SSHKeyPair> { } [DataContract(Namespace = Constants.ServiceManagementNS)] public class SSHKeyPair { [DataMember(Name = "Fingerprint", EmitDefaultValue = false, Order = 1)] public string Fingerprint { get; set; } [DataMember(Name = "Path", EmitDefaultValue = false, Order = 2)] public string Path { get; set; } } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class NetworkConfigurationSet : ConfigurationSet { public override string ConfigurationSetType { get { return "NetworkConfiguration"; } set { base.ConfigurationSetType = value; } } [DataMember(Name = "InputEndpoints", EmitDefaultValue = false, Order = 0)] public Collection<InputEndpoint> InputEndpoints { get { return base.GetValue<Collection<InputEndpoint>>("InputEndpoints"); } set { base.SetValue("InputEndpoints", value); } } [DataMember(Name = "SubnetNames", EmitDefaultValue = false, Order = 1)] public SubnetNamesCollection SubnetNames { get { return this.GetValue<SubnetNamesCollection>("SubnetNames"); } set { this.SetValue("SubnetNames", value); } } } [DataContract(Name = "InputEndpoint", Namespace = Constants.ServiceManagementNS)] public class InputEndpoint : Mergable<InputEndpoint> { ////[DataMember(Name = "EnableDirectServerReturn", EmitDefaultValue = false, Order = 0)] ////private bool? enableDirectServerReturn ////{ //// get //// { //// return this.GetField<bool>("EnableDirectServerReturn"); //// } //// set //// { //// this.SetField("EnableDirectServerReturn", value); //// } ////} ////public bool EnableDirectServerReturn ////{ //// get //// { //// return base.GetValue<bool>("EnableDirectServerReturn"); //// } //// set //// { //// base.SetValue("EnableDirectServerReturn", value); //// } ////} [DataMember(Name = "LoadBalancedEndpointSetName", EmitDefaultValue = false, Order = 1)] public string LoadBalancedEndpointSetName { get { return base.GetValue<string>("LoadBalancedEndpointSetName"); } set { base.SetValue("LoadBalancedEndpointSetName", value); } } [DataMember(Name = "LocalPort", EmitDefaultValue = false, Order = 2)] private int? localPort { get { return base.GetField<int>("LocalPort"); } set { base.SetField("LocalPort", value); } } public int LocalPort { get { return base.GetValue<int>("LocalPort"); } set { base.SetValue("LocalPort", value); } } [DataMember(Name = "Name", EmitDefaultValue = false, Order = 3)] public string Name { get { return base.GetValue<string>("Name"); } set { base.SetValue("Name", value); } } [DataMember(Name = "Port", EmitDefaultValue = false, Order = 4)] public int? Port { get { return base.GetValue<int?>("Port"); } set { base.SetValue("Port", value); } } [DataMember(Name = "LoadBalancerProbe", EmitDefaultValue = false, Order = 5)] public LoadBalancerProbe LoadBalancerProbe { get { return base.GetValue<LoadBalancerProbe>("LoadBalancerProbe"); } set { base.SetValue("LoadBalancerProbe", value); } } [DataMember(Name = "Protocol", EmitDefaultValue = false, Order = 6)] public string Protocol { get { return base.GetValue<string>("Protocol"); } set { base.SetValue("Protocol", value); } } [DataMember(Name = "Vip", EmitDefaultValue = false, Order = 7)] public string Vip { get { return base.GetValue<string>("Vip"); } set { base.SetValue("Vip", value); } } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class LoadBalancerProbe : Mergable<LoadBalancerProbe> { [DataMember(Name = "Path", EmitDefaultValue = false, Order = 0)] public string Path { get { return base.GetValue<string>("Path"); } set { base.SetValue("Path", value); } } [DataMember(Name = "Port", EmitDefaultValue = false, Order = 1)] private int? port { get { return base.GetField<int>("Port"); } set { base.SetField("Port", value); } } public int Port { get { return base.GetValue<int>("Port"); } set { base.SetValue("Port", value); } } [DataMember(Name = "Protocol", EmitDefaultValue = false, Order = 2)] public string Protocol { get { return base.GetValue<string>("Protocol"); } set { base.SetValue("Protocol", value); } } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class CertificateSetting : Mergable<CertificateSetting> { [DataMember(Name = "StoreLocation", EmitDefaultValue = false, Order = 0)] public string StoreLocation { get { return base.GetValue<string>("StoreLocation"); } set { base.SetValue<string>("StoreLocation", value); } } [DataMember(Name = "StoreName", EmitDefaultValue = false, Order = 1)] public string StoreName { get { return base.GetValue<string>("StoreName"); } set { base.SetValue<string>("StoreName", value); } } [DataMember(Name = "Thumbprint", EmitDefaultValue = false, Order = 2)] public string Thumbprint { get { return base.GetValue<string>("Thumbprint"); } set { base.SetValue<string>("Thumbprint", value); } } } [CollectionDataContract(Name = "CertificateSettings", Namespace = Constants.ServiceManagementNS)] public class CertificateSettingList : List<CertificateSetting> { } [CollectionDataContract(Name = "SubnetNames", ItemName = "SubnetName", Namespace = Constants.ServiceManagementNS)] public class SubnetNamesCollection : Collection<string> { } #endregion #region DataDisk [DataContract(Namespace = Constants.ServiceManagementNS)] public class DataVirtualHardDisk : Mergable<DataVirtualHardDisk> { [DataMember(Name = "HostCaching", EmitDefaultValue = false, Order = 0)] public string HostCaching { get { return this.GetValue<string>("HostCaching"); } set { this.SetValue("HostCaching", value); } } [DataMember(Name = "DiskLabel", EmitDefaultValue = false, Order = 1)] public string DiskLabel { get { return this.GetValue<string>("DiskLabel"); } set { this.SetValue("DiskLabel", value); } } [DataMember(Name = "DiskName", EmitDefaultValue = false, Order = 2)] public string DiskName { get { return base.GetValue<string>("DiskName"); } set { base.SetValue("DiskName", value); } } [DataMember(Name = "Lun", EmitDefaultValue = false, Order = 3)] public int Lun ////Even though we are changing this to INT now; because it is persisted as XML it could just work fine fro deserialize. { get { return this.GetValue<int>("Lun"); } set { this.SetValue("Lun", value); } } [DataMember(Name = "LogicalDiskSizeInGB", EmitDefaultValue = false, Order = 4)] private int? logicalDiskSizeInGB { get { return this.GetField<int>("LogicalDiskSizeInGB"); } set { this.SetField("LogicalDiskSizeInGB", value); } } public int LogicalDiskSizeInGB { get { return this.GetValue<int>("LogicalDiskSizeInGB"); } set { this.SetValue("LogicalDiskSizeInGB", value); } } [DataMember(Name = "MediaLink", EmitDefaultValue = false, Order = 5)] public Uri MediaLink { get { return this.GetValue<Uri>("MediaLink"); } set { this.SetValue("MediaLink", value); } } [DataMember(Name = "SourceMediaLink", EmitDefaultValue = false, Order = 6)] public Uri SourceMediaLink { get { return this.GetValue<Uri>("SourceMediaLink"); } set { this.SetValue("SourceMediaLink", value); } } } #endregion #region OSDisk [DataContract(Namespace = Constants.ServiceManagementNS)] public class OSVirtualHardDisk : Mergable<OSVirtualHardDisk> { [DataMember(Name = "HostCaching", EmitDefaultValue = false, Order = 0)] public string HostCaching { get { return this.GetValue<string>("HostCaching"); } set { this.SetValue("HostCaching", value); } } [DataMember(Name = "DiskLabel", EmitDefaultValue = false, Order = 1)] public string DiskLabel { get { return this.GetValue<string>("DiskLabel"); } set { this.SetValue("DiskLabel", value); } } [DataMember(Name = "DiskName", EmitDefaultValue = false, Order = 2)] public string DiskName { get { return this.GetValue<string>("DiskName"); } set { this.SetValue("DiskName", value); } } [DataMember(Name = "MediaLink", EmitDefaultValue = false, Order = 3)] public Uri MediaLink { get { return this.GetValue<Uri>("MediaLink"); } set { this.SetValue("MediaLink", value); } } [DataMember(Name = "SourceImageName", EmitDefaultValue = false, Order = 4)] public string SourceImageName { get { return this.GetValue<string>("SourceImageName"); } set { this.SetValue("SourceImageName", value); } } [DataMember(Name = "OS", EmitDefaultValue = false, Order = 5)] public string OS { get { return this.GetValue<string>("OS"); } set { this.SetValue("OS", value); } } } #endregion #region RoleOperation [DataContract(Namespace = Constants.ServiceManagementNS)] public class RoleOperation : IExtensibleDataObject { [DataMember(EmitDefaultValue = false, Order = 0)] public virtual string OperationType { get; set; } protected RoleOperation() { } #region IExtensibleDataObject Members public ExtensionDataObject ExtensionData { get; set; } #endregion } [DataContract(Namespace = Constants.ServiceManagementNS)] public class ShutdownRoleOperation : RoleOperation { public override string OperationType { get { return "ShutdownRoleOperation"; } set { } } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class StartRoleOperation : RoleOperation { public override string OperationType { get { return "StartRoleOperation"; } set { } } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class RestartRoleOperation : RoleOperation { public override string OperationType { get { return "RestartRoleOperation"; } set { } } } [DataContract(Namespace = Constants.ServiceManagementNS)] public class CaptureRoleOperation : RoleOperation { public override string OperationType { get { return "CaptureRoleOperation"; } set { } } [DataMember(EmitDefaultValue = false, Order = 0)] public string PostCaptureAction { get; set; } [DataMember(EmitDefaultValue = false, Order = 1)] public ProvisioningConfigurationSet ProvisioningConfiguration { get; set; } [DataMember(EmitDefaultValue = false, Order = 2)] public string TargetImageLabel { get; set; } [DataMember(EmitDefaultValue = false, Order = 3)] public string TargetImageName { get; set; } } [DataContract(Namespace = Constants.ServiceManagementNS)] public enum PostCaptureAction { [EnumMember] Delete, [EnumMember] Reprovision } [DataContract(Namespace = Constants.ServiceManagementNS)] public enum PowerState { [EnumMember] Unknown, [EnumMember] Starting, [EnumMember] Started, [EnumMember] Stopping, [EnumMember] Stopped, } #endregion }
{ "content_hash": "8428c0c20b614f4fba69b1d8502547e9", "timestamp": "", "source": "github", "line_count": 1005, "max_line_length": 143, "avg_line_length": 26.534328358208956, "alnum_prop": 0.496006299921251, "repo_name": "alpon/azure-sdk-tools", "id": "12709ed34423f78b0243a95cc36012670eee2c0a", "size": "26669", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "WindowsAzurePowershell/src/ServiceManagement/ResourceModel/DurableVMRole.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "2474908" }, { "name": "JavaScript", "bytes": "418" }, { "name": "PHP", "bytes": "41" }, { "name": "PowerShell", "bytes": "59181" }, { "name": "Python", "bytes": "12722" }, { "name": "Shell", "bytes": "7769" } ], "symlink_target": "" }
/** * THIS FILE IS AUTO-GENERATED * DON'T MAKE CHANGES HERE */ import { createE } from '../../factoriesNumber.js' export const eDependencies = { createE }
{ "content_hash": "ec8b238e7b819e1cac6c5c77f178a91b", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 50, "avg_line_length": 17.88888888888889, "alnum_prop": 0.6645962732919255, "repo_name": "Michayal/michayal.github.io", "id": "c096d0a05b62d6ec464291607a0766d973166903", "size": "161", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/mathjs/src/entry/dependenciesNumber/dependenciesE.generated.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "16564" }, { "name": "JavaScript", "bytes": "2034596" }, { "name": "Shell", "bytes": "123" } ], "symlink_target": "" }
package org.apache.storm.messaging.jxio; import org.apache.storm.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by seokwoo on 2017-05-12. */ public class JxioUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { private static final Logger LOG = LoggerFactory.getLogger(JxioUncaughtExceptionHandler.class); @Override public void uncaughtException(Thread t, Throwable e) { try { Utils.handleUncaughtException(e); } catch (Error error) { LOG.error("Received error in JXIO thread.. terminating server..."); Runtime.getRuntime().exit(1); } } }
{ "content_hash": "1aedd8ec34e3cfeb6044b64e7957be2f", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 98, "avg_line_length": 32.04761904761905, "alnum_prop": 0.6968796433878157, "repo_name": "dke-knu/i2am", "id": "785d2cdb1996960a4886141833ac64c9419da742", "size": "673", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rdma-based-storm/storm-core/src/jvm/org/apache/storm/messaging/jxio/JxioUncaughtExceptionHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13260" }, { "name": "C", "bytes": "93049" }, { "name": "C++", "bytes": "94859" }, { "name": "CSS", "bytes": "86416" }, { "name": "Clojure", "bytes": "641128" }, { "name": "Fancy", "bytes": "6234" }, { "name": "HTML", "bytes": "166144" }, { "name": "Java", "bytes": "11202484" }, { "name": "JavaScript", "bytes": "1260673" }, { "name": "M4", "bytes": "2108" }, { "name": "Makefile", "bytes": "2641" }, { "name": "Python", "bytes": "858643" }, { "name": "Ruby", "bytes": "19572" }, { "name": "Shell", "bytes": "41981" }, { "name": "Thrift", "bytes": "24717" } ], "symlink_target": "" }
// // Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802 // Consulte <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem. // Gerado em: 2019.09.22 às 07:42:51 PM BRT // package br.com.swconsultoria.cte.schema_300.cteModalFerroviario; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Classe Java de SignedInfoType complex type. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * * <pre> * &lt;complexType name="SignedInfoType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="CanonicalizationMethod"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="Algorithm" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" fixed="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="SignatureMethod"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="Algorithm" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" fixed="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="Reference" type="{http://www.w3.org/2000/09/xmldsig#}ReferenceType"/> * &lt;/sequence> * &lt;attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SignedInfoType", namespace = "http://www.w3.org/2000/09/xmldsig#", propOrder = { "canonicalizationMethod", "signatureMethod", "reference" }) public class SignedInfoType { @XmlElement(name = "CanonicalizationMethod", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true) protected SignedInfoType.CanonicalizationMethod canonicalizationMethod; @XmlElement(name = "SignatureMethod", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true) protected SignedInfoType.SignatureMethod signatureMethod; @XmlElement(name = "Reference", namespace = "http://www.w3.org/2000/09/xmldsig#", required = true) protected ReferenceType reference; @XmlAttribute(name = "Id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; /** * Obtém o valor da propriedade canonicalizationMethod. * * @return * possible object is * {@link SignedInfoType.CanonicalizationMethod } * */ public SignedInfoType.CanonicalizationMethod getCanonicalizationMethod() { return canonicalizationMethod; } /** * Define o valor da propriedade canonicalizationMethod. * * @param value * allowed object is * {@link SignedInfoType.CanonicalizationMethod } * */ public void setCanonicalizationMethod(SignedInfoType.CanonicalizationMethod value) { this.canonicalizationMethod = value; } /** * Obtém o valor da propriedade signatureMethod. * * @return * possible object is * {@link SignedInfoType.SignatureMethod } * */ public SignedInfoType.SignatureMethod getSignatureMethod() { return signatureMethod; } /** * Define o valor da propriedade signatureMethod. * * @param value * allowed object is * {@link SignedInfoType.SignatureMethod } * */ public void setSignatureMethod(SignedInfoType.SignatureMethod value) { this.signatureMethod = value; } /** * Obtém o valor da propriedade reference. * * @return * possible object is * {@link ReferenceType } * */ public ReferenceType getReference() { return reference; } /** * Define o valor da propriedade reference. * * @param value * allowed object is * {@link ReferenceType } * */ public void setReference(ReferenceType value) { this.reference = value; } /** * Obtém o valor da propriedade id. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Define o valor da propriedade id. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * <p>Classe Java de anonymous complex type. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="Algorithm" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" fixed="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class CanonicalizationMethod { @XmlAttribute(name = "Algorithm", required = true) @XmlSchemaType(name = "anyURI") protected String algorithm; /** * Obtém o valor da propriedade algorithm. * * @return * possible object is * {@link String } * */ public String getAlgorithm() { if (algorithm == null) { return "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; } else { return algorithm; } } /** * Define o valor da propriedade algorithm. * * @param value * allowed object is * {@link String } * */ public void setAlgorithm(String value) { this.algorithm = value; } } /** * <p>Classe Java de anonymous complex type. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="Algorithm" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" fixed="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class SignatureMethod { @XmlAttribute(name = "Algorithm", required = true) @XmlSchemaType(name = "anyURI") protected String algorithm; /** * Obtém o valor da propriedade algorithm. * * @return * possible object is * {@link String } * */ public String getAlgorithm() { if (algorithm == null) { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; } else { return algorithm; } } /** * Define o valor da propriedade algorithm. * * @param value * allowed object is * {@link String } * */ public void setAlgorithm(String value) { this.algorithm = value; } } }
{ "content_hash": "007f65f5429e8c15ca4419fd4ee5e950", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 171, "avg_line_length": 30.23611111111111, "alnum_prop": 0.583371612310519, "repo_name": "Samuel-Oliveira/Java_CTe", "id": "62b7be674a29ec651f2ecec441850a624edcfefb", "size": "8727", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/br/com/swconsultoria/cte/schema_300/cteModalFerroviario/SignedInfoType.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "22245053" } ], "symlink_target": "" }
YUI.add('yui2-dragdrop', function(Y) { var YAHOO = Y.YUI2; /** * The drag and drop utility provides a framework for building drag and drop * applications. In addition to enabling drag and drop for specific elements, * the drag and drop elements are tracked by the manager class, and the * interactions between the various elements are tracked during the drag and * the implementing code is notified about these important moments. * @module dragdrop * @title Drag and Drop * @requires yahoo,dom,event * @namespace YAHOO.util */ // Only load the library once. Rewriting the manager class would orphan // existing drag and drop instances. if (!YAHOO.util.DragDropMgr) { /** * DragDropMgr is a singleton that tracks the element interaction for * all DragDrop items in the window. Generally, you will not call * this class directly, but it does have helper methods that could * be useful in your DragDrop implementations. * @class DragDropMgr * @static */ YAHOO.util.DragDropMgr = function() { var Event = YAHOO.util.Event, Dom = YAHOO.util.Dom; return { /** * This property is used to turn on global use of the shim element on all DragDrop instances, defaults to false for backcompat. (Use: YAHOO.util.DDM.useShim = true) * @property useShim * @type Boolean * @static */ useShim: false, /** * This property is used to determine if the shim is active over the screen, default false. * @private * @property _shimActive * @type Boolean * @static */ _shimActive: false, /** * This property is used when useShim is set on a DragDrop object to store the current state of DDM.useShim so it can be reset when a drag operation is done. * @private * @property _shimState * @type Boolean * @static */ _shimState: false, /** * This property is used when useShim is set to true, it will set the opacity on the shim to .5 for debugging. Use: (YAHOO.util.DDM._debugShim = true;) * @private * @property _debugShim * @type Boolean * @static */ _debugShim: false, /** * This method will create a shim element (giving it the id of yui-ddm-shim), it also attaches the mousemove and mouseup listeners to it and attaches a scroll listener on the window * @private * @method _sizeShim * @static */ _createShim: function() { var s = document.createElement('div'); s.id = 'yui-ddm-shim'; if (document.body.firstChild) { document.body.insertBefore(s, document.body.firstChild); } else { document.body.appendChild(s); } s.style.display = 'none'; s.style.backgroundColor = 'red'; s.style.position = 'absolute'; s.style.zIndex = '99999'; Dom.setStyle(s, 'opacity', '0'); this._shim = s; Event.on(s, "mouseup", this.handleMouseUp, this, true); Event.on(s, "mousemove", this.handleMouseMove, this, true); Event.on(window, 'scroll', this._sizeShim, this, true); }, /** * This method will size the shim, called from activate and on window scroll event * @private * @method _sizeShim * @static */ _sizeShim: function() { if (this._shimActive) { var s = this._shim; s.style.height = Dom.getDocumentHeight() + 'px'; s.style.width = Dom.getDocumentWidth() + 'px'; s.style.top = '0'; s.style.left = '0'; } }, /** * This method will create the shim element if needed, then show the shim element, size the element and set the _shimActive property to true * @private * @method _activateShim * @static */ _activateShim: function() { if (this.useShim) { if (!this._shim) { this._createShim(); } this._shimActive = true; var s = this._shim, o = '0'; if (this._debugShim) { o = '.5'; } Dom.setStyle(s, 'opacity', o); this._sizeShim(); s.style.display = 'block'; } }, /** * This method will hide the shim element and set the _shimActive property to false * @private * @method _deactivateShim * @static */ _deactivateShim: function() { this._shim.style.display = 'none'; this._shimActive = false; }, /** * The HTML element created to use as a shim over the document to track mouse movements * @private * @property _shim * @type HTMLElement * @static */ _shim: null, /** * Two dimensional Array of registered DragDrop objects. The first * dimension is the DragDrop item group, the second the DragDrop * object. * @property ids * @type {string: string} * @private * @static */ ids: {}, /** * Array of element ids defined as drag handles. Used to determine * if the element that generated the mousedown event is actually the * handle and not the html element itself. * @property handleIds * @type {string: string} * @private * @static */ handleIds: {}, /** * the DragDrop object that is currently being dragged * @property dragCurrent * @type DragDrop * @private * @static **/ dragCurrent: null, /** * the DragDrop object(s) that are being hovered over * @property dragOvers * @type Array * @private * @static */ dragOvers: {}, /** * the X distance between the cursor and the object being dragged * @property deltaX * @type int * @private * @static */ deltaX: 0, /** * the Y distance between the cursor and the object being dragged * @property deltaY * @type int * @private * @static */ deltaY: 0, /** * Flag to determine if we should prevent the default behavior of the * events we define. By default this is true, but this can be set to * false if you need the default behavior (not recommended) * @property preventDefault * @type boolean * @static */ preventDefault: true, /** * Flag to determine if we should stop the propagation of the events * we generate. This is true by default but you may want to set it to * false if the html element contains other features that require the * mouse click. * @property stopPropagation * @type boolean * @static */ stopPropagation: true, /** * Internal flag that is set to true when drag and drop has been * initialized * @property initialized * @private * @static */ initialized: false, /** * All drag and drop can be disabled. * @property locked * @private * @static */ locked: false, /** * Provides additional information about the the current set of * interactions. Can be accessed from the event handlers. It * contains the following properties: * * out: onDragOut interactions * enter: onDragEnter interactions * over: onDragOver interactions * drop: onDragDrop interactions * point: The location of the cursor * draggedRegion: The location of dragged element at the time * of the interaction * sourceRegion: The location of the source elemtn at the time * of the interaction * validDrop: boolean * @property interactionInfo * @type object * @static */ interactionInfo: null, /** * Called the first time an element is registered. * @method init * @private * @static */ init: function() { this.initialized = true; }, /** * In point mode, drag and drop interaction is defined by the * location of the cursor during the drag/drop * @property POINT * @type int * @static * @final */ POINT: 0, /** * In intersect mode, drag and drop interaction is defined by the * cursor position or the amount of overlap of two or more drag and * drop objects. * @property INTERSECT * @type int * @static * @final */ INTERSECT: 1, /** * In intersect mode, drag and drop interaction is defined only by the * overlap of two or more drag and drop objects. * @property STRICT_INTERSECT * @type int * @static * @final */ STRICT_INTERSECT: 2, /** * The current drag and drop mode. Default: POINT * @property mode * @type int * @static */ mode: 0, /** * Runs method on all drag and drop objects * @method _execOnAll * @private * @static */ _execOnAll: function(sMethod, args) { for (var i in this.ids) { for (var j in this.ids[i]) { var oDD = this.ids[i][j]; if (! this.isTypeOfDD(oDD)) { continue; } oDD[sMethod].apply(oDD, args); } } }, /** * Drag and drop initialization. Sets up the global event handlers * @method _onLoad * @private * @static */ _onLoad: function() { this.init(); Event.on(document, "mouseup", this.handleMouseUp, this, true); Event.on(document, "mousemove", this.handleMouseMove, this, true); Event.on(window, "unload", this._onUnload, this, true); Event.on(window, "resize", this._onResize, this, true); // Event.on(window, "mouseout", this._test); }, /** * Reset constraints on all drag and drop objs * @method _onResize * @private * @static */ _onResize: function(e) { this._execOnAll("resetConstraints", []); }, /** * Lock all drag and drop functionality * @method lock * @static */ lock: function() { this.locked = true; }, /** * Unlock all drag and drop functionality * @method unlock * @static */ unlock: function() { this.locked = false; }, /** * Is drag and drop locked? * @method isLocked * @return {boolean} True if drag and drop is locked, false otherwise. * @static */ isLocked: function() { return this.locked; }, /** * Location cache that is set for all drag drop objects when a drag is * initiated, cleared when the drag is finished. * @property locationCache * @private * @static */ locationCache: {}, /** * Set useCache to false if you want to force object the lookup of each * drag and drop linked element constantly during a drag. * @property useCache * @type boolean * @static */ useCache: true, /** * The number of pixels that the mouse needs to move after the * mousedown before the drag is initiated. Default=3; * @property clickPixelThresh * @type int * @static */ clickPixelThresh: 3, /** * The number of milliseconds after the mousedown event to initiate the * drag if we don't get a mouseup event. Default=1000 * @property clickTimeThresh * @type int * @static */ clickTimeThresh: 1000, /** * Flag that indicates that either the drag pixel threshold or the * mousdown time threshold has been met * @property dragThreshMet * @type boolean * @private * @static */ dragThreshMet: false, /** * Timeout used for the click time threshold * @property clickTimeout * @type Object * @private * @static */ clickTimeout: null, /** * The X position of the mousedown event stored for later use when a * drag threshold is met. * @property startX * @type int * @private * @static */ startX: 0, /** * The Y position of the mousedown event stored for later use when a * drag threshold is met. * @property startY * @type int * @private * @static */ startY: 0, /** * Flag to determine if the drag event was fired from the click timeout and * not the mouse move threshold. * @property fromTimeout * @type boolean * @private * @static */ fromTimeout: false, /** * Each DragDrop instance must be registered with the DragDropMgr. * This is executed in DragDrop.init() * @method regDragDrop * @param {DragDrop} oDD the DragDrop object to register * @param {String} sGroup the name of the group this element belongs to * @static */ regDragDrop: function(oDD, sGroup) { if (!this.initialized) { this.init(); } if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } this.ids[sGroup][oDD.id] = oDD; }, /** * Removes the supplied dd instance from the supplied group. Executed * by DragDrop.removeFromGroup, so don't call this function directly. * @method removeDDFromGroup * @private * @static */ removeDDFromGroup: function(oDD, sGroup) { if (!this.ids[sGroup]) { this.ids[sGroup] = {}; } var obj = this.ids[sGroup]; if (obj && obj[oDD.id]) { delete obj[oDD.id]; } }, /** * Unregisters a drag and drop item. This is executed in * DragDrop.unreg, use that method instead of calling this directly. * @method _remove * @private * @static */ _remove: function(oDD) { for (var g in oDD.groups) { if (g) { var item = this.ids[g]; if (item && item[oDD.id]) { delete item[oDD.id]; } } } delete this.handleIds[oDD.id]; }, /** * Each DragDrop handle element must be registered. This is done * automatically when executing DragDrop.setHandleElId() * @method regHandle * @param {String} sDDId the DragDrop id this element is a handle for * @param {String} sHandleId the id of the element that is the drag * handle * @static */ regHandle: function(sDDId, sHandleId) { if (!this.handleIds[sDDId]) { this.handleIds[sDDId] = {}; } this.handleIds[sDDId][sHandleId] = sHandleId; }, /** * Utility function to determine if a given element has been * registered as a drag drop item. * @method isDragDrop * @param {String} id the element id to check * @return {boolean} true if this element is a DragDrop item, * false otherwise * @static */ isDragDrop: function(id) { return ( this.getDDById(id) ) ? true : false; }, /** * Returns the drag and drop instances that are in all groups the * passed in instance belongs to. * @method getRelated * @param {DragDrop} p_oDD the obj to get related data for * @param {boolean} bTargetsOnly if true, only return targetable objs * @return {DragDrop[]} the related instances * @static */ getRelated: function(p_oDD, bTargetsOnly) { var oDDs = []; for (var i in p_oDD.groups) { for (var j in this.ids[i]) { var dd = this.ids[i][j]; if (! this.isTypeOfDD(dd)) { continue; } if (!bTargetsOnly || dd.isTarget) { oDDs[oDDs.length] = dd; } } } return oDDs; }, /** * Returns true if the specified dd target is a legal target for * the specifice drag obj * @method isLegalTarget * @param {DragDrop} the drag obj * @param {DragDrop} the target * @return {boolean} true if the target is a legal target for the * dd obj * @static */ isLegalTarget: function (oDD, oTargetDD) { var targets = this.getRelated(oDD, true); for (var i=0, len=targets.length;i<len;++i) { if (targets[i].id == oTargetDD.id) { return true; } } return false; }, /** * My goal is to be able to transparently determine if an object is * typeof DragDrop, and the exact subclass of DragDrop. typeof * returns "object", oDD.constructor.toString() always returns * "DragDrop" and not the name of the subclass. So for now it just * evaluates a well-known variable in DragDrop. * @method isTypeOfDD * @param {Object} the object to evaluate * @return {boolean} true if typeof oDD = DragDrop * @static */ isTypeOfDD: function (oDD) { return (oDD && oDD.__ygDragDrop); }, /** * Utility function to determine if a given element has been * registered as a drag drop handle for the given Drag Drop object. * @method isHandle * @param {String} id the element id to check * @return {boolean} true if this element is a DragDrop handle, false * otherwise * @static */ isHandle: function(sDDId, sHandleId) { return ( this.handleIds[sDDId] && this.handleIds[sDDId][sHandleId] ); }, /** * Returns the DragDrop instance for a given id * @method getDDById * @param {String} id the id of the DragDrop object * @return {DragDrop} the drag drop object, null if it is not found * @static */ getDDById: function(id) { for (var i in this.ids) { if (this.ids[i][id]) { return this.ids[i][id]; } } return null; }, /** * Fired after a registered DragDrop object gets the mousedown event. * Sets up the events required to track the object being dragged * @method handleMouseDown * @param {Event} e the event * @param oDD the DragDrop object being dragged * @private * @static */ handleMouseDown: function(e, oDD) { //this._activateShim(); this.currentTarget = YAHOO.util.Event.getTarget(e); this.dragCurrent = oDD; var el = oDD.getEl(); // track start position this.startX = YAHOO.util.Event.getPageX(e); this.startY = YAHOO.util.Event.getPageY(e); this.deltaX = this.startX - el.offsetLeft; this.deltaY = this.startY - el.offsetTop; this.dragThreshMet = false; this.clickTimeout = setTimeout( function() { var DDM = YAHOO.util.DDM; DDM.startDrag(DDM.startX, DDM.startY); DDM.fromTimeout = true; }, this.clickTimeThresh ); }, /** * Fired when either the drag pixel threshold or the mousedown hold * time threshold has been met. * @method startDrag * @param x {int} the X position of the original mousedown * @param y {int} the Y position of the original mousedown * @static */ startDrag: function(x, y) { if (this.dragCurrent && this.dragCurrent.useShim) { this._shimState = this.useShim; this.useShim = true; } this._activateShim(); clearTimeout(this.clickTimeout); var dc = this.dragCurrent; if (dc && dc.events.b4StartDrag) { dc.b4StartDrag(x, y); dc.fireEvent('b4StartDragEvent', { x: x, y: y }); } if (dc && dc.events.startDrag) { dc.startDrag(x, y); dc.fireEvent('startDragEvent', { x: x, y: y }); } this.dragThreshMet = true; }, /** * Internal function to handle the mouseup event. Will be invoked * from the context of the document. * @method handleMouseUp * @param {Event} e the event * @private * @static */ handleMouseUp: function(e) { if (this.dragCurrent) { clearTimeout(this.clickTimeout); if (this.dragThreshMet) { if (this.fromTimeout) { this.fromTimeout = false; this.handleMouseMove(e); } this.fromTimeout = false; this.fireEvents(e, true); } else { } this.stopDrag(e); this.stopEvent(e); } }, /** * Utility to stop event propagation and event default, if these * features are turned on. * @method stopEvent * @param {Event} e the event as returned by this.getEvent() * @static */ stopEvent: function(e) { if (this.stopPropagation) { YAHOO.util.Event.stopPropagation(e); } if (this.preventDefault) { YAHOO.util.Event.preventDefault(e); } }, /** * Ends the current drag, cleans up the state, and fires the endDrag * and mouseUp events. Called internally when a mouseup is detected * during the drag. Can be fired manually during the drag by passing * either another event (such as the mousemove event received in onDrag) * or a fake event with pageX and pageY defined (so that endDrag and * onMouseUp have usable position data.). Alternatively, pass true * for the silent parameter so that the endDrag and onMouseUp events * are skipped (so no event data is needed.) * * @method stopDrag * @param {Event} e the mouseup event, another event (or a fake event) * with pageX and pageY defined, or nothing if the * silent parameter is true * @param {boolean} silent skips the enddrag and mouseup events if true * @static */ stopDrag: function(e, silent) { var dc = this.dragCurrent; // Fire the drag end event for the item that was dragged if (dc && !silent) { if (this.dragThreshMet) { if (dc.events.b4EndDrag) { dc.b4EndDrag(e); dc.fireEvent('b4EndDragEvent', { e: e }); } if (dc.events.endDrag) { dc.endDrag(e); dc.fireEvent('endDragEvent', { e: e }); } } if (dc.events.mouseUp) { dc.onMouseUp(e); dc.fireEvent('mouseUpEvent', { e: e }); } } if (this._shimActive) { this._deactivateShim(); if (this.dragCurrent && this.dragCurrent.useShim) { this.useShim = this._shimState; this._shimState = false; } } this.dragCurrent = null; this.dragOvers = {}; }, /** * Internal function to handle the mousemove event. Will be invoked * from the context of the html element. * * @TODO figure out what we can do about mouse events lost when the * user drags objects beyond the window boundary. Currently we can * detect this in internet explorer by verifying that the mouse is * down during the mousemove event. Firefox doesn't give us the * button state on the mousemove event. * @method handleMouseMove * @param {Event} e the event * @private * @static */ handleMouseMove: function(e) { var dc = this.dragCurrent; if (dc) { // var button = e.which || e.button; // check for IE mouseup outside of page boundary if (YAHOO.util.Event.isIE && !e.button) { this.stopEvent(e); return this.handleMouseUp(e); } else { if (e.clientX < 0 || e.clientY < 0) { //This will stop the element from leaving the viewport in FF, Opera & Safari //Not turned on yet //this.stopEvent(e); //return false; } } if (!this.dragThreshMet) { var diffX = Math.abs(this.startX - YAHOO.util.Event.getPageX(e)); var diffY = Math.abs(this.startY - YAHOO.util.Event.getPageY(e)); if (diffX > this.clickPixelThresh || diffY > this.clickPixelThresh) { this.startDrag(this.startX, this.startY); } } if (this.dragThreshMet) { if (dc && dc.events.b4Drag) { dc.b4Drag(e); dc.fireEvent('b4DragEvent', { e: e}); } if (dc && dc.events.drag) { dc.onDrag(e); dc.fireEvent('dragEvent', { e: e}); } if (dc) { this.fireEvents(e, false); } } this.stopEvent(e); } }, /** * Iterates over all of the DragDrop elements to find ones we are * hovering over or dropping on * @method fireEvents * @param {Event} e the event * @param {boolean} isDrop is this a drop op or a mouseover op? * @private * @static */ fireEvents: function(e, isDrop) { var dc = this.dragCurrent; // If the user did the mouse up outside of the window, we could // get here even though we have ended the drag. // If the config option dragOnly is true, bail out and don't fire the events if (!dc || dc.isLocked() || dc.dragOnly) { return; } var x = YAHOO.util.Event.getPageX(e), y = YAHOO.util.Event.getPageY(e), pt = new YAHOO.util.Point(x,y), pos = dc.getTargetCoord(pt.x, pt.y), el = dc.getDragEl(), events = ['out', 'over', 'drop', 'enter'], curRegion = new YAHOO.util.Region( pos.y, pos.x + el.offsetWidth, pos.y + el.offsetHeight, pos.x ), oldOvers = [], // cache the previous dragOver array inGroupsObj = {}, inGroups = [], data = { outEvts: [], overEvts: [], dropEvts: [], enterEvts: [] }; // Check to see if the object(s) we were hovering over is no longer // being hovered over so we can fire the onDragOut event for (var i in this.dragOvers) { var ddo = this.dragOvers[i]; if (! this.isTypeOfDD(ddo)) { continue; } if (! this.isOverTarget(pt, ddo, this.mode, curRegion)) { data.outEvts.push( ddo ); } oldOvers[i] = true; delete this.dragOvers[i]; } for (var sGroup in dc.groups) { if ("string" != typeof sGroup) { continue; } for (i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (! this.isTypeOfDD(oDD)) { continue; } if (oDD.isTarget && !oDD.isLocked() && oDD != dc) { if (this.isOverTarget(pt, oDD, this.mode, curRegion)) { inGroupsObj[sGroup] = true; // look for drop interactions if (isDrop) { data.dropEvts.push( oDD ); // look for drag enter and drag over interactions } else { // initial drag over: dragEnter fires if (!oldOvers[oDD.id]) { data.enterEvts.push( oDD ); // subsequent drag overs: dragOver fires } else { data.overEvts.push( oDD ); } this.dragOvers[oDD.id] = oDD; } } } } } this.interactionInfo = { out: data.outEvts, enter: data.enterEvts, over: data.overEvts, drop: data.dropEvts, point: pt, draggedRegion: curRegion, sourceRegion: this.locationCache[dc.id], validDrop: isDrop }; for (var inG in inGroupsObj) { inGroups.push(inG); } // notify about a drop that did not find a target if (isDrop && !data.dropEvts.length) { this.interactionInfo.validDrop = false; if (dc.events.invalidDrop) { dc.onInvalidDrop(e); dc.fireEvent('invalidDropEvent', { e: e }); } } for (i = 0; i < events.length; i++) { var tmp = null; if (data[events[i] + 'Evts']) { tmp = data[events[i] + 'Evts']; } if (tmp && tmp.length) { var type = events[i].charAt(0).toUpperCase() + events[i].substr(1), ev = 'onDrag' + type, b4 = 'b4Drag' + type, cev = 'drag' + type + 'Event', check = 'drag' + type; if (this.mode) { if (dc.events[b4]) { dc[b4](e, tmp, inGroups); dc.fireEvent(b4 + 'Event', { event: e, info: tmp, group: inGroups }); } if (dc.events[check]) { dc[ev](e, tmp, inGroups); dc.fireEvent(cev, { event: e, info: tmp, group: inGroups }); } } else { for (var b = 0, len = tmp.length; b < len; ++b) { if (dc.events[b4]) { dc[b4](e, tmp[b].id, inGroups[0]); dc.fireEvent(b4 + 'Event', { event: e, info: tmp[b].id, group: inGroups[0] }); } if (dc.events[check]) { dc[ev](e, tmp[b].id, inGroups[0]); dc.fireEvent(cev, { event: e, info: tmp[b].id, group: inGroups[0] }); } } } } } }, /** * Helper function for getting the best match from the list of drag * and drop objects returned by the drag and drop events when we are * in INTERSECT mode. It returns either the first object that the * cursor is over, or the object that has the greatest overlap with * the dragged element. * @method getBestMatch * @param {DragDrop[]} dds The array of drag and drop objects * targeted * @return {DragDrop} The best single match * @static */ getBestMatch: function(dds) { var winner = null; var len = dds.length; if (len == 1) { winner = dds[0]; } else { // Loop through the targeted items for (var i=0; i<len; ++i) { var dd = dds[i]; // If the cursor is over the object, it wins. If the // cursor is over multiple matches, the first one we come // to wins. if (this.mode == this.INTERSECT && dd.cursorIsOver) { winner = dd; break; // Otherwise the object with the most overlap wins } else { if (!winner || !winner.overlap || (dd.overlap && winner.overlap.getArea() < dd.overlap.getArea())) { winner = dd; } } } } return winner; }, /** * Refreshes the cache of the top-left and bottom-right points of the * drag and drop objects in the specified group(s). This is in the * format that is stored in the drag and drop instance, so typical * usage is: * <code> * YAHOO.util.DragDropMgr.refreshCache(ddinstance.groups); * </code> * Alternatively: * <code> * YAHOO.util.DragDropMgr.refreshCache({group1:true, group2:true}); * </code> * @TODO this really should be an indexed array. Alternatively this * method could accept both. * @method refreshCache * @param {Object} groups an associative array of groups to refresh * @static */ refreshCache: function(groups) { // refresh everything if group array is not provided var g = groups || this.ids; for (var sGroup in g) { if ("string" != typeof sGroup) { continue; } for (var i in this.ids[sGroup]) { var oDD = this.ids[sGroup][i]; if (this.isTypeOfDD(oDD)) { var loc = this.getLocation(oDD); if (loc) { this.locationCache[oDD.id] = loc; } else { delete this.locationCache[oDD.id]; } } } } }, /** * This checks to make sure an element exists and is in the DOM. The * main purpose is to handle cases where innerHTML is used to remove * drag and drop objects from the DOM. IE provides an 'unspecified * error' when trying to access the offsetParent of such an element * @method verifyEl * @param {HTMLElement} el the element to check * @return {boolean} true if the element looks usable * @static */ verifyEl: function(el) { try { if (el) { var parent = el.offsetParent; if (parent) { return true; } } } catch(e) { } return false; }, /** * Returns a Region object containing the drag and drop element's position * and size, including the padding configured for it * @method getLocation * @param {DragDrop} oDD the drag and drop object to get the * location for * @return {YAHOO.util.Region} a Region object representing the total area * the element occupies, including any padding * the instance is configured for. * @static */ getLocation: function(oDD) { if (! this.isTypeOfDD(oDD)) { return null; } var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l; try { pos= YAHOO.util.Dom.getXY(el); } catch (e) { } if (!pos) { return null; } x1 = pos[0]; x2 = x1 + el.offsetWidth; y1 = pos[1]; y2 = y1 + el.offsetHeight; t = y1 - oDD.padding[0]; r = x2 + oDD.padding[1]; b = y2 + oDD.padding[2]; l = x1 - oDD.padding[3]; return new YAHOO.util.Region( t, r, b, l ); }, /** * Checks the cursor location to see if it over the target * @method isOverTarget * @param {YAHOO.util.Point} pt The point to evaluate * @param {DragDrop} oTarget the DragDrop object we are inspecting * @param {boolean} intersect true if we are in intersect mode * @param {YAHOO.util.Region} pre-cached location of the dragged element * @return {boolean} true if the mouse is over the target * @private * @static */ isOverTarget: function(pt, oTarget, intersect, curRegion) { // use cache if available var loc = this.locationCache[oTarget.id]; if (!loc || !this.useCache) { loc = this.getLocation(oTarget); this.locationCache[oTarget.id] = loc; } if (!loc) { return false; } oTarget.cursorIsOver = loc.contains( pt ); // DragDrop is using this as a sanity check for the initial mousedown // in this case we are done. In POINT mode, if the drag obj has no // contraints, we are done. Otherwise we need to evaluate the // region the target as occupies to determine if the dragged element // overlaps with it. var dc = this.dragCurrent; if (!dc || (!intersect && !dc.constrainX && !dc.constrainY)) { //if (oTarget.cursorIsOver) { //} return oTarget.cursorIsOver; } oTarget.overlap = null; // Get the current location of the drag element, this is the // location of the mouse event less the delta that represents // where the original mousedown happened on the element. We // need to consider constraints and ticks as well. if (!curRegion) { var pos = dc.getTargetCoord(pt.x, pt.y); var el = dc.getDragEl(); curRegion = new YAHOO.util.Region( pos.y, pos.x + el.offsetWidth, pos.y + el.offsetHeight, pos.x ); } var overlap = curRegion.intersect(loc); if (overlap) { oTarget.overlap = overlap; return (intersect) ? true : oTarget.cursorIsOver; } else { return false; } }, /** * unload event handler * @method _onUnload * @private * @static */ _onUnload: function(e, me) { this.unregAll(); }, /** * Cleans up the drag and drop events and objects. * @method unregAll * @private * @static */ unregAll: function() { if (this.dragCurrent) { this.stopDrag(); this.dragCurrent = null; } this._execOnAll("unreg", []); //for (var i in this.elementCache) { //delete this.elementCache[i]; //} //this.elementCache = {}; this.ids = {}; }, /** * A cache of DOM elements * @property elementCache * @private * @static * @deprecated elements are not cached now */ elementCache: {}, /** * Get the wrapper for the DOM element specified * @method getElWrapper * @param {String} id the id of the element to get * @return {YAHOO.util.DDM.ElementWrapper} the wrapped element * @private * @deprecated This wrapper isn't that useful * @static */ getElWrapper: function(id) { var oWrapper = this.elementCache[id]; if (!oWrapper || !oWrapper.el) { oWrapper = this.elementCache[id] = new this.ElementWrapper(YAHOO.util.Dom.get(id)); } return oWrapper; }, /** * Returns the actual DOM element * @method getElement * @param {String} id the id of the elment to get * @return {Object} The element * @deprecated use YAHOO.util.Dom.get instead * @static */ getElement: function(id) { return YAHOO.util.Dom.get(id); }, /** * Returns the style property for the DOM element (i.e., * document.getElById(id).style) * @method getCss * @param {String} id the id of the elment to get * @return {Object} The style property of the element * @deprecated use YAHOO.util.Dom instead * @static */ getCss: function(id) { var el = YAHOO.util.Dom.get(id); return (el) ? el.style : null; }, /** * Inner class for cached elements * @class DragDropMgr.ElementWrapper * @for DragDropMgr * @private * @deprecated */ ElementWrapper: function(el) { /** * The element * @property el */ this.el = el || null; /** * The element id * @property id */ this.id = this.el && el.id; /** * A reference to the style property * @property css */ this.css = this.el && el.style; }, /** * Returns the X position of an html element * @method getPosX * @param el the element for which to get the position * @return {int} the X coordinate * @for DragDropMgr * @deprecated use YAHOO.util.Dom.getX instead * @static */ getPosX: function(el) { return YAHOO.util.Dom.getX(el); }, /** * Returns the Y position of an html element * @method getPosY * @param el the element for which to get the position * @return {int} the Y coordinate * @deprecated use YAHOO.util.Dom.getY instead * @static */ getPosY: function(el) { return YAHOO.util.Dom.getY(el); }, /** * Swap two nodes. In IE, we use the native method, for others we * emulate the IE behavior * @method swapNode * @param n1 the first node to swap * @param n2 the other node to swap * @static */ swapNode: function(n1, n2) { if (n1.swapNode) { n1.swapNode(n2); } else { var p = n2.parentNode; var s = n2.nextSibling; if (s == n1) { p.insertBefore(n1, n2); } else if (n2 == n1.nextSibling) { p.insertBefore(n2, n1); } else { n1.parentNode.replaceChild(n2, n1); p.insertBefore(n1, s); } } }, /** * Returns the current scroll position * @method getScroll * @private * @static */ getScroll: function () { var t, l, dde=document.documentElement, db=document.body; if (dde && (dde.scrollTop || dde.scrollLeft)) { t = dde.scrollTop; l = dde.scrollLeft; } else if (db) { t = db.scrollTop; l = db.scrollLeft; } else { } return { top: t, left: l }; }, /** * Returns the specified element style property * @method getStyle * @param {HTMLElement} el the element * @param {string} styleProp the style property * @return {string} The value of the style property * @deprecated use YAHOO.util.Dom.getStyle * @static */ getStyle: function(el, styleProp) { return YAHOO.util.Dom.getStyle(el, styleProp); }, /** * Gets the scrollTop * @method getScrollTop * @return {int} the document's scrollTop * @static */ getScrollTop: function () { return this.getScroll().top; }, /** * Gets the scrollLeft * @method getScrollLeft * @return {int} the document's scrollTop * @static */ getScrollLeft: function () { return this.getScroll().left; }, /** * Sets the x/y position of an element to the location of the * target element. * @method moveToEl * @param {HTMLElement} moveEl The element to move * @param {HTMLElement} targetEl The position reference element * @static */ moveToEl: function (moveEl, targetEl) { var aCoord = YAHOO.util.Dom.getXY(targetEl); YAHOO.util.Dom.setXY(moveEl, aCoord); }, /** * Gets the client height * @method getClientHeight * @return {int} client height in px * @deprecated use YAHOO.util.Dom.getViewportHeight instead * @static */ getClientHeight: function() { return YAHOO.util.Dom.getViewportHeight(); }, /** * Gets the client width * @method getClientWidth * @return {int} client width in px * @deprecated use YAHOO.util.Dom.getViewportWidth instead * @static */ getClientWidth: function() { return YAHOO.util.Dom.getViewportWidth(); }, /** * Numeric array sort function * @method numericSort * @static */ numericSort: function(a, b) { return (a - b); }, /** * Internal counter * @property _timeoutCount * @private * @static */ _timeoutCount: 0, /** * Trying to make the load order less important. Without this we get * an error if this file is loaded before the Event Utility. * @method _addListeners * @private * @static */ _addListeners: function() { var DDM = YAHOO.util.DDM; if ( YAHOO.util.Event && document ) { DDM._onLoad(); } else { if (DDM._timeoutCount > 2000) { } else { setTimeout(DDM._addListeners, 10); if (document && document.body) { DDM._timeoutCount += 1; } } } }, /** * Recursively searches the immediate parent and all child nodes for * the handle element in order to determine wheter or not it was * clicked. * @method handleWasClicked * @param node the html element to inspect * @static */ handleWasClicked: function(node, id) { if (this.isHandle(id, node.id)) { return true; } else { // check to see if this is a text node child of the one we want var p = node.parentNode; while (p) { if (this.isHandle(id, p.id)) { return true; } else { p = p.parentNode; } } } return false; } }; }(); // shorter alias, save a few bytes YAHOO.util.DDM = YAHOO.util.DragDropMgr; YAHOO.util.DDM._addListeners(); } (function() { var Event=YAHOO.util.Event; var Dom=YAHOO.util.Dom; /** * Defines the interface and base operation of items that that can be * dragged or can be drop targets. It was designed to be extended, overriding * the event handlers for startDrag, onDrag, onDragOver, onDragOut. * Up to three html elements can be associated with a DragDrop instance: * <ul> * <li>linked element: the element that is passed into the constructor. * This is the element which defines the boundaries for interaction with * other DragDrop objects.</li> * <li>handle element(s): The drag operation only occurs if the element that * was clicked matches a handle element. By default this is the linked * element, but there are times that you will want only a portion of the * linked element to initiate the drag operation, and the setHandleElId() * method provides a way to define this.</li> * <li>drag element: this represents an the element that would be moved along * with the cursor during a drag operation. By default, this is the linked * element itself as in {@link YAHOO.util.DD}. setDragElId() lets you define * a separate element that would be moved, as in {@link YAHOO.util.DDProxy} * </li> * </ul> * This class should not be instantiated until the onload event to ensure that * the associated elements are available. * The following would define a DragDrop obj that would interact with any * other DragDrop obj in the "group1" group: * <pre> * dd = new YAHOO.util.DragDrop("div1", "group1"); * </pre> * Since none of the event handlers have been implemented, nothing would * actually happen if you were to run the code above. Normally you would * override this class or one of the default implementations, but you can * also override the methods you want on an instance of the class... * <pre> * dd.onDragDrop = function(e, id) { * &nbsp;&nbsp;alert("dd was dropped on " + id); * } * </pre> * @namespace YAHOO.util * @class DragDrop * @constructor * @param {String} id of the element that is linked to this instance * @param {String} sGroup the group of related DragDrop objects * @param {object} config an object containing configurable attributes * Valid properties for DragDrop: * padding, isTarget, maintainOffset, primaryButtonOnly, */ YAHOO.util.DragDrop = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); } }; YAHOO.util.DragDrop.prototype = { /** * An Object Literal containing the events that we will be using: mouseDown, b4MouseDown, mouseUp, b4StartDrag, startDrag, b4EndDrag, endDrag, mouseUp, drag, b4Drag, invalidDrop, b4DragOut, dragOut, dragEnter, b4DragOver, dragOver, b4DragDrop, dragDrop * By setting any of these to false, then event will not be fired. * @property events * @type object */ events: null, /** * @method on * @description Shortcut for EventProvider.subscribe, see <a href="YAHOO.util.EventProvider.html#subscribe">YAHOO.util.EventProvider.subscribe</a> */ on: function() { this.subscribe.apply(this, arguments); }, /** * The id of the element associated with this object. This is what we * refer to as the "linked element" because the size and position of * this element is used to determine when the drag and drop objects have * interacted. * @property id * @type String */ id: null, /** * Configuration attributes passed into the constructor * @property config * @type object */ config: null, /** * The id of the element that will be dragged. By default this is same * as the linked element , but could be changed to another element. Ex: * YAHOO.util.DDProxy * @property dragElId * @type String * @private */ dragElId: null, /** * the id of the element that initiates the drag operation. By default * this is the linked element, but could be changed to be a child of this * element. This lets us do things like only starting the drag when the * header element within the linked html element is clicked. * @property handleElId * @type String * @private */ handleElId: null, /** * An associative array of HTML tags that will be ignored if clicked. * @property invalidHandleTypes * @type {string: string} */ invalidHandleTypes: null, /** * An associative array of ids for elements that will be ignored if clicked * @property invalidHandleIds * @type {string: string} */ invalidHandleIds: null, /** * An indexted array of css class names for elements that will be ignored * if clicked. * @property invalidHandleClasses * @type string[] */ invalidHandleClasses: null, /** * The linked element's absolute X position at the time the drag was * started * @property startPageX * @type int * @private */ startPageX: 0, /** * The linked element's absolute X position at the time the drag was * started * @property startPageY * @type int * @private */ startPageY: 0, /** * The group defines a logical collection of DragDrop objects that are * related. Instances only get events when interacting with other * DragDrop object in the same group. This lets us define multiple * groups using a single DragDrop subclass if we want. * @property groups * @type {string: string} */ groups: null, /** * Individual drag/drop instances can be locked. This will prevent * onmousedown start drag. * @property locked * @type boolean * @private */ locked: false, /** * Lock this instance * @method lock */ lock: function() { this.locked = true; }, /** * Unlock this instace * @method unlock */ unlock: function() { this.locked = false; }, /** * By default, all instances can be a drop target. This can be disabled by * setting isTarget to false. * @property isTarget * @type boolean */ isTarget: true, /** * The padding configured for this drag and drop object for calculating * the drop zone intersection with this object. * @property padding * @type int[] */ padding: null, /** * If this flag is true, do not fire drop events. The element is a drag only element (for movement not dropping) * @property dragOnly * @type Boolean */ dragOnly: false, /** * If this flag is true, a shim will be placed over the screen/viewable area to track mouse events. Should help with dragging elements over iframes and other controls. * @property useShim * @type Boolean */ useShim: false, /** * Cached reference to the linked element * @property _domRef * @private */ _domRef: null, /** * Internal typeof flag * @property __ygDragDrop * @private */ __ygDragDrop: true, /** * Set to true when horizontal contraints are applied * @property constrainX * @type boolean * @private */ constrainX: false, /** * Set to true when vertical contraints are applied * @property constrainY * @type boolean * @private */ constrainY: false, /** * The left constraint * @property minX * @type int * @private */ minX: 0, /** * The right constraint * @property maxX * @type int * @private */ maxX: 0, /** * The up constraint * @property minY * @type int * @type int * @private */ minY: 0, /** * The down constraint * @property maxY * @type int * @private */ maxY: 0, /** * The difference between the click position and the source element's location * @property deltaX * @type int * @private */ deltaX: 0, /** * The difference between the click position and the source element's location * @property deltaY * @type int * @private */ deltaY: 0, /** * Maintain offsets when we resetconstraints. Set to true when you want * the position of the element relative to its parent to stay the same * when the page changes * * @property maintainOffset * @type boolean */ maintainOffset: false, /** * Array of pixel locations the element will snap to if we specified a * horizontal graduation/interval. This array is generated automatically * when you define a tick interval. * @property xTicks * @type int[] */ xTicks: null, /** * Array of pixel locations the element will snap to if we specified a * vertical graduation/interval. This array is generated automatically * when you define a tick interval. * @property yTicks * @type int[] */ yTicks: null, /** * By default the drag and drop instance will only respond to the primary * button click (left button for a right-handed mouse). Set to true to * allow drag and drop to start with any mouse click that is propogated * by the browser * @property primaryButtonOnly * @type boolean */ primaryButtonOnly: true, /** * The availabe property is false until the linked dom element is accessible. * @property available * @type boolean */ available: false, /** * By default, drags can only be initiated if the mousedown occurs in the * region the linked element is. This is done in part to work around a * bug in some browsers that mis-report the mousedown if the previous * mouseup happened outside of the window. This property is set to true * if outer handles are defined. * * @property hasOuterHandles * @type boolean * @default false */ hasOuterHandles: false, /** * Property that is assigned to a drag and drop object when testing to * see if it is being targeted by another dd object. This property * can be used in intersect mode to help determine the focus of * the mouse interaction. DDM.getBestMatch uses this property first to * determine the closest match in INTERSECT mode when multiple targets * are part of the same interaction. * @property cursorIsOver * @type boolean */ cursorIsOver: false, /** * Property that is assigned to a drag and drop object when testing to * see if it is being targeted by another dd object. This is a region * that represents the area the draggable element overlaps this target. * DDM.getBestMatch uses this property to compare the size of the overlap * to that of other targets in order to determine the closest match in * INTERSECT mode when multiple targets are part of the same interaction. * @property overlap * @type YAHOO.util.Region */ overlap: null, /** * Code that executes immediately before the startDrag event * @method b4StartDrag * @private */ b4StartDrag: function(x, y) { }, /** * Abstract method called after a drag/drop object is clicked * and the drag or mousedown time thresholds have beeen met. * @method startDrag * @param {int} X click location * @param {int} Y click location */ startDrag: function(x, y) { /* override this */ }, /** * Code that executes immediately before the onDrag event * @method b4Drag * @private */ b4Drag: function(e) { }, /** * Abstract method called during the onMouseMove event while dragging an * object. * @method onDrag * @param {Event} e the mousemove event */ onDrag: function(e) { /* override this */ }, /** * Abstract method called when this element fist begins hovering over * another DragDrop obj * @method onDragEnter * @param {Event} e the mousemove event * @param {String|DragDrop[]} id In POINT mode, the element * id this is hovering over. In INTERSECT mode, an array of one or more * dragdrop items being hovered over. */ onDragEnter: function(e, id) { /* override this */ }, /** * Code that executes immediately before the onDragOver event * @method b4DragOver * @private */ b4DragOver: function(e) { }, /** * Abstract method called when this element is hovering over another * DragDrop obj * @method onDragOver * @param {Event} e the mousemove event * @param {String|DragDrop[]} id In POINT mode, the element * id this is hovering over. In INTERSECT mode, an array of dd items * being hovered over. */ onDragOver: function(e, id) { /* override this */ }, /** * Code that executes immediately before the onDragOut event * @method b4DragOut * @private */ b4DragOut: function(e) { }, /** * Abstract method called when we are no longer hovering over an element * @method onDragOut * @param {Event} e the mousemove event * @param {String|DragDrop[]} id In POINT mode, the element * id this was hovering over. In INTERSECT mode, an array of dd items * that the mouse is no longer over. */ onDragOut: function(e, id) { /* override this */ }, /** * Code that executes immediately before the onDragDrop event * @method b4DragDrop * @private */ b4DragDrop: function(e) { }, /** * Abstract method called when this item is dropped on another DragDrop * obj * @method onDragDrop * @param {Event} e the mouseup event * @param {String|DragDrop[]} id In POINT mode, the element * id this was dropped on. In INTERSECT mode, an array of dd items this * was dropped on. */ onDragDrop: function(e, id) { /* override this */ }, /** * Abstract method called when this item is dropped on an area with no * drop target * @method onInvalidDrop * @param {Event} e the mouseup event */ onInvalidDrop: function(e) { /* override this */ }, /** * Code that executes immediately before the endDrag event * @method b4EndDrag * @private */ b4EndDrag: function(e) { }, /** * Fired when we are done dragging the object * @method endDrag * @param {Event} e the mouseup event */ endDrag: function(e) { /* override this */ }, /** * Code executed immediately before the onMouseDown event * @method b4MouseDown * @param {Event} e the mousedown event * @private */ b4MouseDown: function(e) { }, /** * Event handler that fires when a drag/drop obj gets a mousedown * @method onMouseDown * @param {Event} e the mousedown event */ onMouseDown: function(e) { /* override this */ }, /** * Event handler that fires when a drag/drop obj gets a mouseup * @method onMouseUp * @param {Event} e the mouseup event */ onMouseUp: function(e) { /* override this */ }, /** * Override the onAvailable method to do what is needed after the initial * position was determined. * @method onAvailable */ onAvailable: function () { }, /** * Returns a reference to the linked element * @method getEl * @return {HTMLElement} the html element */ getEl: function() { if (!this._domRef) { this._domRef = Dom.get(this.id); } return this._domRef; }, /** * Returns a reference to the actual element to drag. By default this is * the same as the html element, but it can be assigned to another * element. An example of this can be found in YAHOO.util.DDProxy * @method getDragEl * @return {HTMLElement} the html element */ getDragEl: function() { return Dom.get(this.dragElId); }, /** * Sets up the DragDrop object. Must be called in the constructor of any * YAHOO.util.DragDrop subclass * @method init * @param id the id of the linked element * @param {String} sGroup the group of related items * @param {object} config configuration attributes */ init: function(id, sGroup, config) { this.initTarget(id, sGroup, config); Event.on(this._domRef || this.id, "mousedown", this.handleMouseDown, this, true); // Event.on(this.id, "selectstart", Event.preventDefault); for (var i in this.events) { this.createEvent(i + 'Event'); } }, /** * Initializes Targeting functionality only... the object does not * get a mousedown handler. * @method initTarget * @param id the id of the linked element * @param {String} sGroup the group of related items * @param {object} config configuration attributes */ initTarget: function(id, sGroup, config) { // configuration attributes this.config = config || {}; this.events = {}; // create a local reference to the drag and drop manager this.DDM = YAHOO.util.DDM; // initialize the groups object this.groups = {}; // assume that we have an element reference instead of an id if the // parameter is not a string if (typeof id !== "string") { this._domRef = id; id = Dom.generateId(id); } // set the id this.id = id; // add to an interaction group this.addToGroup((sGroup) ? sGroup : "default"); // We don't want to register this as the handle with the manager // so we just set the id rather than calling the setter. this.handleElId = id; Event.onAvailable(id, this.handleOnAvailable, this, true); // the linked element is the element that gets dragged by default this.setDragElId(id); // by default, clicked anchors will not start drag operations. // @TODO what else should be here? Probably form fields. this.invalidHandleTypes = { A: "A" }; this.invalidHandleIds = {}; this.invalidHandleClasses = []; this.applyConfig(); }, /** * Applies the configuration parameters that were passed into the constructor. * This is supposed to happen at each level through the inheritance chain. So * a DDProxy implentation will execute apply config on DDProxy, DD, and * DragDrop in order to get all of the parameters that are available in * each object. * @method applyConfig */ applyConfig: function() { this.events = { mouseDown: true, b4MouseDown: true, mouseUp: true, b4StartDrag: true, startDrag: true, b4EndDrag: true, endDrag: true, drag: true, b4Drag: true, invalidDrop: true, b4DragOut: true, dragOut: true, dragEnter: true, b4DragOver: true, dragOver: true, b4DragDrop: true, dragDrop: true }; if (this.config.events) { for (var i in this.config.events) { if (this.config.events[i] === false) { this.events[i] = false; } } } // configurable properties: // padding, isTarget, maintainOffset, primaryButtonOnly this.padding = this.config.padding || [0, 0, 0, 0]; this.isTarget = (this.config.isTarget !== false); this.maintainOffset = (this.config.maintainOffset); this.primaryButtonOnly = (this.config.primaryButtonOnly !== false); this.dragOnly = ((this.config.dragOnly === true) ? true : false); this.useShim = ((this.config.useShim === true) ? true : false); }, /** * Executed when the linked element is available * @method handleOnAvailable * @private */ handleOnAvailable: function() { this.available = true; this.resetConstraints(); this.onAvailable(); }, /** * Configures the padding for the target zone in px. Effectively expands * (or reduces) the virtual object size for targeting calculations. * Supports css-style shorthand; if only one parameter is passed, all sides * will have that padding, and if only two are passed, the top and bottom * will have the first param, the left and right the second. * @method setPadding * @param {int} iTop Top pad * @param {int} iRight Right pad * @param {int} iBot Bot pad * @param {int} iLeft Left pad */ setPadding: function(iTop, iRight, iBot, iLeft) { // this.padding = [iLeft, iRight, iTop, iBot]; if (!iRight && 0 !== iRight) { this.padding = [iTop, iTop, iTop, iTop]; } else if (!iBot && 0 !== iBot) { this.padding = [iTop, iRight, iTop, iRight]; } else { this.padding = [iTop, iRight, iBot, iLeft]; } }, /** * Stores the initial placement of the linked element. * @method setInitialPosition * @param {int} diffX the X offset, default 0 * @param {int} diffY the Y offset, default 0 * @private */ setInitPosition: function(diffX, diffY) { var el = this.getEl(); if (!this.DDM.verifyEl(el)) { if (el && el.style && (el.style.display == 'none')) { } else { } return; } var dx = diffX || 0; var dy = diffY || 0; var p = Dom.getXY( el ); this.initPageX = p[0] - dx; this.initPageY = p[1] - dy; this.lastPageX = p[0]; this.lastPageY = p[1]; this.setStartPosition(p); }, /** * Sets the start position of the element. This is set when the obj * is initialized, the reset when a drag is started. * @method setStartPosition * @param pos current position (from previous lookup) * @private */ setStartPosition: function(pos) { var p = pos || Dom.getXY(this.getEl()); this.deltaSetXY = null; this.startPageX = p[0]; this.startPageY = p[1]; }, /** * Add this instance to a group of related drag/drop objects. All * instances belong to at least one group, and can belong to as many * groups as needed. * @method addToGroup * @param sGroup {string} the name of the group */ addToGroup: function(sGroup) { this.groups[sGroup] = true; this.DDM.regDragDrop(this, sGroup); }, /** * Remove's this instance from the supplied interaction group * @method removeFromGroup * @param {string} sGroup The group to drop */ removeFromGroup: function(sGroup) { if (this.groups[sGroup]) { delete this.groups[sGroup]; } this.DDM.removeDDFromGroup(this, sGroup); }, /** * Allows you to specify that an element other than the linked element * will be moved with the cursor during a drag * @method setDragElId * @param id {string} the id of the element that will be used to initiate the drag */ setDragElId: function(id) { this.dragElId = id; }, /** * Allows you to specify a child of the linked element that should be * used to initiate the drag operation. An example of this would be if * you have a content div with text and links. Clicking anywhere in the * content area would normally start the drag operation. Use this method * to specify that an element inside of the content div is the element * that starts the drag operation. * @method setHandleElId * @param id {string} the id of the element that will be used to * initiate the drag. */ setHandleElId: function(id) { if (typeof id !== "string") { id = Dom.generateId(id); } this.handleElId = id; this.DDM.regHandle(this.id, id); }, /** * Allows you to set an element outside of the linked element as a drag * handle * @method setOuterHandleElId * @param id the id of the element that will be used to initiate the drag */ setOuterHandleElId: function(id) { if (typeof id !== "string") { id = Dom.generateId(id); } Event.on(id, "mousedown", this.handleMouseDown, this, true); this.setHandleElId(id); this.hasOuterHandles = true; }, /** * Remove all drag and drop hooks for this element * @method unreg */ unreg: function() { Event.removeListener(this.id, "mousedown", this.handleMouseDown); this._domRef = null; this.DDM._remove(this); }, /** * Returns true if this instance is locked, or the drag drop mgr is locked * (meaning that all drag/drop is disabled on the page.) * @method isLocked * @return {boolean} true if this obj or all drag/drop is locked, else * false */ isLocked: function() { return (this.DDM.isLocked() || this.locked); }, /** * Fired when this object is clicked * @method handleMouseDown * @param {Event} e * @param {YAHOO.util.DragDrop} oDD the clicked dd object (this dd obj) * @private */ handleMouseDown: function(e, oDD) { var button = e.which || e.button; if (this.primaryButtonOnly && button > 1) { return; } if (this.isLocked()) { return; } // firing the mousedown events prior to calculating positions var b4Return = this.b4MouseDown(e), b4Return2 = true; if (this.events.b4MouseDown) { b4Return2 = this.fireEvent('b4MouseDownEvent', e); } var mDownReturn = this.onMouseDown(e), mDownReturn2 = true; if (this.events.mouseDown) { mDownReturn2 = this.fireEvent('mouseDownEvent', e); } if ((b4Return === false) || (mDownReturn === false) || (b4Return2 === false) || (mDownReturn2 === false)) { return; } this.DDM.refreshCache(this.groups); // var self = this; // setTimeout( function() { self.DDM.refreshCache(self.groups); }, 0); // Only process the event if we really clicked within the linked // element. The reason we make this check is that in the case that // another element was moved between the clicked element and the // cursor in the time between the mousedown and mouseup events. When // this happens, the element gets the next mousedown event // regardless of where on the screen it happened. var pt = new YAHOO.util.Point(Event.getPageX(e), Event.getPageY(e)); if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) { } else { if (this.clickValidator(e)) { // set the initial element position this.setStartPosition(); // start tracking mousemove distance and mousedown time to // determine when to start the actual drag this.DDM.handleMouseDown(e, this); // this mousedown is mine this.DDM.stopEvent(e); } else { } } }, /** * @method clickValidator * @description Method validates that the clicked element * was indeed the handle or a valid child of the handle * @param {Event} e */ clickValidator: function(e) { var target = YAHOO.util.Event.getTarget(e); return ( this.isValidHandleChild(target) && (this.id == this.handleElId || this.DDM.handleWasClicked(target, this.id)) ); }, /** * Finds the location the element should be placed if we want to move * it to where the mouse location less the click offset would place us. * @method getTargetCoord * @param {int} iPageX the X coordinate of the click * @param {int} iPageY the Y coordinate of the click * @return an object that contains the coordinates (Object.x and Object.y) * @private */ getTargetCoord: function(iPageX, iPageY) { var x = iPageX - this.deltaX; var y = iPageY - this.deltaY; if (this.constrainX) { if (x < this.minX) { x = this.minX; } if (x > this.maxX) { x = this.maxX; } } if (this.constrainY) { if (y < this.minY) { y = this.minY; } if (y > this.maxY) { y = this.maxY; } } x = this.getTick(x, this.xTicks); y = this.getTick(y, this.yTicks); return {x:x, y:y}; }, /** * Allows you to specify a tag name that should not start a drag operation * when clicked. This is designed to facilitate embedding links within a * drag handle that do something other than start the drag. * @method addInvalidHandleType * @param {string} tagName the type of element to exclude */ addInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); this.invalidHandleTypes[type] = type; }, /** * Lets you to specify an element id for a child of a drag handle * that should not initiate a drag * @method addInvalidHandleId * @param {string} id the element id of the element you wish to ignore */ addInvalidHandleId: function(id) { if (typeof id !== "string") { id = Dom.generateId(id); } this.invalidHandleIds[id] = id; }, /** * Lets you specify a css class of elements that will not initiate a drag * @method addInvalidHandleClass * @param {string} cssClass the class of the elements you wish to ignore */ addInvalidHandleClass: function(cssClass) { this.invalidHandleClasses.push(cssClass); }, /** * Unsets an excluded tag name set by addInvalidHandleType * @method removeInvalidHandleType * @param {string} tagName the type of element to unexclude */ removeInvalidHandleType: function(tagName) { var type = tagName.toUpperCase(); // this.invalidHandleTypes[type] = null; delete this.invalidHandleTypes[type]; }, /** * Unsets an invalid handle id * @method removeInvalidHandleId * @param {string} id the id of the element to re-enable */ removeInvalidHandleId: function(id) { if (typeof id !== "string") { id = Dom.generateId(id); } delete this.invalidHandleIds[id]; }, /** * Unsets an invalid css class * @method removeInvalidHandleClass * @param {string} cssClass the class of the element(s) you wish to * re-enable */ removeInvalidHandleClass: function(cssClass) { for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) { if (this.invalidHandleClasses[i] == cssClass) { delete this.invalidHandleClasses[i]; } } }, /** * Checks the tag exclusion list to see if this click should be ignored * @method isValidHandleChild * @param {HTMLElement} node the HTMLElement to evaluate * @return {boolean} true if this is a valid tag type, false if not */ isValidHandleChild: function(node) { var valid = true; // var n = (node.nodeName == "#text") ? node.parentNode : node; var nodeName; try { nodeName = node.nodeName.toUpperCase(); } catch(e) { nodeName = node.nodeName; } valid = valid && !this.invalidHandleTypes[nodeName]; valid = valid && !this.invalidHandleIds[node.id]; for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) { valid = !Dom.hasClass(node, this.invalidHandleClasses[i]); } return valid; }, /** * Create the array of horizontal tick marks if an interval was specified * in setXConstraint(). * @method setXTicks * @private */ setXTicks: function(iStartX, iTickSize) { this.xTicks = []; this.xTickSize = iTickSize; var tickMap = {}; for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) { if (!tickMap[i]) { this.xTicks[this.xTicks.length] = i; tickMap[i] = true; } } this.xTicks.sort(this.DDM.numericSort) ; }, /** * Create the array of vertical tick marks if an interval was specified in * setYConstraint(). * @method setYTicks * @private */ setYTicks: function(iStartY, iTickSize) { this.yTicks = []; this.yTickSize = iTickSize; var tickMap = {}; for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) { if (!tickMap[i]) { this.yTicks[this.yTicks.length] = i; tickMap[i] = true; } } this.yTicks.sort(this.DDM.numericSort) ; }, /** * By default, the element can be dragged any place on the screen. Use * this method to limit the horizontal travel of the element. Pass in * 0,0 for the parameters if you want to lock the drag to the y axis. * @method setXConstraint * @param {int} iLeft the number of pixels the element can move to the left * @param {int} iRight the number of pixels the element can move to the * right * @param {int} iTickSize optional parameter for specifying that the * element * should move iTickSize pixels at a time. */ setXConstraint: function(iLeft, iRight, iTickSize) { this.leftConstraint = parseInt(iLeft, 10); this.rightConstraint = parseInt(iRight, 10); this.minX = this.initPageX - this.leftConstraint; this.maxX = this.initPageX + this.rightConstraint; if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); } this.constrainX = true; }, /** * Clears any constraints applied to this instance. Also clears ticks * since they can't exist independent of a constraint at this time. * @method clearConstraints */ clearConstraints: function() { this.constrainX = false; this.constrainY = false; this.clearTicks(); }, /** * Clears any tick interval defined for this instance * @method clearTicks */ clearTicks: function() { this.xTicks = null; this.yTicks = null; this.xTickSize = 0; this.yTickSize = 0; }, /** * By default, the element can be dragged any place on the screen. Set * this to limit the vertical travel of the element. Pass in 0,0 for the * parameters if you want to lock the drag to the x axis. * @method setYConstraint * @param {int} iUp the number of pixels the element can move up * @param {int} iDown the number of pixels the element can move down * @param {int} iTickSize optional parameter for specifying that the * element should move iTickSize pixels at a time. */ setYConstraint: function(iUp, iDown, iTickSize) { this.topConstraint = parseInt(iUp, 10); this.bottomConstraint = parseInt(iDown, 10); this.minY = this.initPageY - this.topConstraint; this.maxY = this.initPageY + this.bottomConstraint; if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); } this.constrainY = true; }, /** * resetConstraints must be called if you manually reposition a dd element. * @method resetConstraints */ resetConstraints: function() { // Maintain offsets if necessary if (this.initPageX || this.initPageX === 0) { // figure out how much this thing has moved var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0; var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0; this.setInitPosition(dx, dy); // This is the first time we have detected the element's position } else { this.setInitPosition(); } if (this.constrainX) { this.setXConstraint( this.leftConstraint, this.rightConstraint, this.xTickSize ); } if (this.constrainY) { this.setYConstraint( this.topConstraint, this.bottomConstraint, this.yTickSize ); } }, /** * Normally the drag element is moved pixel by pixel, but we can specify * that it move a number of pixels at a time. This method resolves the * location when we have it set up like this. * @method getTick * @param {int} val where we want to place the object * @param {int[]} tickArray sorted array of valid points * @return {int} the closest tick * @private */ getTick: function(val, tickArray) { if (!tickArray) { // If tick interval is not defined, it is effectively 1 pixel, // so we return the value passed to us. return val; } else if (tickArray[0] >= val) { // The value is lower than the first tick, so we return the first // tick. return tickArray[0]; } else { for (var i=0, len=tickArray.length; i<len; ++i) { var next = i + 1; if (tickArray[next] && tickArray[next] >= val) { var diff1 = val - tickArray[i]; var diff2 = tickArray[next] - val; return (diff2 > diff1) ? tickArray[i] : tickArray[next]; } } // The value is larger than the last tick, so we return the last // tick. return tickArray[tickArray.length - 1]; } }, /** * toString method * @method toString * @return {string} string representation of the dd obj */ toString: function() { return ("DragDrop " + this.id); } }; YAHOO.augment(YAHOO.util.DragDrop, YAHOO.util.EventProvider); /** * @event mouseDownEvent * @description Provides access to the mousedown event. The mousedown does not always result in a drag operation. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4MouseDownEvent * @description Provides access to the mousedown event, before the mouseDownEvent gets fired. Returning false will cancel the drag. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event mouseUpEvent * @description Fired from inside DragDropMgr when the drag operation is finished. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4StartDragEvent * @description Fires before the startDragEvent, returning false will cancel the startDrag Event. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event startDragEvent * @description Occurs after a mouse down and the drag threshold has been met. The drag threshold default is either 3 pixels of mouse movement or 1 full second of holding the mousedown. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4EndDragEvent * @description Fires before the endDragEvent. Returning false will cancel. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event endDragEvent * @description Fires on the mouseup event after a drag has been initiated (startDrag fired). * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragEvent * @description Occurs every mousemove event while dragging. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragEvent * @description Fires before the dragEvent. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event invalidDropEvent * @description Fires when the dragged objects is dropped in a location that contains no drop targets. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragOutEvent * @description Fires before the dragOutEvent * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragOutEvent * @description Fires when a dragged object is no longer over an object that had the onDragEnter fire. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragEnterEvent * @description Occurs when the dragged object first interacts with another targettable drag and drop object. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragOverEvent * @description Fires before the dragOverEvent. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragOverEvent * @description Fires every mousemove event while over a drag and drop object. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragDropEvent * @description Fires before the dragDropEvent * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragDropEvent * @description Fires when the dragged objects is dropped on another. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ })(); /** * A DragDrop implementation where the linked element follows the * mouse cursor during a drag. * @class DD * @extends YAHOO.util.DragDrop * @constructor * @param {String} id the id of the linked element * @param {String} sGroup the group of related DragDrop items * @param {object} config an object containing configurable attributes * Valid properties for DD: * scroll */ YAHOO.util.DD = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); } }; YAHOO.extend(YAHOO.util.DD, YAHOO.util.DragDrop, { /** * When set to true, the utility automatically tries to scroll the browser * window when a drag and drop element is dragged near the viewport boundary. * Defaults to true. * @property scroll * @type boolean */ scroll: true, /** * Sets the pointer offset to the distance between the linked element's top * left corner and the location the element was clicked * @method autoOffset * @param {int} iPageX the X coordinate of the click * @param {int} iPageY the Y coordinate of the click */ autoOffset: function(iPageX, iPageY) { var x = iPageX - this.startPageX; var y = iPageY - this.startPageY; this.setDelta(x, y); }, /** * Sets the pointer offset. You can call this directly to force the * offset to be in a particular location (e.g., pass in 0,0 to set it * to the center of the object, as done in YAHOO.widget.Slider) * @method setDelta * @param {int} iDeltaX the distance from the left * @param {int} iDeltaY the distance from the top */ setDelta: function(iDeltaX, iDeltaY) { this.deltaX = iDeltaX; this.deltaY = iDeltaY; }, /** * Sets the drag element to the location of the mousedown or click event, * maintaining the cursor location relative to the location on the element * that was clicked. Override this if you want to place the element in a * location other than where the cursor is. * @method setDragElPos * @param {int} iPageX the X coordinate of the mousedown or drag event * @param {int} iPageY the Y coordinate of the mousedown or drag event */ setDragElPos: function(iPageX, iPageY) { // the first time we do this, we are going to check to make sure // the element has css positioning var el = this.getDragEl(); this.alignElWithMouse(el, iPageX, iPageY); }, /** * Sets the element to the location of the mousedown or click event, * maintaining the cursor location relative to the location on the element * that was clicked. Override this if you want to place the element in a * location other than where the cursor is. * @method alignElWithMouse * @param {HTMLElement} el the element to move * @param {int} iPageX the X coordinate of the mousedown or drag event * @param {int} iPageY the Y coordinate of the mousedown or drag event */ alignElWithMouse: function(el, iPageX, iPageY) { var oCoord = this.getTargetCoord(iPageX, iPageY); if (!this.deltaSetXY) { var aCoord = [oCoord.x, oCoord.y]; YAHOO.util.Dom.setXY(el, aCoord); var newLeft = parseInt( YAHOO.util.Dom.getStyle(el, "left"), 10 ); var newTop = parseInt( YAHOO.util.Dom.getStyle(el, "top" ), 10 ); this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ]; } else { YAHOO.util.Dom.setStyle(el, "left", (oCoord.x + this.deltaSetXY[0]) + "px"); YAHOO.util.Dom.setStyle(el, "top", (oCoord.y + this.deltaSetXY[1]) + "px"); } this.cachePosition(oCoord.x, oCoord.y); var self = this; setTimeout(function() { self.autoScroll.call(self, oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth); }, 0); }, /** * Saves the most recent position so that we can reset the constraints and * tick marks on-demand. We need to know this so that we can calculate the * number of pixels the element is offset from its original position. * @method cachePosition * @param iPageX the current x position (optional, this just makes it so we * don't have to look it up again) * @param iPageY the current y position (optional, this just makes it so we * don't have to look it up again) */ cachePosition: function(iPageX, iPageY) { if (iPageX) { this.lastPageX = iPageX; this.lastPageY = iPageY; } else { var aCoord = YAHOO.util.Dom.getXY(this.getEl()); this.lastPageX = aCoord[0]; this.lastPageY = aCoord[1]; } }, /** * Auto-scroll the window if the dragged object has been moved beyond the * visible window boundary. * @method autoScroll * @param {int} x the drag element's x position * @param {int} y the drag element's y position * @param {int} h the height of the drag element * @param {int} w the width of the drag element * @private */ autoScroll: function(x, y, h, w) { if (this.scroll) { // The client height var clientH = this.DDM.getClientHeight(); // The client width var clientW = this.DDM.getClientWidth(); // The amt scrolled down var st = this.DDM.getScrollTop(); // The amt scrolled right var sl = this.DDM.getScrollLeft(); // Location of the bottom of the element var bot = h + y; // Location of the right of the element var right = w + x; // The distance from the cursor to the bottom of the visible area, // adjusted so that we don't scroll if the cursor is beyond the // element drag constraints var toBot = (clientH + st - y - this.deltaY); // The distance from the cursor to the right of the visible area var toRight = (clientW + sl - x - this.deltaX); // How close to the edge the cursor must be before we scroll // var thresh = (document.all) ? 100 : 40; var thresh = 40; // How many pixels to scroll per autoscroll op. This helps to reduce // clunky scrolling. IE is more sensitive about this ... it needs this // value to be higher. var scrAmt = (document.all) ? 80 : 30; // Scroll down if we are near the bottom of the visible page and the // obj extends below the crease if ( bot > clientH && toBot < thresh ) { window.scrollTo(sl, st + scrAmt); } // Scroll up if the window is scrolled down and the top of the object // goes above the top border if ( y < st && st > 0 && y - st < thresh ) { window.scrollTo(sl, st - scrAmt); } // Scroll right if the obj is beyond the right border and the cursor is // near the border. if ( right > clientW && toRight < thresh ) { window.scrollTo(sl + scrAmt, st); } // Scroll left if the window has been scrolled to the right and the obj // extends past the left border if ( x < sl && sl > 0 && x - sl < thresh ) { window.scrollTo(sl - scrAmt, st); } } }, /* * Sets up config options specific to this class. Overrides * YAHOO.util.DragDrop, but all versions of this method through the * inheritance chain are called */ applyConfig: function() { YAHOO.util.DD.superclass.applyConfig.call(this); this.scroll = (this.config.scroll !== false); }, /* * Event that fires prior to the onMouseDown event. Overrides * YAHOO.util.DragDrop. */ b4MouseDown: function(e) { this.setStartPosition(); // this.resetConstraints(); this.autoOffset(YAHOO.util.Event.getPageX(e), YAHOO.util.Event.getPageY(e)); }, /* * Event that fires prior to the onDrag event. Overrides * YAHOO.util.DragDrop. */ b4Drag: function(e) { this.setDragElPos(YAHOO.util.Event.getPageX(e), YAHOO.util.Event.getPageY(e)); }, toString: function() { return ("DD " + this.id); } ////////////////////////////////////////////////////////////////////////// // Debugging ygDragDrop events that can be overridden ////////////////////////////////////////////////////////////////////////// /* startDrag: function(x, y) { }, onDrag: function(e) { }, onDragEnter: function(e, id) { }, onDragOver: function(e, id) { }, onDragOut: function(e, id) { }, onDragDrop: function(e, id) { }, endDrag: function(e) { } */ /** * @event mouseDownEvent * @description Provides access to the mousedown event. The mousedown does not always result in a drag operation. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4MouseDownEvent * @description Provides access to the mousedown event, before the mouseDownEvent gets fired. Returning false will cancel the drag. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event mouseUpEvent * @description Fired from inside DragDropMgr when the drag operation is finished. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4StartDragEvent * @description Fires before the startDragEvent, returning false will cancel the startDrag Event. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event startDragEvent * @description Occurs after a mouse down and the drag threshold has been met. The drag threshold default is either 3 pixels of mouse movement or 1 full second of holding the mousedown. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4EndDragEvent * @description Fires before the endDragEvent. Returning false will cancel. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event endDragEvent * @description Fires on the mouseup event after a drag has been initiated (startDrag fired). * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragEvent * @description Occurs every mousemove event while dragging. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragEvent * @description Fires before the dragEvent. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event invalidDropEvent * @description Fires when the dragged objects is dropped in a location that contains no drop targets. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragOutEvent * @description Fires before the dragOutEvent * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragOutEvent * @description Fires when a dragged object is no longer over an object that had the onDragEnter fire. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragEnterEvent * @description Occurs when the dragged object first interacts with another targettable drag and drop object. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragOverEvent * @description Fires before the dragOverEvent. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragOverEvent * @description Fires every mousemove event while over a drag and drop object. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragDropEvent * @description Fires before the dragDropEvent * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragDropEvent * @description Fires when the dragged objects is dropped on another. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ }); /** * A DragDrop implementation that inserts an empty, bordered div into * the document that follows the cursor during drag operations. At the time of * the click, the frame div is resized to the dimensions of the linked html * element, and moved to the exact location of the linked element. * * References to the "frame" element refer to the single proxy element that * was created to be dragged in place of all DDProxy elements on the * page. * * @class DDProxy * @extends YAHOO.util.DD * @constructor * @param {String} id the id of the linked html element * @param {String} sGroup the group of related DragDrop objects * @param {object} config an object containing configurable attributes * Valid properties for DDProxy in addition to those in DragDrop: * resizeFrame, centerFrame, dragElId */ YAHOO.util.DDProxy = function(id, sGroup, config) { if (id) { this.init(id, sGroup, config); this.initFrame(); } }; /** * The default drag frame div id * @property YAHOO.util.DDProxy.dragElId * @type String * @static */ YAHOO.util.DDProxy.dragElId = "ygddfdiv"; YAHOO.extend(YAHOO.util.DDProxy, YAHOO.util.DD, { /** * By default we resize the drag frame to be the same size as the element * we want to drag (this is to get the frame effect). We can turn it off * if we want a different behavior. * @property resizeFrame * @type boolean */ resizeFrame: true, /** * By default the frame is positioned exactly where the drag element is, so * we use the cursor offset provided by YAHOO.util.DD. Another option that works only if * you do not have constraints on the obj is to have the drag frame centered * around the cursor. Set centerFrame to true for this effect. * @property centerFrame * @type boolean */ centerFrame: false, /** * Creates the proxy element if it does not yet exist * @method createFrame */ createFrame: function() { var self=this, body=document.body; if (!body || !body.firstChild) { setTimeout( function() { self.createFrame(); }, 50 ); return; } var div=this.getDragEl(), Dom=YAHOO.util.Dom; if (!div) { div = document.createElement("div"); div.id = this.dragElId; var s = div.style; s.position = "absolute"; s.visibility = "hidden"; s.cursor = "move"; s.border = "2px solid #aaa"; s.zIndex = 999; s.height = "25px"; s.width = "25px"; var _data = document.createElement('div'); Dom.setStyle(_data, 'height', '100%'); Dom.setStyle(_data, 'width', '100%'); /** * If the proxy element has no background-color, then it is considered to the "transparent" by Internet Explorer. * Since it is "transparent" then the events pass through it to the iframe below. * So creating a "fake" div inside the proxy element and giving it a background-color, then setting it to an * opacity of 0, it appears to not be there, however IE still thinks that it is so the events never pass through. */ Dom.setStyle(_data, 'background-color', '#ccc'); Dom.setStyle(_data, 'opacity', '0'); div.appendChild(_data); /** * It seems that IE will fire the mouseup event if you pass a proxy element over a select box * Placing the IFRAME element inside seems to stop this issue */ if (YAHOO.env.ua.ie) { //Only needed for Internet Explorer var ifr = document.createElement('iframe'); ifr.setAttribute('src', 'javascript: false;'); ifr.setAttribute('scrolling', 'no'); ifr.setAttribute('frameborder', '0'); div.insertBefore(ifr, div.firstChild); Dom.setStyle(ifr, 'height', '100%'); Dom.setStyle(ifr, 'width', '100%'); Dom.setStyle(ifr, 'position', 'absolute'); Dom.setStyle(ifr, 'top', '0'); Dom.setStyle(ifr, 'left', '0'); Dom.setStyle(ifr, 'opacity', '0'); Dom.setStyle(ifr, 'zIndex', '-1'); Dom.setStyle(ifr.nextSibling, 'zIndex', '2'); } // appendChild can blow up IE if invoked prior to the window load event // while rendering a table. It is possible there are other scenarios // that would cause this to happen as well. body.insertBefore(div, body.firstChild); } }, /** * Initialization for the drag frame element. Must be called in the * constructor of all subclasses * @method initFrame */ initFrame: function() { this.createFrame(); }, applyConfig: function() { YAHOO.util.DDProxy.superclass.applyConfig.call(this); this.resizeFrame = (this.config.resizeFrame !== false); this.centerFrame = (this.config.centerFrame); this.setDragElId(this.config.dragElId || YAHOO.util.DDProxy.dragElId); }, /** * Resizes the drag frame to the dimensions of the clicked object, positions * it over the object, and finally displays it * @method showFrame * @param {int} iPageX X click position * @param {int} iPageY Y click position * @private */ showFrame: function(iPageX, iPageY) { var el = this.getEl(); var dragEl = this.getDragEl(); var s = dragEl.style; this._resizeProxy(); if (this.centerFrame) { this.setDelta( Math.round(parseInt(s.width, 10)/2), Math.round(parseInt(s.height, 10)/2) ); } this.setDragElPos(iPageX, iPageY); YAHOO.util.Dom.setStyle(dragEl, "visibility", "visible"); }, /** * The proxy is automatically resized to the dimensions of the linked * element when a drag is initiated, unless resizeFrame is set to false * @method _resizeProxy * @private */ _resizeProxy: function() { if (this.resizeFrame) { var DOM = YAHOO.util.Dom; var el = this.getEl(); var dragEl = this.getDragEl(); var bt = parseInt( DOM.getStyle(dragEl, "borderTopWidth" ), 10); var br = parseInt( DOM.getStyle(dragEl, "borderRightWidth" ), 10); var bb = parseInt( DOM.getStyle(dragEl, "borderBottomWidth" ), 10); var bl = parseInt( DOM.getStyle(dragEl, "borderLeftWidth" ), 10); if (isNaN(bt)) { bt = 0; } if (isNaN(br)) { br = 0; } if (isNaN(bb)) { bb = 0; } if (isNaN(bl)) { bl = 0; } var newWidth = Math.max(0, el.offsetWidth - br - bl); var newHeight = Math.max(0, el.offsetHeight - bt - bb); DOM.setStyle( dragEl, "width", newWidth + "px" ); DOM.setStyle( dragEl, "height", newHeight + "px" ); } }, // overrides YAHOO.util.DragDrop b4MouseDown: function(e) { this.setStartPosition(); var x = YAHOO.util.Event.getPageX(e); var y = YAHOO.util.Event.getPageY(e); this.autoOffset(x, y); // This causes the autoscroll code to kick off, which means autoscroll can // happen prior to the check for a valid drag handle. // this.setDragElPos(x, y); }, // overrides YAHOO.util.DragDrop b4StartDrag: function(x, y) { // show the drag frame this.showFrame(x, y); }, // overrides YAHOO.util.DragDrop b4EndDrag: function(e) { YAHOO.util.Dom.setStyle(this.getDragEl(), "visibility", "hidden"); }, // overrides YAHOO.util.DragDrop // By default we try to move the element to the last location of the frame. // This is so that the default behavior mirrors that of YAHOO.util.DD. endDrag: function(e) { var DOM = YAHOO.util.Dom; var lel = this.getEl(); var del = this.getDragEl(); // Show the drag frame briefly so we can get its position // del.style.visibility = ""; DOM.setStyle(del, "visibility", ""); // Hide the linked element before the move to get around a Safari // rendering bug. //lel.style.visibility = "hidden"; DOM.setStyle(lel, "visibility", "hidden"); YAHOO.util.DDM.moveToEl(lel, del); //del.style.visibility = "hidden"; DOM.setStyle(del, "visibility", "hidden"); //lel.style.visibility = ""; DOM.setStyle(lel, "visibility", ""); }, toString: function() { return ("DDProxy " + this.id); } /** * @event mouseDownEvent * @description Provides access to the mousedown event. The mousedown does not always result in a drag operation. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4MouseDownEvent * @description Provides access to the mousedown event, before the mouseDownEvent gets fired. Returning false will cancel the drag. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event mouseUpEvent * @description Fired from inside DragDropMgr when the drag operation is finished. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4StartDragEvent * @description Fires before the startDragEvent, returning false will cancel the startDrag Event. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event startDragEvent * @description Occurs after a mouse down and the drag threshold has been met. The drag threshold default is either 3 pixels of mouse movement or 1 full second of holding the mousedown. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4EndDragEvent * @description Fires before the endDragEvent. Returning false will cancel. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event endDragEvent * @description Fires on the mouseup event after a drag has been initiated (startDrag fired). * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragEvent * @description Occurs every mousemove event while dragging. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragEvent * @description Fires before the dragEvent. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event invalidDropEvent * @description Fires when the dragged objects is dropped in a location that contains no drop targets. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragOutEvent * @description Fires before the dragOutEvent * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragOutEvent * @description Fires when a dragged object is no longer over an object that had the onDragEnter fire. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragEnterEvent * @description Occurs when the dragged object first interacts with another targettable drag and drop object. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragOverEvent * @description Fires before the dragOverEvent. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragOverEvent * @description Fires every mousemove event while over a drag and drop object. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event b4DragDropEvent * @description Fires before the dragDropEvent * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ /** * @event dragDropEvent * @description Fires when the dragged objects is dropped on another. * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. */ }); /** * A DragDrop implementation that does not move, but can be a drop * target. You would get the same result by simply omitting implementation * for the event callbacks, but this way we reduce the processing cost of the * event listener and the callbacks. * @class DDTarget * @extends YAHOO.util.DragDrop * @constructor * @param {String} id the id of the element that is a drop target * @param {String} sGroup the group of related DragDrop objects * @param {object} config an object containing configurable attributes * Valid properties for DDTarget in addition to those in * DragDrop: * none */ YAHOO.util.DDTarget = function(id, sGroup, config) { if (id) { this.initTarget(id, sGroup, config); } }; // YAHOO.util.DDTarget.prototype = new YAHOO.util.DragDrop(); YAHOO.extend(YAHOO.util.DDTarget, YAHOO.util.DragDrop, { toString: function() { return ("DDTarget " + this.id); } }); YAHOO.register("dragdrop", YAHOO.util.DragDropMgr, {version: "2.6.0", build: "1321"}); }, '2.6.0' ,{"requires": ["yui2-yahoo", "yui2-dom", "yui2-event"]});
{ "content_hash": "31a5753ed2b26bc8b5a2b3e9fd7c3ed1", "timestamp": "", "source": "github", "line_count": 3621, "max_line_length": 256, "avg_line_length": 34.16763325048329, "alnum_prop": 0.5602120901059642, "repo_name": "inikoo/fact", "id": "6459bab09eaebe48de2dbc17d88026d233c8f34b", "size": "123874", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libs/yui/yui-2in3/dist/2.6.0/build/yui2-dragdrop/yui2-dragdrop.js", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "18806" }, { "name": "CSS", "bytes": "9907391" }, { "name": "JavaScript", "bytes": "100688322" }, { "name": "PHP", "bytes": "4382356" }, { "name": "Perl", "bytes": "414074" }, { "name": "Python", "bytes": "28243" }, { "name": "Shell", "bytes": "142079" } ], "symlink_target": "" }
package appl.simpleAppl; import java.net.InetAddress; import java.net.UnknownHostException; public class HostName { public String exec(){ try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } }
{ "content_hash": "a09784195643ba3344339ff999a18959", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 51, "avg_line_length": 20.235294117647058, "alnum_prop": 0.6831395348837209, "repo_name": "AndreJCL/JCL", "id": "db0b0178a5f019a17077129c3b3ce41b7047c618", "size": "344", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "JCL_Samples/Jcl_Android_examples/app/src/main/java/appl/simpleAppl/HostName.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "29718" }, { "name": "Batchfile", "bytes": "352" }, { "name": "C", "bytes": "233412" }, { "name": "C++", "bytes": "407461" }, { "name": "CSS", "bytes": "26526" }, { "name": "HTML", "bytes": "2300" }, { "name": "Java", "bytes": "9174474" }, { "name": "JavaScript", "bytes": "3422" }, { "name": "Makefile", "bytes": "514" }, { "name": "Objective-C", "bytes": "4515" }, { "name": "Perl", "bytes": "3605" }, { "name": "Python", "bytes": "8346" }, { "name": "Shell", "bytes": "1097" } ], "symlink_target": "" }
// ========================================================================== // Project: MySystem.NodeView // Copyright: @2011 Concord Consortium // ========================================================================== /*globals MySystem RaphaelViews */ sc_require('views/editable_label'); sc_require('views/terminal'); sc_require('views/remove_button'); /** @class Display class for displaying a Node. Expects its 'content' property to be a MySystem.Node record. @extends SC.RaphaelView */ MySystem.NodeView = RaphaelViews.RaphaelView.extend(SC.ContentDisplay, /** @scope MySystem.NodeView.prototype */ { childViews: 'removeButtonView titleView terminalA terminalB'.w(), contentDisplayProperties: 'x y image title'.w(), displayProperties: 'bodyWidth bodyHeight bodyColor bodyOpacity borderColor borderOpacity borderWidth borderRadius imageWidth imageHeight enableNodeLabelDisplay'.w(), // PROPERTIES isSelected: NO, isDragging: NO, isHovered: NO, verticalMargin: 0, horizontalMargin: 0, bodyWidthBinding: SC.Binding.oneWay("MySystem.activityController.content.nodeWidth"), bodyHeightBinding: SC.Binding.oneWay("MySystem.activityController.content.nodeHeight"), terminalRadiusBinding: SC.Binding.oneWay("MySystem.activityController.content.terminalRadius"), enableNodeLabelDisplayBinding: SC.Binding.oneWay("MySystem.activityController.content.enableNodeLabelDisplay"), bodyColor: '#000000', // the node s/b visually transparent, but not transparent to mouse events, so it must have a fill bodyOpacity: 0, fontSize: 14, // for titleView titleBinding: '*content.title', xBinding: '*content.x', yBinding: '*content.y', centerX: function () { return this.get('x') + this.get('bodyWidth') / 2; }.property('x', 'bodyWidth').cacheable(), titleY: function () { return this.get('y') + this.get('bodyHeight') + this.get('fontSize') + this.get('terminalRadius'); }.property('y', 'bodyHeight').cacheable(), terminalAY: function() { return this.get('y'); // could parameterize this better later }.property('y', 'bodyHeight').cacheable(), terminalBY: function() { return this.get('y') + this.get('bodyHeight'); // could parameterize this better later }.property('y', 'bodyHeight').cacheable(), borderColor: function () { return this.get('isSelected') ? 'rgb(173, 216, 230)' : '#CCCCCC'; }.property('isSelected').cacheable(), borderOpacity: 1.0, borderWidth: function () { return this.get('isSelected') ? 4 : 1; }.property('isSelected'), borderRadius: 5, // place-holder for our rendered raphael image object // this is the nodes 'image'. _raphaelImage: null, // place-holder for our rendered raphael rectangle object // this is the nodes 'border' essentially. _raphaelRect: null, diagramControllerBinding: 'MySystem.nodesController', onlySelectedDiagramObjectBinding: '*diagramController.onlySelectedObject', isOnlySelectedDiagramObject: function () { return this.get('onlySelectedDiagramObject') === this.get('content'); }.property('onlySelectedDiagramObject', 'content'), isRemoveButtonVisible: function () { return this.get('isHovered') || this.get('isOnlySelectedDiagramObject'); }.property('isHovered', 'isOnlySelectedDiagramObject'), // CHILD VIEWS removeButtonView: MySystem.RemoveButtonView.design({ isVisibleBinding: '.parentView.isRemoveButtonVisible', parentBorderColorBinding: '.parentView.borderColor', parentXBinding: '.parentView.x', parentBodyWidthBinding: '.parentView.bodyWidth', normalCircleStrokeBinding: '.parentBorderColor', hoveredCircleStroke: '#666', normalCircleFill: '#FFF', hoveredCircleFill: '#666', normalXStrokeBinding: '.parentBorderColor', hoveredXStroke: '#FFF', cx: function () { return this.get('parentX') + this.get('parentBodyWidth'); }.property('parentX', 'parentBodyWidth'), cyBinding: '.parentView.y' }), titleView: MySystem.EditableLabelView.design({ isEditable: NO, isVisibleBinding: '.parentView.enableNodeLabelDisplay', fontSizeBinding: '.parentView.fontSize', textColor: '#000', textBinding: '.parentView.title', centerXBinding: '.parentView.centerX', centerYBinding: '.parentView.titleY', selectMe: function() { var currentNode = this.getPath('parentView.content'); MySystem.nodesController.unselectAll(); MySystem.nodesController.selectObject(currentNode); }.observes('isEditing') }), terminalA: MySystem.TerminalView.design({ xBinding: '.parentView.centerX', yBinding: '.parentView.terminalAY', radiusBinding: SC.Binding.oneWay(".parentView.terminalRadius"), isVisible: YES }), terminalB: MySystem.TerminalView.design({ xBinding: '.parentView.centerX', yBinding: '.parentView.terminalBY', radiusBinding: SC.Binding.oneWay(".parentView.terminalRadius"), isVisible: YES }), // RENDER METHODS renderCallback: function (raphaelCanvas, attrs,imageAttrs) { this._raphaelRect = raphaelCanvas.rect(); this._raphaelImage = raphaelCanvas.image(); this._raphaelRect.attr(attrs); this._raphaelImage.attr(imageAttrs); return raphaelCanvas.set().push(this._raphaelRect,this._raphaelImage); }, render: function (context, firstTime) { var content = this.get('content'); var hMargin = this.get('horizontalMargin'); var vMargin = this.get('verticalMargin'); if (firstTime) { // when we first load this image, create a new Image object so we can inspect // the actual width and height, and then scale the rendered image appropriately // while keeping the aspect ratio var image = new Image(); var self = this; image.onload = function() { self.setImageDimensions(image); }; image.src = content.get('image'); } var attrs = { 'x': content.get('x'), 'y': content.get('y'), 'r': this.get('borderRadius'), 'width': this.get('bodyWidth'), 'height': this.get('bodyHeight'), 'fill': this.get('bodyColor'), 'fill-opacity': this.get('bodyOpacity'), 'stroke': this.get('borderColor'), 'stroke-width': this.get('borderWidth'), 'stroke-opacity': this.get('borderOpacity') }, imageAttrs = { src: content.get('image'), x: hMargin + content.get('x'), // +((hMargin-this.get('imageWidth'))/2), // center narrow images y: content.get('y'),// vMargin + content.get('y'), width: this.get('imageWidth') || 10, height: this.get('imageHeight')|| 10 }; if (firstTime) { context.callback(this, this.renderCallback, attrs, imageAttrs); this.renderChildViews(context,firstTime); } else { this._raphaelRect.attr(attrs); this._raphaelImage.attr(imageAttrs); } }, setImageDimensions: function (image) { image.onload = null; if (image.width > 1){ var bodyWidth = this.get('bodyWidth'), bodyHeight = this.get('bodyHeight'), targetWidth = bodyWidth * 0.9, targetHeight = bodyHeight * 0.9, srcWidth = image.width, srcHeight = image.height, scaledHeight = (targetHeight / srcHeight), scaledWidth = (targetWidth / srcWidth), scalar = scaledWidth < scaledHeight ? scaledWidth : scaledHeight, newWidth = srcWidth * scalar, newHeight = srcHeight * scalar, hMargin = (bodyWidth - newWidth) / 2, vMargin = (bodyHeight - newHeight) / 2; SC.RunLoop.begin(); this.set('imageWidth', newWidth); this.set('imageHeight', newHeight); this.set('horizontalMargin', hMargin); this.set('verticalMargin', vMargin); SC.RunLoop.end(); } }, // EVENT METHODS GO HERE: mouseEntered: function () { this.set('isHovered', YES); return YES; }, mouseExited: function () { this.set('isHovered', NO); return YES; }, removeButtonClicked: function () { MySystem.statechart.sendAction('deleteDiagramObject', this, this.get('content')); return YES; } }); MySystem.NodeView.mixin({ DROP_OFFSET: {x: 21, y: 16} });
{ "content_hash": "b6689e32213eabdbe57fcaf2ceaf2b8a", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 167, "avg_line_length": 33.39922480620155, "alnum_prop": 0.6275966113496576, "repo_name": "concord-consortium/mysystem_sc", "id": "9c32a434ae768fbfe2e1aa8028ff298f91faf67c", "size": "8617", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/my_system/views/node.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "2251" }, { "name": "JavaScript", "bytes": "1751386" }, { "name": "Ruby", "bytes": "38251" }, { "name": "Shell", "bytes": "2460" } ], "symlink_target": "" }
package co.tyec.selenium.extjswebdriver; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; /** * @author Asaf Levy * @version $Revision: 1.0 */ public class Menu extends ExtJSComponent { public Menu(WebDriver driver, By by) { super(driver, by); } public Menu(WebDriver driver, WebElement topElement) { super(driver, topElement); } /** * Method click. * * @param itemKey * String */ public void click(final String itemKey) { final String id = String.valueOf(execScriptOnExtJsCmp("el.items.items[" + getExpression() + ".items.indexOfKey('" + itemKey + "')].el.dom.id")); driver.findElement(By.xpath("//*[@id='" + id + "']")).click(); } /** * Method click. * * @param propName * String * @param propValue * String */ public void click(final String propName, final String propValue) { final String id = String.valueOf(execScriptOnExtJsCmp("return extCmp.items.items[" + getExpression() + ".items.findIndex('" + propName + "', '" + propValue + "')].el.dom.id")); topElement.findElement(By.xpath("//*[@id='" + id + "']")).click(); } }
{ "content_hash": "41998823f8cff10029fadc47882f1cee", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 131, "avg_line_length": 25.826923076923077, "alnum_prop": 0.5621742367833209, "repo_name": "tayloryork/SeleniumExtend", "id": "3857f4c30273b4a12f97b361452adae1aa81d684", "size": "1343", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/co/tyec/selenium/extjswebdriver/Menu.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "57" }, { "name": "HTML", "bytes": "588" }, { "name": "Java", "bytes": "98911" }, { "name": "JavaScript", "bytes": "3343041" } ], "symlink_target": "" }
namespace Google.Cloud.SecretManager.V1.Snippets { // [START secretmanager_v1_generated_SecretManagerService_UpdateSecret_async_flattened] using Google.Cloud.SecretManager.V1; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; public sealed partial class GeneratedSecretManagerServiceClientSnippets { /// <summary>Snippet for UpdateSecretAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task UpdateSecretAsync() { // Create client SecretManagerServiceClient secretManagerServiceClient = await SecretManagerServiceClient.CreateAsync(); // Initialize request argument(s) Secret secret = new Secret(); FieldMask updateMask = new FieldMask(); // Make the request Secret response = await secretManagerServiceClient.UpdateSecretAsync(secret, updateMask); } } // [END secretmanager_v1_generated_SecretManagerService_UpdateSecret_async_flattened] }
{ "content_hash": "88e5d9736cd83768e0c60f6b6c722ead", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 115, "avg_line_length": 44.148148148148145, "alnum_prop": 0.6921140939597316, "repo_name": "jskeet/gcloud-dotnet", "id": "8d3e32592f6ae3c44250ea58a44bbe412c37d81a", "size": "1814", "binary": false, "copies": "2", "ref": "refs/heads/bq-migration", "path": "apis/Google.Cloud.SecretManager.V1/Google.Cloud.SecretManager.V1.GeneratedSnippets/SecretManagerServiceClient.UpdateSecretAsyncSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1725" }, { "name": "C#", "bytes": "1829733" } ], "symlink_target": "" }
/** * Example showing how to upload a file using a `Curl` instance using http method `PUT` * But now instead of passing the file descriptor as the `READDATA` option, we will use the * `READFUNCTION` option. */ const path = require('path') const fs = require('fs') const crypto = require('crypto') const { Curl } = require('../dist') const curl = new Curl() const url = 'httpbin.org/put' const fileSize = 64 * 1024 //64KB const fileName = path.resolve(__dirname, 'upload.test') // write random bytes to a file, this will be our upload file. fs.writeFileSync(fileName, crypto.randomBytes(fileSize)) console.log('File Size: ', fs.statSync(fileName).size) console.log('\n'.repeat(5)) const stream = fs.createReadStream(fileName) stream.on('ready', () => { // enabling VERBOSE mode so we can get more details on what is going on. curl.setOpt(Curl.option.VERBOSE, true) // set UPLOAD to a truthy value to enable PUT upload. curl.setOpt(Curl.option.UPLOAD, true) // this is not required, but it let us tell libcurl // the amount of data we are going to send // If we don't specify this, libcurl will keep calling our READFUNCTION // until we return 0 from it. You can test that commenting this line. curl.setOpt(Curl.option.INFILESIZE, fileSize) // the internal upload buffer is by default 64kb, let's set it to 16 which is the minimum possible curl.setOpt(Curl.option.UPLOAD_BUFFERSIZE, 19 * 1024) curl.setOpt(Curl.option.READFUNCTION, (buffer, size, nmemb) => { const amountToRead = size * nmemb console.log(`There are ${stream.readableLength} bytes ready to be read`) console.log(`Trying to read ${amountToRead} bytes`) const data = stream.read(amountToRead) if (!data) { console.log('No data remaining in the stream') return 0 } console.log(`Read ${data.length} bytes`) const totalWritten = data.copy(buffer) console.log(`Written ${data.length} bytes`) // we could also return CurlReadFunc.Abort or CurlReadFunc.Pause here. return totalWritten }) curl.setOpt(Curl.option.URL, url) curl.on('end', function (statusCode, body) { console.log('Response from httpbin:') console.log({ statusCode, body: JSON.parse(body), }) fs.unlinkSync(fileName) this.close() }) curl.on('error', function (error, errorCode) { console.log(error, errorCode) fs.unlinkSync(fileName) this.close() }) curl.perform() })
{ "content_hash": "ac779ef0b325a025b52666dd321cba78", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 100, "avg_line_length": 28.58139534883721, "alnum_prop": 0.6875508543531327, "repo_name": "JCMais/node-libcurl", "id": "5698e8f761775fcfbc743cd68a7c3d0b9388c103", "size": "2658", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "examples/08-file-upload-stream.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "642" }, { "name": "C++", "bytes": "168541" }, { "name": "Dockerfile", "bytes": "551" }, { "name": "HTML", "bytes": "599" }, { "name": "JavaScript", "bytes": "45289" }, { "name": "PowerShell", "bytes": "895" }, { "name": "Python", "bytes": "9040" }, { "name": "Shell", "bytes": "50032" }, { "name": "TypeScript", "bytes": "560143" } ], "symlink_target": "" }
<?xml version='1.0'?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.activemq.examples.broker</groupId> <artifactId>jms-examples</artifactId> <version>2.18.0-SNAPSHOT</version> </parent> <artifactId>http-transport</artifactId> <packaging>jar</packaging> <name>ActiveMQ Artemis JMS Http Transport Example</name> <properties> <activemq.basedir>${project.basedir}/../../../..</activemq.basedir> </properties> <dependencies> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>artemis-jms-client-all</artifactId> <version>${project.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.activemq</groupId> <artifactId>artemis-maven-plugin</artifactId> <executions> <execution> <id>create</id> <goals> <goal>create</goal> </goals> <configuration> <ignore>${noServer}</ignore> <configuration>${basedir}/target/classes/activemq/server0</configuration> </configuration> </execution> <execution> <id>start</id> <goals> <goal>cli</goal> </goals> <configuration> <ignore>${noServer}</ignore> <spawn>true</spawn> <testURI>tcp://localhost:8080?http-enabled=true</testURI> <args> <param>run</param> </args> </configuration> </execution> <execution> <id>runClient</id> <goals> <goal>runClient</goal> </goals> <configuration> <clientClass>org.apache.activemq.artemis.jms.example.HttpTransportExample</clientClass> </configuration> </execution> <execution> <id>stop</id> <goals> <goal>cli</goal> </goals> <configuration> <ignore>${noServer}</ignore> <args> <param>stop</param> </args> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>org.apache.activemq.examples.broker</groupId> <artifactId>http-transport</artifactId> <version>${project.version}</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> </plugin> </plugins> </build> </project>
{ "content_hash": "17d3d1abdfd20b559a070dea9c144390", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 201, "avg_line_length": 36.267857142857146, "alnum_prop": 0.5384047267355982, "repo_name": "jbertram/activemq-artemis", "id": "5109c701461939631294ec4106f5bf04e131b1e0", "size": "4062", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "examples/features/standard/http-transport/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7894" }, { "name": "CSS", "bytes": "66196" }, { "name": "Groovy", "bytes": "169650" }, { "name": "HTML", "bytes": "28321" }, { "name": "Java", "bytes": "32261402" }, { "name": "JavaScript", "bytes": "252799" }, { "name": "Shell", "bytes": "40937" } ], "symlink_target": "" }
<!-- Copyright 2005-2008 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://stlab.adobe.com/licenses.html) Some files are held under additional license. Please see "http://stlab.adobe.com/licenses.html" for more information. --> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <TITLE>Adobe Software Technology Lab: Selection</TITLE> <META HTTP-EQUIV="content-type" CONTENT="text/html;charset=ISO-8859-1"/> <LINK TYPE="text/css" REL="stylesheet" HREF="adobe_source.css"/> <LINK REL="alternate" TITLE="stlab.adobe.com RSS" HREF="http://sourceforge.net/export/rss2_projnews.php?group_id=132417&amp;rss_fulltext=1" TYPE="application/rss+xml"/> <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script> </head> <body> <div id='content'> <table><tr> <td colspan='5'> <div id='opensource_banner'> <table style='width: 100%; padding: 5px;'><tr> <td align='left'> <a href='index.html' style='border: none'><img src='stlab2007.jpg' alt="stlab.adobe.com"/></a> </td> <td align='right'> <a href='http://www.adobe.com' style='border: none'><img src='adobe_hlogo.gif' alt="Adobe Systems Incorporated"/></a> </td> </tr></table> </div> </td></tr><tr> <td valign="top"> <div id='navtable' height='100%'> <div style='margin: 5px'> <h4>Documentation</h4> <a href="group__asl__overview.html">Overview</a><br/> <a href="asl_readme.html">Building ASL</a><br/> <a href="asl_toc.html">Documentation</a><br/> <a href="http://stlab.adobe.com/wiki/index.php/Supplementary_ASL_Documentation">Library Wiki Docs</a><br/> <a href="asl_indices.html">Indices</a><br/> <a href="http://stlab.adobe.com/perforce/">Browse Perforce</a><br/> <h4>More Info</h4> <a href="asl_release_notes.html">Release Notes</a><br/> <a href="http://stlab.adobe.com/wiki/">Wiki</a><br/> <a href="asl_search.html">Site Search</a><br/> <a href="licenses.html">License</a><br/> <a href="success_stories.html">Success Stories</a><br/> <a href="asl_contributors.html">Contributors</a><br/> <h4>Media</h4> <a href="http://sourceforge.net/project/showfiles.php?group_id=132417&amp;package_id=145420">Download</a><br/> <a href="asl_download_perforce.html">Perforce Depots</a><br/> <h4>Support</h4> <a href="http://sourceforge.net/projects/adobe-source/">ASL SourceForge Home</a><br/> <a href="http://sourceforge.net/mail/?group_id=132417">Mailing Lists</a><br/> <a href="http://sourceforge.net/forum/?group_id=132417">Discussion Forums</a><br/> <a href="http://sourceforge.net/tracker/?atid=724218&amp;group_id=132417&amp;func=browse">Report Bugs</a><br/> <a href="http://sourceforge.net/tracker/?atid=724221&amp;group_id=132417&amp;func=browse">Suggest Features</a><br/> <a href="asl_contributing.html">Contribute to ASL</a><br/> <h4>RSS</h4> <a href="http://sourceforge.net/export/rss2_projnews.php?group_id=132417">Short-text news</a><br/> <a href="http://sourceforge.net/export/rss2_projnews.php?group_id=132417&amp;rss_fulltext=1">Full-text news</a><br/> <a href="http://sourceforge.net/export/rss2_projfiles.php?group_id=132417">File releases</a><br/> <h4>Other Adobe Projects</h4> <a href="http://sourceforge.net/adobe/">Open @ Adobe</a><br/> <a href="http://opensource.adobe.com/">Adobe Open Source</a><br/> <a href="http://labs.adobe.com/">Adobe Labs</a><br/> <a href="http://stlab.adobe.com/amg/">Adobe Media Gallery</a><br/> <a href="http://stlab.adobe.com/performance/">C++ Benchmarks</a><br/> <h4>Other Resources</h4> <a href="http://boost.org">Boost</a><br/> <a href="http://www.riaforge.com/">RIAForge</a><br/> <a href="http://www.sgi.com/tech/stl">SGI STL</a><br/> </div> </div> </td> <td id='maintable' width="100%" valign="top"> <!-- End Header --> <!-- Generated by Doxygen 1.7.2 --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> </div> <div class="headertitle"> <h1>Selection<br/> <small> [<a class="el" href="group__asl__libraries.html">Libraries</a>]</small> </h1> </div> </div> <div class="contents"> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="nested-classes"></a> Classes</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classadobe_1_1selection__t.html">selection_t</a></td></tr> <tr><td class="mdescLeft">&#160;</td><td class="mdescRight">A container used to represent a linear boolean selection. <a href="classadobe_1_1selection__t.html#_details">More...</a><br/></td></tr> </table> </div> <!-- Begin Footer --> </td></tr> </table> </div> <!-- content --> <div class='footerdiv'> <div id='footersub'> <ul> <li><a href="http://www.adobe.com/go/gftray_foot_aboutadobe">Company</a>&nbsp;|&nbsp;</li> <li><a href="http://www.adobe.com/go/gftray_foot_privacy_security">Online Privacy Policy</a>&nbsp;|&nbsp;</li> <li><a href="http://www.adobe.com/go/gftray_foot_terms">Terms of Use</a>&nbsp;|&nbsp;</li> <li><a href="http://www.adobe.com/go/gftray_foot_contact_adobe">Contact Us</a>&nbsp;|&nbsp;</li> <li><a href="http://www.adobe.com/go/gftray_foot_accessibility">Accessibility</a>&nbsp;|&nbsp;</li> <li><a href="http://www.adobe.com/go/gftray_foot_report_piracy">Report Piracy</a>&nbsp;|&nbsp;</li> <li><a href="http://www.adobe.com/go/gftray_foot_permissions_trademarks">Permissions &amp; Trademarks</a>&nbsp;|&nbsp;</li> <li><a href="http://www.adobe.com/go/gftray_foot_product_license_agreements">Product License Agreements</a>&nbsp;|&nbsp;</li> <li><a href="http://www.adobe.com/go/gftray_foot_feedback">Send Feedback</a></li> </ul> <div> <p>Copyright &#169; 2006-2007 Adobe Systems Incorporated.</p> <p>Use of this website signifies your agreement to the <a href="http://www.adobe.com/go/gftray_foot_terms">Terms of Use</a> and <a href="http://www.adobe.com/go/gftray_foot_privacy_security">Online Privacy Policy</a>.</p> <p>Search powered by <a href="http://www.google.com/" target="new">Google</a></p> </div> </div> </div> <script type="text/javascript"> _uacct = "UA-396569-1"; urchinTracker(); </script> </body> </html>
{ "content_hash": "a879fac9bcc9a537d47f7013491ba69b", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 233, "avg_line_length": 47.64335664335665, "alnum_prop": 0.6289446646117716, "repo_name": "brycelelbach/asl", "id": "fa1c7fdf02510f0d1480c5af62f8659dfd09ebab", "size": "6813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documentation/html/group__selection.html", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1846467" }, { "name": "Perl", "bytes": "167978" }, { "name": "Shell", "bytes": "3594" } ], "symlink_target": "" }
/** * Generated with Acceleo */ package org.wso2.developerstudio.eclipse.gmf.esb.parts.forms; // Start of user code for imports import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent; import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent; import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart; import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent; import org.eclipse.emf.eef.runtime.part.impl.SectionPropertiesEditingPart; import org.eclipse.emf.eef.runtime.ui.parts.PartComposer; import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence; import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence; import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep; import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils; import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.forms.widgets.Section; import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository; import org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlResultMappingPropertiesEditionPart; import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages; // End of user code /** * * */ public class SqlResultMappingPropertiesEditionPartForm extends SectionPropertiesEditingPart implements IFormPropertiesEditionPart, SqlResultMappingPropertiesEditionPart { protected Text propertyName; protected Text columnId; /** * For {@link ISection} use only. */ public SqlResultMappingPropertiesEditionPartForm() { super(); } /** * Default constructor * @param editionComponent the {@link IPropertiesEditionComponent} that manage this part * */ public SqlResultMappingPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) { super(editionComponent); } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart# * createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit) * */ public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) { ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent); Form form = scrolledForm.getForm(); view = form.getBody(); GridLayout layout = new GridLayout(); layout.numColumns = 3; view.setLayout(layout); createControls(widgetFactory, view); return scrolledForm; } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart# * createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite) * */ public void createControls(final FormToolkit widgetFactory, Composite view) { CompositionSequence sqlResultMappingStep = new BindingCompositionSequence(propertiesEditionComponent); CompositionStep propertiesStep = sqlResultMappingStep.addStep(EsbViewsRepository.SqlResultMapping.Properties.class); propertiesStep.addStep(EsbViewsRepository.SqlResultMapping.Properties.propertyName); propertiesStep.addStep(EsbViewsRepository.SqlResultMapping.Properties.columnId); composer = new PartComposer(sqlResultMappingStep) { @Override public Composite addToPart(Composite parent, Object key) { if (key == EsbViewsRepository.SqlResultMapping.Properties.class) { return createPropertiesGroup(widgetFactory, parent); } if (key == EsbViewsRepository.SqlResultMapping.Properties.propertyName) { return createPropertyNameText(widgetFactory, parent); } if (key == EsbViewsRepository.SqlResultMapping.Properties.columnId) { return createColumnIdText(widgetFactory, parent); } return parent; } }; composer.compose(view); } /** * */ protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) { Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED); propertiesSection.setText(EsbMessages.SqlResultMappingPropertiesEditionPart_PropertiesGroupLabel); GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL); propertiesSectionData.horizontalSpan = 3; propertiesSection.setLayoutData(propertiesSectionData); Composite propertiesGroup = widgetFactory.createComposite(propertiesSection); GridLayout propertiesGroupLayout = new GridLayout(); propertiesGroupLayout.numColumns = 3; propertiesGroup.setLayout(propertiesGroupLayout); propertiesSection.setClient(propertiesGroup); return propertiesGroup; } protected Composite createPropertyNameText(FormToolkit widgetFactory, Composite parent) { createDescription(parent, EsbViewsRepository.SqlResultMapping.Properties.propertyName, EsbMessages.SqlResultMappingPropertiesEditionPart_PropertyNameLabel); propertyName = widgetFactory.createText(parent, ""); //$NON-NLS-1$ propertyName.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); widgetFactory.paintBordersFor(parent); GridData propertyNameData = new GridData(GridData.FILL_HORIZONTAL); propertyName.setLayoutData(propertyNameData); propertyName.addFocusListener(new FocusAdapter() { /** * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent( SqlResultMappingPropertiesEditionPartForm.this, EsbViewsRepository.SqlResultMapping.Properties.propertyName, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, propertyName.getText())); propertiesEditionComponent .firePropertiesChanged(new PropertiesEditionEvent( SqlResultMappingPropertiesEditionPartForm.this, EsbViewsRepository.SqlResultMapping.Properties.propertyName, PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST, null, propertyName.getText())); } } /** * @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent) */ @Override public void focusGained(FocusEvent e) { if (propertiesEditionComponent != null) { propertiesEditionComponent .firePropertiesChanged(new PropertiesEditionEvent( SqlResultMappingPropertiesEditionPartForm.this, null, PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED, null, null)); } } }); propertyName.addKeyListener(new KeyAdapter() { /** * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlResultMappingPropertiesEditionPartForm.this, EsbViewsRepository.SqlResultMapping.Properties.propertyName, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, propertyName.getText())); } } }); EditingUtils.setID(propertyName, EsbViewsRepository.SqlResultMapping.Properties.propertyName); EditingUtils.setEEFtype(propertyName, "eef::Text"); //$NON-NLS-1$ FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.SqlResultMapping.Properties.propertyName, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$ // Start of user code for createPropertyNameText // End of user code return parent; } protected Composite createColumnIdText(FormToolkit widgetFactory, Composite parent) { createDescription(parent, EsbViewsRepository.SqlResultMapping.Properties.columnId, EsbMessages.SqlResultMappingPropertiesEditionPart_ColumnIdLabel); columnId = widgetFactory.createText(parent, ""); //$NON-NLS-1$ columnId.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); widgetFactory.paintBordersFor(parent); GridData columnIdData = new GridData(GridData.FILL_HORIZONTAL); columnId.setLayoutData(columnIdData); columnId.addFocusListener(new FocusAdapter() { /** * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent) * */ @Override @SuppressWarnings("synthetic-access") public void focusLost(FocusEvent e) { if (propertiesEditionComponent != null) { propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent( SqlResultMappingPropertiesEditionPartForm.this, EsbViewsRepository.SqlResultMapping.Properties.columnId, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, columnId.getText())); propertiesEditionComponent .firePropertiesChanged(new PropertiesEditionEvent( SqlResultMappingPropertiesEditionPartForm.this, EsbViewsRepository.SqlResultMapping.Properties.columnId, PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST, null, columnId.getText())); } } /** * @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent) */ @Override public void focusGained(FocusEvent e) { if (propertiesEditionComponent != null) { propertiesEditionComponent .firePropertiesChanged(new PropertiesEditionEvent( SqlResultMappingPropertiesEditionPartForm.this, null, PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED, null, null)); } } }); columnId.addKeyListener(new KeyAdapter() { /** * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent) * */ @Override @SuppressWarnings("synthetic-access") public void keyPressed(KeyEvent e) { if (e.character == SWT.CR) { if (propertiesEditionComponent != null) propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(SqlResultMappingPropertiesEditionPartForm.this, EsbViewsRepository.SqlResultMapping.Properties.columnId, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, columnId.getText())); } } }); EditingUtils.setID(columnId, EsbViewsRepository.SqlResultMapping.Properties.columnId); EditingUtils.setEEFtype(columnId, "eef::Text"); //$NON-NLS-1$ FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.SqlResultMapping.Properties.columnId, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$ // Start of user code for createColumnIdText // End of user code return parent; } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent) * */ public void firePropertiesChanged(IPropertiesEditionEvent event) { // Start of user code for tab synchronization // End of user code } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlResultMappingPropertiesEditionPart#getPropertyName() * */ public String getPropertyName() { return propertyName.getText(); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlResultMappingPropertiesEditionPart#setPropertyName(String newValue) * */ public void setPropertyName(String newValue) { if (newValue != null) { propertyName.setText(newValue); } else { propertyName.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.SqlResultMapping.Properties.propertyName); if (eefElementEditorReadOnlyState && propertyName.isEnabled()) { propertyName.setEnabled(false); propertyName.setToolTipText(EsbMessages.SqlResultMapping_ReadOnly); } else if (!eefElementEditorReadOnlyState && !propertyName.isEnabled()) { propertyName.setEnabled(true); } } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlResultMappingPropertiesEditionPart#getColumnId() * */ public String getColumnId() { return columnId.getText(); } /** * {@inheritDoc} * * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.SqlResultMappingPropertiesEditionPart#setColumnId(String newValue) * */ public void setColumnId(String newValue) { if (newValue != null) { columnId.setText(newValue); } else { columnId.setText(""); //$NON-NLS-1$ } boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.SqlResultMapping.Properties.columnId); if (eefElementEditorReadOnlyState && columnId.isEnabled()) { columnId.setEnabled(false); columnId.setToolTipText(EsbMessages.SqlResultMapping_ReadOnly); } else if (!eefElementEditorReadOnlyState && !columnId.isEnabled()) { columnId.setEnabled(true); } } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle() * */ public String getTitle() { return EsbMessages.SqlResultMapping_Part_Title; } // Start of user code additional methods // End of user code }
{ "content_hash": "df28db10d3d253af1ae5ab38bd631640", "timestamp": "", "source": "github", "line_count": 377, "max_line_length": 281, "avg_line_length": 36.246684350132625, "alnum_prop": 0.7688254665203074, "repo_name": "prabushi/devstudio-tooling-esb", "id": "a51f94f93e57b503872c16b29ab5efb41a706016", "size": "13665", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/parts/forms/SqlResultMappingPropertiesEditionPartForm.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "41098" }, { "name": "HTML", "bytes": "731356" }, { "name": "Java", "bytes": "77332976" }, { "name": "JavaScript", "bytes": "475592" }, { "name": "Shell", "bytes": "7727" } ], "symlink_target": "" }
namespace Calabonga.TestTask13.AspNetCore.Infrastructure.QueryParams { /// <summary> /// QueryParams for Post /// </summary> public class PostPagedListQueryParams : PagedListQueryParams { public string CategoryName { get; set; } public string Tag { get; set; } } }
{ "content_hash": "c413e79fddd3ed033dc9227a4221e954", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 71, "avg_line_length": 25.416666666666668, "alnum_prop": 0.659016393442623, "repo_name": "Calabonga/Calabonga.TestTask13", "id": "2fada00d7ef3038a549a12550d360e4f4cb35eef", "size": "307", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Solution/Calabonga.TestTask13.AspNetCore/Infrastructure/QueryParams/PostPagedListQueryParams.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "151586" }, { "name": "CSS", "bytes": "3681" }, { "name": "JavaScript", "bytes": "144231" } ], "symlink_target": "" }
package io.opencensus.scala.akka.http import akka.actor.ActorSystem import akka.http.scaladsl.model.{HttpRequest, HttpResponse} import io.opencensus.scala.http.testSuite.MockStats import io.opencensus.scala.stats.{Distribution, MeasurementDouble} import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AsyncFlatSpec import org.scalatest.matchers.should.Matchers import scala.concurrent.Future class StatsClientSpec extends AsyncFlatSpec with BeforeAndAfterAll with Matchers { implicit val system: ActorSystem = ActorSystem() def statsClientWithMock: (StatsClient, MockStats) = { val mockStats = new MockStats val client = new StatsClient { override private[http] val stats = mockStats } (client, mockStats) } it should "register the correct view" in { val (client, mock) = statsClientWithMock val doRequest = client.recorded(_ => Future.successful(HttpResponse()), "routeName") doRequest(HttpRequest()).flatMap(_.discardEntityBytes().future()).map { _ => mock.registeredViews should have length 1 val roundtripLatency = mock.registeredViews.head roundtripLatency.name shouldBe "opencensus.io/http/client/roundtrip_latency" roundtripLatency.measure.name shouldBe "opencensus.io/http/client/roundtrip_latency" roundtripLatency.aggregation shouldBe a[Distribution] } } it should "record the correct measure value" in { val (client, mock) = statsClientWithMock val doRequest = client.recorded(_ => Future.successful(HttpResponse()), "routeName") doRequest(HttpRequest()).flatMap(_.discardEntityBytes().future()).map { _ => val (measurement, _) = mock.recordedMeasurements.head measurement match { case MeasurementDouble(measure, value) => measure.name shouldBe "opencensus.io/http/client/roundtrip_latency" value.toInt shouldBe >(0) case other => fail(s"Expected MeasurementDouble got $other") } } } it should "record the correct measure tags" in { val (client, mock) = statsClientWithMock val doRequest = client.recorded(_ => Future.successful(HttpResponse()), "routeName") doRequest(HttpRequest()).flatMap(_.discardEntityBytes().future()).map { _ => mock.recordedMeasurements should have length 1 val (_, tags) = mock.recordedMeasurements.head val tagsKeyValues = tags.map(tag => (tag.key.getName, tag.value.asString())) val expectedTags = List( "http_client_method" -> "GET", "http_client_route" -> "routeName", "http_client_status" -> "200" ) tagsKeyValues should contain theSameElementsAs expectedTags } } override def afterAll(): Unit = { system.terminate() super.afterAll() } }
{ "content_hash": "09bb41c9ff5eaceb4c343391a8dd2f89", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 90, "avg_line_length": 31.43820224719101, "alnum_prop": 0.6983559685489635, "repo_name": "census-ecosystem/opencensus-scala", "id": "bc9a83e2395b13463835032bf5e6759fe2168f9b", "size": "2798", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "akka-http/src/test/scala/io/opencensus/scala/akka/http/StatsClientSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "382" }, { "name": "Scala", "bytes": "140513" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <words> <word> <english>badge</english> <polish>identyfikator</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>chat to (v)</english> <polish>gadać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>Who did you vote for in the last election</english> <polish>Na kogo głosowałeś w ostatnich wyborach</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>childhood memories</english> <polish>wspomnienia z dzieciństwa</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>avoid</english> <polish>unikać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>be proud OF/ABOUT sth</english> <polish>być dumnym Z czegoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>daily life</english> <polish>codzienne życie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>dangerous</english> <polish>niebezpieczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>personal questions</english> <polish>osobiste pytania</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>half-sister</english> <polish>siostra przyrodnia</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>like != dislike</english> <polish>lubić != nielubić</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>a pan</english> <polish>rondel</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>improve</english> <polish>polepszyć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>chat up</english> <polish>zagadywać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>disastrous (have a disastrous date)</english> <polish>fatalny, katastrofalny (mieć fatalną randkę)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>in spite of ( = despite)</english> <polish>pomimo</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>smart suit</english> <polish>eleganckie ubranie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>involve</english> <polish>angażować, wiązać, dotyczyć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>embarrassing</english> <polish>żenujący</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>eyebrows</english> <polish>brwi</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>funeral</english> <polish>pogrzeb</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>have a date</english> <polish>mieć randkę</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>raise (we raised our eyebrows)</english> <polish>wznosić, unosić (unieśliśmy brwi)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>trust</english> <polish>ufać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>agony</english> <polish>agonia</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>amused</english> <polish>rozbawiony</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>assertive</english> <polish>asertywny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>awkward</english> <polish>niezręczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>banker</english> <polish>bankier</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>bell</english> <polish>dzwonek</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>bubbly</english> <polish>radosny, nadpobudliwie radosny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>complex (n)</english> <polish>kompleks</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>complicated</english> <polish>skomplikowany, złożony</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>courtship</english> <polish>zaloty, narzeczeństwo</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>current</english> <polish>obecny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>deafening (deafening music)</english> <polish>ogłuszający (ogłuszająca muzyka)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>discotheque</english> <polish>dyskoteka</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>double (v)</english> <polish>podwajać się</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>despise</english> <polish>gardzić</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>edit</english> <polish>edytować</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>egotistical</english> <polish>egoistyczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>eliminate</english> <polish>eliminować, usuwać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>event</english> <polish>impreza</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>evolve (evolve over the centuries)</english> <polish>rozwijać się, ewoluować (ewoluować przez wieki)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>exchange</english> <polish>wymieniać na coś, rozmieniać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>farewell</english> <polish>pożegnalny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>frenzied</english> <polish>szaleńczy, oszalały, desperacki</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>fresh</english> <polish>świeży</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>grimace</english> <polish>grymas</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>giggling</english> <polish>chichotać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>guilty</english> <polish>winny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>guy</english> <polish>facet</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>housekeeper</english> <polish>osoba prowadząca dom, gosposia</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>imaginative</english> <polish>pomysłowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>impression</english> <polish>wrażenie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>inferiority (I’m an egotistical maniac with an inferiority complex.)</english> <polish>niższość (Jestem egoistycznym maniakiem z kompleksem niższości)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>injection</english> <polish>zastrzyk</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>labour (Labour party)</english> <polish>siła robocza (Partia Pracy)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>management consultant</english> <polish>doradca ds. zarządzania, doradca zarządu</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>maniac</english> <polish>maniak</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>match (n)</english> <polish>dopasowanie, dobrana para</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>gentle (gentle courtship)</english> <polish>łagodne, delikatne (delikatne zaloty)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>overuse</english> <polish>nadużywać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>participants</english> <polish>uczestnicy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>pose (Journalists posed as students to investigate the story. )</english> <polish>podawać się za kogoś, pozować (Dziennikarze podawali się za studentów aby zbadać historię)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>awake / fall asleep</english> <polish>obudzony / zasnąć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>possesion</english> <polish>własność, dobytek</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>pre-prepared</english> <polish>wcześniej przygotowany</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>pre-school (n)</english> <polish>przedszkole</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>propose</english> <polish>oświadczyć się</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>prospective (prospective partner)</english> <polish>potencjalny (potencjalny partner)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>publishes</english> <polish>publikować</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>quick-fire (The politician was asked quick-fire questions.)</english> <polish>krzyżowy ogień (Politycy byli przepytywani w krzyżowym ogniu pytań)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>ritual</english> <polish>rytuał</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>scorecard</english> <polish>arkusz odpowiedzi</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>shift (n)</english> <polish>zmiana (w pracy)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>smoothly</english> <polish>gładko</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>solo singer / lead singer</english> <polish>solowy wokalista / główny wokalista (w zespole)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>speed-dating</english> <polish>błyskawiczna randka</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>treasured (What's your most treasured possesion ?)</english> <polish>wartościowy, cenny (Co najbardziej wartościowego posiadasz ?)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>tricks</english> <polish>sztuczki</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>type</english> <polish>typ</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>unknow</english> <polish>nieznany</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>unmarried</english> <polish>niezamężna, nieżonaty</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>watchful</english> <polish>uważny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>Who would play you in the film of your life?</english> <polish>kto zagrałby Ciebie w filmie o Twoim życiu?</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>immediately</english> <polish>natychmiast</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>go along</english> <polish>iść naprzód</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>pretend</english> <polish>udawać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>pleased (They were pleased)</english> <polish>zadowolony (Oni byli zadowoleni)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>A</subpart> </word> <word> <english>adventurous</english> <polish>śmiały, lubiący przygody</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>arrogant</english> <polish>arogancki</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>as hard as nail</english> <polish>niewzruszony jak skała (twardy jak paznokieć)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>assertive</english> <polish>asertywny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>bad-tempered</english> <polish>wybuchowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>calm</english> <polish>spokojny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>cheerful</english> <polish>radosny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>cold fish</english> <polish>zimny jak ryba</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>conscientious [konszyjenszys]</english> <polish>sumienny, skrypulatny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>easy-going</english> <polish>łatwy w pożyciu</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>eccentric</english> <polish>ekscentryczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>forgetful</english> <polish>zapominalski</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>funny</english> <polish>zabawny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>heart of gold</english> <polish>złote serce</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>immature</english> <polish>niedojrzały</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>impulsive</english> <polish>impulsywny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>insecure != self-confident</english> <polish>niepewny siebie != pewny siebie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>insincere</english> <polish>nieszczery</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>loyal != disloyal</english> <polish>lojalny != nielojalnny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>moody</english> <polish>humorzasty</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>open-minded</english> <polish>o szerokich horyzontach, otwarty</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>optimistic</english> <polish>optymistyczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>pain in the neck</english> <polish>nie do wytrzymania, irytujący (idiom)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>pessimistic</english> <polish>pesymistyczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>possessive</english> <polish>zaborczy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>reliable != unreliable</english> <polish>godny zaufania, niezawodny != nie godny zaufania, zawodny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>rely</english> <polish>polegać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>reserved</english> <polish>skryty, powściągliwy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>self-confident</english> <polish>pewny siebie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>sensible</english> <polish>rozsądny, sensowny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>sensitive</english> <polish>wrażliwy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>stubborn</english> <polish>uparty</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>vain</english> <polish>próżny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>well-balanced</english> <polish>zrównoważony</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>wise</english> <polish>mądry, mądry życiowo</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>childhood</english> <polish>dzieciństwo</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>deduce</english> <polish>wnioskować, dedukować</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>handwriting</english> <polish>charakter pisma</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>illegible</english> <polish>nieczytelny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>initials</english> <polish>inicjały</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>either ... or ...</english> <polish>albo ... albo ...</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>psychic</english> <polish>wróżka</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>secretive</english> <polish>tajemniczy, skryty</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>sign</english> <polish>podpisywać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>signature</english> <polish>podpis</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>trick</english> <polish>sztuczka, trik</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>ability, abilities</english> <polish>zdolność, zdolności</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>adapt</english> <polish>przystosować się</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>all-time</english> <polish>wszech czasów, ponadczasowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>ambition</english> <polish>ambicja</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>angle</english> <polish>kąt (pomiędzy czymś a czymś)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>bad-mannered</english> <polish>źle wychowany</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>companion</english> <polish>towarzysz, kompan</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>confirm</english> <polish>potwierdzać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>conflict (n)</english> <polish>konflikt (rz.)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>considerate</english> <polish>taktowny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>creative</english> <polish>kreatywny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>descending</english> <polish>opadający</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>dyslexic</english> <polish>dyslektyczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>evidence</english> <polish>materiał dowodowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>refuse</english> <polish>odmawiać, nie zgadzać się</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>flatter / flattering</english> <polish>schelbianie / schlebiający, pochlebny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>geniune</english> <polish>autentyczny, prawdziwy, oryginalny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>graphology</english> <polish>grafologia</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>horizontal / vertical</english> <polish>poziomy / pionowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>identify</english> <polish>identyfikować</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>imply</english> <polish>oznaczać, insynuować, sugerować</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>impressive</english> <polish>robiący wrażenie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>inherit</english> <polish>dziedziczyć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>investigate</english> <polish>prowadzić dochodzenie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>judge</english> <polish>osądzać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>lack (lack of knowledge)</english> <polish>brak, niedostatek</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>lecture</english> <polish>wykład</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>legible != illegible</english> <polish>czytelny != nieczytelny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>low (level)</english> <polish>niski (poziom)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>major (adj.)</english> <polish>ważny, główny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>method</english> <polish>metoda</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>objective</english> <polish>cel</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>overcome (overcome sb's fears, overcome problems)</english> <polish>przezwyciężać, pokonywać (pokonywać czyjeś lęki, pokonywać problemy)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>come up (Coming up with a few names is always impressive)</english> <polish>ukazać się, pojawiąć się, zbliżać, podejść bliżej (Zbliżyć się (pojawić) z nowymi imionami jest zawsze imponujące)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>paranormal</english> <polish>paranormalny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>paraphrasing</english> <polish>parafrazowanie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>persona (strong persona)</english> <polish>osobowość (silna osobowość)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>powerful</english> <polish>silny, potężny, wszechmocny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>preferably (expect preferably something positive)</english> <polish>najchętniej, raczej, najlepiej (oczekiwać najchętniej czegoś pozytywnego)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>prominent</english> <polish>wybitny, czołowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>reflect</english> <polish>odzwierciedlać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>represent</english> <polish>reprezentować</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>satisfied</english> <polish>zadowolony</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>worldwide</english> <polish>ogólnoświatowy, na całym świecie, na świecie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>scar</english> <polish>blizna</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>sceptical</english> <polish>sceptyczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>self-esteem</english> <polish>samoocena, poczucie własnej wartości</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>sincere</english> <polish>szczery</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>sociable</english> <polish>towarzyski</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>stable</english> <polish>stabilny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>statement</english> <polish>oświadczenie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>strategy</english> <polish>strategia</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>surgery</english> <polish>zabieg chirurgiczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>technique</english> <polish>technika</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>temporary</english> <polish>tymczasowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>tempt / tempted</english> <polish>kusić, nakłaniać / kuszony, nakłaniany</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>tendency</english> <polish>tendencja</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>tend</english> <polish>wykazywać tendencję</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>tricks of the trade</english> <polish>tajniki zawodu</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>unambitious</english> <polish>nieambitny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>unsociable</english> <polish>nietowarzyski</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>B</subpart> </word> <word> <english>A&amp;E (Accident and Emergency)</english> <polish>ostry dyżur</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>ache</english> <polish>ból</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>allergic</english> <polish>alergiczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>ankle</english> <polish>kostka (u nogi)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>antibiotic</english> <polish>antybiotyk</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>athma (ezma)</english> <polish>astma</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>bandage</english> <polish>bandaż</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>be sick</english> <polish>wymiotować</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>bleed</english> <polish>krwawić</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>blister</english> <polish>bąbel, pęcherz (po oparzeniu)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>bruise (blue mark)</english> <polish>siniak</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>catch cold</english> <polish>złapać przeziebienie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>cough [kaf]</english> <polish>kaszel</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>deep cut</english> <polish>głębokie skaleczenie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>diarrhoea (dajorija)</english> <polish>biegunka</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>feel dizzy</english> <polish>zawroty głowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>drug</english> <polish>lek</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>earache</english> <polish>ból ucha</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>faint</english> <polish>mdleć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>feel sick</english> <polish>czuć się chorym</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>flu</english> <polish>grypa</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>food poisoning</english> <polish>zatrucie pokarmowe</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>GP (General Practitioner)</english> <polish>lekarz rodzinny, ogólny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>headache</english> <polish>ból głowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>heart attack</english> <polish>zawał serca</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>high (low) blood pressure</english> <polish>wysokie (niskie) ciśnienie krwi</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>hurt</english> <polish>boleć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>illness</english> <polish>choroba</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>injury</english> <polish>uraz, kontuzja</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>medicine</english> <polish>lekarstwo</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>needle</english> <polish>igła</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>operation</english> <polish>operacja</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>pain (in his chest)</english> <polish>ból (w jego klatce piersiowej)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>painkiller</english> <polish>środek przeciwbólowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>rash</english> <polish>wysypka</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>rest</english> <polish>odpoczynek</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>scan</english> <polish>prześwietlenie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>sneeze</english> <polish>kichać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>sore throat</english> <polish>ból gardła</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>specialist</english> <polish>specjalista</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>sprain / sprained</english> <polish>zwichnąć / zwichnięta</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>stitch / stitches</english> <polish>szew / szwy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>stomach ache</english> <polish>ból żołądka</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>stroke</english> <polish>udar, wylew do mózgu</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>swollen</english> <polish>spuchnięty</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>symptom</english> <polish>symptom</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>temperature</english> <polish>temperatura</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>treatment</english> <polish>leczenie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>twist, twisted (ankle)</english> <polish>skręcać, skręcona (kostka)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>unconscious [ankonczys]</english> <polish>nieprzytomny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>wound</english> <polish>rana</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>X-ray</english> <polish>rentgen, prześwietlenie rentgenowski</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>breathe</english> <polish>oddychać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>cell</english> <polish>komórka</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>choke</english> <polish>dławić</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>damage</english> <polish>uszkodzić</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>long-term</english> <polish>długofalowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>panic</english> <polish>panikować</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>sting (stung, stung)</english> <polish>żądlić</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>strengthen (to make sth stronger)</english> <polish>wzmacniać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>stuck</english> <polish>utknąć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>swallow</english> <polish>połykać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>achievement</english> <polish>osiągnięcie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>anti-ageing</english> <polish>przeciw efektom starzenia</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>antiseptic</english> <polish>antybakteryjny, środek odkażający</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>appointment</english> <polish>umówiona wizyta</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>arthritis</english> <polish>artretyzm</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>beneficial</english> <polish>korzystny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>burn</english> <polish>oparzenie, poparzeyć się</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>check-up</english> <polish>badanie kontrolne</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>claim</english> <polish>twierdzić</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>in fact (In fact, it may help)</english> <polish>właściwie, faktycznie (Właściwie, to może pomóc)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>cherry</english> <polish>wiśnia, czereśnia</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>chronic</english> <polish>chroniczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>consciousness [konszysness]</english> <polish>przytomność</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>couch</english> <polish>kanapa</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>deadline</english> <polish>ostateczny termin</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>disease</english> <polish>choroba</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>exhausted</english> <polish>wyczerpany, wykończony</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>glad</english> <polish>zadowolony</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>giggle</english> <polish>chichotać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>gradually</english> <polish>stopniowo, powoli</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>especially</english> <polish>zwłaszcza, szczególnie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>harmful (harmful chemicals)</english> <polish>szkodliwy (szkodliwe chemikalia)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>cause</english> <polish>spowodować, wywołać (v.), przyczyna (n.)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>hug</english> <polish>objęcie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>infection</english> <polish>infekcja</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>inwards</english> <polish>do wewnątrz, do środka</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>upwards</english> <polish>w górę</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>throat</english> <polish>gardło</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>manoeuvre</english> <polish>manewr</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>manual (n)</english> <polish>podręcznik (rz.)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>mechanism</english> <polish>mechanizm</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>memeber</english> <polish>członek</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>moderate (adj)</english> <polish>umiarkowany, średni, o umiarkowanych poglądach</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>nosebleed</english> <polish>krwotok z nosa</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>patient (n)</english> <polish>pacjent (rz.)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>pinch</english> <polish>szczypać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>plaster</english> <polish>plaster</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>poisoning</english> <polish>zatrucie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>pressure</english> <polish>ciśnienie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>process</english> <polish>proces</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>protein</english> <polish>białko, proteina</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>puppy</english> <polish>szczeniak</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>reach</english> <polish>osiągnać cel</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>reaction</english> <polish>reakcja</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>remain</english> <polish>pozostawać, nie zmieniać się</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>response</english> <polish>odpowiedź</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>rush over (to help)</english> <polish>pospieszyć (z pomocą)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>self-repair</english> <polish>samogojenie, samonaprawa</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>short-term</english> <polish>krótkoterminowy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>staff</english> <polish>zespół pracowników</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>switch on</english> <polish>włączyć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>treat (badly)</english> <polish>traktować (źle)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>waist</english> <polish>talia w pasie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>wasp</english> <polish>osa</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>contain</english> <polish>zawierać</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>legibility</english> <polish>czytelność</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>objective (n)</english> <polish>cel (rz.)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>descending != rising</english> <polish>opadający, malejący != wznoszący, rosnący</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>be faced with sth (faced with problems) (when faced with problems, will work to overcome them)</english> <polish>stanąć twarzą w twarz z czymś (stanąć przed problemami) (gdy staniesz przed problemami, będziesz pracował nad przezwyciężeniem ich)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>go through a phase</english> <polish>przejść fazę</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>have a high opinion of sb</english> <polish>mieć wysokie mniemanie o kimś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>look forward to sth</english> <polish>nie móc się doczekać czegoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>talkative</english> <polish>gadatliwy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>dishonest</english> <polish>nieuczciwy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>imaginative</english> <polish>obdarzony wyobraźnią</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>considerate</english> <polish>taktowny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>flatmate</english> <polish>współ-lokator</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>unusual</english> <polish>niezwykły, niezwyczajny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>express sb's ideas</english> <polish>wyrażać czyjeś idee</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>be in a good mood</english> <polish>być w dobrym humorze</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>be good AT sth</english> <polish>być W czymś dobrym</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>support sb</english> <polish>wspierać kogoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>keep sb's head in crisis = calm</english> <polish>zachowujący spokój w kryzysie = spokojny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>share (share some general characteristics)</english> <polish>dzielić się czymś (dzielić jakieś ogólne cechy charakterystyczne)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>have a great sense of humour</english> <polish>mieć wspaniałe poczucie humoru</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>responsible</english> <polish>odpowiedzialny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>helpful != unhelpful</english> <polish>pomocny != nieskory do pomocy, mało pomocny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>practical</english> <polish>praktyczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>critical</english> <polish>krytyczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>ironic</english> <polish>ironiczny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>annoy sb</english> <polish>denerwować kogoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>generous</english> <polish>hojny</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>show sympathy / fear</english> <polish>okazywać współczucie / strach</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>have special powers</english> <polish>mieć specjalnie moce</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>be sceptical</english> <polish>być sceptycznycm</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>key event</english> <polish>kluczowe wydarzenie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>predict sth</english> <polish>przewidzieć coś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>above average</english> <polish>powyżej średniej</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>convince sb</english> <polish>przekonać kogoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>flattering statement</english> <polish>pochlebne oświadczenie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>common medical / health problem</english> <polish>wspólny problem medyczny / problem ze zdrowiem</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>work sth out (working out meaning from context)</english> <polish>zrozumieć (British English), obmyślać, opracować (zrozumieć znaczene z kontekstu)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>frequent, frequently (frequent strategy)</english> <polish>częsty, często (częsta strategia)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>pour water</english> <polish>nalać wody</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>auxiliary</english> <polish>pomocniczy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>add emphasis</english> <polish>dodać nacisk</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>avoid doing sth</english> <polish>unikać robienia czegoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>respond to sth</english> <polish>odpowiedź na coś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>excitement</english> <polish>podekscytowanie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>pick sth up</english> <polish>podnosić coś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>accidentally</english> <polish>przypadkowo</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>break a blister</english> <polish>przekuć pęcherz (bąbel)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>have a serious allergic reaction</english> <polish>mieć poważną reakcję alegiczną</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>be stung (by a wasp)</english> <polish>być ukąszonym przez osę</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>give sb first aid</english> <polish>udzielić komuś pierwszej pomocy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>a sort of / kind of</english> <polish>rodzaj</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>deserted</english> <polish>opustoszały</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>remain stuck (steak remained stuck in her throat)</english> <polish>pozostać utkniętym (stek pozostał (utknięty) w jej gardle)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>get stuck</english> <polish>utknąć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>a bandage put on</english> <polish>założyć bangaż</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>toe</english> <polish>palec u nogi</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>warn sb ABOUT sth</english> <polish>ostrzegać kogoś PRZED czymś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>cut down on</english> <polish>ograniczyć</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>use / fallow the instruction manual</english> <polish>używać / podążać za instrukcjami z podręcznika</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>react quickly and efficiently</english> <polish>reagować szybko i sprawnie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>suffer FROM sth</english> <polish>cierpieć Z jakiegoś powodu</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>certain amount OF sth</english> <polish>pewna ilość czegoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>break up with</english> <polish>zerwać z kimś (znajomość)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>call sb back</english> <polish>oddzwonić do kogoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>chat up sb</english> <polish>zagadywać kogoś (flirtować)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>give up</english> <polish>poddać się, zaprzestać robienia czegoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>slow down</english> <polish>zwolnić, obniżyć prędkość</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>be in touch with sb</english> <polish>być z kimś w kontakcie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>get flu</english> <polish>złapać grypę</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>catch up on sth (I've been catching up on my emails)</english> <polish>nadrabiać zaległości (Nadrabiałem zaległości w (czytanych) mailach)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>apart from</english> <polish>oprócz</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>sightseeing</english> <polish>zwiedzanie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>wait FOR sb</english> <polish>czekać NA kogoś</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>superior</english> <polish>ponadprzeciętny, wybitny, lepszy</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>tie sth (tie round a part of body)</english> <polish>związać coś (obwiązać część ciała)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>chemist</english> <polish>chemik</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>ward</english> <polish>oddział (szpitalny)</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>get over</english> <polish>wyzdrowieć, przeboleć, dochodzić do siebie</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>opperation theatre</english> <polish>sala operacyjna</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> <word> <english>side effects</english> <polish>efekty uboczne</polish> <part>New English File 4 Upper Intermediate - Unit 1</part> <subpart>C</subpart> </word> </words>
{ "content_hash": "cc3491388c799a3428f3f365f02ea179", "timestamp": "", "source": "github", "line_count": 2367, "max_line_length": 156, "avg_line_length": 34.018588931136456, "alnum_prop": 0.5918009984848861, "repo_name": "dariuszwrzesien/DwrLearnEnglish", "id": "dc9ef7647f034bcd56a04244351f556ea452d028", "size": "81027", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/words/words_upper_intermediate_unit_1.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "194" }, { "name": "CSS", "bytes": "37239" }, { "name": "HTML", "bytes": "14502" }, { "name": "JavaScript", "bytes": "42836" }, { "name": "PHP", "bytes": "78729" } ], "symlink_target": "" }
module Viewable class Select < ActiveRecord::Base include Viewable include Admin::Viewable::Select end end
{ "content_hash": "15bd9117e82cf8d30fa6af43153939c1", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 35, "avg_line_length": 19.833333333333332, "alnum_prop": 0.7394957983193278, "repo_name": "o2web/rails_admin_cms", "id": "bee17420a38b8540be6dc3204c49bb811e1eaff6", "size": "119", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/viewable/select.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1696" }, { "name": "CoffeeScript", "bytes": "3783" }, { "name": "HTML", "bytes": "12453" }, { "name": "JavaScript", "bytes": "699" }, { "name": "Ruby", "bytes": "201159" } ], "symlink_target": "" }
<?xml version="1.0" ?> <container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> <!-- <parameters> <parameter key="bootbusiness_theme.example.class">RedKiteLabs\BootbusinessThemeBundle\Example</parameter> </parameters> <services> <service id="bootbusiness_theme.example" class="%bootbusiness_theme.example.class%"> <argument type="service" id="service_id" /> <argument>plain_value</argument> <argument>%parameter_name%</argument> </service> </services> --> </container>
{ "content_hash": "3817ce62fa5a4a06ff678f2753136640", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 120, "avg_line_length": 36.8, "alnum_prop": 0.6589673913043478, "repo_name": "redkite-labs/BootbusinessThemeBundle", "id": "46e43bb189a490990442f850f501c2df5878ae3f", "size": "736", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Resources/config/services.xml", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "43700" }, { "name": "JavaScript", "bytes": "1020" }, { "name": "PHP", "bytes": "2596" } ], "symlink_target": "" }
!==================initialization_1.f90====================== ! { dg-do compile } ! Tests fix for PR25018 in which an ICE resulted from using a ! variable in a parameter initialization expression. In the course ! of developing the fix, various other constraints and limitations ! were tested. ! ! Contributed by Paul Thomas <pault@gcc.gnu.org> ! module const ! The next line is the original error real(8), parameter :: g = - sqrt(2._8) * Gf ! { dg-error "not been declared or is a variable" } contains subroutine foo(ch1, x, y) character(*) :: ch1 ! This is OK because it is a restricted expression. character(len(ch1)) :: ch2 real(8) :: x (1:2, *) real(8) :: y (0:,:) integer :: i real :: z(2, 2) ! However, this gives a warning because it is an initialization expression. integer :: l1 = len (ch1) ! { dg-warning "assumed character length variable" } ! These are warnings because they are gfortran extensions. integer :: m3 = size (x, 1) ! { dg-warning "Evaluation of nonstandard initialization" } integer :: m4(2) = shape (z) ! { dg-warning "Evaluation of nonstandard initialization" } ! This does not depend on non-constant properties. real(8) :: big = huge (x) end subroutine foo end module const ! { dg-final { cleanup-modules "const" } }
{ "content_hash": "813421d2655a55c908183f6a47f3a96b", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 97, "avg_line_length": 33.743589743589745, "alnum_prop": 0.648176291793313, "repo_name": "shaotuanchen/sunflower_exp", "id": "24a1a4fd07281ff16de8a5782f83c6ac7cc043f1", "size": "1316", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "tools/source/gcc-4.2.4/gcc/testsuite/gfortran.dg/initialization_1.f90", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "459993" }, { "name": "Awk", "bytes": "6562" }, { "name": "Batchfile", "bytes": "9028" }, { "name": "C", "bytes": "50326113" }, { "name": "C++", "bytes": "2040239" }, { "name": "CSS", "bytes": "2355" }, { "name": "Clarion", "bytes": "2484" }, { "name": "Coq", "bytes": "61440" }, { "name": "DIGITAL Command Language", "bytes": "69150" }, { "name": "Emacs Lisp", "bytes": "186910" }, { "name": "Fortran", "bytes": "5364" }, { "name": "HTML", "bytes": "2171356" }, { "name": "JavaScript", "bytes": "27164" }, { "name": "Logos", "bytes": "159114" }, { "name": "M", "bytes": "109006" }, { "name": "M4", "bytes": "100614" }, { "name": "Makefile", "bytes": "5409865" }, { "name": "Mercury", "bytes": "702" }, { "name": "Module Management System", "bytes": "56956" }, { "name": "OCaml", "bytes": "253115" }, { "name": "Objective-C", "bytes": "57800" }, { "name": "Papyrus", "bytes": "3298" }, { "name": "Perl", "bytes": "70992" }, { "name": "Perl 6", "bytes": "693" }, { "name": "PostScript", "bytes": "3440120" }, { "name": "Python", "bytes": "40729" }, { "name": "Redcode", "bytes": "1140" }, { "name": "Roff", "bytes": "3794721" }, { "name": "SAS", "bytes": "56770" }, { "name": "SRecode Template", "bytes": "540157" }, { "name": "Shell", "bytes": "1560436" }, { "name": "Smalltalk", "bytes": "10124" }, { "name": "Standard ML", "bytes": "1212" }, { "name": "TeX", "bytes": "385584" }, { "name": "WebAssembly", "bytes": "52904" }, { "name": "Yacc", "bytes": "510934" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>metacoq-checker: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1 / metacoq-checker - 1.0~alpha+8.8</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> metacoq-checker <small> 1.0~alpha+8.8 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-07-11 16:01:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-11 16:01:45 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.12 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.7.1 Formal proof management system. num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.1 Official release 4.09.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matthieu.sozeau@inria.fr&quot; homepage: &quot;https://metacoq.github.io/metacoq&quot; dev-repo: &quot;git+https://github.com/MetaCoq/metacoq.git#coq-8.8&quot; bug-reports: &quot;https://github.com/MetaCoq/metacoq/issues&quot; authors: [&quot;Abhishek Anand &lt;aa755@cs.cornell.edu&gt;&quot; &quot;Simon Boulier &lt;simon.boulier@inria.fr&gt;&quot; &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; &quot;Yannick Forster &lt;forster@ps.uni-saarland.de&gt;&quot; &quot;Fabian Kunze &lt;fkunze@fakusb.de&gt;&quot; &quot;Gregory Malecha &lt;gmalecha@gmail.com&gt;&quot; &quot;Matthieu Sozeau &lt;matthieu.sozeau@inria.fr&gt;&quot; &quot;Nicolas Tabareau &lt;nicolas.tabareau@inria.fr&gt;&quot; &quot;Théo Winterhalter &lt;theo.winterhalter@inria.fr&gt;&quot; ] license: &quot;MIT&quot; build: [ [&quot;sh&quot; &quot;./configure.sh&quot;] [make &quot;-j%{jobs}%&quot; &quot;checker&quot;] ] install: [ [make &quot;-C&quot; &quot;checker&quot; &quot;install&quot;] ] depends: [ &quot;ocaml&quot; {&gt; &quot;4.02.3&quot;} &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} &quot;coq-metacoq-template&quot; {= version} ] synopsis: &quot;Specification of Coq&#39;s type theory and reference checker implementation&quot; description: &quot;&quot;&quot; MetaCoq is a meta-programming framework for Coq. The Checker module provides a complete specification of Coq&#39;s typing and conversion relation along with a reference type-checker that is extracted to a pluging. This provides a command: `MetaCoq Check [global_reference]` that can be used to typecheck a Coq definition using the verified type-checker. &quot;&quot;&quot; url { src: &quot;https://github.com/MetaCoq/metacoq/archive/1.0-alpha+8.8.tar.gz&quot; checksum: &quot;sha256=c2fe122ad30849e99c1e5c100af5490cef0e94246f8eb83f6df3f2ccf9edfc04&quot; }</pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-metacoq-checker.1.0~alpha+8.8 coq.8.7.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1). The following dependencies couldn&#39;t be met: - coq-metacoq-checker -&gt; coq &gt;= 8.8 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq-checker.1.0~alpha+8.8</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "83e39e3849375447254fa70404e2bf2e", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 157, "avg_line_length": 42.83888888888889, "alnum_prop": 0.5592011412268189, "repo_name": "coq-bench/coq-bench.github.io", "id": "2186cc6a339432badf5a2a02606002a7dc3002da", "size": "7714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.7.1/metacoq-checker/1.0~alpha+8.8.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace LosBase\Service\ORM; use Zend\ServiceManager\ServiceLocatorAwareInterface; use Zend\ServiceManager\ServiceLocatorAwareTrait; use LosBase\EventManager\EventProvider; /** * Define os serviços básicos de entidade * * @package LosBase\Service * @author Leandro Silva <leandro@leandrosilva.info> * @link http://leandrosilva.info Development Blog * @link http://github.com/LansoWeb/LosBase for the canonical source repository * @copyright 2011-2015 Leandro Silva (http://leandrosilva.info) * @license http://leandrosilva.info/licenca-bsd New BSD license */ abstract class AbstractEntity extends EventProvider implements ServiceLocatorAwareInterface { use ServiceLocatorAwareTrait; public function save($form, $entity) { $this->getEventManager()->trigger(__FUNCTION__.'.init', $this, [ 'entity' => $entity, 'form' => $form, ]); if (! $form->isValid()) { $this->getEventManager()->trigger(__FUNCTION__.'.invalid', $this, [ 'entity' => $entity, 'form' => $form, ]); return false; } $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default'); $entity = $form->getData(); if ($entity->getId() > 0) { $entity = $em->merge($entity); if (\method_exists($entity, "setUpdated")) { $entity->setUpdated(new \DateTime('now')); } } $this->getEventManager()->trigger(__FUNCTION__, $this, [ 'entity' => $entity, 'form' => $form, ]); $em->persist($entity); $em->flush(); $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, [ 'entity' => $entity, 'form' => $form, ]); return $entity; } public function delete($entity) { if (! is_object($entity)) { throw new \InvalidArgumentException(sprintf("Entity argument must be an object, %s given.", \gettype($entity))); } $this->getEventManager()->trigger(__FUNCTION__.'.init', $this, [ 'entity' => $entity, ]); $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default'); $id = 0; if ($entity->getId() > 0) { $id = $entity->getId(); $em->remove($entity); $em->flush(); } $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, [ 'entityId' => $id, ]); return $entity; } }
{ "content_hash": "b46e5f5a5860933242659c178b710150", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 124, "avg_line_length": 30.892857142857142, "alnum_prop": 0.5472061657032755, "repo_name": "juniorhanun/Base", "id": "5c1c052b6ff74ae6dbd869f253e8c1f952d4c932", "size": "3010", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/los/losbase/src/LosBase/Service/ORM/AbstractEntity.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "CSS", "bytes": "1042" }, { "name": "HTML", "bytes": "12413" }, { "name": "PHP", "bytes": "9934" } ], "symlink_target": "" }
import { BufferGeometry } from '../../core/BufferGeometry'; import { CylinderBufferGeometry } from './CylinderBufferGeometry'; /* * @author: abelnation / http://github.com/abelnation */ function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) { CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ); this.type = 'ConeBufferGeometry'; this.parameters = { radius: radius, height: height, radialSegments: radialSegments, heightSegments: heightSegments, thetaStart: thetaStart, thetaLength: thetaLength }; } ConeBufferGeometry.prototype = Object.create( BufferGeometry.prototype ); ConeBufferGeometry.prototype.constructor = ConeBufferGeometry; export { ConeBufferGeometry };
{ "content_hash": "9d11647d4262831a42b48135cdcb53d4", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 73, "avg_line_length": 23.82857142857143, "alnum_prop": 0.762589928057554, "repo_name": "sole/three.js", "id": "64162a296b7119317afb885d84208f63de3406a2", "size": "834", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/extras/geometries/ConeBufferGeometry.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "139" }, { "name": "C", "bytes": "80088" }, { "name": "C++", "bytes": "116991" }, { "name": "CSS", "bytes": "23395" }, { "name": "GLSL", "bytes": "80553" }, { "name": "HTML", "bytes": "34440" }, { "name": "JavaScript", "bytes": "3664768" }, { "name": "MAXScript", "bytes": "75494" }, { "name": "Python", "bytes": "517599" }, { "name": "Shell", "bytes": "9237" } ], "symlink_target": "" }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Text; namespace SharpVectors.Dom.Svg { /// <summary> /// Summary description for SvgPathSegCurvetoCubicSmoothAbs. /// </summary> public class SvgPathSegCurvetoCubicSmoothRel : SvgPathSegCurvetoCubic, ISvgPathSegCurvetoCubicSmoothRel { #region constructors internal SvgPathSegCurvetoCubicSmoothRel(float x, float y, float x2, float y2) : base(SvgPathSegType.CurveToCubicSmoothRel) { this.x = x; this.y = y; this.x2 = x2; this.y2 = y2; } #endregion #region implementation of ISvgPathSegCurvetoCubicSmoothRel private float x; public float X { get{return x;} set{x = value;} } private float y; public float Y { get{return y;} set{y = value;} } private float x2; public float X2 { get{return x2;} set{x2 = value;} } private float y2; public float Y2 { get{return y2;} set{y2 = value;} } #endregion #region public methods public override PointF AbsXY { get { SvgPathSeg prevSeg = PreviousSeg; PointF prevPoint; if(prevSeg == null) prevPoint = new PointF(0,0); else prevPoint = prevSeg.AbsXY; return new PointF(prevPoint.X + X, prevPoint.Y + Y); } } public override PointF CubicX1Y1 { get { SvgPathSeg prevSeg = PreviousSeg; if(prevSeg == null || !(prevSeg is SvgPathSegCurvetoCubic)) { return prevSeg.AbsXY; } else { PointF prevXY = prevSeg.AbsXY; PointF prevX2Y2 = ((SvgPathSegCurvetoCubic)prevSeg).CubicX2Y2; return new PointF(2 * prevXY.X - prevX2Y2.X, 2 * prevXY.Y - prevX2Y2.Y); } } } public override PointF CubicX2Y2 { get { SvgPathSeg prevSeg = PreviousSeg; PointF prevPoint; if(prevSeg == null) prevPoint = new PointF(0,0); else prevPoint = prevSeg.AbsXY; return new PointF(prevPoint.X + X2, prevPoint.Y + Y2); } } public override string PathText { get { StringBuilder sb = new StringBuilder(); sb.Append(PathSegTypeAsLetter); sb.Append(X2); sb.Append(","); sb.Append(Y2); sb.Append(","); sb.Append(X); sb.Append(","); sb.Append(Y); return sb.ToString(); } } #endregion #region unit tests #endregion } }
{ "content_hash": "8f08977b8de3e588458ef17ff281b082", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 125, "avg_line_length": 19.991666666666667, "alnum_prop": 0.614422676115048, "repo_name": "codebutler/savagesvg", "id": "f6628151a50a87dbb16c8429fe2afb948aae14c8", "size": "2399", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SharpVectorObjectModel/SharpVectors/Dom/Svg/Paths/SvgPathSegCurvetoCubicSmoothRel.cs", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
Takes a burp dump and format/display it in various formats
{ "content_hash": "43522b076b18d252048383d6a7a32d36", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 58, "avg_line_length": 59, "alnum_prop": 0.8135593220338984, "repo_name": "yenda/burp-clj", "id": "4935aa580206cb9783c1203d20c8eb4ee22dbcce", "size": "70", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Clojure", "bytes": "4808" } ], "symlink_target": "" }
package ru.job4j.web; import java.io.IOException; import java.nio.charset.Charset; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.logging.log4j.Logger; /** * Класс EncodingFilter реализует фильтр кодировки. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2018-05-22 * @since 2018-05-10 */ public class EncodingFilter extends AbstractServlet implements Filter { /** * Логгер. */ private Logger logger; /** * Инициализатор. * @param filterConfig конфигурация фильтра * @throws javax.servlet.ServletException исключение сервлета. */ @Override public void init(FilterConfig filterConfig) throws ServletException { try { super.init(); } catch (Exception ex) { this.logger.error("ERROR", ex); } } /** * Производит фильтрацию. * @param request запрос. * @param response ответ. * @param chain цепь. * @throws javax.servlet.ServletException исключение сервлета. * @throws java.io.IOException исключение ввода-вывода. */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { response.setContentType("text/html"); String enc = Charset.defaultCharset().toString(); response.setCharacterEncoding(enc); request.setAttribute("encoding", enc); chain.doFilter(request, response); } catch (Exception ex) { this.logger.error("ERROR", ex); } } /** * Вызывается при уничтожении сервлета. */ @Override public void destroy() { } }
{ "content_hash": "8054c5fff80c2f57020283dbd311a0da", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 132, "avg_line_length": 29.26984126984127, "alnum_prop": 0.670824295010846, "repo_name": "multiscripter/job4j", "id": "35810c8fe57b7540f08ded7645b39d4e4b5e2529", "size": "2035", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "junior/pack3_pre/p1_hibernate/ch4_carStoreIntegrationTests/src/main/java/ru/job4j/web/EncodingFilter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "24873" }, { "name": "Java", "bytes": "3798662" }, { "name": "JavaScript", "bytes": "14668" }, { "name": "XSLT", "bytes": "366" } ], "symlink_target": "" }
#include <iostream> #include "gflags/gflags.h" #include "webrtc/base/logging.h" #include "webrtc/modules/audio_processing/test/conversational_speech/config.h" #include "webrtc/test/testsupport/fileutils.h" namespace webrtc { namespace test { namespace { // Adapting DirExists/FileExists interfaces to DEFINE_validator. auto dir_exists = [](const char* c, const std::string& dirpath) { return DirExists(dirpath); }; auto file_exists = [](const char* c, const std::string& filepath) { return FileExists(filepath); }; const char kUsageDescription[] = "Usage: conversational_speech_generator\n" " -i <path/to/source/audiotracks>\n" " -t <path/to/timing_file.txt>\n" " -o <output/path>\n" "\n\n" "Command-line tool to generate multiple-end audio tracks to simulate " "conversational speech with two or more participants."; DEFINE_string(i, "", "Directory containing the speech turn wav files"); DEFINE_validator(i, dir_exists); DEFINE_string(t, "", "Path to the timing text file"); DEFINE_validator(t, file_exists); DEFINE_string(o, "", "Output wav files destination path"); DEFINE_validator(o, dir_exists); } // namespace int main(int argc, char* argv[]) { google::SetUsageMessage(kUsageDescription); google::ParseCommandLineFlags(&argc, &argv, true); conversational_speech::Config config(FLAGS_i, FLAGS_t, FLAGS_o); // TODO(alessiob): remove line below once debugged. rtc::LogMessage::LogToDebug(rtc::LS_VERBOSE); LOG(LS_VERBOSE) << "i = " << config.audiotracks_path(); LOG(LS_VERBOSE) << "t = " << config.timing_filepath(); LOG(LS_VERBOSE) << "o = " << config.output_path(); return 0; } } // namespace test } // namespace webrtc int main(int argc, char* argv[]) { return webrtc::test::main(argc, argv); }
{ "content_hash": "96a8b792e865a3984a1b911f315b86da", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 78, "avg_line_length": 29.983333333333334, "alnum_prop": 0.6859366314619233, "repo_name": "Alkalyne/webrtctrunk", "id": "923736ffef20c7a8a57c27bf5769fcba980177a6", "size": "2211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/audio_processing/test/conversational_speech/generator.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "22469" }, { "name": "C", "bytes": "3405665" }, { "name": "C++", "bytes": "24404959" }, { "name": "CSS", "bytes": "1617" }, { "name": "Java", "bytes": "643292" }, { "name": "JavaScript", "bytes": "5409" }, { "name": "Matlab", "bytes": "26947" }, { "name": "Objective-C", "bytes": "186937" }, { "name": "Objective-C++", "bytes": "472228" }, { "name": "Protocol Buffer", "bytes": "21689" }, { "name": "Python", "bytes": "146387" }, { "name": "Ruby", "bytes": "615" }, { "name": "Shell", "bytes": "75957" } ], "symlink_target": "" }
import * as React from 'react'; import { OverridableStringUnion } from '@material-ui/types'; import { OverridableComponent, OverrideProps } from '../OverridableComponent'; export interface AvatarPropsVariantOverrides {} export type AvatarVariantDefaults = Record<'circular' | 'rounded' | 'square', true>; export interface AvatarTypeMap<P = {}, D extends React.ElementType = 'div'> { props: P & { /** * Used in combination with `src` or `srcSet` to * provide an alt attribute for the rendered `img` element. */ alt?: string; /** * Used to render icon or text elements inside the Avatar if `src` is not set. * This can be an element, or just a string. */ children?: React.ReactNode; /** * Override or extend the styles applied to the component. */ classes?: { /** Styles applied to the root element. */ root?: string; /** Styles applied to the root element if not `src` or `srcSet`. */ colorDefault?: string; /** Styles applied to the root element if `variant="circular"`. */ circular?: string; /** Styles applied to the root element if `variant="rounded"`. */ rounded?: string; /** Styles applied to the root element if `variant="square"`. */ square?: string; /** Styles applied to the img element if either `src` or `srcSet` is defined. */ img?: string; /** Styles applied to the fallback icon */ fallback?: string; }; /** * Attributes applied to the `img` element if the component is used to display an image. * It can be used to listen for the loading error event. */ imgProps?: React.ImgHTMLAttributes<HTMLImageElement>; /** * The `sizes` attribute for the `img` element. */ sizes?: string; /** * The `src` attribute for the `img` element. */ src?: string; /** * The `srcSet` attribute for the `img` element. * Use this attribute for responsive image display. */ srcSet?: string; /** * The shape of the avatar. */ variant?: OverridableStringUnion<AvatarVariantDefaults, AvatarPropsVariantOverrides>; }; defaultComponent: D; } /** * * Demos: * * - [Avatars](https://material-ui.com/components/avatars/) * * API: * * - [Avatar API](https://material-ui.com/api/avatar/) */ declare const Avatar: OverridableComponent<AvatarTypeMap>; export type AvatarClassKey = keyof NonNullable<AvatarTypeMap['props']['classes']>; export type AvatarProps< D extends React.ElementType = AvatarTypeMap['defaultComponent'], P = {} > = OverrideProps<AvatarTypeMap<P, D>, D>; export default Avatar;
{ "content_hash": "b88c66d94b775ee36057a9ac103cb032", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 92, "avg_line_length": 31.607142857142858, "alnum_prop": 0.64030131826742, "repo_name": "cdnjs/cdnjs", "id": "2da18c423760d6a56ba9d437bfab3a31f863e0de", "size": "2655", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/material-ui/5.0.0-alpha.8/Avatar/Avatar.d.ts", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php // Copyright 2004-present Facebook. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * Used to locate a given frame or window. */ class WebDriverTargetLocator { protected $executor; protected $driver; public function __construct($executor, $driver) { $this->executor = $executor; $this->driver = $driver; } /** * Switch to the main document if the page contains iframes. Otherwise, switch * to the first frame on the page. * * @return WebDriver The driver focused on the top window or the first frame. */ public function defaultContent() { $this->executor->execute('focusFrame', array()); return $this->driver; } /** * Switch to the iframe by its id or name. * * @param WebDriverElement|string $frame The WebDriverElement, the id or the name of the frame. * @return WebDriver The driver focused on the given frame. */ public function frame($frame) { if ($frame instanceof WebDriverElement) { $id = array('ELEMENT' => $frame->getID()); } else { $id = (string)$frame; } $params = array('id' => $id); $this->executor->execute('focusFrame', $params); return $this->driver; } /** * Switch the focus to another window by its handle. * * @param string $handle The handle of the window to be focused on. * @return WebDriver Tge driver focused on the given window. * @see WebDriver::getWindowHandles */ public function window($handle) { $params = array('name' => (string)$handle); $this->executor->execute('focusWindow', $params); return $this->driver; } /** * Switch to the currently active modal dialog for this particular driver * instance. * * @return WebDriverAlert */ public function alert() { return new WebDriverAlert($this->executor); } }
{ "content_hash": "9cf927c39c093802b083dcd158cec190", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 80, "avg_line_length": 28.547619047619047, "alnum_prop": 0.6580483736447039, "repo_name": "Sampa/PP", "id": "2e937991cff6644a8e3b874a38566fde8b95c733", "size": "2398", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "vendor/facebook/webdriver/lib/WebDriverTargetLocator.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1023628" }, { "name": "JavaScript", "bytes": "835348" }, { "name": "PHP", "bytes": "220731" }, { "name": "Shell", "bytes": "5450" } ], "symlink_target": "" }
package edu.cmu.lti.oaqa.baseqa.answer.score.scorers; import com.google.common.collect.ImmutableMap; import edu.cmu.lti.oaqa.baseqa.learning_base.AbstractScorer; import edu.cmu.lti.oaqa.baseqa.learning_base.Scorer; import edu.cmu.lti.oaqa.type.answer.Answer; import edu.cmu.lti.oaqa.type.answer.CandidateAnswerOccurrence; import edu.cmu.lti.oaqa.type.nlp.Focus; import edu.cmu.lti.oaqa.type.nlp.Token; import edu.cmu.lti.oaqa.util.TypeUtil; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.resource.ResourceSpecifier; import java.util.*; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; /** * An instance of an {@link AbstractScorer} for {@link Answer}s that calculates the average distance * between the {@link Focus} token and each {@link CandidateAnswerOccurrence}. * In comparison to {@link TokenProximityAnswerScorer}, only the {@link Focus} token is used, * instead of all the {@link Token}s in the question. * * @see ConceptProximityAnswerScorer * @see TokenProximityAnswerScorer * @see ParseHeadProximityAnswerScorer * * @author <a href="mailto:ziy@cs.cmu.edu">Zi Yang</a> created on 4/29/15 */ public class FocusProximityAnswerScorer extends AbstractScorer<Answer> { private int windowSize; private double infinity; private double smoothing; private String focusLabel; @Override public boolean initialize(ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams) throws ResourceInitializationException { boolean ret = super.initialize(aSpecifier, aAdditionalParams); windowSize = (int) getParameterValue("window-size"); infinity = (double) getParameterValue("infinity"); smoothing = (double) getParameterValue("smoothing"); return ret; } @Override public void prepare(JCas jcas) throws AnalysisEngineProcessException { Focus focus = TypeUtil.getFocus(jcas); focusLabel = focus == null ? null : focus.getLabel(); } @Override public Map<String, Double> score(JCas jcas, Answer answer) { Set<CandidateAnswerOccurrence> caos = TypeUtil.getCandidateAnswerVariants(answer).stream() .map(TypeUtil::getCandidateAnswerOccurrences).flatMap(Collection::stream) .collect(toSet()); double[] precedingDistances = caos.stream().mapToDouble(cao -> { List<String> precedingTokens = JCasUtil.selectPreceding(Token.class, cao, windowSize) .stream().sorted(Comparator.comparing(Token::getEnd, Comparator.reverseOrder())) .map(Token::getLemmaForm).collect(toList()); double precedingDistance = precedingTokens.indexOf(focusLabel); if (precedingDistance == -1) precedingDistance = infinity; return precedingDistance; }).toArray(); double[] followingDistances = caos.stream().mapToDouble(cao -> { List<String> followingTokens = JCasUtil.selectFollowing(Token.class, cao, windowSize) .stream().sorted(Comparator.comparing(Token::getBegin)).map(Token::getLemmaForm) .collect(toList()); double followingDistance = followingTokens.indexOf(focusLabel); if (followingDistance == -1) followingDistance = infinity; return followingDistance; }).toArray(); ImmutableMap.Builder<String, Double> builder = ImmutableMap.builder(); Scorer.generateSummaryDistanceFeatures(precedingDistances, builder, infinity, smoothing, "focus-preceding", "avg", "max", "min", "pos-ratio"); Scorer.generateSummaryDistanceFeatures(followingDistances, builder, infinity, smoothing, "focus-following", "avg", "max", "min", "pos-ratio"); return builder.build(); } }
{ "content_hash": "8d947de4a00f688d10ce696fc6cbcf3a", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 100, "avg_line_length": 41.483870967741936, "alnum_prop": 0.7358735095904614, "repo_name": "oaqa/bioasq", "id": "92a257469266b3ee0d14d260985f869c7418805c", "size": "4508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/edu/cmu/lti/oaqa/baseqa/answer/score/scorers/FocusProximityAnswerScorer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "684299" }, { "name": "Python", "bytes": "5965" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <copyright file="Camera.h" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ #pragma once #include <windows.h> #include <xnamath.h> class CCamera { public: XMMATRIX View; /// <summary> /// Constructor /// </summary> CCamera(); /// <summary> /// Handles window messages, used to process input /// </summary> /// <param name="hWnd">window message is for</param> /// <param name="uMsg">message</param> /// <param name="wParam">message data</param> /// <param name="lParam">additional message data</param> /// <returns>result of message processing</returns> LRESULT HandleMessages(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); /// <summary> /// Reset the camera state to initial values /// </summary> void Reset(); /// <summary> /// Update the view matrix /// </summary> void Update(); /// <summary> /// Get the camera's up vector /// </summary> /// <returns>camera's up vector</returns> XMVECTOR GetUp() { return m_up; } /// <summary> /// Get the camera's right vector /// </summary> /// <returns>camera's right vector</returns> XMVECTOR GetRight() { return m_right; } /// <summary> /// Get the camera's position vector /// </summary> /// <returns>camera's position vector</returns> XMVECTOR GetEye() { return m_eye; } private: float m_rotationSpeed; float m_movementSpeed; float m_yaw; float m_pitch; XMVECTOR m_eye; XMVECTOR m_at; XMVECTOR m_up; XMVECTOR m_forward; XMVECTOR m_right; XMVECTOR m_atBasis; XMVECTOR m_upBasis; };
{ "content_hash": "22aae82f89256d7b56a9a4a7a532ed33", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 81, "avg_line_length": 25.445945945945947, "alnum_prop": 0.5443441317047265, "repo_name": "gsteelman/utd", "id": "05a987b3c18661ae95709fbb6b272ea89bcd49cf", "size": "1885", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cs6V81-kinect-research/project/Camera.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Arduino", "bytes": "596" }, { "name": "C", "bytes": "149459" }, { "name": "C++", "bytes": "851953" }, { "name": "CSS", "bytes": "43006" }, { "name": "FLUX", "bytes": "5154" }, { "name": "Java", "bytes": "363012" }, { "name": "JavaScript", "bytes": "67059" }, { "name": "Objective-C", "bytes": "582" }, { "name": "Python", "bytes": "2518" }, { "name": "Shell", "bytes": "5699" }, { "name": "TeX", "bytes": "193155" } ], "symlink_target": "" }
import pytest from xs.parsers import EtreeParser from xs.test.test_complextype import Student, EXPECTED_STUDENT_XML def test_parse_string(): parser = EtreeParser() parser.register(Student) student = parser.parse_string(EXPECTED_STUDENT_XML) assert isinstance(student, Student) assert student.name == "Joe Cool" assert student.grade == [75, 89, 66]
{ "content_hash": "283a339998a095358e9cd56944c56c4f", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 66, "avg_line_length": 26.857142857142858, "alnum_prop": 0.7287234042553191, "repo_name": "gtback/excess", "id": "465a67d5581f05372b97da67ec757f6ad0a78d33", "size": "376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xs/test/parsers/test_etree.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "40869" } ], "symlink_target": "" }
import collections from mitmproxy.net.http.headers import Headers, parse_content_type, assemble_content_type from mitmproxy.test.tutils import raises class TestHeaders: def _2host(self): return Headers( ( (b"Host", b"example.com"), (b"host", b"example.org") ) ) def test_init(self): headers = Headers() assert len(headers) == 0 headers = Headers([[b"Host", b"example.com"]]) assert len(headers) == 1 assert headers["Host"] == "example.com" headers = Headers(Host="example.com") assert len(headers) == 1 assert headers["Host"] == "example.com" headers = Headers( [[b"Host", b"invalid"]], Host="example.com" ) assert len(headers) == 1 assert headers["Host"] == "example.com" headers = Headers( [[b"Host", b"invalid"], [b"Accept", b"text/plain"]], Host="example.com" ) assert len(headers) == 2 assert headers["Host"] == "example.com" assert headers["Accept"] == "text/plain" with raises(TypeError): Headers([[b"Host", u"not-bytes"]]) def test_set(self): headers = Headers() headers[u"foo"] = u"1" headers[b"bar"] = b"2" headers["baz"] = b"3" with raises(TypeError): headers["foobar"] = 42 assert len(headers) == 3 def test_bytes(self): headers = Headers(Host="example.com") assert bytes(headers) == b"Host: example.com\r\n" headers = Headers([ [b"Host", b"example.com"], [b"Accept", b"text/plain"] ]) assert bytes(headers) == b"Host: example.com\r\nAccept: text/plain\r\n" headers = Headers() assert bytes(headers) == b"" def test_replace_simple(self): headers = Headers(Host="example.com", Accept="text/plain") replacements = headers.replace("Host: ", "X-Host: ") assert replacements == 1 assert headers["X-Host"] == "example.com" assert "Host" not in headers assert headers["Accept"] == "text/plain" def test_replace_multi(self): headers = self._2host() headers.replace(r"Host: example\.com", r"Host: example.de") assert headers.get_all("Host") == ["example.de", "example.org"] def test_replace_remove_spacer(self): headers = Headers(Host="example.com") replacements = headers.replace(r"Host: ", "X-Host ") assert replacements == 0 assert headers["Host"] == "example.com" def test_replace_with_count(self): headers = Headers(Host="foobarfoo.com", Accept="foo/bar") replacements = headers.replace("foo", "bar", count=1) assert replacements == 1 def test_parse_content_type(): p = parse_content_type assert p("text/html") == ("text", "html", {}) assert p("text") is None v = p("text/html; charset=UTF-8") assert v == ('text', 'html', {'charset': 'UTF-8'}) def test_assemble_content_type(): p = assemble_content_type assert p("text", "html", {}) == "text/html" assert p("text", "html", {"charset": "utf8"}) == "text/html; charset=utf8" assert p("text", "html", collections.OrderedDict([("charset", "utf8"), ("foo", "bar")])) == "text/html; charset=utf8; foo=bar"
{ "content_hash": "bcb20e575e97197ce0d16b2bcd9d59dd", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 130, "avg_line_length": 32.009433962264154, "alnum_prop": 0.5552608311229, "repo_name": "dwfreed/mitmproxy", "id": "8e0f770d700b08d0a13d8d0c6551d882d6a19def", "size": "3393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/mitmproxy/net/http/test_headers.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "208058" }, { "name": "HTML", "bytes": "4270" }, { "name": "JavaScript", "bytes": "2149949" }, { "name": "PowerShell", "bytes": "494" }, { "name": "Python", "bytes": "1378470" }, { "name": "Shell", "bytes": "3660" } ], "symlink_target": "" }
if(NOT DEFINED CMAKE_INSTALL_PREFIX) set(CMAKE_INSTALL_PREFIX "/home/bladestery/Sapphire/example_apps/AndroidStudioMinnie/sapphire/.externalNativeBuild/cmake/debug/armeabi/install") endif() string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) if(BUILD_TYPE) string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") else() set(CMAKE_INSTALL_CONFIG_NAME "Debug") endif() message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") endif() # Set the component getting installed. if(NOT CMAKE_INSTALL_COMPONENT) if(COMPONENT) message(STATUS "Install component: \"${COMPONENT}\"") set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") else() set(CMAKE_INSTALL_COMPONENT) endif() endif() # Install shared libraries without execute permission? if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) set(CMAKE_INSTALL_SO_NO_EXE "1") endif()
{ "content_hash": "06c2df0fbfdbb917d58a9347351a106e", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 146, "avg_line_length": 32.483870967741936, "alnum_prop": 0.7189672293942403, "repo_name": "bladestery/Sapphire", "id": "b7763427887d002ac657472090d116b242d8557e", "size": "1121", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "example_apps/AndroidStudioMinnie/sapphire/.externalNativeBuild/cmake/debug/armeabi/modules/highgui/.highgui/cmake_install.cmake", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "139298" }, { "name": "C++", "bytes": "1444206" }, { "name": "CMake", "bytes": "3964660" }, { "name": "Java", "bytes": "14581743" }, { "name": "Makefile", "bytes": "107081" }, { "name": "Python", "bytes": "11485" }, { "name": "Shell", "bytes": "495" } ], "symlink_target": "" }
#include "GlipStudio.hpp" #include <QDateTime> #include <QDebug> #include <QFontDatabase> // Special function, for redirection of qDebug, qCritical, etc. to a file : #if QT_VERSION >= 0x050000 void customMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) #else void customMessageHandler(QtMsgType type, const char *msgCStr) #endif { QDateTime dateTime = QDateTime::currentDateTime(); QString txt; #if QT_VERSION < 0x050000 const QString msg = QString::fromAscii(msgCStr); #endif switch (type) { case QtDebugMsg: txt = QString("[%1] DEBUG :\n%2").arg(dateTime.toString()).arg(msg); break; case QtWarningMsg: txt = QString("[%1] WARNING :\n%2").arg(dateTime.toString()).arg(msg); break; case QtCriticalMsg: txt = QString("[%1] CRITICAL :\n%2").arg(dateTime.toString()).arg(msg); break; case QtFatalMsg: txt = QString("[%1] FATAL :\n%2").arg(dateTime.toString()).arg(msg); break; default : txt = QString("[%1] UNKNOWN :\n%2").arg(dateTime.toString()).arg(msg); } std::cout << txt.toStdString() << std::endl; QFile outFile("errorLog.txt"); outFile.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream stream(&outFile); stream << txt << "\n"; if(type==QtFatalMsg) abort(); } // GlipStudio : GlipStudio::GlipStudio(int& argc, char** argv) : QApplication(argc, argv), window(NULL), variableTracker(NULL), editor(NULL), collection(NULL), pipelineManager(NULL) { #if QT_VERSION >= 0x050000 qInstallMessageHandler(reinterpret_cast<QtMessageHandler>(customMessageHandler)); #else qInstallMsgHandler(customMessageHandler); #endif loadStyleSheet(); loadFonts(); window = new QVGL::MainWidget; variableTracker = new QVGL::VariablesTrackerSubWidget; editor = new QGED::CodeEditorTabsSubWidget; collection = new QGIC::ImageItemsCollectionSubWidget; pipelineManager = new QGPM::PipelineManagerSubWidget(); // Add Subwidgets : window->addSubWidget(editor); window->addSubWidget(variableTracker); window->addSubWidget(collection); window->addSubWidget(pipelineManager); editor->hide(); variableTracker->hide(); collection->hide(); pipelineManager->hide(); // Connections : QObject::connect(window, SIGNAL(requestQuit()), this, SLOT(processQuitRequest())); QObject::connect(collection, SIGNAL(addViewRequest(QVGL::View*)), window, SLOT(addView(QVGL::View*))); QObject::connect(collection, SIGNAL(addViewsTableRequest(QVGL::ViewsTable*)), window, SLOT(addViewsTable(QVGL::ViewsTable*))); QObject::connect(editor->getCodeEditorPtr(), SIGNAL(compileSource(std::string, std::string, std::string, void*, const QObject*)), pipelineManager->getManagerPtr(), SLOT(compileSource(std::string, std::string, std::string, void*, const QObject*))); QObject::connect(collection->getCollectionPtr(), SIGNAL(imageItemAdded(QGIC::ImageItem*)), pipelineManager->getManagerPtr(), SLOT(addImageItem(QGIC::ImageItem*))); QObject::connect(pipelineManager->getManagerPtr(), SIGNAL(addViewRequest(QVGL::View*)), window, SLOT(addView(QVGL::View*))); QObject::connect(pipelineManager->getManagerPtr(), SIGNAL(addViewsTableRequest(QVGL::ViewsTable*)), window, SLOT(addViewsTable(QVGL::ViewsTable*))); QObject::connect(pipelineManager->getManagerPtr(), SIGNAL(addImageItemRequest(HdlTexture*, const QString)), collection->getCollectionPtr(), SLOT(addImageItem(HdlTexture*, const QString))); QObject::connect(pipelineManager->getManagerPtr(), SIGNAL(editFile(const QString)), editor->getCodeEditorPtr(), SLOT(open(const QString&))); window->resize(900, 600); window->show(); } GlipStudio::~GlipStudio(void) { delete pipelineManager; delete collection; delete editor; delete variableTracker; delete window; } void GlipStudio::loadStyleSheet(void) { const QString stylesheetFilename = "stylesheet.css"; QFile stylesheetFile(stylesheetFilename); if(!stylesheetFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QString path = QDir::currentPath(); std::cout << "Preparing exception : " << stylesheetFile.fileName().toStdString() << " and " << path.toStdString() << std::endl; Exception e("GlipStudio::GlipStudio - The style sheet \"" + stylesheetFile.fileName().toStdString() + "\" could not be loaded (from " + path.toStdString() + ").", __FILE__, __LINE__); qCritical() << e.what(); QMessageBox messageBox(QMessageBox::Warning, "Error", tr("The style sheet \"%1\" could not be loaded.\nIn %2. The execution will continue with default theme on your system.").arg(stylesheetFile.fileName()).arg(path), QMessageBox::Ok); messageBox.exec(); } else { QTextStream stylesheetStream(&stylesheetFile); QString stylesheet = stylesheetStream.readAll(); // Set style : QApplication::setStyleSheet(stylesheet); } } void GlipStudio::loadFonts(void) { // Load fonts : int fid = QFontDatabase::addApplicationFont("Fonts/SourceCodePro-Regular.ttf"); //if( fid < 0) // std::cerr << "Could not locate the font!" << std::endl; fid = QFontDatabase::addApplicationFont("Fonts/SourceCodePro-Black.ttf"); //if( fid < 0) // std::cerr << "Could not locate the font!" << std::endl; fid = QFontDatabase::addApplicationFont("Fonts/SourceCodePro-Bold.ttf"); //if( fid < 0) // std::cerr << "Could not locate the font!" << std::endl; fid = QFontDatabase::addApplicationFont("Fonts/SourceCodePro-Light.ttf"); //if( fid < 0) // std::cerr << "Could not locate the font!" << std::endl; fid = QFontDatabase::addApplicationFont("Fonts/SourceCodePro-ExtraLight.ttf"); //if( fid < 0) // std::cerr << "Could not locate the font!" << std::endl; fid = QFontDatabase::addApplicationFont("Fonts/SourceCodePro-Medium.ttf"); //if( fid < 0) // std::cerr << "Could not locate the font!" << std::endl; fid = QFontDatabase::addApplicationFont("Fonts/SourceCodePro-Semibold.ttf"); //if( fid < 0) // std::cerr << "Could not locate the font!" << std::endl; /*std::cout << "Font list : " << std::endl; QFontDatabase db; foreach(const QString& family, QFontDatabase::applicationFontFamilies(fid)) { std::cout << " " << family.toStdString() << std::endl; foreach(const QString& style, db.styles(family)) std::cout << " " << style.toStdString() << std::endl; } std::cout << "End font list." << std::endl;*/ } void GlipStudio::processQuitRequest(void) { QApplication::quit(); } bool GlipStudio::notify(QObject * receiver, QEvent * event) { try { return QApplication::notify(receiver, event); } catch(std::exception& e) { // Save : qWarning() << e.what(); // Warning : QMessageBox messageBox(QMessageBox::Warning, "Error", tr("An exception was caught. However, you might be able to continue execution."), QMessageBox::Ok); messageBox.setDetailedText(e.what()); messageBox.exec(); } return false; }
{ "content_hash": "1ac987790345998184d5f575bfee4172", "timestamp": "", "source": "github", "line_count": 202, "max_line_length": 253, "avg_line_length": 34.806930693069305, "alnum_prop": 0.6824064855639311, "repo_name": "headupinclouds/GLIP-Lib", "id": "c1b862f88e2e7710ff14472281a5120d251c4f11", "size": "7031", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tools/GlipStudio/src/GlipStudio.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2067850" }, { "name": "C++", "bytes": "2134014" }, { "name": "CMake", "bytes": "2972" }, { "name": "CSS", "bytes": "26436" }, { "name": "GLSL", "bytes": "33281" }, { "name": "HTML", "bytes": "1967" }, { "name": "QMake", "bytes": "8906" }, { "name": "Shell", "bytes": "1548" } ], "symlink_target": "" }
#if defined(USE_TI_XML) || defined(USE_TI_NETWORK) #import "TIDOMDOMImplementationProxy.h" #import "TIDOMDocumentTypeProxy.h" #import "TiDOMDocumentProxy.h" #import "TiDOMValidator.h" #import "TiUtils.h" @implementation TIDOMDOMImplementation -(id)hasFeature:(id)args { ENSURE_ARG_COUNT(args, 2); NSString *feature = [args objectAtIndex:0]; ENSURE_STRING_OR_NIL(feature); NSString *version = [args objectAtIndex:1]; ENSURE_STRING_OR_NIL(version); if(feature != nil) { if( (version == nil) || ([[version lowercaseString] compare:@"1.0"] == 0) || ([[version lowercaseString] compare:@"2.0"] == 0) ) { if([[feature lowercaseString] compare:@"core"] == 0) return NUMBOOL(YES); else if([[feature lowercaseString] compare:@"xml"] == 0) return NUMBOOL(YES); else return NUMBOOL(NO); } } return NUMBOOL(NO); } -(id)createDocumentType:(id)args { ENSURE_ARG_COUNT(args, 3); NSString* qualifiedName; NSString* publicId; NSString* systemId; ENSURE_ARG_OR_NIL_AT_INDEX(qualifiedName,args,0,NSString); ENSURE_ARG_OR_NIL_AT_INDEX(publicId,args,1,NSString); ENSURE_ARG_OR_NIL_AT_INDEX(systemId,args,2,NSString); GDataXMLNode* resultElement = [GDataXMLNode dtdWithQualifiedName:qualifiedName publicId:publicId sysId:systemId]; id context = ([self executionContext]==nil)?[self pageContext]:[self executionContext]; TIDOMDocumentTypeProxy * result = [[[TIDOMDocumentTypeProxy alloc] _initWithPageContext:context] autorelease]; [result setNode:resultElement]; [result setDocument:nil]; [TiDOMNodeProxy setNode:result forXMLNode:[resultElement XMLNode]]; return result; } -(id)createDocument:(id)args { ENSURE_ARG_COUNT(args, 3); NSString* theURI = [args objectAtIndex:0]; NSString* qualifiedName = [args objectAtIndex:1]; TIDOMDocumentTypeProxy* docType = [args objectAtIndex:2]; ENSURE_STRING_OR_NIL(theURI); ENSURE_STRING(qualifiedName); ENSURE_TYPE_OR_NIL(docType, TIDOMDocumentTypeProxy); //Validate the parameters NSString *error = nil; NSString *suberror = nil; [TiDOMNodeProxy validateElementParameters:qualifiedName withUri:theURI reason:&error subreason:&suberror]; if (error != nil) { [self throwException:error subreason:suberror location:CODELOCATION]; } NSString* prefix = [GDataXMLNode prefixForName:qualifiedName]; NSString* localName = [GDataXMLNode localNameForName:qualifiedName]; //Create the new NS pointer xmlChar *pre = NULL; xmlChar *href = NULL; if(theURI != nil) { href = (xmlChar*)[theURI UTF8String]; } if ([prefix length] > 0) { pre = (xmlChar*) [prefix UTF8String]; } xmlNsPtr theNewNs = xmlNewNs(NULL, // parent node href, pre); //Create the doc node with root element xmlNodePtr rootPtr = xmlNewNode(theNewNs, (xmlChar*)[localName UTF8String]); rootPtr->nsDef = theNewNs; xmlDocPtr doc = xmlNewDoc(NULL); xmlDocSetRootElement(doc, rootPtr); if (docType != nil) { GDataXMLNode *docTypeNode = [docType node]; xmlNodePtr ret = xmlAddChild((xmlNodePtr)doc, [docTypeNode XMLNode]); if (ret != NULL) { //Now it is part of the tree so switch flag to ensur it gets freed when doc is released [docTypeNode setShouldFreeXMLNode:NO]; } } GDataXMLDocument * theDocument = [[[GDataXMLDocument alloc]initWithDocument:doc]autorelease]; id context = ([self executionContext]==nil)?[self pageContext]:[self executionContext]; TiDOMDocumentProxy * result = [[[TiDOMDocumentProxy alloc] _initWithPageContext:context] autorelease]; [result setNode:[theDocument rootElement]]; [result setDocument:theDocument]; [TiDOMNodeProxy setNode:result forXMLNode:(xmlNodePtr)doc]; return result; } @end #endif
{ "content_hash": "a3c88dff7c7c4fe7bd5f68623923c43c", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 136, "avg_line_length": 32.868852459016395, "alnum_prop": 0.6658354114713217, "repo_name": "joshualambert/GO", "id": "66d39e5b8f959cd8b8257a065db71c56ed79474e", "size": "4317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/iphone/Classes/TIDOMDOMImplementationProxy.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "131207" }, { "name": "C++", "bytes": "63511" }, { "name": "D", "bytes": "784156" }, { "name": "JavaScript", "bytes": "1105515" }, { "name": "Objective-C", "bytes": "3265170" }, { "name": "Shell", "bytes": "155" } ], "symlink_target": "" }
package com.intellij.vcs.log.ui.actions; import com.intellij.openapi.actionSystem.ActionPromoter; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcs.log.VcsLogDataKeys; import com.intellij.vcs.log.VcsLogUi; import com.intellij.vcs.log.history.FileHistoryUi; import com.intellij.vcs.log.ui.actions.history.CompareRevisionsFromHistoryAction; import org.jetbrains.annotations.NotNull; import java.util.List; public class VcsLogActionPromoter implements ActionPromoter { @Override public List<AnAction> promote(@NotNull List<AnAction> actions, @NotNull DataContext context) { List<AnAction> promoted = ContainerUtil.newArrayList(); VcsLogUi ui = VcsLogDataKeys.VCS_LOG_UI.getData(context); if (ui != null && ui instanceof FileHistoryUi) { CompareRevisionsFromHistoryAction compareAction = ContainerUtil.findInstance(actions, CompareRevisionsFromHistoryAction.class); if (compareAction != null) promoted.add(compareAction); } return promoted; } }
{ "content_hash": "f44285c56bd5315927cd970cb39c8b44", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 133, "avg_line_length": 37.2, "alnum_prop": 0.7983870967741935, "repo_name": "semonte/intellij-community", "id": "2a30b3257a5e14b8fb0392a651922b97cd772fde", "size": "1716", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/VcsLogActionPromoter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "60580" }, { "name": "C", "bytes": "211556" }, { "name": "C#", "bytes": "1264" }, { "name": "C++", "bytes": "197528" }, { "name": "CMake", "bytes": "1675" }, { "name": "CSS", "bytes": "201445" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groovy", "bytes": "3222009" }, { "name": "HLSL", "bytes": "57" }, { "name": "HTML", "bytes": "1895767" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "164918191" }, { "name": "JavaScript", "bytes": "570364" }, { "name": "Jupyter Notebook", "bytes": "93222" }, { "name": "Kotlin", "bytes": "4472431" }, { "name": "Lex", "bytes": "147154" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "51270" }, { "name": "Objective-C", "bytes": "27941" }, { "name": "Perl", "bytes": "903" }, { "name": "Perl6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6680" }, { "name": "Python", "bytes": "25421481" }, { "name": "Roff", "bytes": "37534" }, { "name": "Ruby", "bytes": "1217" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "65719" }, { "name": "Smalltalk", "bytes": "338" }, { "name": "TeX", "bytes": "25473" }, { "name": "Thrift", "bytes": "1846" }, { "name": "TypeScript", "bytes": "9469" }, { "name": "Visual Basic", "bytes": "77" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
"""Class definitions for trainable aligners""" from __future__ import annotations import os import shutil import time from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple from montreal_forced_aligner.abc import ModelExporterMixin, TopLevelMfaWorker from montreal_forced_aligner.alignment.base import CorpusAligner from montreal_forced_aligner.db import Dictionary from montreal_forced_aligner.exceptions import ConfigError, KaldiProcessingError from montreal_forced_aligner.helper import load_configuration, mfa_open, parse_old_features from montreal_forced_aligner.models import AcousticModel, DictionaryModel from montreal_forced_aligner.utils import log_kaldi_errors if TYPE_CHECKING: from argparse import Namespace from montreal_forced_aligner.abc import MetaDict from montreal_forced_aligner.acoustic_modeling.base import AcousticModelTrainingMixin __all__ = ["TrainableAligner"] class TrainableAligner(CorpusAligner, TopLevelMfaWorker, ModelExporterMixin): """ Train acoustic model Parameters ---------- training_configuration : list[tuple[str, dict[str, Any]]] Training identifiers and parameters for training blocks phone_set_type: str Type of phone set to use for acoustic modeling See Also -------- :class:`~montreal_forced_aligner.alignment.base.CorpusAligner` For dictionary and corpus parsing parameters and alignment parameters :class:`~montreal_forced_aligner.abc.TopLevelMfaWorker` For top-level parameters :class:`~montreal_forced_aligner.abc.ModelExporterMixin` For model export parameters Attributes ---------- param_dict: dict[str, Any] Parameters to pass to training blocks final_identifier: str Identifier of the final training block current_subset: int Current training block's subset current_acoustic_model: :class:`~montreal_forced_aligner.models.AcousticModel` Acoustic model to use in aligning, based on previous training block training_configs: dict[str, :class:`~montreal_forced_aligner.acoustic_modeling.base.AcousticModelTrainingMixin`] Training blocks """ def __init__( self, training_configuration: List[Tuple[str, Dict[str, Any]]] = None, phone_set_type: str = None, **kwargs, ): self.param_dict = { k: v for k, v in kwargs.items() if not k.endswith("_directory") and not k.endswith("_path") and k not in ["clean", "num_jobs", "speaker_characters"] } self.final_identifier = None self.current_subset: int = 0 self.current_aligner: Optional[AcousticModelTrainingMixin] = None self.current_trainer: Optional[AcousticModelTrainingMixin] = None self.current_acoustic_model: Optional[AcousticModel] = None super().__init__(**kwargs) if phone_set_type and phone_set_type != "UNKNOWN": self.dictionary_model = DictionaryModel( self.dictionary_model.path, phone_set_type=phone_set_type ) self.phone_set_type = self.dictionary_model.phone_set_type os.makedirs(self.output_directory, exist_ok=True) self.training_configs: Dict[str, AcousticModelTrainingMixin] = {} if training_configuration is None: training_configuration = TrainableAligner.default_training_configurations() for k, v in training_configuration: self.add_config(k, v) @classmethod def default_training_configurations(cls) -> List[Tuple[str, Dict[str, Any]]]: """Default MFA training configuration""" training_params = [] training_params.append(("monophone", {"subset": 10000, "boost_silence": 1.25})) training_params.append( ( "triphone", { "subset": 20000, "boost_silence": 1.25, "num_leaves": 2000, "max_gaussians": 10000, }, ) ) training_params.append( ("lda", {"subset": 20000, "num_leaves": 2500, "max_gaussians": 15000}) ) training_params.append( ("sat", {"subset": 20000, "num_leaves": 2500, "max_gaussians": 15000}) ) training_params.append( ("sat", {"subset": 50000, "num_leaves": 4200, "max_gaussians": 40000}) ) training_params.append(("pronunciation_probabilities", {"subset": 50000})) training_params.append( ("sat", {"subset": 150000, "num_leaves": 5000, "max_gaussians": 100000}) ) training_params.append( ( "pronunciation_probabilities", {"subset": 150000, "optional": True}, ) ) training_params.append( ( "sat", { "subset": 0, "num_leaves": 7000, "optional": True, "max_gaussians": 150000, "num_iterations": 20, "quick": True, }, ) ) return training_params @classmethod def parse_parameters( cls, config_path: Optional[str] = None, args: Optional[Namespace] = None, unknown_args: Optional[List[str]] = None, ) -> MetaDict: """ Parse configuration parameters from a config file and command line arguments Parameters ---------- config_path: str, optional Path to yaml configuration file args: :class:`~argparse.Namespace`, optional Arguments parsed by argparse unknown_args: list[str], optional List of unknown arguments from argparse Returns ------- dict[str, Any] Dictionary of specified configuration parameters """ global_params = {} training_params = [] use_default = True if config_path: data = load_configuration(config_path) training_params = [] for k, v in data.items(): if k == "training": for t in v: for k2, v2 in t.items(): if "features" in v2: global_params.update(parse_old_features(v2["features"])) del v2["features"] training_params.append((k2, v2)) elif k == "features": global_params.update(parse_old_features(v)) else: if v is None and k in cls.nullable_fields: v = [] global_params[k] = v if training_params: use_default = False if use_default: # default training configuration training_params = TrainableAligner.default_training_configurations() if training_params: if training_params[0][0] != "monophone": raise ConfigError("The first round of training must be monophone.") global_params["training_configuration"] = training_params global_params.update(cls.parse_args(args, unknown_args)) return global_params def setup(self) -> None: """Setup for acoustic model training""" if self.initialized: return self.check_previous_run() try: self.load_corpus() self.write_training_information() for config in self.training_configs.values(): if isinstance(config, str): continue config.non_silence_phones = self.non_silence_phones except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise self.initialized = True @property def workflow_identifier(self) -> str: """Acoustic model training identifier""" return "train_acoustic_model" @property def configuration(self) -> MetaDict: """Configuration for the worker""" config = super().configuration config.update( { "dictionary_path": self.dictionary_model.path, "corpus_directory": self.corpus_directory, } ) return config @property def meta(self) -> MetaDict: """Metadata about the final round of training""" return self.training_configs[self.final_identifier].meta def add_config(self, train_type: str, params: MetaDict) -> None: """ Add a trainer to the pipeline Parameters ---------- train_type: str Type of trainer to add, one of ``monophone``, ``triphone``, ``lda`` or ``sat`` params: dict[str, Any] Parameters to initialize trainer Raises ------ :class:`~montreal_forced_aligner.exceptions.ConfigError` If an invalid train_type is specified """ from montreal_forced_aligner.acoustic_modeling.lda import LdaTrainer from montreal_forced_aligner.acoustic_modeling.monophone import MonophoneTrainer from montreal_forced_aligner.acoustic_modeling.pronunciation_probabilities import ( # noqa PronunciationProbabilityTrainer, ) from montreal_forced_aligner.acoustic_modeling.sat import SatTrainer from montreal_forced_aligner.acoustic_modeling.triphone import TriphoneTrainer p = {} p.update(self.param_dict) p.update(params) identifier = train_type index = 2 while identifier in self.training_configs: identifier = f"{train_type}_{index}" index += 1 self.final_identifier = identifier if train_type == "monophone": p = { k: v for k, v in p.items() if k in MonophoneTrainer.get_configuration_parameters() } config = MonophoneTrainer(identifier=identifier, worker=self, **p) elif train_type == "triphone": p = {k: v for k, v in p.items() if k in TriphoneTrainer.get_configuration_parameters()} config = TriphoneTrainer(identifier=identifier, worker=self, **p) elif train_type == "lda": p = {k: v for k, v in p.items() if k in LdaTrainer.get_configuration_parameters()} config = LdaTrainer(identifier=identifier, worker=self, **p) elif train_type == "sat": p = {k: v for k, v in p.items() if k in SatTrainer.get_configuration_parameters()} config = SatTrainer(identifier=identifier, worker=self, **p) elif train_type == "pronunciation_probabilities": p = { k: v for k, v in p.items() if k in PronunciationProbabilityTrainer.get_configuration_parameters() } previous_trainer = self.training_configs[list(self.training_configs.keys())[-1]] config = PronunciationProbabilityTrainer( identifier=identifier, previous_trainer=previous_trainer, worker=self, **p ) else: raise ConfigError(f"Invalid training type '{train_type}' in config file") self.training_configs[identifier] = config def export_model(self, output_model_path: str) -> None: """ Export an acoustic model to the specified path Parameters ---------- output_model_path : str Path to save acoustic model """ if "pronunciation_probabilities" in self.training_configs: export_directory = os.path.dirname(output_model_path) if export_directory: os.makedirs(export_directory, exist_ok=True) silence_probs = self.training_configs[ "pronunciation_probabilities" ].silence_probabilities with self.session() as session: for d in session.query(Dictionary): base_name = self.dictionary_base_names[d.id] if d.use_g2p: shutil.copyfile( self.phone_symbol_table_path, os.path.join( self.training_configs[self.final_identifier].working_directory, "phones.txt", ), ) shutil.copyfile( self.grapheme_symbol_table_path, os.path.join( self.training_configs[self.final_identifier].working_directory, "graphemes.txt", ), ) shutil.copyfile( d.lexicon_fst_path, os.path.join( self.training_configs[self.final_identifier].working_directory, self.dictionary_base_names[d.id] + ".fst", ), ) else: output_dictionary_path = os.path.join( export_directory, base_name + ".dict" ) self.export_lexicon( d.id, output_dictionary_path, probability=True, silence_probabilities=silence_probs, ) self.training_configs[self.final_identifier].export_model(output_model_path) self.log_info(f"Saved model to {output_model_path}") @property def tree_path(self) -> str: """Tree path of the final model""" return self.training_configs[self.final_identifier].tree_path def train(self) -> None: """ Run through the training configurations to produce a final acoustic model """ self.setup() previous = None begin = time.time() for trainer in self.training_configs.values(): if self.current_subset is None and trainer.optional: self.log_info( "Exiting training early to save time as the corpus is below the subset size for later training stages" ) break if trainer.subset < self.num_utterances: self.current_subset = trainer.subset else: self.current_subset = None trainer.subset = 0 if previous is not None: self.current_aligner = previous os.makedirs(self.working_directory, exist_ok=True) self.current_acoustic_model = AcousticModel( previous.exported_model_path, self.working_directory ) self.align() if trainer.identifier.startswith("pronunciation_probabilities"): trainer.train_pronunciation_probabilities() else: trainer.train() previous = trainer self.final_identifier = trainer.identifier self.log_info(f"Completed training in {time.time()-begin} seconds!") self.current_subset = None self.current_aligner = previous os.makedirs(self.working_log_directory, exist_ok=True) self.current_acoustic_model = AcousticModel( previous.exported_model_path, self.working_directory ) def export_files( self, output_directory: str, output_format: Optional[str] = None, include_original_text: bool = False, ) -> None: """ Export a TextGrid file for every sound file in the dataset Parameters ---------- output_directory: str Directory to save to """ self.align() super(TrainableAligner, self).export_files( output_directory, output_format, include_original_text ) @property def num_current_utterances(self) -> int: """Number of utterances in the current subset""" if self.current_subset and self.current_subset < self.num_utterances: return self.current_subset return self.num_utterances @property def align_options(self) -> MetaDict: """Alignment options""" if self.current_aligner is not None: return self.current_aligner.align_options return super().align_options def align(self) -> None: """ Multiprocessing function that aligns based on the current model. See Also -------- :class:`~montreal_forced_aligner.alignment.multiprocessing.AlignFunction` Multiprocessing helper function for each job :meth:`.AlignMixin.align_arguments` Job method for generating arguments for the helper function :kaldi_steps:`align_si` Reference Kaldi script :kaldi_steps:`align_fmllr` Reference Kaldi script """ done_path = os.path.join(self.working_directory, "done") if os.path.exists(done_path): self.log_debug(f"Skipping {self.current_aligner.identifier} alignments") return try: self.current_acoustic_model.export_model(self.working_directory) self.speaker_independent = True self.compile_train_graphs() self.align_utterances() if self.current_acoustic_model.meta["features"]["uses_speaker_adaptation"]: arguments = self.calc_fmllr_arguments() missing_transforms = False for arg in arguments: for path in arg.trans_paths.values(): if not os.path.exists(path): missing_transforms = True if missing_transforms: assert self.alignment_model_path.endswith(".alimdl") self.calc_fmllr() self.speaker_independent = False assert self.alignment_model_path.endswith(".mdl") self.align_utterances() if self.current_subset: self.log_debug( f"Analyzing alignment diagnostics for {self.current_aligner.identifier} on {self.current_subset} utterances" ) else: self.log_debug( f"Analyzing alignment diagnostics for {self.current_aligner.identifier} on the full corpus" ) self.compile_information() with mfa_open(done_path, "w"): pass except Exception as e: if isinstance(e, KaldiProcessingError): import logging logger = logging.getLogger(self.identifier) log_kaldi_errors(e.error_logs, logger) e.update_log_file(logger) raise @property def alignment_model_path(self) -> str: """Current alignment model path""" path = os.path.join(self.working_directory, "final.alimdl") if os.path.exists(path) and self.speaker_independent: return path return self.model_path @property def model_path(self) -> str: """Current model path""" if self.current_trainer is not None: return self.current_trainer.model_path return os.path.join(self.working_directory, "final.mdl") @property def data_directory(self) -> str: """Current data directory based on the trainer's subset""" return self.subset_directory(self.current_subset) @property def working_directory(self) -> Optional[str]: """Working directory""" if self.current_trainer is not None and not self.current_trainer.training_complete: return self.current_trainer.working_directory if self.current_aligner is None: return None return os.path.join(self.output_directory, f"{self.current_aligner.identifier}_ali") @property def working_log_directory(self) -> Optional[str]: """Current log directory""" return os.path.join(self.working_directory, "log")
{ "content_hash": "4ab0d4569194e25e37a8d0932ae66e04", "timestamp": "", "source": "github", "line_count": 527, "max_line_length": 128, "avg_line_length": 39.1157495256167, "alnum_prop": 0.565440962452702, "repo_name": "MontrealCorpusTools/Montreal-Forced-Aligner", "id": "9b85256b1173dc87c1ae4361935a53cd8cae6ae1", "size": "20614", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "montreal_forced_aligner/acoustic_modeling/trainer.py", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "95" }, { "name": "F*", "bytes": "414" }, { "name": "Python", "bytes": "1430732" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ConsoleApplication8")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApplication8")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2d7dde71-7f45-48e3-8ff0-0e8558aa13e4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "bb517e818a51b87f8cd9c8ecf01c1f80", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.19444444444444, "alnum_prop": 0.7476966690290574, "repo_name": "Koopakiller/Forum-Samples", "id": "4041ad5a3374ad3787ce7a493edaba35de93bbe1", "size": "1414", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Why implementing an interface instead of inherit a class/Why implementing an interface instead of inherit a class/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "211928" }, { "name": "Visual Basic", "bytes": "30641" } ], "symlink_target": "" }
<!--OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO LIGHT-GOLD-CALL-OUT XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX--> <table border="0" cellpadding="0" cellspacing="0" width="100%" class="light-gold-background"> <tr> <!--CALL OUT HEAD--> <td class="text callout-head" style="background-color: #e8e3d3; color: #4b2e83; font-family: 'Open Sans', arial, helvetica, sans-serif; font-size: 20px; font-weight: 600; line-height: 24px; padding: 15px 25px 5px 25px; text-align: center; text-transform: uppercase; vertical-align: middle;"> Very Short Call Out Message </td> <!--END CALL OUT HEAD--> </tr> <tr> <!--CALL OUT PARAGRAPH--> <td class="text callout-paragraph" style="background-color: #e8e3d3; color: #3d3d3d; font-family: 'Open Sans', arial, helvetica, sans-serif; font-size: 13px; font-weight: 400; line-height: 18.2px; padding: 0 25px 20px 15px; text-align: center; vertical-align: middle;"> Venis ea eosae occulpari odit volum. Quiati diorerc hiliquam, sernatquibus sent, que poriorem sustet aut voluptas cium re nait en dit is doleng at thist ud anta proa. </td> <!--END CALL OUT PARAGRAPH--> </tr> </table> <!-- OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO LIGHT-GOLD-END CALL-OUT THE NEXT MANNEQUIN SNIPPET - TABLE - CAN GO BELOW XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-->
{ "content_hash": "84ca549e617260105d4ae563cd99668d", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 315, "avg_line_length": 69.69565217391305, "alnum_prop": 0.577666874610106, "repo_name": "UWAA/mannequin", "id": "86353039c49089b39af6d4f37da5c9731065fa52", "size": "1603", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "snippets/call-outs/light-gold.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "588046" } ], "symlink_target": "" }
#ifndef _FSL_FLEXCAN_EDMA_H_ #define _FSL_FLEXCAN_EDMA_H_ #include "fsl_flexcan.h" #include "fsl_edma.h" /*! * @addtogroup flexcan_edma_driver * @{ */ /******************************************************************************* * Definitions ******************************************************************************/ /*! @name Driver version */ /*@{*/ /*! @brief FlexCAN EDMA driver version. */ #define FSL_FLEXCAN_EDMA_DRIVER_VERSION (MAKE_VERSION(2, 8, 1)) /*@}*/ /* Forward declaration of the handle typedef. */ typedef struct _flexcan_edma_handle flexcan_edma_handle_t; /*! @brief FlexCAN transfer callback function. */ typedef void (*flexcan_edma_transfer_callback_t)(CAN_Type *base, flexcan_edma_handle_t *handle, status_t status, void *userData); /*! * @brief FlexCAN eDMA handle */ struct _flexcan_edma_handle { flexcan_edma_transfer_callback_t callback; /*!< Callback function. */ void *userData; /*!< FlexCAN callback function parameter.*/ edma_handle_t *rxFifoEdmaHandle; /*!< The EDMA handler for Rx FIFO. */ volatile uint8_t rxFifoState; /*!< Rx FIFO transfer state. */ #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) size_t frameNum; /*!< The number of messages that need to be received. */ flexcan_fd_frame_t *framefd; /*!< Point to the buffer of CAN Message to be received from Enhanced Rx FIFO. */ #endif }; /******************************************************************************* * API ******************************************************************************/ #if defined(__cplusplus) extern "C" { #endif /*! * @name eDMA transactional * @{ */ /*! * @brief Initializes the FlexCAN handle, which is used in transactional functions. * * @param base FlexCAN peripheral base address. * @param handle Pointer to flexcan_edma_handle_t structure. * @param callback The callback function. * @param userData The parameter of the callback function. * @param rxFifoEdmaHandle User-requested DMA handle for Rx FIFO DMA transfer. */ void FLEXCAN_TransferCreateHandleEDMA(CAN_Type *base, flexcan_edma_handle_t *handle, flexcan_edma_transfer_callback_t callback, void *userData, edma_handle_t *rxFifoEdmaHandle); /*! * @brief Prepares the eDMA transfer configuration for FLEXCAN Legacy RX FIFO. * * This function prepares the eDMA transfer configuration structure according to FLEXCAN Legacy RX FIFO. * * @param base FlexCAN peripheral base address. * @param pFifoXfer FlexCAN Rx FIFO EDMA transfer structure, see #flexcan_fifo_transfer_t. * @param pEdmaConfig The user configuration structure of type edma_transfer_t. * */ void FLEXCAN_PrepareTransfConfiguration(CAN_Type *base, flexcan_fifo_transfer_t *pFifoXfer, edma_transfer_config_t *pEdmaConfig); /*! * @brief Start Transfer Data from the FLEXCAN Legacy Rx FIFO using eDMA. * * This function to Update edma transfer confiugration and Start eDMA transfer * * @param base FlexCAN peripheral base address. * @param handle Pointer to flexcan_edma_handle_t structure. * @param pEdmaConfig The user configuration structure of type edma_transfer_t. * @retval kStatus_Success if succeed, others failed. * @retval kStatus_FLEXCAN_RxFifoBusy Previous transfer ongoing. */ status_t FLEXCAN_StartTransferDatafromRxFIFO(CAN_Type *base, flexcan_edma_handle_t *handle, edma_transfer_config_t *pEdmaConfig); /*! * @brief Receives the CAN Message from the Legacy Rx FIFO using eDMA. * * This function receives the CAN Message using eDMA. This is a non-blocking function, which returns * right away. After the CAN Message is received, the receive callback function is called. * * @param base FlexCAN peripheral base address. * @param handle Pointer to flexcan_edma_handle_t structure. * @param pFifoXfer FlexCAN Rx FIFO EDMA transfer structure, see #flexcan_fifo_transfer_t. * @retval kStatus_Success if succeed, others failed. * @retval kStatus_FLEXCAN_RxFifoBusy Previous transfer ongoing. */ status_t FLEXCAN_TransferReceiveFifoEDMA(CAN_Type *base, flexcan_edma_handle_t *handle, flexcan_fifo_transfer_t *pFifoXfer); /*! * @brief Aborts the receive Legacy/Enhanced Rx FIFO process which used eDMA. * * This function aborts the receive Legacy/Enhanced Rx FIFO process which used eDMA. * * @param base FlexCAN peripheral base address. * @param handle Pointer to flexcan_edma_handle_t structure. */ void FLEXCAN_TransferAbortReceiveFifoEDMA(CAN_Type *base, flexcan_edma_handle_t *handle); #if (defined(FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) && FSL_FEATURE_FLEXCAN_HAS_ENHANCED_RX_FIFO) /*! * @brief Receives the CAN FD Message from the Enhanced Rx FIFO using eDMA. * * This function receives the CAN FD Message using eDMA. This is a non-blocking function, which returns * right away. After the CAN Message is received, the receive callback function is called. * * @param base FlexCAN peripheral base address. * @param handle Pointer to flexcan_edma_handle_t structure. * @param pFifoXfer FlexCAN Rx FIFO EDMA transfer structure, see #flexcan_fifo_transfer_t. * @retval kStatus_Success if succeed, others failed. * @retval kStatus_FLEXCAN_RxFifoBusy Previous transfer ongoing. */ status_t FLEXCAN_TransferReceiveEnhancedFifoEDMA(CAN_Type *base, flexcan_edma_handle_t *handle, flexcan_fifo_transfer_t *pFifoXfer); /*! * @brief Gets the Enhanced Rx Fifo transfer status during a interrupt non-blocking receive. * * @param base FlexCAN peripheral base address. * @param handle FlexCAN handle pointer. * @param count Number of CAN messages receive so far by the non-blocking transaction. * @retval kStatus_InvalidArgument count is Invalid. * @retval kStatus_Success Successfully return the count. */ status_t FLEXCAN_TransferGetReceiveEnhancedFifoCountEMDA(CAN_Type *base, flexcan_edma_handle_t *handle, size_t *count); #endif /*@}*/ #if defined(__cplusplus) } #endif /*! @}*/ #endif /* _FSL_FLEXCAN_EDMA_H_ */
{ "content_hash": "e1cdf8c89e3986579b7a8374519eb866", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 119, "avg_line_length": 40.10843373493976, "alnum_prop": 0.6302192850705918, "repo_name": "RT-Thread/rt-thread", "id": "b7e86cb5dd42789480e08821c16c04169ed06703", "size": "6812", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bsp/imxrt/libraries/MIMXRT1060/MIMXRT1060/drivers/fsl_flexcan_edma.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "20211623" }, { "name": "Batchfile", "bytes": "77561" }, { "name": "C", "bytes": "1056417995" }, { "name": "C++", "bytes": "945403" }, { "name": "CMake", "bytes": "250858" }, { "name": "CSS", "bytes": "138218" }, { "name": "GDB", "bytes": "11796" }, { "name": "HTML", "bytes": "4763477" }, { "name": "JavaScript", "bytes": "637" }, { "name": "LLVM", "bytes": "10344" }, { "name": "Lex", "bytes": "7026" }, { "name": "Logos", "bytes": "7238" }, { "name": "Lua", "bytes": "922" }, { "name": "M4", "bytes": "17515" }, { "name": "Makefile", "bytes": "485713" }, { "name": "Pawn", "bytes": "1250" }, { "name": "Perl", "bytes": "16728" }, { "name": "Python", "bytes": "3175087" }, { "name": "RPC", "bytes": "14162" }, { "name": "Shell", "bytes": "422027" }, { "name": "Tcl", "bytes": "179" }, { "name": "Yacc", "bytes": "30555" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- Copyright (c) 2017, David Schoenbauer <dschoenbauer@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of David Schoenbauer, Ctimt nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --> <!-- see http://www.phpunit.de/wiki/Documentation --> <!--phpunit bootstrap="/path/to/bootstrap.php" colors="false" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnFailure="true"> </phpunit--> <phpunit bootstrap="bootstrap.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" stopOnFailure="false"> <filter> <whitelist processUncoveredFilesFromWhitelist="true"> <directory suffix=".php">../src</directory> <exclude> <directory suffix="Interface.php">../src</directory> <directory>./vendor</directory> <directory suffix=".php">../src/Config/Enum</directory> <directory>./tests</directory> </exclude> </whitelist> </filter> <logging> <log type="coverage-clover" target="../vendor/coverage/clover.xml"/> </logging> </phpunit>
{ "content_hash": "1e630cbba09bde355ebe7f29ded88287", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 80, "avg_line_length": 43.85245901639344, "alnum_prop": 0.7099065420560747, "repo_name": "dschoenbauer/config", "id": "d656aaeeae838af6627a1761f9df9941fb978db9", "size": "2675", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "tests/configuration.xml", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "8819" } ], "symlink_target": "" }
<?php namespace Pixeloid\AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Response; use Pixeloid\AppBundle\Entity\Accomodation; use Pixeloid\AppBundle\Entity\Room as Room; use Pixeloid\AppBundle\Form\EventRegistrationType; use Symfony\Component\Form\Extension\Core\Type\HiddenType; class DefaultController extends Controller { public function indexAction() { $event = $this->container->get('pixeloid_app.event_site_manager')->getCurrentEvent(); if (!$event) { $response = $this->forward('Pixeloid\AppBundle\Controller\WebsiteController::indexAction', array( )); // ... further modify the response or return it directly return $response; # code... } $em = $this->getDoctrine()->getManager(); $preRegForm = $this->createForm(EventRegistrationType::class, null, array( 'action' => $this->generateUrl('eventregistration_new'), 'method' => 'POST', )); $preRegForm->add('pre_registration', HiddenType::class, array('data' => true)); $accommodations = $em->getRepository('Pixeloid\AppBundle\Entity\Accomodation')->getAllAccommodationsByEvent($event->getId()); foreach ($accommodations as $acc) { foreach ($acc->getRooms() as $room) { $free = $em->getRepository('Pixeloid\AppBundle\Entity\Room')->getFreeRooms($room); // echo $room->getAccomodation() .'---' . $room->getRoomType() .'---' . $free['total'] . '/' . $free['free'] .'<br>'; $room->freeRooms = $free; } } return $this->render('@PixeloidApp/Default/index.html.twig', array( 'accommodations_available' => $em->getRepository('Pixeloid\AppBundle\Entity\Accomodation')->getAccommodationsByEvent($event->getId()), 'accommodations' => $accommodations, 'regtypes' => $em->getRepository('Pixeloid\AppBundle\Entity\RegistrantType')->getRegistrantTypesByEvent($event->getId()), 'pre_register_form' => $preRegForm->createView(), 'sections' => $this->getProgram(), 'presentations' => $this->getPresentations(), )); } public function presentationsAction() { $em = $this->getDoctrine()->getManager(); $event = $this->container->get('pixeloid_app.event_site_manager')->getCurrentEvent(); $qb = $em->getRepository('PixeloidAppBundle:PresentationSection') ->createQueryBuilder('ps') ->select('ps') ->innerJoin('ps.presentations', 'p') ->leftJoin('p.event', 'e') ->leftJoin('p.eventRegistration', 'reg') ->where('ps.event = :event') ->andWhere('reg IS NULL') ->orderBy('ps.id', 'ASC') ->setParameters(array( 'event' => $event, )); return $this->render('@PixeloidApp/Default/presentations.html.twig', array( 'sections' =>$qb->getQuery()->getResult(), )); } public function galleryAction() { $event = $this->container->get('pixeloid_app.event_site_manager')->getCurrentEvent(); $galleries = $event->getGalleries(); if (!$galleries->count()) { return $this->redirect($this->generateUrl('pixeloid_app_index')); } return $this->render('@PixeloidApp/Default/gallery.html.twig', array( 'galleries' => $galleries, )); } public function infoAction() { $event = $this->container->get('pixeloid_app.event_site_manager')->getCurrentEvent(); return $this->render('@PixeloidApp/Default/info.html.twig', array( )); } /** * @return Response */ public function mapAction() { $em = $this->getDoctrine()->getManager(); $event = $this->container->get('pixeloid_app.event_site_manager')->getCurrentEvent(); $qb = $em->createQueryBuilder(); $qb->select('a, r') ->from('PixeloidAppBundle:Accomodation', 'a') ->join('a.rooms', 'r') ->where('r.event = :event') ->setParameter('event', $event) ->distinct(true) ; $accomodations =$qb->getQuery()->getResult(); return $this->render('@PixeloidApp/Default/map.html.twig', array( 'accomodations' => $accomodations )); } public function registerAction() { return $this->render('@PixeloidApp/Default/register.html.twig'); } public function abstractSubmissionAction($step) { return $this->render('@PixeloidApp/Default/abstract-submission.html.twig'); } public function programmeAction() { return $this->render('@PixeloidApp/Default/programme.html.twig'); } public function importantAction() { return $this->render('@PixeloidApp/Default/important.html.twig'); } public function yigAction() { return $this->render('@PixeloidApp/Default/yig.html.twig'); } public function facultyAction() { return $this->render('@PixeloidApp/Default/faculty.html.twig'); } public function englishAction() { return $this->render('@PixeloidApp/Default/english.html.twig'); } public function privacyAction() { return $this->render('@PixeloidApp/Default/privacy.html.twig'); } public function termsAction() { return $this->render('@PixeloidApp/Default/terms.html.twig'); } public function szalonAction() { return $this->render('@PixeloidApp/Default/szalon.html.twig'); } private function getPresentations() { $em = $this->getDoctrine()->getManager(); $event = $this->container->get('pixeloid_app.event_site_manager')->getCurrentEvent(); $qb = $em->getRepository('PixeloidAppBundle:Presentation')->createQueryBuilder('presentation'); $qb->select( 'presentation', 'author') ->leftJoin('presentation.event', 'e') ->leftJoin('presentation.authors', 'author') ->where('presentation.status = true') ->orWhere('presentation.id IS NULL') ->andWhere('presentation.event = :event') ->addOrderBy('presentation.start', 'ASC') ->addOrderBy('author.id', 'ASC') ->setParameters(array( 'event' => $event, )); $presentations = $qb->getQuery()->getResult(); foreach ($presentations as $presentation) { $names = array(); $institutions = array(); foreach ($presentation->getAuthors() as $i => $author) { $institutions[$author->getInstitution()]['name'] = $author->getInstitution(); $names[] = array( 'name' => $author->getName(), 'index' => $author->getInstitution(), ); } foreach ($institutions as $i => $institution) { $institutions[$i]['index'] = array_search($i, array_keys($institutions)) + 1; } foreach ($names as $i => $name) { $names[$i]['index'] = array_search($name['index'], array_keys($institutions)) + 1; } // foreach ($presentation->getAuthors() as $i => $author) { // $institutions[$author->getInstitution()]['name'] = $author->getInstitution(); // } $presentation->plainauthors = array( 'institutions' => $institutions, 'names' => $names, ); } return $presentations; } private function getProgram($id = null) { $em = $this->getDoctrine()->getManager(); $event = $this->container->get('pixeloid_app.event_site_manager')->getCurrentEvent(); $qb = $em->getRepository('PixeloidAppBundle:PresentationSection')->createQueryBuilder('section'); $qb->select('section', 'presentation', 'author', 'cv') ->leftJoin('section.event', 'e') ->leftJoin('section.presentations', 'presentation') ->leftJoin('presentation.authors', 'author') ->leftJoin('presentation.cv', 'cv') ->where('presentation.status = true') ->orWhere('presentation.id IS NULL') ->andWhere('section.event = :event') ->orderBy('section.start', 'ASC') ->addOrderBy('presentation.start', 'ASC') ->addOrderBy('author.id', 'ASC') ->setParameters(array( 'event' => $event, )); if ($id) { $qb->andWhere('section.id = :id') ->setParameter('id', $id); } $sections = $qb->getQuery()->getResult(); $sections = $this->buildAuthors($sections); return $sections; } private function buildAuthors($sections) { foreach ($sections as $section) { foreach ($section->getPresentations() as $presentation) { $names = array(); $institutions = array(); foreach ($presentation->getAuthors() as $i => $author) { $institutions[$author->getInstitution()]['name'] = $author->getInstitution(); $names[] = array( 'name' => $author->getName(), 'index' => $author->getInstitution(), ); } foreach ($institutions as $i => $institution) { $institutions[$i]['index'] = array_search($i, array_keys($institutions)) + 1; } foreach ($names as $i => $name) { $names[$i]['index'] = array_search($name['index'], array_keys($institutions)) + 1; } // foreach ($presentation->getAuthors() as $i => $author) { // $institutions[$author->getInstitution()]['name'] = $author->getInstitution(); // } $authors[$presentation->getId()] = array( 'institutions' => $institutions, 'names' => $names, ); } $result = array(); foreach ($section->getPresentations() as $entity) { $entity->plainauthors = $authors[$entity->getId()]; // $firstauthor = reset($entity->plainauthors['names']); // $result[($entity->getStart() ? $entity->getStart()->getTimestamp() : 'xxx' ). '-' . $firstauthor['name'].$entity->getId()] = $entity; } // ksort($result); // $section->setPresentations($result); } return $sections; } }
{ "content_hash": "e6cc5e08096c7a822677bfa58e72c28e", "timestamp": "", "source": "github", "line_count": 341, "max_line_length": 152, "avg_line_length": 32.58357771260997, "alnum_prop": 0.5364953649536496, "repo_name": "pixeloid/event_microsite", "id": "f0f8b0b67ca88830eeac64fb0a8d283f77567613", "size": "11111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Pixeloid/AppBundle/Controller/DefaultController.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "37380013" }, { "name": "HTML", "bytes": "2868863" }, { "name": "JavaScript", "bytes": "7555943" }, { "name": "PHP", "bytes": "718370" }, { "name": "Ruby", "bytes": "2976" } ], "symlink_target": "" }
/* @file leaf_stdio.h Created on: Jan 15, 2015 Author: Andriy Panasenko <apanasenko@cybervisiontech.com> */ #ifndef LEAF_STDIO_H_ #define LEAF_STDIO_H_ #include <stdio.h> #endif /* LEAF_STDIO_H_ */
{ "content_hash": "46e3cc8b095dc31f948de7962ad3f610", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 62, "avg_line_length": 14.928571428571429, "alnum_prop": 0.6746411483253588, "repo_name": "zofuthan/kaa", "id": "75b2beb2efe2d7c37449525911014db3ca4c966d", "size": "810", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/client-multi/client-c/src/kaa/platform-impl/stm32/leafMapleMini/leaf_stdio.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "19815" }, { "name": "Batchfile", "bytes": "4577" }, { "name": "C", "bytes": "1334799" }, { "name": "C++", "bytes": "1142799" }, { "name": "CMake", "bytes": "65181" }, { "name": "CSS", "bytes": "10183" }, { "name": "HTML", "bytes": "3112" }, { "name": "Java", "bytes": "8175012" }, { "name": "Makefile", "bytes": "5316" }, { "name": "Python", "bytes": "128276" }, { "name": "Shell", "bytes": "130848" }, { "name": "Thrift", "bytes": "21163" }, { "name": "XSLT", "bytes": "4062" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation, Inc. All rights reserved. // Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; namespace Microsoft.AspNet.Identity { /// <summary> /// Interface that maps users to login providers, i.e. Google, Facebook, Twitter, Microsoft /// </summary> /// <typeparam name="TUser"></typeparam> public interface IUserLoginStore<TUser> : IUserLoginStore<TUser, string> where TUser : class, IUser<string> { } /// <summary> /// Interface that maps users to login providers, i.e. Google, Facebook, Twitter, Microsoft /// </summary> /// <typeparam name="TUser"></typeparam> /// <typeparam name="TKey"></typeparam> public interface IUserLoginStore<TUser, in TKey> : IUserStore<TUser, TKey> where TUser : class, IUser<TKey> { /// <summary> /// Adds a user login with the specified provider and key /// </summary> /// <param name="user"></param> /// <param name="login"></param> /// <returns></returns> Task AddLoginAsync(TUser user, UserLoginInfo login); /// <summary> /// Removes the user login with the specified combination if it exists /// </summary> /// <param name="user"></param> /// <param name="login"></param> /// <returns></returns> Task RemoveLoginAsync(TUser user, UserLoginInfo login); /// <summary> /// Returns the linked accounts for this user /// </summary> /// <param name="user"></param> /// <returns></returns> Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user); /// <summary> /// Returns the user associated with this login /// </summary> /// <returns></returns> Task<TUser> FindAsync(UserLoginInfo login); } }
{ "content_hash": "bd52234ad2cedbc52ae5d1bc1f1109ec", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 111, "avg_line_length": 37.0188679245283, "alnum_prop": 0.6055045871559633, "repo_name": "eocampo/IdentityFromScratch", "id": "810f47bbfe43d602be00381781feb4e8cd54b4fe", "size": "1964", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Libraries/Microsoft.AspNet.Identity.Core/IUserLoginStore.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "108" }, { "name": "C#", "bytes": "500511" }, { "name": "CSS", "bytes": "960" } ], "symlink_target": "" }
package sbn.core.distributions import sbn.core.variables.{Assignment, Assignments, Variable} /** * This trait defines the intrinsic methods of every kind of distribution. */ trait Distribution extends Product with Serializable{ /** * Returns the label of the distribution. * * @return The label of the distribution. */ def label: String /** * Returns the number of parameters of the distribution. * * @return The number of parameters of the distribution. */ def numberOfParameters: Int } /** * This trait defines a conditional distribution, which is a probability distribution whose values are conditioned to a * subset of variables. */ // TODO: this ConditionalDistribution correctly abstract the distributions that have multinomial parents only (Normal_Normal would be different, for example) trait ConditionalDistribution extends Distribution{ /** * Returns the set of variables that condition it. * * @return the set of variables that condition it. */ def conditioningVariables: Set[Variable] /** * Returns the univariate distribution of an [[Assignment]] given a conditional distribution. If we think of the * [[ConditionalDistribution]] as a matrix of parameters (a Conditional Probability Table), this method would return * a row of this matrix, which corresponds o a [[UnivariateDistribution]]. * * @param assignments the values of the conditioning variables. * @throws IllegalArgumentException if the provided [[Assignments]] object is invalid for the distribution. * @return a new [[UnivariateDistribution]] object associated to the [[Assignment]] */ @throws[IllegalArgumentException] def getUnivariateDistribution(assignments: Assignments): UnivariateDistribution /** * For a random variable X whose values are distributed according to this distribution, which is constrained to a * set of conditioning variables S that take specific values ([[Assignments]]), this method returns P(X = x | assignments). * For example, assignments could be composed of 2 conditioning variables (A, B) that take the values of A=a and B=b * respectively. * * In other words, this method represents the conditional probability mass function (CPMF) for this distribution * given the values of its conditioning variables. * * If we think of the [[ConditionalDistribution]] as a matrix of parameters (a Conditional Probability Table), the * assignments would represent a specific row of the CPT and x would represent a column. In the case that the * variable's type is Real (not finite), the probability associated to x will be 0, given the infinite number of * columns (infinite number of points). * * @param assignments the values assigned to the conditioning variables. * @param x the value of the main variable. * @throws IllegalArgumentException if the provided [[Assignments]] object is invalid for the distribution. * @return the conditional probability represented by a [[Double]] value. */ @throws[IllegalArgumentException] def conditionalProbability(assignments: Assignments, x: Double): Double /** * For a random variable X whose values are distributed according to this distribution, which is constrained to a * set of conditioning variables S that take specific values ([[Assignments]]), this method returns P(X = x | assignments). * * In other words, this method represents the logarithm of the conditional probability mass function (CPMF) for this * distribution given the values of its conditioning variables. * * If we think of the [[ConditionalDistribution]] as a matrix of parameters (a Conditional Probability Table), the * assignments would represent a specific row of the CPT and x would represent a column. In the case that the * variable's type is Real (not finite), the probability associated to x will be 0, given the infinite number of * columns (infinite number of points). Therefore its logProbability will be log(0). * * @param assignments the values assigned to the conditioning variables. * @param x the value of the main variable. * @throws IllegalArgumentException if the provided [[Assignments]] object is invalid for the distribution. * @return the log conditional probability represented by a [[Double]] value. */ @throws[IllegalArgumentException] def logConditionalProbability(assignments: Assignments, x: Double): Double /** * For a random variable X whose values are distributed according to this distribution, which is constrained to a * set of conditioning variables S that take specific values ([[Assignments]]), this method returns P(x0 < X <= x1 | assignments). * * If we think of the [[ConditionalDistribution]] as a matrix of parameters (a Conditional Probability Table), the * assignments would represent a specific row of the CPT and [x0, x1] would represent an interval. This method would return * the probability associated to that interval of values. * * @param assignments the conditioning variables and their associated values. * @param x0 the lower bound. * @param x1 the upper bound. * @throws IllegalArgumentException if x0 > x1 or if the provided [[Assignments]] object is invalid for the distribution. * @return the probability that this distribution will take a value in the interval (x0, x1], given its conditioning * variables' values. */ @throws[IllegalArgumentException] def conditionalProbability(assignments: Assignments, x0: Double, x1: Double): Double /** * For a random variable X whose values are distributed according to this distribution, which is constrained to a * set of conditioning variables S that take specific values ([[Assignments]]), this method returns P(X <= x | assignments). * * In other words, this method represents the conditional (cumulative) distribution function (CCDF) for this distribution * given the values of its conditioning variables. * * @param assignments the conditioning variables and their associated values. * @param x the value of the main variable that represent the point at which the CCDF is evaluated. * @throws IllegalArgumentException if the provided [[Assignments]] object is invalid for the distribution. * @return the probability that a variable with this distribution will take a value less than or equal to x, given its set of * conditioning variables. */ @throws[IllegalArgumentException] def cumulativeConditionalProbability(assignments: Assignments, x: Double): Double /** * Returns the conditional probability density function (CPDF) of this distribution evaluated at the specified point x. This * distribution is conditioned by a set of variables S that take specific values [[Assignments]]). * * @param assignments the values assigned to the conditioning variables. * @param x the point at which the CPDF is evaluated. * @return the value of the conditional probability density function at point x. */ def conditionalDensity(assignments: Assignments, x: Double): Double /** * Returns the conditional probability density function (CPDF) of this distribution evaluated at the specified point x. This * distribution is conditioned by a set of variables S that take specific values [[Assignments]]). * * @param assignments the values assigned to the conditioning variables. * @param x the point at which the CPDF is evaluated. * @return the logarithm of the value of the conditional probability density function at point x. */ def logConditionalDensity(assignments: Assignments, x: Double): Double } /** * This trait defines a univariate distribution, which is a probability distribution of only one random variable. */ trait UnivariateDistribution extends Distribution{ /** * Returns a vector containing the parameters of the distribution. * * @return A collection of double values corresponding to the parameters of the distribution. */ def parameters: Vector[Double] /** * Returns a randomly sampled double value. * * @return a randomly sampled double value. */ def sample: Double /** * For a random variable X whose values are distributed according to this distribution, this method returns * P(X = x). In other words, this method represents the probability mass function (PMF) for the distribution. * * @param x the provided point at which the PMF is evaluated. * @throws IllegalArgumentException if x is an invalid value. * @return the value of the PMF at the provided point. */ @throws[IllegalArgumentException] def probability(x: Double): Double /** * For a random variable X whose values are distributed according to this distribution, this method returns * log P(X = x), where 'log' is the natural logarithm. In other words, this method represents the * logarithm of the probability mass function (PMF) for the distribution. * * @param x the provided point at which the PMF is evaluated. * @throws IllegalArgumentException if x is an invalid value. * @return the value of the log(PMF) at the provided point. */ @throws[IllegalArgumentException] def logProbability(x: Double): Double /** * For a random variable X whose values are distributed according to this distribution, this method returns * P(x0 < X <= x1). * * @param x0 the lower bound. * @param x1 the upper bound. * @throws IllegalArgumentException if x0 > x1. * @return the probability that this distribution will take a value in the interval (x0, x1]. */ @throws[IllegalArgumentException] def probability(x0: Double, x1: Double): Double /** * For a random variable X whose values are distributed according to this distribution, this method returns * P(X <= x). In other words, this method represents the (cumulative) distribution function (CDF) * for this distribution. * * @param x the point at which the CDF is evaluated. * @return the probability that a variable with this distribution will take a value less than or equal to x. */ @throws[IllegalArgumentException] def cumulativeProbability(x: Double): Double /** * Returns the probability density function (PDF) of this distribution evaluated at the specified point x. * In general, the PDF is the derivative of the [[cumulativeProbability(x: Double)]]. If the derivative does not * exist at x, then an appropriate replacement should be returned, e.g. [[Double.PositiveInfinity]], * [[Double.NaN]], or the limit inferior or limit superior of the difference quotient. * * @param x the point at which the PDF is evaluated. * @return the value of the probability density function at point x. */ def density(x: Double): Double /** * Returns the natural logarithm of the probability density function (PDF) of this distribution evaluated at the * specified point x. In general, the PDF is the derivative of the [[cumulativeProbability(x: Double)]]. * If the derivative does not exist at x, then an appropriate replacement should be returned, * e.g. [[Double.PositiveInfinity]], [[Double.NaN]], or the limit inferior or limit superior of the difference quotient. * * @param x the point at which the PDF is evaluated. * @return the logarithm of the value of the probability density function at point x. */ def logDensity(x: Double): Double }
{ "content_hash": "cb58d14e54717396937096f9bdb5a825", "timestamp": "", "source": "github", "line_count": 234, "max_line_length": 157, "avg_line_length": 49.58119658119658, "alnum_prop": 0.7284950870539563, "repo_name": "fernandoj92/sbn", "id": "d8d45db13a98a395fd66d859be520ea8ed5a2d8d", "size": "11602", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/scala/sbn/core/distributions/Distribution.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "154962" } ], "symlink_target": "" }
package ru.adios.budgeter.adapters; import android.support.annotation.Nullable; import java.io.Serializable; import javax.annotation.concurrent.ThreadSafe; /** * Created by Michail Kulikov * 12/2/15 */ @ThreadSafe public interface ParentingDataExtractor<T, I extends Serializable> extends DataExtractor<T, I> { @Nullable IdentifiedData<T, I> extractParent(I id); }
{ "content_hash": "6c14f07587ec352cd150c214b33b3117", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 96, "avg_line_length": 18.285714285714285, "alnum_prop": 0.7578125, "repo_name": "adiosmsu/budgeter-app", "id": "2c5f4b8c2e4bbfea8fd1f1139cb8966c2e32feec", "size": "1077", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/ru/adios/budgeter/adapters/ParentingDataExtractor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "486944" } ], "symlink_target": "" }
<?xml version="1.0"?> <doc> <assembly> <name>CanadaAlertSystemApi</name> </assembly> <members> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.ApiDescriptionExtensions.GetFriendlyId(System.Web.Http.Description.ApiDescription)"> <summary> Generates an URI-friendly ID for the <see cref="T:System.Web.Http.Description.ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" </summary> <param name="description">The <see cref="T:System.Web.Http.Description.ApiDescription"/>.</param> <returns>The ID as a string.</returns> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfig"> <summary> Use this class to customize the Help Page. For example you can set a custom <see cref="T:System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation or you can provide the samples for the requests/responses. </summary> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.Controllers.HelpController"> <summary> The controller that will handle requests for the help page. </summary> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetDocumentationProvider(System.Web.Http.HttpConfiguration,System.Web.Http.Description.IDocumentationProvider)"> <summary> Sets the documentation provider for help page. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="documentationProvider">The documentation provider.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetSampleObjects(System.Web.Http.HttpConfiguration,System.Collections.Generic.IDictionary{System.Type,System.Object})"> <summary> Sets the objects that will be used by the formatters to produce sample requests/responses. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="sampleObjects">The sample objects.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetSampleRequest(System.Web.Http.HttpConfiguration,System.Object,System.Net.Http.Headers.MediaTypeHeaderValue,System.String,System.String)"> <summary> Sets the sample request directly for the specified media type and action. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="sample">The sample request.</param> <param name="mediaType">The media type.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetSampleRequest(System.Web.Http.HttpConfiguration,System.Object,System.Net.Http.Headers.MediaTypeHeaderValue,System.String,System.String,System.String[])"> <summary> Sets the sample request directly for the specified media type and action with parameters. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="sample">The sample request.</param> <param name="mediaType">The media type.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> <param name="parameterNames">The parameter names.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetSampleResponse(System.Web.Http.HttpConfiguration,System.Object,System.Net.Http.Headers.MediaTypeHeaderValue,System.String,System.String)"> <summary> Sets the sample request directly for the specified media type of the action. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="sample">The sample response.</param> <param name="mediaType">The media type.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetSampleResponse(System.Web.Http.HttpConfiguration,System.Object,System.Net.Http.Headers.MediaTypeHeaderValue,System.String,System.String,System.String[])"> <summary> Sets the sample response directly for the specified media type of the action with specific parameters. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="sample">The sample response.</param> <param name="mediaType">The media type.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> <param name="parameterNames">The parameter names.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetSampleForType(System.Web.Http.HttpConfiguration,System.Object,System.Net.Http.Headers.MediaTypeHeaderValue,System.Type)"> <summary> Sets the sample directly for all actions with the specified type and media type. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="sample">The sample.</param> <param name="mediaType">The media type.</param> <param name="type">The parameter type or return type of an action.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetActualRequestType(System.Web.Http.HttpConfiguration,System.Type,System.String,System.String)"> <summary> Specifies the actual type of <see cref="T:System.Net.Http.ObjectContent`1"/> passed to the <see cref="T:System.Net.Http.HttpRequestMessage"/> in an action. The help page will use this information to produce more accurate request samples. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="type">The type.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetActualRequestType(System.Web.Http.HttpConfiguration,System.Type,System.String,System.String,System.String[])"> <summary> Specifies the actual type of <see cref="T:System.Net.Http.ObjectContent`1"/> passed to the <see cref="T:System.Net.Http.HttpRequestMessage"/> in an action. The help page will use this information to produce more accurate request samples. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="type">The type.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> <param name="parameterNames">The parameter names.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetActualResponseType(System.Web.Http.HttpConfiguration,System.Type,System.String,System.String)"> <summary> Specifies the actual type of <see cref="T:System.Net.Http.ObjectContent`1"/> returned as part of the <see cref="T:System.Net.Http.HttpRequestMessage"/> in an action. The help page will use this information to produce more accurate response samples. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="type">The type.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetActualResponseType(System.Web.Http.HttpConfiguration,System.Type,System.String,System.String,System.String[])"> <summary> Specifies the actual type of <see cref="T:System.Net.Http.ObjectContent`1"/> returned as part of the <see cref="T:System.Net.Http.HttpRequestMessage"/> in an action. The help page will use this information to produce more accurate response samples. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="type">The type.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> <param name="parameterNames">The parameter names.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.GetHelpPageSampleGenerator(System.Web.Http.HttpConfiguration)"> <summary> Gets the help page sample generator. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <returns>The help page sample generator.</returns> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.SetHelpPageSampleGenerator(System.Web.Http.HttpConfiguration,CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator)"> <summary> Sets the help page sample generator. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="sampleGenerator">The help page sample generator.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageConfigurationExtensions.GetHelpPageApiModel(System.Web.Http.HttpConfiguration,System.String)"> <summary> Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. </summary> <param name="config">The <see cref="T:System.Web.Http.HttpConfiguration"/>.</param> <param name="apiDescriptionId">The <see cref="T:System.Web.Http.Description.ApiDescription"/> ID.</param> <returns> An <see cref="T:CanadaAlertSystemApi.Areas.HelpPage.Models.HelpPageApiModel"/> </returns> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.Models.HelpPageApiModel"> <summary> The model that represents an API displayed on the help page. </summary> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.Models.HelpPageApiModel.#ctor"> <summary> Initializes a new instance of the <see cref="T:CanadaAlertSystemApi.Areas.HelpPage.Models.HelpPageApiModel"/> class. </summary> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.Models.HelpPageApiModel.ApiDescription"> <summary> Gets or sets the <see cref="P:CanadaAlertSystemApi.Areas.HelpPage.Models.HelpPageApiModel.ApiDescription"/> that describes the API. </summary> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.Models.HelpPageApiModel.SampleRequests"> <summary> Gets the sample requests associated with the API. </summary> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.Models.HelpPageApiModel.SampleResponses"> <summary> Gets the sample responses associated with the API. </summary> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.Models.HelpPageApiModel.ErrorMessages"> <summary> Gets the error messages associated with this model. </summary> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator"> <summary> This class will generate the samples for the help page. </summary> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.#ctor"> <summary> Initializes a new instance of the <see cref="T:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator"/> class. </summary> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.GetSampleRequests(System.Web.Http.Description.ApiDescription)"> <summary> Gets the request body samples for a given <see cref="T:System.Web.Http.Description.ApiDescription"/>. </summary> <param name="api">The <see cref="T:System.Web.Http.Description.ApiDescription"/>.</param> <returns>The samples keyed by media type.</returns> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.GetSampleResponses(System.Web.Http.Description.ApiDescription)"> <summary> Gets the response body samples for a given <see cref="T:System.Web.Http.Description.ApiDescription"/>. </summary> <param name="api">The <see cref="T:System.Web.Http.Description.ApiDescription"/>.</param> <returns>The samples keyed by media type.</returns> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.GetSample(System.Web.Http.Description.ApiDescription,CanadaAlertSystemApi.Areas.HelpPage.SampleDirection)"> <summary> Gets the request or response body samples. </summary> <param name="api">The <see cref="T:System.Web.Http.Description.ApiDescription"/>.</param> <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> <returns>The samples keyed by media type.</returns> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.GetActionSample(System.String,System.String,System.Collections.Generic.IEnumerable{System.String},System.Type,System.Net.Http.Formatting.MediaTypeFormatter,System.Net.Http.Headers.MediaTypeHeaderValue,CanadaAlertSystemApi.Areas.HelpPage.SampleDirection)"> <summary> Search for samples that are provided directly through <see cref="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.ActionSamples"/>. </summary> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> <param name="parameterNames">The parameter names.</param> <param name="type">The CLR type.</param> <param name="formatter">The formatter.</param> <param name="mediaType">The media type.</param> <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> <returns>The sample that matches the parameters.</returns> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.GetSampleObject(System.Type)"> <summary> Gets the sample object that will be serialized by the formatters. First, it will look at the <see cref="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="T:CanadaAlertSystemApi.Areas.HelpPage.ObjectGenerator"/>. </summary> <param name="type">The type.</param> <returns>The sample object.</returns> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.ResolveType(System.Web.Http.Description.ApiDescription,System.String,System.String,System.Collections.Generic.IEnumerable{System.String},CanadaAlertSystemApi.Areas.HelpPage.SampleDirection,System.Collections.ObjectModel.Collection{System.Net.Http.Formatting.MediaTypeFormatter}@)"> <summary> Resolves the type of the action parameter or return value when <see cref="T:System.Net.Http.HttpRequestMessage"/> or <see cref="T:System.Net.Http.HttpResponseMessage"/> is used. </summary> <param name="api">The <see cref="T:System.Web.Http.Description.ApiDescription"/>.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> <param name="parameterNames">The parameter names.</param> <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> <param name="formatters">The formatters.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.WriteSampleObjectUsingFormatter(System.Net.Http.Formatting.MediaTypeFormatter,System.Object,System.Type,System.Net.Http.Headers.MediaTypeHeaderValue)"> <summary> Writes the sample object using formatter. </summary> <param name="formatter">The formatter.</param> <param name="value">The value.</param> <param name="type">The type.</param> <param name="mediaType">Type of the media.</param> <returns></returns> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.ActualHttpMessageTypes"> <summary> Gets CLR types that are used as the content of <see cref="T:System.Net.Http.HttpRequestMessage"/> or <see cref="T:System.Net.Http.HttpResponseMessage"/>. </summary> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.ActionSamples"> <summary> Gets the objects that are used directly as samples for certain actions. </summary> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleGenerator.SampleObjects"> <summary> Gets the objects that are serialized as samples by the supported formatters. </summary> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey"> <summary> This is used to identify the place where the sample should be applied. </summary> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.#ctor(System.Net.Http.Headers.MediaTypeHeaderValue,System.Type)"> <summary> Creates a new <see cref="T:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey"/> based on media type and CLR type. </summary> <param name="mediaType">The media type.</param> <param name="type">The CLR type.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.#ctor(CanadaAlertSystemApi.Areas.HelpPage.SampleDirection,System.String,System.String,System.Collections.Generic.IEnumerable{System.String})"> <summary> Creates a new <see cref="T:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey"/> based on <see cref="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.SampleDirection"/>, controller name, action name and parameter names. </summary> <param name="sampleDirection">The <see cref="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.SampleDirection"/>.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> <param name="parameterNames">The parameter names.</param> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.#ctor(System.Net.Http.Headers.MediaTypeHeaderValue,CanadaAlertSystemApi.Areas.HelpPage.SampleDirection,System.String,System.String,System.Collections.Generic.IEnumerable{System.String})"> <summary> Creates a new <see cref="T:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey"/> based on media type, <see cref="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.SampleDirection"/>, controller name, action name and parameter names. </summary> <param name="mediaType">The media type.</param> <param name="sampleDirection">The <see cref="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.SampleDirection"/>.</param> <param name="controllerName">Name of the controller.</param> <param name="actionName">Name of the action.</param> <param name="parameterNames">The parameter names.</param> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.ControllerName"> <summary> Gets the name of the controller. </summary> <value> The name of the controller. </value> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.ActionName"> <summary> Gets the name of the action. </summary> <value> The name of the action. </value> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.MediaType"> <summary> Gets the media type. </summary> <value> The media type. </value> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.ParameterNames"> <summary> Gets the parameter names. </summary> </member> <member name="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.SampleDirection"> <summary> Gets the <see cref="P:CanadaAlertSystemApi.Areas.HelpPage.HelpPageSampleKey.SampleDirection"/>. </summary> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.ImageSample"> <summary> This represents an image sample on the help page. There's a display template named ImageSample associated with this class. </summary> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.ImageSample.#ctor(System.String)"> <summary> Initializes a new instance of the <see cref="T:CanadaAlertSystemApi.Areas.HelpPage.ImageSample"/> class. </summary> <param name="src">The URL of an image.</param> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.InvalidSample"> <summary> This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. </summary> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.ObjectGenerator"> <summary> This class will create an object of a given type and populate it with sample data. </summary> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.ObjectGenerator.GenerateObject(System.Type)"> <summary> Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: Simple types: <see cref="T:System.Int32"/>, <see cref="T:System.String"/>, <see cref="T:System.Enum"/>, <see cref="T:System.DateTime"/>, <see cref="T:System.Uri"/>, etc. Complex types: POCO types. Nullables: <see cref="T:System.Nullable`1"/>. Arrays: arrays of simple types or complex types. Key value pairs: <see cref="T:System.Collections.Generic.KeyValuePair`2"/> Tuples: <see cref="T:System.Tuple`1"/>, <see cref="T:System.Tuple`2"/>, etc Dictionaries: <see cref="T:System.Collections.Generic.IDictionary`2"/> or anything deriving from <see cref="T:System.Collections.Generic.IDictionary`2"/>. Collections: <see cref="T:System.Collections.Generic.IList`1"/>, <see cref="T:System.Collections.Generic.IEnumerable`1"/>, <see cref="T:System.Collections.Generic.ICollection`1"/>, <see cref="T:System.Collections.IList"/>, <see cref="T:System.Collections.IEnumerable"/>, <see cref="T:System.Collections.ICollection"/> or anything deriving from <see cref="T:System.Collections.Generic.ICollection`1"/> or <see cref="T:System.Collections.IList"/>. Queryables: <see cref="T:System.Linq.IQueryable"/>, <see cref="T:System.Linq.IQueryable`1"/>. </summary> <param name="type">The type.</param> <returns>An object of the given type.</returns> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.SampleDirection"> <summary> Indicates whether the sample is used for request or response </summary> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.TextSample"> <summary> This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. </summary> </member> <member name="T:CanadaAlertSystemApi.Areas.HelpPage.XmlDocumentationProvider"> <summary> A custom <see cref="T:System.Web.Http.Description.IDocumentationProvider"/> that reads the API documentation from an XML documentation file. </summary> </member> <member name="M:CanadaAlertSystemApi.Areas.HelpPage.XmlDocumentationProvider.#ctor(System.String)"> <summary> Initializes a new instance of the <see cref="T:CanadaAlertSystemApi.Areas.HelpPage.XmlDocumentationProvider"/> class. </summary> <param name="documentPath">The physical path to XML document.</param> </member> <member name="F:CanadaAlertSystemApi.Controllers.AlertsController.AlertSystem"> <summary> Alert system object. </summary> </member> <member name="F:CanadaAlertSystemApi.Controllers.AlertsController.AlertSystemConfigured"> <summary> Holds if the alert system has been configured. </summary> </member> <member name="M:CanadaAlertSystemApi.Controllers.AlertsController.#ctor"> <summary> Setups the Alerts Controller. </summary> </member> <member name="M:CanadaAlertSystemApi.Controllers.AlertsController.GetAlerts"> <summary> Returns all alerts. </summary> <returns>All alerts.</returns> </member> </members> </doc>
{ "content_hash": "d9cd7f1cd54db559ccc62275c2dce6e9", "timestamp": "", "source": "github", "line_count": 421, "max_line_length": 457, "avg_line_length": 66.0332541567696, "alnum_prop": 0.6648201438848921, "repo_name": "zachomedia/canada-alert-system", "id": "0e93041f7ec3ebb8c15b628a0b6337cb0cbfdebb", "size": "27800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CanadaAlertSystem/CanadaAlertSystemApi/App_Data/XmlDocument.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "114" }, { "name": "C#", "bytes": "148757" }, { "name": "CSS", "bytes": "3050" }, { "name": "JavaScript", "bytes": "445362" }, { "name": "PowerShell", "bytes": "13265" }, { "name": "Puppet", "bytes": "84082" } ], "symlink_target": "" }
package fr.lteconsulting.hexa.client.event; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; import fr.lteconsulting.hexa.client.event.DeletedEvent.DeletedEventHandler; public class DeletedEvent<T> extends GwtEvent<DeletedEventHandler<T>> { private T item; public DeletedEvent( T item ) { this.item = item; } public T getItem() { return item; } public interface DeletedEventHandler<T> extends EventHandler { void onDeleted( T item ); } public static Type<DeletedEventHandler<?>> TYPE = new Type<>(); @SuppressWarnings( "unchecked" ) @Override public com.google.gwt.event.shared.GwtEvent.Type<DeletedEventHandler<T>> getAssociatedType() { return (Type<DeletedEventHandler<T>>)(Type<?>)TYPE; } @Override protected void dispatch( DeletedEventHandler<T> handler ) { handler.onDeleted( item ); } }
{ "content_hash": "59ca8c879730a593c599f413dfabb599", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 93, "avg_line_length": 21.9, "alnum_prop": 0.747716894977169, "repo_name": "ltearno/hexa.tools", "id": "7dac0a78cdb1438384557e76a1739ae3c045c4a4", "size": "876", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hexa.core/src/main/java/fr/lteconsulting/hexa/client/event/DeletedEvent.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "133" }, { "name": "CSS", "bytes": "17215" }, { "name": "Groovy", "bytes": "85" }, { "name": "HTML", "bytes": "5857" }, { "name": "Java", "bytes": "2299917" }, { "name": "JavaScript", "bytes": "961360" } ], "symlink_target": "" }
package org.jboss.da.lookup.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Builder; import lombok.Data; import lombok.NonNull; import lombok.extern.jackson.Jacksonized; import org.jboss.da.model.rest.NPMPackage; import javax.validation.constraints.NotNull; import java.util.Set; /** * * @author Honza Brázdil &lt;jbrazdil@redhat.com&gt; */ @Data @Jacksonized @Builder(builderClassName = "Builder") @JsonIgnoreProperties(ignoreUnknown = true) public class NPMVersionsRequest { @NotNull private final VersionFilter filter; @NotNull @lombok.Builder.Default private final VersionDistanceRule distanceRule = VersionDistanceRule.RECOMMENDED_REPLACEMENT; @NotNull private final String mode; @NonNull private final Set<NPMPackage> packages; @lombok.Builder.Default private final boolean includeBad = false; }
{ "content_hash": "61b08efa48987f716e3a4469488520a0", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 97, "avg_line_length": 23.121951219512194, "alnum_prop": 0.7732067510548524, "repo_name": "project-ncl/dependency-analysis", "id": "ff5032c596af4fe360c08858519894a3a9d4fe24", "size": "1576", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "reports-model/src/main/java/org/jboss/da/lookup/model/NPMVersionsRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "710069" }, { "name": "Python", "bytes": "70512" }, { "name": "Shell", "bytes": "33736" } ], "symlink_target": "" }
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> DEBUG - 2014-12-18 10:08:33 --> Config Class Initialized DEBUG - 2014-12-18 10:08:33 --> Hooks Class Initialized DEBUG - 2014-12-18 10:08:33 --> Utf8 Class Initialized DEBUG - 2014-12-18 10:08:33 --> UTF-8 Support Enabled DEBUG - 2014-12-18 10:08:33 --> URI Class Initialized DEBUG - 2014-12-18 10:08:33 --> Router Class Initialized DEBUG - 2014-12-18 10:08:33 --> Output Class Initialized DEBUG - 2014-12-18 10:08:33 --> Security Class Initialized DEBUG - 2014-12-18 10:08:33 --> Input Class Initialized DEBUG - 2014-12-18 10:08:33 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 10:08:33 --> Language Class Initialized DEBUG - 2014-12-18 10:08:33 --> Loader Class Initialized DEBUG - 2014-12-18 10:08:33 --> Database Driver Class Initialized ERROR - 2014-12-18 10:08:33 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 DEBUG - 2014-12-18 10:08:33 --> XML-RPC Class Initialized DEBUG - 2014-12-18 10:08:33 --> Controller Class Initialized DEBUG - 2014-12-18 10:08:33 --> Config file loaded: application/config/rest.php DEBUG - 2014-12-18 10:08:33 --> Helper loaded: inflector_helper DEBUG - 2014-12-18 10:08:35 --> Model Class Initialized DEBUG - 2014-12-18 10:08:36 --> Model Class Initialized DEBUG - 2014-12-18 11:38:49 --> Config Class Initialized DEBUG - 2014-12-18 11:38:49 --> Hooks Class Initialized DEBUG - 2014-12-18 11:38:49 --> Utf8 Class Initialized DEBUG - 2014-12-18 11:38:49 --> UTF-8 Support Enabled DEBUG - 2014-12-18 11:38:49 --> URI Class Initialized DEBUG - 2014-12-18 11:38:49 --> Router Class Initialized DEBUG - 2014-12-18 11:38:49 --> Output Class Initialized DEBUG - 2014-12-18 11:38:49 --> Security Class Initialized DEBUG - 2014-12-18 11:38:49 --> Input Class Initialized DEBUG - 2014-12-18 11:38:49 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 11:38:49 --> Language Class Initialized DEBUG - 2014-12-18 11:38:49 --> Loader Class Initialized DEBUG - 2014-12-18 11:38:49 --> Database Driver Class Initialized ERROR - 2014-12-18 11:38:49 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 DEBUG - 2014-12-18 11:38:49 --> XML-RPC Class Initialized DEBUG - 2014-12-18 11:38:49 --> Controller Class Initialized DEBUG - 2014-12-18 11:38:49 --> Config file loaded: application/config/rest.php DEBUG - 2014-12-18 11:38:49 --> Helper loaded: inflector_helper DEBUG - 2014-12-18 11:38:51 --> Model Class Initialized DEBUG - 2014-12-18 11:38:51 --> Model Class Initialized DEBUG - 2014-12-18 13:15:42 --> Config Class Initialized DEBUG - 2014-12-18 13:15:42 --> Hooks Class Initialized DEBUG - 2014-12-18 13:15:42 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:15:42 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:15:42 --> URI Class Initialized DEBUG - 2014-12-18 13:15:42 --> Router Class Initialized DEBUG - 2014-12-18 13:15:42 --> Output Class Initialized DEBUG - 2014-12-18 13:15:42 --> Security Class Initialized DEBUG - 2014-12-18 13:15:42 --> Input Class Initialized DEBUG - 2014-12-18 13:15:42 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:15:42 --> Language Class Initialized DEBUG - 2014-12-18 13:15:43 --> Loader Class Initialized DEBUG - 2014-12-18 13:15:43 --> Database Driver Class Initialized ERROR - 2014-12-18 13:15:43 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 DEBUG - 2014-12-18 13:15:43 --> XML-RPC Class Initialized DEBUG - 2014-12-18 13:15:43 --> Controller Class Initialized DEBUG - 2014-12-18 13:15:43 --> Config file loaded: application/config/rest.php DEBUG - 2014-12-18 13:15:43 --> Helper loaded: inflector_helper DEBUG - 2014-12-18 13:15:45 --> Model Class Initialized DEBUG - 2014-12-18 13:15:45 --> Model Class Initialized DEBUG - 2014-12-18 13:15:51 --> Config Class Initialized DEBUG - 2014-12-18 13:15:51 --> Hooks Class Initialized DEBUG - 2014-12-18 13:15:51 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:15:51 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:15:51 --> URI Class Initialized DEBUG - 2014-12-18 13:15:51 --> Router Class Initialized DEBUG - 2014-12-18 13:15:51 --> Output Class Initialized DEBUG - 2014-12-18 13:15:51 --> Security Class Initialized DEBUG - 2014-12-18 13:15:51 --> Input Class Initialized DEBUG - 2014-12-18 13:15:51 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:15:51 --> Language Class Initialized DEBUG - 2014-12-18 13:15:51 --> Loader Class Initialized DEBUG - 2014-12-18 13:15:51 --> Database Driver Class Initialized ERROR - 2014-12-18 13:15:51 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 DEBUG - 2014-12-18 13:15:51 --> XML-RPC Class Initialized DEBUG - 2014-12-18 13:15:51 --> Controller Class Initialized DEBUG - 2014-12-18 13:15:51 --> Config file loaded: application/config/rest.php DEBUG - 2014-12-18 13:15:51 --> Helper loaded: inflector_helper DEBUG - 2014-12-18 13:15:53 --> Model Class Initialized DEBUG - 2014-12-18 13:15:53 --> Model Class Initialized DEBUG - 2014-12-18 13:16:31 --> Config Class Initialized DEBUG - 2014-12-18 13:16:31 --> Hooks Class Initialized DEBUG - 2014-12-18 13:16:31 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:16:31 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:16:31 --> URI Class Initialized DEBUG - 2014-12-18 13:16:31 --> Router Class Initialized DEBUG - 2014-12-18 13:16:31 --> Output Class Initialized DEBUG - 2014-12-18 13:16:31 --> Security Class Initialized DEBUG - 2014-12-18 13:16:31 --> Input Class Initialized DEBUG - 2014-12-18 13:16:31 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:16:31 --> Language Class Initialized DEBUG - 2014-12-18 13:16:31 --> Loader Class Initialized DEBUG - 2014-12-18 13:16:31 --> Database Driver Class Initialized ERROR - 2014-12-18 13:16:31 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 DEBUG - 2014-12-18 13:16:31 --> XML-RPC Class Initialized DEBUG - 2014-12-18 13:16:31 --> Controller Class Initialized DEBUG - 2014-12-18 13:16:31 --> Config file loaded: application/config/rest.php DEBUG - 2014-12-18 13:16:31 --> Helper loaded: inflector_helper DEBUG - 2014-12-18 13:16:33 --> Model Class Initialized DEBUG - 2014-12-18 13:16:33 --> Model Class Initialized ERROR - 2014-12-18 13:16:33 --> Severity: Notice --> Array to string conversion /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/application/controllers/api/users.php 181 ERROR - 2014-12-18 13:16:33 --> Severity: Warning --> Cannot modify header information - headers already sent by (output started at /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/core/Exceptions.php:185) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/application/libraries/REST_Controller.php 485 ERROR - 2014-12-18 13:16:33 --> Severity: Warning --> Cannot modify header information - headers already sent by (output started at /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/core/Exceptions.php:185) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/core/Common.php 442 ERROR - 2014-12-18 13:16:33 --> Severity: Warning --> Cannot modify header information - headers already sent by (output started at /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/core/Exceptions.php:185) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/application/libraries/REST_Controller.php 503 DEBUG - 2014-12-18 13:17:07 --> Config Class Initialized DEBUG - 2014-12-18 13:17:07 --> Hooks Class Initialized DEBUG - 2014-12-18 13:17:07 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:17:07 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:17:07 --> URI Class Initialized DEBUG - 2014-12-18 13:17:07 --> Router Class Initialized DEBUG - 2014-12-18 13:17:07 --> Output Class Initialized DEBUG - 2014-12-18 13:17:07 --> Security Class Initialized DEBUG - 2014-12-18 13:17:07 --> Input Class Initialized DEBUG - 2014-12-18 13:17:07 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:17:07 --> Language Class Initialized DEBUG - 2014-12-18 13:17:07 --> Loader Class Initialized DEBUG - 2014-12-18 13:17:07 --> Database Driver Class Initialized ERROR - 2014-12-18 13:17:07 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 DEBUG - 2014-12-18 13:17:07 --> XML-RPC Class Initialized DEBUG - 2014-12-18 13:17:07 --> Controller Class Initialized DEBUG - 2014-12-18 13:17:07 --> Config file loaded: application/config/rest.php DEBUG - 2014-12-18 13:17:07 --> Helper loaded: inflector_helper DEBUG - 2014-12-18 13:17:08 --> Model Class Initialized DEBUG - 2014-12-18 13:17:08 --> Model Class Initialized DEBUG - 2014-12-18 13:22:21 --> Config Class Initialized DEBUG - 2014-12-18 13:22:21 --> Hooks Class Initialized DEBUG - 2014-12-18 13:22:21 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:22:21 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:22:21 --> URI Class Initialized DEBUG - 2014-12-18 13:22:21 --> Router Class Initialized DEBUG - 2014-12-18 13:22:21 --> Output Class Initialized DEBUG - 2014-12-18 13:22:21 --> Security Class Initialized DEBUG - 2014-12-18 13:22:21 --> Input Class Initialized DEBUG - 2014-12-18 13:22:21 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:22:21 --> Language Class Initialized DEBUG - 2014-12-18 13:22:21 --> Loader Class Initialized DEBUG - 2014-12-18 13:22:21 --> Database Driver Class Initialized ERROR - 2014-12-18 13:22:21 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 DEBUG - 2014-12-18 13:22:21 --> XML-RPC Class Initialized DEBUG - 2014-12-18 13:22:21 --> Controller Class Initialized DEBUG - 2014-12-18 13:22:21 --> Config file loaded: application/config/rest.php DEBUG - 2014-12-18 13:22:21 --> Helper loaded: inflector_helper DEBUG - 2014-12-18 13:22:22 --> Model Class Initialized DEBUG - 2014-12-18 13:22:22 --> Model Class Initialized DEBUG - 2014-12-18 13:22:54 --> Config Class Initialized DEBUG - 2014-12-18 13:22:54 --> Hooks Class Initialized DEBUG - 2014-12-18 13:22:54 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:22:54 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:22:54 --> URI Class Initialized DEBUG - 2014-12-18 13:22:54 --> Router Class Initialized DEBUG - 2014-12-18 13:22:54 --> Output Class Initialized DEBUG - 2014-12-18 13:22:54 --> Security Class Initialized DEBUG - 2014-12-18 13:22:54 --> Input Class Initialized DEBUG - 2014-12-18 13:22:54 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:22:54 --> Language Class Initialized DEBUG - 2014-12-18 13:22:54 --> Loader Class Initialized DEBUG - 2014-12-18 13:22:54 --> Database Driver Class Initialized ERROR - 2014-12-18 13:22:54 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 DEBUG - 2014-12-18 13:22:54 --> XML-RPC Class Initialized DEBUG - 2014-12-18 13:22:54 --> Controller Class Initialized DEBUG - 2014-12-18 13:22:54 --> Config file loaded: application/config/rest.php DEBUG - 2014-12-18 13:22:54 --> Helper loaded: inflector_helper DEBUG - 2014-12-18 13:22:56 --> Model Class Initialized DEBUG - 2014-12-18 13:22:56 --> Model Class Initialized DEBUG - 2014-12-18 13:50:37 --> Config Class Initialized DEBUG - 2014-12-18 13:50:37 --> Hooks Class Initialized DEBUG - 2014-12-18 13:50:37 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:50:37 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:50:37 --> URI Class Initialized DEBUG - 2014-12-18 13:50:37 --> Router Class Initialized DEBUG - 2014-12-18 13:50:38 --> Output Class Initialized DEBUG - 2014-12-18 13:50:38 --> Security Class Initialized DEBUG - 2014-12-18 13:50:38 --> Input Class Initialized DEBUG - 2014-12-18 13:50:38 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:50:38 --> Language Class Initialized DEBUG - 2014-12-18 13:50:38 --> Loader Class Initialized DEBUG - 2014-12-18 13:50:38 --> Database Driver Class Initialized ERROR - 2014-12-18 13:50:38 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:50:38 --> Severity: Warning --> mysql_pconnect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:50:38 --> Unable to connect to the database DEBUG - 2014-12-18 13:50:38 --> Language file loaded: language/english/db_lang.php DEBUG - 2014-12-18 13:50:49 --> Config Class Initialized DEBUG - 2014-12-18 13:50:49 --> Hooks Class Initialized DEBUG - 2014-12-18 13:50:49 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:50:49 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:50:49 --> URI Class Initialized DEBUG - 2014-12-18 13:50:49 --> Router Class Initialized DEBUG - 2014-12-18 13:50:49 --> Output Class Initialized DEBUG - 2014-12-18 13:50:49 --> Security Class Initialized DEBUG - 2014-12-18 13:50:49 --> Input Class Initialized DEBUG - 2014-12-18 13:50:49 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:50:49 --> Language Class Initialized DEBUG - 2014-12-18 13:50:49 --> Loader Class Initialized DEBUG - 2014-12-18 13:50:49 --> Database Driver Class Initialized ERROR - 2014-12-18 13:50:49 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:50:49 --> Severity: Warning --> mysql_pconnect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:50:49 --> Unable to connect to the database DEBUG - 2014-12-18 13:50:49 --> Language file loaded: language/english/db_lang.php DEBUG - 2014-12-18 13:50:59 --> Config Class Initialized DEBUG - 2014-12-18 13:50:59 --> Hooks Class Initialized DEBUG - 2014-12-18 13:50:59 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:50:59 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:50:59 --> URI Class Initialized DEBUG - 2014-12-18 13:50:59 --> Router Class Initialized DEBUG - 2014-12-18 13:50:59 --> Output Class Initialized DEBUG - 2014-12-18 13:50:59 --> Security Class Initialized DEBUG - 2014-12-18 13:50:59 --> Input Class Initialized DEBUG - 2014-12-18 13:50:59 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:50:59 --> Language Class Initialized DEBUG - 2014-12-18 13:50:59 --> Loader Class Initialized DEBUG - 2014-12-18 13:50:59 --> Database Driver Class Initialized ERROR - 2014-12-18 13:50:59 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:50:59 --> Severity: Warning --> mysql_pconnect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:50:59 --> Unable to connect to the database DEBUG - 2014-12-18 13:50:59 --> Language file loaded: language/english/db_lang.php DEBUG - 2014-12-18 13:51:14 --> Config Class Initialized DEBUG - 2014-12-18 13:51:14 --> Hooks Class Initialized DEBUG - 2014-12-18 13:51:14 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:51:14 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:51:14 --> URI Class Initialized DEBUG - 2014-12-18 13:51:14 --> Router Class Initialized DEBUG - 2014-12-18 13:51:14 --> Output Class Initialized DEBUG - 2014-12-18 13:51:14 --> Security Class Initialized DEBUG - 2014-12-18 13:51:14 --> Input Class Initialized DEBUG - 2014-12-18 13:51:14 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:51:14 --> Language Class Initialized DEBUG - 2014-12-18 13:51:14 --> Loader Class Initialized DEBUG - 2014-12-18 13:51:14 --> Database Driver Class Initialized ERROR - 2014-12-18 13:51:14 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:51:14 --> Severity: Warning --> mysql_pconnect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:51:14 --> Unable to connect to the database DEBUG - 2014-12-18 13:51:14 --> Language file loaded: language/english/db_lang.php DEBUG - 2014-12-18 13:51:28 --> Config Class Initialized DEBUG - 2014-12-18 13:51:28 --> Hooks Class Initialized DEBUG - 2014-12-18 13:51:28 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:51:28 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:51:28 --> URI Class Initialized DEBUG - 2014-12-18 13:51:28 --> Router Class Initialized DEBUG - 2014-12-18 13:51:28 --> Output Class Initialized DEBUG - 2014-12-18 13:51:28 --> Security Class Initialized DEBUG - 2014-12-18 13:51:28 --> Input Class Initialized DEBUG - 2014-12-18 13:51:28 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:51:28 --> Language Class Initialized DEBUG - 2014-12-18 13:51:28 --> Loader Class Initialized DEBUG - 2014-12-18 13:51:28 --> Database Driver Class Initialized ERROR - 2014-12-18 13:51:28 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:51:28 --> Severity: Warning --> mysql_pconnect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:51:28 --> Unable to connect to the database DEBUG - 2014-12-18 13:51:28 --> Language file loaded: language/english/db_lang.php DEBUG - 2014-12-18 13:51:33 --> Config Class Initialized DEBUG - 2014-12-18 13:51:33 --> Hooks Class Initialized DEBUG - 2014-12-18 13:51:33 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:51:33 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:51:33 --> URI Class Initialized DEBUG - 2014-12-18 13:51:33 --> Router Class Initialized DEBUG - 2014-12-18 13:51:33 --> Output Class Initialized DEBUG - 2014-12-18 13:51:33 --> Security Class Initialized DEBUG - 2014-12-18 13:51:33 --> Input Class Initialized DEBUG - 2014-12-18 13:51:33 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:51:33 --> Language Class Initialized DEBUG - 2014-12-18 13:51:33 --> Loader Class Initialized DEBUG - 2014-12-18 13:51:33 --> Database Driver Class Initialized ERROR - 2014-12-18 13:51:33 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:51:33 --> Severity: Warning --> mysql_pconnect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:51:33 --> Unable to connect to the database DEBUG - 2014-12-18 13:51:33 --> Language file loaded: language/english/db_lang.php DEBUG - 2014-12-18 13:51:48 --> Config Class Initialized DEBUG - 2014-12-18 13:51:48 --> Hooks Class Initialized DEBUG - 2014-12-18 13:51:48 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:51:48 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:51:48 --> URI Class Initialized DEBUG - 2014-12-18 13:51:48 --> Router Class Initialized DEBUG - 2014-12-18 13:51:48 --> Output Class Initialized DEBUG - 2014-12-18 13:51:48 --> Security Class Initialized DEBUG - 2014-12-18 13:51:48 --> Input Class Initialized DEBUG - 2014-12-18 13:51:48 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:51:48 --> Language Class Initialized DEBUG - 2014-12-18 13:51:48 --> Loader Class Initialized DEBUG - 2014-12-18 13:51:48 --> Database Driver Class Initialized ERROR - 2014-12-18 13:51:48 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:51:48 --> Severity: Warning --> mysql_pconnect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:51:48 --> Unable to connect to the database DEBUG - 2014-12-18 13:51:48 --> Language file loaded: language/english/db_lang.php DEBUG - 2014-12-18 13:53:31 --> Config Class Initialized DEBUG - 2014-12-18 13:53:31 --> Hooks Class Initialized DEBUG - 2014-12-18 13:53:31 --> Utf8 Class Initialized DEBUG - 2014-12-18 13:53:31 --> UTF-8 Support Enabled DEBUG - 2014-12-18 13:53:31 --> URI Class Initialized DEBUG - 2014-12-18 13:53:31 --> Router Class Initialized DEBUG - 2014-12-18 13:53:32 --> Output Class Initialized DEBUG - 2014-12-18 13:53:32 --> Security Class Initialized DEBUG - 2014-12-18 13:53:32 --> Input Class Initialized DEBUG - 2014-12-18 13:53:32 --> Global POST and COOKIE data sanitized DEBUG - 2014-12-18 13:53:32 --> Language Class Initialized DEBUG - 2014-12-18 13:53:32 --> Loader Class Initialized DEBUG - 2014-12-18 13:53:32 --> Database Driver Class Initialized ERROR - 2014-12-18 13:53:32 --> Severity: 8192 --> mysql_pconnect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:53:32 --> Severity: Warning --> mysql_pconnect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2) /Volumes/Data/www/thunderbirds/thunderbirds-hub-site/system/database/drivers/mysql/mysql_driver.php 91 ERROR - 2014-12-18 13:53:32 --> Unable to connect to the database DEBUG - 2014-12-18 13:53:32 --> Language file loaded: language/english/db_lang.php
{ "content_hash": "0b899b30b07591f90062559d0d0b0fa2", "timestamp": "", "source": "github", "line_count": 302, "max_line_length": 316, "avg_line_length": 79.35099337748345, "alnum_prop": 0.7376064096144216, "repo_name": "umapathymanohar/isearchnyc-ci", "id": "609d061f5bb3b3c3e8d72a67a83a6f0231ffec19", "size": "23964", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/logs/log-2014-12-18.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "277" }, { "name": "CSS", "bytes": "6593" }, { "name": "HTML", "bytes": "1302682" }, { "name": "JavaScript", "bytes": "10896" }, { "name": "PHP", "bytes": "3602966" } ], "symlink_target": "" }
/* Node.js KC3改 Node Object Represents a single battle on a node Used by SortieManager */ (function(){ "use strict"; window.KC3Node = function(sortie_id, id, UTCTime){ this.sortie = (sortie_id || 0); this.id = (id || 0); this.type = ""; this.stime = UTCTime; this.isPvP = false; }; // static function. predicts battle rank, // arguments are beginHPs, endHPs in following structure: // { ally: [array of hps] // , enemy: [array of hps] // } // arrays are all begins at 0 KC3Node.predictRank = function(beginHPs, endHPs) { console.assert( beginHPs.ally.length === endHPs.ally.length, "ally data length mismatched"); console.assert( beginHPs.enemy.length === endHPs.enemy.length, "enemy data length mismatched"); // removes "-1"s in begin HPs // also removes data from same position // in end HPs // in addition, negative end HP values are set to 0 function normalizeHP(begins, ends) { var nBegins = []; var nEnds = []; for (var i=0; i<begins.length; ++i) { if (begins[i] !== -1) { console.assert( begins[i] > 0, "wrong begin HP"); nBegins.push(begins[i]); nEnds.push( ends[i]<0 ? 0 : ends[i] ); } } return [nBegins,nEnds]; } // perform normalization var result1, result2; result1 = normalizeHP(beginHPs.ally, endHPs.ally); result2 = normalizeHP(beginHPs.enemy, endHPs.enemy); // create new objs leaving old data intact beginHPs = { ally: result1[0], enemy: result2[0] }; endHPs = { ally: result1[1], enemy: result2[1] }; var allySunkCount = endHPs.ally.filter(function(x){return x===0;}).length; var allyCount = endHPs.ally.length; var enemySunkCount = endHPs.enemy.filter(function(x){return x===0;}).length; var enemyCount = endHPs.enemy.length; var requiredSunk = enemyCount === 6 ? 4 : Math.ceil( enemyCount / 2); var i; // damage taken by ally var allyGauge = 0; var allyBeginHP = 0; for (i=0; i<allyCount; ++i) { allyGauge += beginHPs.ally[i] - endHPs.ally[i]; allyBeginHP += beginHPs.ally[i]; } var enemyGauge = 0; var enemyBeginHP = 0; for (i=0; i<enemyCount; ++i) { enemyGauge += beginHPs.enemy[i] - endHPs.enemy[i]; enemyBeginHP += beginHPs.enemy[i]; } var allyGaugeRate = Math.floor(allyGauge / allyBeginHP * 100); var enemyGaugeRate = Math.floor(enemyGauge / enemyBeginHP * 100); var equalOrMore = enemyGaugeRate > (0.9 * allyGaugeRate); var superior = enemyGaugeRate > 0 && enemyGaugeRate > (2.5 * allyGaugeRate); if (allySunkCount === 0) { if (enemySunkCount === enemyCount) { return allyGauge === 0 ? "SS" : "S"; } if (enemySunkCount >= requiredSunk) return "A"; if (endHPs.enemy[0] === 0) return "B"; if (superior) return "B"; } else { if (enemySunkCount === enemyCount) return "B"; if (endHPs.enemy[0] === 0 && allySunkCount < enemySunkCount) return "B"; if (superior) return "B"; if (endHPs.enemy[0] === 0) return "C"; } if (enemyGauge > 0 && equalOrMore) return "C"; if (allySunkCount > 0 && allyCount === 1) return "E"; return "D"; }; KC3Node.prototype.defineAsBattle = function( nodeData ){ this.type = "battle"; this.startNight = false; // If passed initial values if(typeof nodeData != "undefined"){ // If passed raw data from compass //"api_event_id":4,"api_event_kind":1 if(typeof nodeData.api_event_kind != "undefined"){ this.eships = []; this.eventKind = nodeData.api_event_kind; this.eventId = nodeData.api_event_id; this.gaugeDamage = 0; // calculate this on result screen. make it fair :D } // If passed formatted enemy list from PVP if(typeof nodeData.pvp_opponents != "undefined"){ this.eships = nodeData.pvp_opponents; this.gaugeDamage = -1; } } this.enemySunk = [false, false, false, false, false, false]; this.enemyHP = [0,0,0,0,0,0]; this.originalHPs = [0,0,0,0,0,0,0,0,0,0,0,0,0]; this.allyNoDamage = true; this.nodalXP = 0; this.lostShips = [[],[]]; this.mvps = []; this.dameConConsumed = []; this.dameConConsumedEscort = []; return this; }; KC3Node.prototype.defineAsResource = function( nodeData ){ this.type = "resource"; this.item = nodeData.api_itemget.api_icon_id; this.icon = function(folder){ return folder+( ["fuel","ammo","steel","bauxite","ibuild","bucket","devmat","compass","","box1","box2","box3"] [nodeData.api_itemget.api_icon_id-1] )+".png"; }; this.amount = nodeData.api_itemget.api_getcount; if(this.item < 8) KC3SortieManager.materialGain[this.item-1] += this.amount; return this; }; KC3Node.prototype.defineAsBounty = function( nodeData ){ var self = this, maps = JSON.parse(localStorage.maps), ckey = ["m",KC3SortieManager.map_world,KC3SortieManager.map_num].join(""); this.type = "bounty"; this.item = nodeData.api_itemget_eo_comment.api_id; this.icon = function(folder){ return folder+( ["fuel","ammo","steel","bauxite","ibuild","bucket","devmat","compass"] [self.item-1] )+".png"; }; this.amount = nodeData.api_itemget_eo_comment.api_getcount; KC3SortieManager.materialGain[this.item-1] += this.amount; maps[ckey].clear |= (++maps[ckey].kills) >= KC3Meta.gauge(ckey.replace("m","")); localStorage.maps = JSON.stringify(maps); return this; }; KC3Node.prototype.defineAsMaelstrom = function( nodeData ){ this.type = "maelstrom"; this.item = nodeData.api_happening.api_icon_id; this.icon = function(folder){ return folder+( ["fuel","ammo","steel","bauxite","ibuild","bucket","devmat","compass"] [nodeData.api_happening.api_icon_id-1] )+".png"; }; this.amount = nodeData.api_happening.api_count; return this; }; KC3Node.prototype.defineAsSelector = function( nodeData ){ console.log("defining as selector", nodeData); this.type = "select"; this.choices = [ KC3Meta.nodeLetter( KC3SortieManager.map_world, KC3SortieManager.map_num, nodeData.api_select_route.api_select_cells[0] ), KC3Meta.nodeLetter( KC3SortieManager.map_world, KC3SortieManager.map_num, nodeData.api_select_route.api_select_cells[1] ) ]; console.log("choices", this.choices); return this; }; KC3Node.prototype.defineAsTransport = function( nodeData ){ this.type = "transport"; this.amount = KC3SortieManager.getSortieFleet().map(function(fleetId){ return PlayerManager.fleets[fleetId].ship().filter(function(ship){ return !(ship.didFlee); }).map(function(ship){ return ship.countDrums(); }).reduce(function(pre,cur){ return pre+cur; },0); }).reduce(function(pre,cur){ return pre+cur; },0); return this; }; KC3Node.prototype.defineAsDud = function( nodeData ){ this.type = ""; return this; }; /* BATTLE FUNCTIONS ---------------------------------------------*/ KC3Node.prototype.engage = function( battleData, fleetSent ){ this.battleDay = battleData; var enemyships = battleData.api_ship_ke; if(enemyships[0]==-1){ enemyships.splice(0,1); } this.eships = enemyships; this.eformation = battleData.api_formation[1]; this.eParam = battleData.api_eParam; this.eKyouka = battleData.api_eKyouka; this.eSlot = battleData.api_eSlot; this.supportFlag = (battleData.api_support_flag>0); this.yasenFlag = (battleData.api_midnight_flag>0); this.originalHPs = battleData.api_nowhps; var beginHPs = { ally: battleData.api_nowhps.slice(1,7), enemy: battleData.api_nowhps.slice(7,13) }; this.dayBeginHPs = beginHPs; this.detection = KC3Meta.detection( battleData.api_search[0] ); this.engagement = KC3Meta.engagement( battleData.api_formation[2] ); // Air phases var planePhase = battleData.api_kouku.api_stage1 || { api_touch_plane:[-1,-1], api_f_count :0, api_f_lostcount:0, api_e_count :0, api_e_lostcount:0, }, attackPhase = battleData.api_kouku.api_stage2; this.fcontactId = planePhase.api_touch_plane[0]; this.fcontact = this.fcontactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo"); this.econtactId = planePhase.api_touch_plane[1]; this.econtact = this.econtactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo"); this.airbattle = KC3Meta.airbattle( planePhase.api_disp_seiku ); if(!!attackPhase && !!attackPhase.api_air_fire){ this.antiAirFire = [ attackPhase.api_air_fire ]; } // Fighter phase 1 this.planeFighters = { player:[ planePhase.api_f_count, planePhase.api_f_lostcount ], abyssal:[ planePhase.api_e_count, planePhase.api_e_lostcount ] }; if( this.planeFighters.player[0]===0 && this.planeFighters.abyssal[0]===0 && attackPhase===null ){ this.airbattle = KC3Meta.airbattle(5); } // Bombing phase 1 this.planeBombers = { player:[0,0], abyssal:[0,0] }; if(attackPhase !== null){ this.planeBombers.player[0] = attackPhase.api_f_count; this.planeBombers.player[1] = attackPhase.api_f_lostcount; this.planeBombers.abyssal[0] = attackPhase.api_e_count; this.planeBombers.abyssal[1] = attackPhase.api_e_lostcount; } // Fighter phase 2 if(typeof battleData.api_kouku2 != "undefined"){ this.planeFighters.player[1] += battleData.api_kouku2.api_stage1.api_f_lostcount; this.planeFighters.abyssal[1] += battleData.api_kouku2.api_stage1.api_e_lostcount; // Bombine phase 2 if(battleData.api_kouku2.api_stage2 !== null){ this.planeBombers.player[1] += battleData.api_kouku2.api_stage2.api_f_lostcount; this.planeBombers.abyssal[1] += battleData.api_kouku2.api_stage2.api_e_lostcount; if(!!battleData.api_kouku2.api_stage2.api_air_fire){ if(!this.antiAirFire || this.antiAirFire.length<1){ this.antiAirFire = [null]; } this.antiAirFire[1] = battleData.api_kouku2.api_stage2.api_air_fire; } } } var PS = window.PS; var DA = PS["KanColle.DamageAnalysis.FFI"]; var result = null; var i = 0; var fleet; var dameConCode; var shipNum; var ship; var fleetId = parseInt(fleetSent) || KC3SortieManager.fleetSent; if ((typeof PlayerManager.combinedFleet === "undefined") || (PlayerManager.combinedFleet === 0) || fleetId>1){ // single fleet: not combined, or sent fleet is not first fleet // Update our fleet fleet = PlayerManager.fleets[fleetId - 1]; // damecon ignored for PvP dameConCode = KC3SortieManager.isPvP() ? [0,0,0, 0,0,0] : fleet.getDameConCodes(); result = DA.analyzeBattleJS(dameConCode, battleData); // console.debug("Damage analysis result", result); var endHPs = { ally: beginHPs.ally.slice(), enemy: beginHPs.enemy.slice() }; // Update enemy ships for (i = 7; i < 13; i++) { this.enemyHP[i-7] = result.enemy[i-7]; endHPs.enemy[i-7] = result.enemy[i-7] ? result.enemy[i-7].hp : -1; this.enemySunk[i-7] = result.enemy[i-7] ? result.enemy[i-7].sunk : true; } // update player ships shipNum = fleet.countShips(); for(i = 0; i < shipNum; i++) { ship = fleet.ship(i); ship.afterHp[0] = result.main[i].hp; this.allyNoDamage &= ship.hp[0]==ship.afterHp[0]; ship.afterHp[1] = ship.hp[1]; endHPs.ally[i] = result.main[i].hp; // Check if damecon consumed, if yes, get item consumed if (result.main[i].dameConConsumed){ this.dameConConsumed[i] = ship.findDameCon(); } else { this.dameConConsumed[i] = false; } } if(ConfigManager.info_btrank && // long distance aerial battle not predictable for now, see #1333 // but go for aerial battle (eventKind:4) possible Yasen [6].indexOf(this.eventKind)<0 ){ this.predictedRank = KC3Node.predictRank( beginHPs, endHPs ); // console.debug("Rank Predict:", this.predictedRank); } } else { // combined fleet dameConCode = PlayerManager.fleets[0].getDameConCodes() .concat( PlayerManager.fleets[1].getDameConCodes() ); console.assert(dameConCode.length === 12, "dameConCode length should be 12 for combined fleets"); if (PlayerManager.combinedFleet === 1) { // Carrier Task Force result = DA.analyzeCTFBattleJS(dameConCode,battleData); } else if (PlayerManager.combinedFleet === 2) { // Surface Task Force result = DA.analyzeSTFBattleJS(dameConCode,battleData); } else if (PlayerManager.combinedFleet === 3) { // Transport Escort result = DA.analyzeTECFBattleJS(dameConCode,battleData); } else { console.error( "Unknown combined fleet code: " + PlayerManager.combinedFleet ); } // Update enemy for(i = 1; i <= 6; i++) { var enemy = result.enemy[i-1]; if (enemy !== null) { this.enemyHP[i-1] = enemy; this.enemySunk[i-1] = enemy.sunk; } } // Update main fleet fleet = PlayerManager.fleets[0]; shipNum = fleet.countShips(); var mainFleet = result.main; for(i = 0; i < shipNum; i++) { ship = fleet.ship(i); ship.afterHp[0] = mainFleet[i].hp; this.allyNoDamage &= ship.hp[0]==ship.afterHp[0]; ship.afterHp[1] = ship.hp[1]; // Check if damecon consumed, if yes, get item consumed if (mainFleet[i].dameConConsumed){ this.dameConConsumed[i] = ship.findDameCon(); } else { this.dameConConsumed[i] = false; } } // Update escort fleet fleet = PlayerManager.fleets[1]; shipNum = fleet.countShips(); var escortFleet = result.escort; for(i = 0; i < shipNum; i++) { ship = fleet.ship(i); ship.afterHp[0] = escortFleet[i].hp; this.allyNoDamage &= ship.hp[0]==ship.afterHp[0]; ship.afterHp[1] = ship.hp[1]; // Check if damecon consumed, if yes, get item consumed if (escortFleet[i].dameConConsumed){ this.dameConConsumedEscort[i] = ship.findDameCon(); } else { this.dameConConsumedEscort[i] = false; } } } if(this.gaugeDamage > -1) { this.gaugeDamage = Math.min(this.originalHPs[7],this.originalHPs[7] - this.enemyHP[0].hp); (function(sortieData){ var maps = localStorage.getObject('maps'), desg = ['m',sortieData.map_world,sortieData.map_num].join(''); if(this.isBoss() && maps[desg].kind == 'gauge-hp') { maps[desg].baseHp = maps[desg].baseHp || this.originalHPs[7]; } localStorage.setObject('maps',maps); }).call(this,KC3SortieManager); } // Record encoutners only if on sortie if(KC3SortieManager.onSortie > 0) { // Validate values if(KC3SortieManager.map_world < 1){ return true; } if(KC3SortieManager.map_num < 1){ return true; } // Save the enemy encounter var ed = { world: KC3SortieManager.map_world, map: KC3SortieManager.map_num, node: this.id, form: this.eformation, ke: JSON.stringify(this.eships) }; ed.uniqid = ed.world+"/"+ed.map+"/"+ed.node+"/"+ed.form+"/"+ed.ke; KC3Database.Encounter(ed); // Save enemy info for(i = 0; i < 6; i++) { var enemyId = this.eships[i] || -1; // Only record ships with ID more than 500 coz abyss only if (enemyId > 500) { KC3Database.Enemy({ id: enemyId, hp: this.battleDay.api_maxhps[i+7], fp: this.battleDay.api_eParam[i][0], tp: this.battleDay.api_eParam[i][1], aa: this.battleDay.api_eParam[i][2], ar: this.battleDay.api_eParam[i][3], eq1: this.battleDay.api_eSlot[i][0], eq2: this.battleDay.api_eSlot[i][1], eq3: this.battleDay.api_eSlot[i][2], eq4: this.battleDay.api_eSlot[i][3] }); } } } }; KC3Node.prototype.engageNight = function( nightData, fleetSent, setAsOriginalHP ){ if(typeof setAsOriginalHP == "undefined"){ setAsOriginalHP = true; } this.battleNight = nightData; this.startNight = (fleetSent !== undefined); var enemyships = nightData.api_ship_ke; if(enemyships[0]==-1){ enemyships.splice(0,1); } this.eships = enemyships; this.eformation = this.eformation || nightData.api_formation[1]; this.eParam = nightData.api_eParam; this.eKyouka = nightData.api_eKyouka; this.eSlot = nightData.api_eSlot; // if we did not started at night, at this point dayBeginHPs should be available var beginHPs = { ally: [], enemy: [] }; if (this.dayBeginHPs) { beginHPs = this.dayBeginHPs; } else { beginHPs.ally = nightData.api_nowhps.slice(1,7); beginHPs.enemy = nightData.api_nowhps.slice(7,13); } if(setAsOriginalHP){ this.originalHPs = nightData.api_nowhps; } this.engagement = this.engagement || KC3Meta.engagement( nightData.api_formation[2] ); this.fcontactId = nightData.api_touch_plane[0]; // masterId of slotitem, starts from 1 this.fcontact = this.fcontactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo"); this.econtactId = nightData.api_touch_plane[1]; this.econtact = this.econtactId > 0 ? KC3Meta.term("BattleContactYes") : KC3Meta.term("BattleContactNo"); this.flarePos = nightData.api_flare_pos[0]; // Star shell user pos 1-6 this.eFlarePos = nightData.api_flare_pos[1]; // PvP opponent only, abyss star shell not existed yet var PS = window.PS; var DA = PS["KanColle.DamageAnalysis.FFI"]; var result = null; var i = 0; var fleet; var dameConCode; var shipNum; var ship; var fleetId = parseInt(fleetSent) || KC3SortieManager.fleetSent; // COMBINED FLEET if (PlayerManager.combinedFleet && (fleetId <= 1)) { fleet = PlayerManager.fleets[1]; dameConCode = fleet.getDameConCodes(); result = DA.analyzeCombinedNightBattleJS(dameConCode, nightData); // SINGLE FLEET } else { // single fleet: not combined, or sent fleet is not first fleet fleet = PlayerManager.fleets[fleetId - 1]; // damecon ignored for PvP dameConCode = KC3SortieManager.isPvP() ? [0,0,0, 0,0,0] : fleet.getDameConCodes(); result = DA.analyzeNightBattleJS(dameConCode, nightData); } var endHPs = { ally: beginHPs.ally.slice(), enemy: beginHPs.enemy.slice() }; for (i = 7; i < 13; i++) { this.enemyHP[i-7] = result.enemy[i-7]; endHPs.enemy[i-7] = result.enemy[i-7] ? result.enemy[i-7].hp : -1; this.enemySunk[i-7] = result.enemy[i-7] ? result.enemy[i-7].sunk : true; } shipNum = fleet.countShips(); for(i = 0; i < shipNum; i++) { ship = fleet.ship(i); ship.hp = [ship.afterHp[0], ship.afterHp[1]]; ship.morale = Math.max(0,Math.min(100,ship.morale+(fleetSent ? 1 : -3 ))); ship.afterHp[0] = result.main[i].hp; this.allyNoDamage &= ship.hp[0]==ship.afterHp[0]; ship.afterHp[1] = ship.hp[1]; endHPs.ally[i] = result.main[i].hp; } if(ConfigManager.info_btrank){ this.predictedRankNight = KC3Node.predictRank( beginHPs, endHPs ); // console.debug("Rank Predict (Night):", this.predictedRankNight); } if(this.gaugeDamage > -1) this.gaugeDamage = this.gaugeDamage + Math.min(nightData.api_nowhps[7],nightData.api_nowhps[7] - this.enemyHP[0].hp); }; KC3Node.prototype.night = function( nightData ){ this.engageNight(nightData, null, false); }; KC3Node.prototype.results = function( resultData ){ try { this.rating = resultData.api_win_rank; this.nodalXP = resultData.api_get_base_exp; if(this.allyNoDamage && this.rating === "S") this.rating = "SS"; console.log("This battle, the ally fleet has no damage:",this.allyNoDamage); if(this.isBoss()) { var maps = localStorage.getObject('maps'), ckey = ["m",KC3SortieManager.map_world,KC3SortieManager.map_num].join(""), stat = maps[ckey].stat, srid = KC3SortieManager.onSortie; /* DESPAIR STATISTICS ==> */ if(stat) { var fs = [this.gaugeDamage,this.originalHPs[7]], pt = 'dummy', sb = stat.onBoss, oc = 0; fs.push(fs[0]/fs[1]); fs.push(fs[1]-fs[0]); switch(true){ case (fs[0] === 0): pt = 'fresh'; break; case (fs[2] < 0.25): pt = 'graze'; break; case (fs[2] < 0.50): pt = 'light'; break; case (fs[2] < 0.75): pt = 'modrt'; break; case (fs[3] > 9): pt = 'heavy'; break; case (fs[3] > 1): pt = 'despe'; break; case (fs[3] == 1): pt = 'endur'; break; case (fs[3] < 1): pt = 'destr'; break; } sb[pt].push(srid); oc = sb[pt].length; console.info('Current sortie recorded as',pt,'.'); console.info('You\'ve done this',oc,'time'+(oc != 1 ? 's' : '')+'.','Good luck, see you next time!'); } /* ==> DESPAIR STATISTICS */ /* FLAGSHIP ATTACKING ==> */ console.log("Damaged Flagship ",this.gaugeDamage,"/",maps[ckey].curhp || 0,"pts"); switch(maps[ckey].kind) { case 'single': /* Single Victory */ break; case 'multiple': /* Kill-based */ if((KC3Meta.gauge(ckey.replace("m","")) - (maps[ckey].kills || 0)) > 0) maps[ckey].kills += resultData.api_destsf; break; case 'gauge-hp': /* HP-Gauge */ if((this.gaugeDamage >= 0) && (maps[ckey].curhp || 0) > 0) { maps[ckey].curhp -= this.gaugeDamage; if(maps[ckey].curhp <= 0) // if last kill -- check whether flagship is killed or not -- flagship killed = map clear maps[ckey].curhp = 1-(maps[ckey].clear = resultData.api_destsf); } break; case 'gauge-tp': /* TP-Gauge */ /* TP Gauge */ var TPdata = resultData.api_landing_hp; this.gaugeDamage = Math.min(TPdata.api_now_hp,TPdata.api_sub_value); maps[ckey].curhp = TPdata.api_now_hp - this.gaugeDamage; maps[ckey].maxhp = TPdata.api_max_hp - 0; break; default: /* Undefined */ break; } maps[ckey].clear |= resultData.api_first_clear; // obtaining clear once if(stat) { stat.onBoss.hpdat[srid] = [maps[ckey].curhp,maps[ckey].maxhp]; if(resultData.api_first_clear) stat.onClear = srid; // retrieve sortie ID for first clear mark } /* ==> FLAGSHIP ATTACKING */ localStorage.setObject('maps',maps); } var ship_get = []; if(typeof resultData.api_get_ship != "undefined"){ this.drop = resultData.api_get_ship.api_ship_id; KC3ShipManager.pendingShipNum += 1; KC3GearManager.pendingGearNum += KC3Meta.defaultEquip(this.drop); console.log("Drop " + resultData.api_get_ship.api_ship_name + " (" + this.drop + ") Equip " + KC3Meta.defaultEquip(this.drop)); ship_get.push(this.drop); }else{ this.drop = 0; } /* api_get_eventitem :海域攻略報酬 イベント海域突破時のみ存在 api_type :報酬種別 1=アイテム, 2=艦娘, 3=装備 api_id :ID api_value :個数? */ (function(resultEventItems){ console.log("event result",resultEventItems); (resultEventItems || []).forEach(function(eventItem){ switch(eventItem.api_type){ case 1: // Item if(eventItem.api_id.inside(1,4)) { KC3SortieManager.materialGain[eventItem.api_id+3] += eventItem.api_value; } break; case 2: // Ship ship_get.push(eventItem.api_id); break; case 3: // Equip break; default: console.log("unknown type",eventItem); break; } }); }).call(this,resultData.api_get_eventitem); ConfigManager.load(); ship_get.forEach(function(newShipId){ var wish_kind = ["salt","wish"]; wish_kind.some(function(wishType){ var wish_key = [wishType,'list'].join('_'), wish_id = ConfigManager[wish_key].indexOf(newShipId)+1; if(wish_id){ ConfigManager[wish_key].splice(wish_id-1,1); console.warn("Removed",KC3Meta.shipName(KC3Master.ship(newShipId).api_name),"from",wishType,"list"); ConfigManager.lock_prep.push(newShipId); return true; } else { return false; } }); }); ConfigManager.save(); this.mvps = [resultData.api_mvp || 0,resultData.api_mvp_combined || 0].filter(function(x){return !!x;}); var lostCheck = (resultData.api_lost_flag) ? [resultData.api_lost_flag,null] : /* if api_lost_flag is explicitly specified */ [resultData.api_get_ship_exp,resultData.api_get_ship_exp_combined].map(function(expData,fleetId){ return expData ? expData.slice(1) : []; // filter out first dummy element, be aware for undefined item }).map(function(expData,fleetId){ /* Example data: "api_get_ship_exp":[-1,420,140,140,140,-1,-1], "api_get_exp_lvup":[[177,300,600],[236,300,600],[118,300],[118,300]], "api_get_ship_exp_combined":[-1,420,140,140,-1,-1,-1], "api_get_exp_lvup_combined":[[177,300,600],[236,300,600],[118,300],[118,300]] Logic : - for ship_exp indices, start from 1. - compare ship_exp data, check it if -1 - (fail condition) ignore, set as non-sink and skip to next one - compare the current index with the neighboring array (exp_lvup), check if an array exists on that index - if it exists, mark as sunk Source: https://gitter.im/KC3Kai/Public?at=5662e448c15bca7e3c96376f */ return expData.map(function(data,slotId){ return (data == -1) && !!resultData[['api_get','exp_lvup','combined'].slice(0,fleetId+2).join('_')][slotId]; }); }), fleetDesg = [KC3SortieManager.fleetSent - 1,1]; // designated fleet (fleet mapping) this.lostShips = lostCheck.map(function(lostFlags,fleetNum){ console.log("lostFlags",fleetNum, lostFlags); return (lostFlags || []).filter(function(x){return x>=0;}).map(function(checkSunk,rosterPos){ if(!!checkSunk) { var rtv = PlayerManager.fleets[fleetDesg[fleetNum]].ships[rosterPos]; if(KC3ShipManager.get(rtv).didFlee) return 0; console.log("このクソ提督、深海に%c%s%cが沈んだ (ID:%d)", 'color:red,font-weight:bold', KC3ShipManager.get(rtv).master().api_name, 'color:initial,font-weight:initial', rtv ); return rtv; } else { return 0; } }).filter(function(shipId){return shipId;}); }); //var enemyCVL = [510, 523, 560]; //var enemyCV = [512, 525, 528, 565, 579]; //var enemySS = [530, 532, 534, 531, 533, 535, 570, 571, 572]; //var enemyAP = [513, 526, 558]; for(var i = 0; i < 6; i++) { if (this.enemySunk[i]) { var enemyShip = KC3Master.ship(this.eships[i]); if (!enemyShip) { console.log("Cannot find enemy " + this.eships[i]); } else if (this.eships[i] < 500) { console.log("Enemy ship is not Abyssal!"); } else { switch(enemyShip.api_stype) { case 7: // 7 = CVL case 11: // 11 = CV console.log("You sunk a CV"+((enemyShip.api_stype==7)?"L":"")); KC3QuestManager.get(217).increment(); KC3QuestManager.get(211).increment(); KC3QuestManager.get(220).increment(); break; case 13: // 13 = SS console.log("You sunk a SS"); KC3QuestManager.get(230).increment(); KC3QuestManager.get(228).increment(); break; case 15: // 15 = AP console.log("You sunk a AP"); KC3QuestManager.get(218).increment(); KC3QuestManager.get(212).increment(); KC3QuestManager.get(213).increment(); KC3QuestManager.get(221).increment(); break; } } } } } catch (e) { console.error("Captured an exception ==>", e,"\n==> proceeds safely"); } finally { this.saveBattleOnDB(resultData); } }; KC3Node.prototype.resultsPvP = function( resultData ){ try { this.rating = resultData.api_win_rank; this.nodalXP = resultData.api_get_base_exp; if(this.allyNoDamage && this.rating === "S") this.rating = "SS"; this.mvps = [resultData.api_mvp || 0]; } catch (e) { console.error("Captured an exception ==>", e,"\n==> proceeds safely"); } finally { // Reserved for future PvP history storage //this.saveBattleOnDB(resultData); } }; KC3Node.prototype.isBoss = function(){ //console.log("Meet Boss: " + ((this.eventKind === 1) && (this.eventId === 5))); return ((this.eventKind === 1) && (this.eventId === 5)); }; KC3Node.prototype.saveBattleOnDB = function( resultData ){ KC3Database.Battle({ sortie_id: (this.sortie || KC3SortieManager.onSortie || 0), node: this.id, enemyId: (this.epattern || 0), data: (this.battleDay || {}), yasen: (this.battleNight || {}), rating: this.rating, drop: this.drop, time: this.stime, baseEXP: this.nodalXP, hqEXP: resultData.api_get_exp || 0, shizunde: this.lostShips.map(function(fleetLost){ return fleetLost.map(function(shipSunk){ return KC3ShipManager.get(shipSunk).masterId; }); }), mvp: this.mvps }); }; })();
{ "content_hash": "bfb1c3d1ec68a7eb8f71cbace408507b", "timestamp": "", "source": "github", "line_count": 882, "max_line_length": 131, "avg_line_length": 33.28231292517007, "alnum_prop": 0.6119911429058082, "repo_name": "KC-TH/KC3Kai", "id": "7c294e348849bc9f76425ddb86e11cfa8a4018c6", "size": "29463", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/library/objects/Node.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "317225" }, { "name": "Emacs Lisp", "bytes": "56" }, { "name": "HTML", "bytes": "284583" }, { "name": "JavaScript", "bytes": "1051487" } ], "symlink_target": "" }
<?php namespace conquer\oauth2; use yii\web\IdentityInterface; /** * Interface OAtuh2IdentityInterface * @package conquer\oauth2 * @author Dmitry Fedorenko */ interface OAuth2IdentityInterface { /** * Find idenity by username * @param string $username current username * @return IdentityInterface */ public static function findIdentityByUsername($username); /** * Validates password * @param string $password password to validate * @return bool if password provided is valid for current user */ public function validatePassword($password); }
{ "content_hash": "e25ee7a950de89cca5ceefb4ea70653e", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 66, "avg_line_length": 21.678571428571427, "alnum_prop": 0.700164744645799, "repo_name": "borodulin/yii2-oauth2-server", "id": "3c216edae4dd59f801127053bf28040ff4bb4eb7", "size": "801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/OAuth2IdentityInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64620" } ], "symlink_target": "" }
package org.apache.oozie.servlet; import org.apache.oozie.service.AuthorizationService; import org.apache.oozie.service.ProxyUserService; import org.apache.oozie.service.Services; import org.apache.oozie.service.ForTestAuthorizationService; import org.apache.oozie.service.ForTestWorkflowStoreService; import org.apache.oozie.test.EmbeddedServletContainer; import org.apache.oozie.test.XDataTestCase; import org.apache.oozie.test.XFsTestCase; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import java.util.concurrent.Callable; public abstract class DagServletTestCase extends XDataTestCase { private EmbeddedServletContainer container; private String servletPath; protected String getContextURL() { return container.getContextURL(); } protected URL createURL(String servletPath, String resource, Map<String, String> parameters) throws Exception { StringBuilder sb = new StringBuilder(); sb.append(container.getServletURL(servletPath)); if (resource != null && resource.length() > 0) { sb.append("/").append(resource); } if (parameters.size() > 0) { String separator = "?"; for (Map.Entry<String, String> param : parameters.entrySet()) { sb.append(separator).append(URLEncoder.encode(param.getKey(), "UTF-8")).append("=") .append(URLEncoder.encode(param.getValue(), "UTF-8")); separator = "&"; } } return new URL(sb.toString()); } protected URL createURL(String resource, Map<String, String> parameters) throws Exception { return createURL(servletPath, resource, parameters); } @SuppressWarnings("unchecked") protected void runTest(String servletPath, Class servletClass, boolean securityEnabled, Callable<Void> assertions) throws Exception { runTest(new String[]{servletPath}, new Class[]{servletClass}, securityEnabled, assertions); } protected void runTest(String[] servletPath, Class[] servletClass, boolean securityEnabled, Callable<Void> assertions) throws Exception { Services services = new Services(); this.servletPath = servletPath[0]; try { String proxyUser = getTestUser(); services.getConf().set(ProxyUserService.CONF_PREFIX + proxyUser + ProxyUserService.HOSTS, "*"); services.getConf().set(ProxyUserService.CONF_PREFIX + proxyUser + ProxyUserService.GROUPS, "*"); services.init(); services.getConf().setBoolean(AuthorizationService.CONF_SECURITY_ENABLED, securityEnabled); Services.get().setService(ForTestAuthorizationService.class); Services.get().setService(ForTestWorkflowStoreService.class); Services.get().setService(MockDagEngineService.class); Services.get().setService(MockCoordinatorEngineService.class); container = new EmbeddedServletContainer("oozie"); for (int i = 0; i < servletPath.length; i++) { container.addServletEndpoint(servletPath[i], servletClass[i]); } container.addFilter("*", HostnameFilter.class); container.addFilter("*", AuthFilter.class); setSystemProperty("user.name", getTestUser()); container.start(); assertions.call(); } finally { this.servletPath = null; if (container != null) { container.stop(); } services.destroy(); container = null; } } }
{ "content_hash": "86042d2b50fca6f344d0ef05e720c57c", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 118, "avg_line_length": 41.333333333333336, "alnum_prop": 0.6387096774193548, "repo_name": "cbaenziger/oozie", "id": "ce731a16bae5b8652021dd0816bd206f48a68ac1", "size": "4527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/test/java/org/apache/oozie/servlet/DagServletTestCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "16115" }, { "name": "CSS", "bytes": "27272" }, { "name": "HTML", "bytes": "8786" }, { "name": "Java", "bytes": "10168055" }, { "name": "JavaScript", "bytes": "143427" }, { "name": "PowerShell", "bytes": "9356" }, { "name": "Python", "bytes": "1349" }, { "name": "Shell", "bytes": "114386" } ], "symlink_target": "" }
<?php namespace Igoreus\BloomFilter\Test\Hash; use Igoreus\BloomFilter\Hash\Jenkins; class JenkinsTest extends \PHPUnit_Framework_TestCase { /** * @test */ public function hash() { $hash = new Jenkins(); $value = 'test value'; $expected = '4b9f03c9478b2ae8'; $this->assertEquals($expected, $hash->hash($value)); } }
{ "content_hash": "e55026e7cbab61d897a484bf3244c092", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 60, "avg_line_length": 18.9, "alnum_prop": 0.6031746031746031, "repo_name": "igoreus/bloomfilter", "id": "b4a0cf23bad85594a9913537841797477e87d781", "size": "378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Hash/JenkinsTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "26912" } ], "symlink_target": "" }
//• Write a program that reads a string, reverses it and prints the result at the console. using System; using System.Text; class ReverseStringProblem { static void Main() { Console.WriteLine("Please enter some text: "); string input = Console.ReadLine(); string reversed = ReverseString(input); Console.WriteLine(reversed); } static string ReverseString(string input) { StringBuilder sb = new StringBuilder(); for (int i = input.Length - 1; i >= 0; i--) { sb.Append(input[i]); } return sb.ToString(); } }
{ "content_hash": "336c36b3632596b4bf678d7a8af4d7b9", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 91, "avg_line_length": 23.807692307692307, "alnum_prop": 0.5977382875605816, "repo_name": "VanyaD/CSharp-Part2", "id": "1fb5e7b00c0ddbabe546db2a617efe89cddb5e41", "size": "623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "StringsAndTextProcessingHomework/02. Reverse string/02. Reverse string.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "254702" }, { "name": "Visual Basic", "bytes": "9415" } ], "symlink_target": "" }
#include <linux/kernel.h> #include <linux/types.h> #include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/dma-mapping.h> #include <asm/irq.h> #include <asm/io.h> #include <asm/dma.h> #include <asm/jazz.h> #include <asm/jazzdma.h> #include <scsi/scsi_host.h> #include "esp_scsi.h" #define DRV_MODULE_NAME "jazz_esp" #define PFX DRV_MODULE_NAME ": " #define DRV_VERSION "1.000" #define DRV_MODULE_RELDATE "May 19, 2007" static void jazz_esp_write8(struct esp *esp, u8 val, unsigned long reg) { *(volatile u8 *)(esp->regs + reg) = val; } static u8 jazz_esp_read8(struct esp *esp, unsigned long reg) { return *(volatile u8 *)(esp->regs + reg); } static dma_addr_t jazz_esp_map_single(struct esp *esp, void *buf, size_t sz, int dir) { return dma_map_single(esp->dev, buf, sz, dir); } static int jazz_esp_map_sg(struct esp *esp, struct scatterlist *sg, int num_sg, int dir) { return dma_map_sg(esp->dev, sg, num_sg, dir); } static void jazz_esp_unmap_single(struct esp *esp, dma_addr_t addr, size_t sz, int dir) { dma_unmap_single(esp->dev, addr, sz, dir); } static void jazz_esp_unmap_sg(struct esp *esp, struct scatterlist *sg, int num_sg, int dir) { dma_unmap_sg(esp->dev, sg, num_sg, dir); } static int jazz_esp_irq_pending(struct esp *esp) { if (jazz_esp_read8(esp, ESP_STATUS) & ESP_STAT_INTR) return 1; return 0; } static void jazz_esp_reset_dma(struct esp *esp) { vdma_disable ((int)esp->dma_regs); } static void jazz_esp_dma_drain(struct esp *esp) { /* nothing to do */ } static void jazz_esp_dma_invalidate(struct esp *esp) { vdma_disable ((int)esp->dma_regs); } static void jazz_esp_send_dma_cmd(struct esp *esp, u32 addr, u32 esp_count, u32 dma_count, int write, u8 cmd) { BUG_ON(!(cmd & ESP_CMD_DMA)); jazz_esp_write8(esp, (esp_count >> 0) & 0xff, ESP_TCLOW); jazz_esp_write8(esp, (esp_count >> 8) & 0xff, ESP_TCMED); vdma_disable ((int)esp->dma_regs); if (write) vdma_set_mode ((int)esp->dma_regs, DMA_MODE_READ); else vdma_set_mode ((int)esp->dma_regs, DMA_MODE_WRITE); vdma_set_addr ((int)esp->dma_regs, addr); vdma_set_count ((int)esp->dma_regs, dma_count); vdma_enable ((int)esp->dma_regs); scsi_esp_cmd(esp, cmd); } static int jazz_esp_dma_error(struct esp *esp) { u32 enable = vdma_get_enable((int)esp->dma_regs); if (enable & (R4030_MEM_INTR|R4030_ADDR_INTR)) return 1; return 0; } static const struct esp_driver_ops jazz_esp_ops = { .esp_write8 = jazz_esp_write8, .esp_read8 = jazz_esp_read8, .map_single = jazz_esp_map_single, .map_sg = jazz_esp_map_sg, .unmap_single = jazz_esp_unmap_single, .unmap_sg = jazz_esp_unmap_sg, .irq_pending = jazz_esp_irq_pending, .reset_dma = jazz_esp_reset_dma, .dma_drain = jazz_esp_dma_drain, .dma_invalidate = jazz_esp_dma_invalidate, .send_dma_cmd = jazz_esp_send_dma_cmd, .dma_error = jazz_esp_dma_error, }; static int __devinit esp_jazz_probe(struct platform_device *dev) { struct scsi_host_template *tpnt = &scsi_esp_template; struct Scsi_Host *host; struct esp *esp; struct resource *res; int err; host = scsi_host_alloc(tpnt, sizeof(struct esp)); err = -ENOMEM; if (!host) goto fail; host->max_id = 8; esp = shost_priv(host); esp->host = host; esp->dev = dev; esp->ops = &jazz_esp_ops; res = platform_get_resource(dev, IORESOURCE_MEM, 0); if (!res) goto fail_unlink; esp->regs = (void __iomem *)res->start; if (!esp->regs) goto fail_unlink; res = platform_get_resource(dev, IORESOURCE_MEM, 1); if (!res) goto fail_unlink; esp->dma_regs = (void __iomem *)res->start; esp->command_block = dma_alloc_coherent(esp->dev, 16, &esp->command_block_dma, GFP_KERNEL); if (!esp->command_block) goto fail_unmap_regs; host->irq = platform_get_irq(dev, 0); err = request_irq(host->irq, scsi_esp_intr, IRQF_SHARED, "ESP", esp); if (err < 0) goto fail_unmap_command_block; esp->scsi_id = 7; esp->host->this_id = esp->scsi_id; esp->scsi_id_mask = (1 << esp->scsi_id); esp->cfreq = 40000000; dev_set_drvdata(&dev->dev, esp); err = scsi_esp_register(esp, &dev->dev); if (err) goto fail_free_irq; return 0; fail_free_irq: free_irq(host->irq, esp); fail_unmap_command_block: dma_free_coherent(esp->dev, 16, esp->command_block, esp->command_block_dma); fail_unmap_regs: fail_unlink: scsi_host_put(host); fail: return err; } static int __devexit esp_jazz_remove(struct platform_device *dev) { struct esp *esp = dev_get_drvdata(&dev->dev); unsigned int irq = esp->host->irq; scsi_esp_unregister(esp); free_irq(irq, esp); dma_free_coherent(esp->dev, 16, esp->command_block, esp->command_block_dma); scsi_host_put(esp->host); return 0; } /* work with hotplug and coldplug */ MODULE_ALIAS("platform:jazz_esp"); static struct platform_driver esp_jazz_driver = { .probe = esp_jazz_probe, .remove = __devexit_p(esp_jazz_remove), .driver = { .name = "jazz_esp", .owner = THIS_MODULE, }, }; static int __init jazz_esp_init(void) { return platform_driver_register(&esp_jazz_driver); } static void __exit jazz_esp_exit(void) { platform_driver_unregister(&esp_jazz_driver); } MODULE_DESCRIPTION("JAZZ ESP SCSI driver"); MODULE_AUTHOR("Thomas Bogendoerfer (tsbogend@alpha.franken.de)"); MODULE_LICENSE("GPL"); MODULE_VERSION(DRV_VERSION); module_init(jazz_esp_init); module_exit(jazz_esp_exit);
{ "content_hash": "7cc33086c3f2653427025d8daa5b75b5", "timestamp": "", "source": "github", "line_count": 245, "max_line_length": 75, "avg_line_length": 22.163265306122447, "alnum_prop": 0.6674033149171271, "repo_name": "lunaczp/learning", "id": "b2d481dd37505f43f25d9c0cc79659e900bb25ca", "size": "5556", "binary": false, "copies": "801", "ref": "refs/heads/master", "path": "category/os/linux/linux-2.6.32/linux/drivers/scsi/jazz_esp.c", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "4526" }, { "name": "Assembly", "bytes": "14500403" }, { "name": "Awk", "bytes": "21252" }, { "name": "Batchfile", "bytes": "2526" }, { "name": "C", "bytes": "381839655" }, { "name": "C++", "bytes": "10162228" }, { "name": "CMake", "bytes": "68196" }, { "name": "CSS", "bytes": "3943" }, { "name": "D", "bytes": "1022" }, { "name": "DTrace", "bytes": "4528" }, { "name": "Fortran", "bytes": "1834" }, { "name": "GAP", "bytes": "4344" }, { "name": "GDB", "bytes": "31864" }, { "name": "Gnuplot", "bytes": "148" }, { "name": "Go", "bytes": "732" }, { "name": "HTML", "bytes": "86756" }, { "name": "Java", "bytes": "8286" }, { "name": "JavaScript", "bytes": "238365" }, { "name": "Lex", "bytes": "121233" }, { "name": "Limbo", "bytes": "1609" }, { "name": "Lua", "bytes": "96" }, { "name": "M4", "bytes": "483288" }, { "name": "Makefile", "bytes": "1915601" }, { "name": "Nix", "bytes": "180099" }, { "name": "Objective-C", "bytes": "1742504" }, { "name": "OpenEdge ABL", "bytes": "4238" }, { "name": "PHP", "bytes": "27984629" }, { "name": "Pascal", "bytes": "74868" }, { "name": "Perl", "bytes": "317465" }, { "name": "Perl 6", "bytes": "6916" }, { "name": "Python", "bytes": "21547" }, { "name": "R", "bytes": "1112" }, { "name": "Roff", "bytes": "435717" }, { "name": "Scilab", "bytes": "22980" }, { "name": "Shell", "bytes": "468206" }, { "name": "UnrealScript", "bytes": "20840" }, { "name": "Vue", "bytes": "563" }, { "name": "XSLT", "bytes": "7946" }, { "name": "Yacc", "bytes": "172805" }, { "name": "sed", "bytes": "2073" } ], "symlink_target": "" }
/* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f4xx_it.h" /** @addtogroup STM32F4xx_HAL_Examples * @{ */ /** @addtogroup FLASH_Program * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M4 Processor Exceptions Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /** * @brief This function handles Memory Manage exception. * @param None * @retval None */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * @param None * @retval None */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * @param None * @retval None */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles Debug Monitor exception. * @param None * @retval None */ void DebugMon_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { } /** * @brief This function handles SysTick Handler. * @param None * @retval None */ void SysTick_Handler(void) { HAL_IncTick(); } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f4xx.s). */ /******************************************************************************/ /** * @brief This function handles PPP interrupt request. * @param None * @retval None */ /*void PPP_IRQHandler(void) { }*/ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "content_hash": "1096c7267e6d5a279386d1ed70fbcb2b", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 80, "avg_line_length": 22.635135135135137, "alnum_prop": 0.4388059701492537, "repo_name": "matianfu/stm32f4cube", "id": "f947cf8020f95e107652e18faacf32325eec8b50", "size": "5586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Projects/STM32F401-Discovery/Examples/FLASH/FLASH_EraseProgram/Src/stm32f4xx_it.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "6084165" }, { "name": "C", "bytes": "39072064" }, { "name": "C++", "bytes": "863728" }, { "name": "CMake", "bytes": "10718" }, { "name": "CSS", "bytes": "7146" }, { "name": "HTML", "bytes": "2039955" }, { "name": "Makefile", "bytes": "22025" }, { "name": "Objective-C", "bytes": "1848" }, { "name": "Perl", "bytes": "17688" }, { "name": "Shell", "bytes": "23874" }, { "name": "Tcl", "bytes": "72" } ], "symlink_target": "" }
// Header file for Ulno_Buttons // // author: ulno // created: 2016-03-01 #ifndef _Ulno_BUTTONS_H #define _Ulno_BUTTONS_H #define MAX_BUTTONS 32 /** * helper class for ulno_Buttons (representing one instance of a button) */ class Ulno_Button { public: static const int GENERIC = 0; static const int TOUCH = 1; static const int PUSH = 2; protected: int type; int id; int gpio; // related main gpio pin bool state; int debounce_max; int debouncer; bool use_pullup; inline bool update_state() { if(debouncer>=debounce_max/2) { state = true; } else { state = false; } return state; } inline void increase_debouncer() { if(debouncer < debounce_max) debouncer ++; } inline void decrease_debouncer() { if(debouncer > 0) debouncer --; } void debug_base(int debug_level); public: Ulno_Button(int id, int gpio, int debounce, bool pullup); inline int get_id() {return id;} inline bool get_state() {return state;} inline int get_type() {return type;} virtual bool check(); virtual void debug(int debug_level); }; /** * This class handles several touch or push buttons */ class Ulno_Buttons { public: static const int FIRE=' '; static const int DOWN=14; static const int LEFT=2; static const int RIGHT=6; static const int UP=16; static const int ESCAPE=27; private: Ulno_Button * button_array[MAX_BUTTONS]; int default_threshold; int default_debounce_max; int default_discharge_delay_ms; // wait after pulling down before measuring in ms bool default_use_internal_pullup; bool default_measure_direction_ischarge; // when true, a touch is measured when charge did NOT happen in threshold time. When false, measure if charge was succesfull in the time. int _size; // number of buttons defined /*void pull_down_all(); void set_input_all();*/ void init( int debounce, int threshold, int discharge_delay_ms, bool internal_pullup, bool chargedelay ); int debug_count; int debug_level; int debug_frame; public: // add info for touchbuttons Ulno_Buttons( int debounce, int threshold, int discharge_delay_ms, bool internal_pullup, bool chargedelay); Ulno_Buttons(); // default init for internal pullups and metal touch sensors void debug( int level, int count ); // debug level: 0=off, 1=info, 2=all; count: <0: never, n: every n calls void add_push_button(int id, int gpio_pin); // add a push button for a given gpio_pin and assign id void add_push_button(int id, int gpio_pin, bool internal_pullup); // add a push button for a given gpio_pin and assign id void add_touch_button(int id, int gpio_pin); // add a button for a given gpio_pin and assign id void add_touch_button(int id, int gpio_pin, int threshold); // also specify button-specific threshold void add_touch_button(int id, int gpio_pin, bool internal_pullup, int threshold); // also specify pull-up-use bool check(); // check and update state of all buttons, if one pressed return true, else false int get_button(int id); // get state of button with specific id inline int size() { return _size; }; // number of buttons managed inline int get_button_id(int nr) { return button_array[nr]->get_id(); } inline int get_button_state(int nr) { // state return button_array[nr]->get_state(); } // TODO: add calibration settings }; #endif // _Ulno_BUTTONS_H
{ "content_hash": "d81bfa330a9e38956c2bc8b7b88199cb", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 180, "avg_line_length": 30.43243243243243, "alnum_prop": 0.6947898164594435, "repo_name": "ulno/libni", "id": "e90a347475a3e2d0f245c711b4da2f4ffd4b7699", "size": "3378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "controller/esp8266/libraries/lib/ulno_buttons/ulno_buttons.h", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "6437" }, { "name": "C", "bytes": "278" }, { "name": "C++", "bytes": "23892" }, { "name": "CSS", "bytes": "1069" }, { "name": "HTML", "bytes": "1536" }, { "name": "Java", "bytes": "68841" }, { "name": "JavaScript", "bytes": "24" }, { "name": "Python", "bytes": "10247" }, { "name": "Shell", "bytes": "82" } ], "symlink_target": "" }
$LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'holdem' require 'spec' require 'spec/autorun' Spec::Runner.configure do |config| end
{ "content_hash": "0db2856eed902977c2f50768406bd2dd", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 66, "avg_line_length": 23.11111111111111, "alnum_prop": 0.6875, "repo_name": "denis/holdem", "id": "dfe980be8b3e65d7e21c8529b591b42ff28caa9d", "size": "208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "2316" } ], "symlink_target": "" }
package csci567.loginactivity; /** * Created by bryandixon on 4/10/16. */ public class FirebaseItem { private String message; //private String uid; public FirebaseItem() { // empty default constructor, necessary for Firebase to be able to deserialize blog posts } public FirebaseItem(String message){ this.message=message; //this.uid = uid; } public String getMessage(){ return message; } public void setMessage(String message){ this.message=message; } /* public String getUid(){ return uid; } public void setUid(String uid){ this.uid=uid; }*/ }
{ "content_hash": "e564651db6d5c988f1331ad4ed761718", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 97, "avg_line_length": 18.135135135135137, "alnum_prop": 0.6110283159463488, "repo_name": "CSUChico-CSCI567/CSCI567-Workspace-Spring-2016", "id": "d47c8d02225a59fc67c62deb585879bfcd3cb9fb", "size": "671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LoginActivity_Lecture16/app/src/main/java/csci567/loginactivity/FirebaseItem.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "67306" } ], "symlink_target": "" }
export { default } from './AnimationController';
{ "content_hash": "af08c92f2baa0af0e2508d0a138d5b74", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 48, "avg_line_length": 49, "alnum_prop": 0.7346938775510204, "repo_name": "kradio3/react-mdc-web", "id": "29e802bd4dcd7afea65a6cc9008b7181892983b4", "size": "49", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Animation/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "93469" } ], "symlink_target": "" }
echo Parallel execution: concurrency 6 x 1mln node tests/load/parallel.promise.js node tests/load/parallel.compose.js node tests/load/parallel.collect.js echo echo Sequential execution: concurrency 6 x 100k node tests/load/sequential.promise.js node tests/load/sequential.compose.js echo echo Poolify: array vs symbol 300 times node tests/load/poolify.array.js node tests/load/poolify.symbol.js node tests/load/poolify.opt.js echo echo Collector: 1mnl node tests/load/collect.js node tests/load/collect.class.js node tests/load/collect.prototype.js node tests/load/collect.functor.js
{ "content_hash": "3523a603e01d694d5b7c72d91282c46d", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 47, "avg_line_length": 30.736842105263158, "alnum_prop": 0.8253424657534246, "repo_name": "metarhia/MetaSync", "id": "5099a681f9e72e86a92f8711da965af62684fd06", "size": "584", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/load/run.sh", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "55691" } ], "symlink_target": "" }
package legit import ( "errors" "testing" "github.com/stretchr/testify/assert" ) func TestErrors_Error(t *testing.T) { assert.Equal(t, "foo", Errors{errors.New("foo"), errors.New("bar")}.Error()) assert.Equal(t, "", Errors{}.Error()) } func TestStructError_Error(t *testing.T) { assert.Equal(t, "foo: bar", StructError{Field: "foo", Message: errors.New("bar")}.Error()) } func TestSliceError_Error(t *testing.T) { assert.Equal(t, "1: bar", SliceError{Index: 1, Message: errors.New("bar")}.Error()) }
{ "content_hash": "6ab3b94857211b329d5ed0726bddd9c0", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 91, "avg_line_length": 24.38095238095238, "alnum_prop": 0.671875, "repo_name": "jamescun/legit", "id": "91014d94d4988f9c46aa46dc75fc48568736dd1c", "size": "512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "error_test.go", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Go", "bytes": "29212" } ], "symlink_target": "" }
"""This module corresponds to functionality documented at https://blockchain.info/api/api_receive """ from .. import util import json class ReceiveResponse: def __init__(self, address, index, callback): self.address = address self.index = index self.callback_url = callback class LogEntry: def __init__(self, callback_url, called_at, raw_response, response_code): self.callback_url = callback_url self.called_at = called_at self.raw_response = raw_response self.response_code = response_code def receive(xpub, callback, api_key): """Call the '/v2/receive' endpoint and create a forwarding address. :param str xpub: extended public key to generate payment address :param str callback: callback URI that will be called upon payment :param str api_key: Blockchain.info API V2 key :return: an instance of :class:`ReceiveResponse` class """ params = {'xpub': xpub, 'key': api_key, 'callback': callback} resource = 'v2/receive?' + util.urlencode(params) resp = util.call_api(resource, base_url='https://api.blockchain.info/') json_resp = json.loads(resp) payment_response = ReceiveResponse(json_resp['address'], json_resp['index'], json_resp['callback']) return payment_response def callback_log(callback, api_key): """Call the 'v2/receive/callback_log' endpoint and returns the callback log for a given callback URI with parameters. :param callback: callback URI :param api_key: Blockchain.info API V2 key :return: a list of :class:`LogEntry` objects """ params = {'key': api_key, 'callback': callback} resource = 'v2/receive/callback_log?' + util.urlencode(params) resp = util.call_api(resource, base_url='https://api.blockchain.info/') json_resp = json.loads(resp) return [LogEntry(e['callback'], e['called_at'], e['raw_response'], e['response_code']) for e in json_resp] def check_gap(xpub, api_key): """Call the 'v2/receive/checkgap' endpoint and returns the callback log for a given callback URI with parameters. :param str xpub: extended public key :param str api_key: Blockchain.info API V2 key :return: an int """ params = {'key': api_key, 'xpub': xpub} resource = 'v2/receive/checkgap?' + util.urlencode(params) resp = util.call_api(resource, base_url='https://api.blockchain.info/') json_resp = json.loads(resp) return json_resp['gap']
{ "content_hash": "4824c696fb877990eb507250192c6222", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 110, "avg_line_length": 35.27777777777778, "alnum_prop": 0.6539370078740158, "repo_name": "blockchain/api-v1-client-python", "id": "fe3bd710adc9081e96d1788aa0b28450d6ca657c", "size": "2540", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blockchain/v2/receive.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "42629" } ], "symlink_target": "" }
using SF.Sys; using SF.Sys.Clients; using SF.Sys.Collections.Generic; using SF.Sys.NetworkService; using SF.Sys.Services; using SF.Sys.TimeServices; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace SF.Biz.Payments.Platforms.Tests { /// <summary> /// 测试收款提供者 /// </summary> [SupportedDeviceTypes(new[] { ClientDeviceType.WAP, ClientDeviceType.PCBrowser, ClientDeviceType.WinXin})] public class TestCollectProvider : ICollectProvider,ICollectQrCodeResolver,IRefundProvider { public ITimeService TimeService { get; } public IInvokeContext InvokeContext { get; } public TimeSpan? CollectRequestTimeout => null;// TimeSpan.FromMinutes(1); public IServiceInstanceDescriptor ServiceInstanceDescriptor { get; } public TestCollectProvider(ITimeService TimeService, IInvokeContext InvokeContext, IServiceInstanceDescriptor ServiceInstanceDescriptor) { this.TimeService = TimeService; this.InvokeContext = InvokeContext; this.ServiceInstanceDescriptor = ServiceInstanceDescriptor; } public string Title { get { return ServiceInstanceDescriptor.Meta.Title; } } public Task<CollectResponse> GetResultByQuery(CollectStartArgument StartArgument) { var r = new CollectResponse(); return Task.FromResult(r); } public Task<CollectStartStatus> Start(long Ident, CollectStartArgument StartArgument,ClientInfo request, string callbackUrl, string notifyUrl) { var re = new Dictionary<string, string>(); re["redirect"] = $"/Test/TestCollectPayment/{Ident}?amount={StartArgument.Amount}&callback={Uri.EscapeDataString(callbackUrl)}"; re["id"] = Ident.ToString(); re["unittest-notify"] = $"http://localhost/api/collectcallback/{StartArgument.PaymentPlatformId}?id={Ident}&amount={StartArgument.Amount}&user-id={StartArgument.ClientInfo.OperatorId}&user-name=name-{StartArgument.ClientInfo.OperatorId}&user-account=account-{StartArgument.ClientInfo.OperatorId}"; return Task.FromResult( new CollectStartStatus { Expires=TimeService.Now.AddDays(1), Result = re, ExtraData = Json.Stringify( new ExtraData { qr = "http://"+Ident } ) } ); } public async Task<CollectResult> GetResultByNotify(ICollectStartArgumentLoader StartArgumentLoader) { var r = new CollectResponse(); var args = InvokeContext.Request.GetQueryAsDictionary(); r.CompletedTime = TimeService.Now; r.Ident = args.Get("id").ToInt64(); r.AmountCollected = args.Get("amount").ToDecimal(); r.ExtIdent = "EXT-" + r.Ident; r.ExtUserId = args.Get("user-id"); r.ExtUserName = args.Get("user-name"); r.ExtUserAccount = args.Get("user-account"); var req = await StartArgumentLoader.GetRequest(r.Ident); var httpresponse = HttpResponse.Text("OK"); return new CollectResult { Session = new CollectSession { Request = req, Response = r }, HttpResponse = httpresponse }; } public async Task<CollectResult> GetResultByCallback( ICollectStartArgumentLoader StartArgumentLoader) { var r = new CollectResponse(); var args = InvokeContext.Request.GetQueryAsDictionary(); r.CompletedTime = TimeService.Now; r.Ident = args.Get("pid").ToInt64(); r.AmountCollected = args.Get("amount").ToDecimal(); r.ExtIdent = "EXT-" + r.Ident; r.ExtUserId = args.Get("user-id"); r.ExtUserName = args.Get("user-name"); r.ExtUserAccount = args.Get("user-account"); var req = await StartArgumentLoader.GetRequest(r.Ident); //var httpresponse = Request.CreateResponse(System.Net.HttpStatusCode.Redirect); //httpresponse.Headers.Location = new Uri(Request.RequestUri, req.HttpRedirect); return new CollectResult { Session = new CollectSession { Request = req, Response = r }, HttpResponse = HttpResponse.JSRedirectWithoutHistory( new Uri(InvokeContext.Request.GetUri(), req.HttpRedirect) ) }; } class ExtraData { public string qr { get; set; } } public string GetQrCode(string ExtraData) { if (string.IsNullOrWhiteSpace(ExtraData)) return null; var ed = Json.Parse<ExtraData>(ExtraData); return ed.qr; } Task<RefundResponse> IRefundProvider.TryRefund(long Ident,RefundStartArgument StartArgument) { var time = TimeService.Now; var past = time.Subtract(StartArgument.SubmitTime).TotalSeconds / 60; var state = past > 3 ? RefundState.Success : RefundState.Processing; return Task.FromResult(new RefundResponse { Ident=Ident, RefundAmount=StartArgument.Amount, State=state, UpdatedTime=time, Expires= time.AddMinutes(3) }); } } }
{ "content_hash": "2e8ef4e9e9105abd6bc1848bd2732983", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 309, "avg_line_length": 33.46, "alnum_prop": 0.6774257820282925, "repo_name": "etechi/ServiceFramework", "id": "f1bc36ded371868ae973148f149cced498005527", "size": "5035", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Projects/Server/Biz/SF.Biz.Payments.Providers/Test/TestCollectProvider.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "870" }, { "name": "C#", "bytes": "6242754" }, { "name": "CSS", "bytes": "1068392" }, { "name": "HTML", "bytes": "824288" }, { "name": "JavaScript", "bytes": "14132559" }, { "name": "Smalltalk", "bytes": "1054" }, { "name": "TypeScript", "bytes": "4727" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; using DotNetNuke.Framework; using DotNetNuke.Instrumentation; using DotNetNuke.Security.Permissions; using DotNetNuke.Services.Localization; using Dnn.PersonaBar.Library.Helper; namespace Dnn.PersonaBar.Library.Controllers { public class ModulesController : ServiceLocator<IModulesController, ModulesController>, IModulesController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulesController)); private IContentVerifier _contentVerifier; public ModulesController() : this(new ContentVerifier()) { } public ModulesController(IContentVerifier contentVerifier) { this._contentVerifier = contentVerifier; } protected override Func<IModulesController> GetFactory() { return () => new ModulesController(); } public List<ModuleInfo> AddNewModule(PortalSettings portalSettings, string title, int desktopModuleId, int tabId, string paneName, int position, int permissionType, string align, out KeyValuePair<HttpStatusCode, string> message) { message = new KeyValuePair<HttpStatusCode, string>(); var page = TabController.Instance.GetTab(tabId, portalSettings.PortalId); if (page == null) { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.NotFound, string.Format(Localization.GetString("Prompt_PageNotFound", Constants.LocalResourcesFile), tabId)); return null; } if (!TabPermissionController.CanManagePage(page)) { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.NotFound, Localization.GetString("Prompt_InsufficientPermissions", Constants.LocalResourcesFile)); return null; } var moduleList = new List<ModuleInfo>(); foreach (var objModuleDefinition in ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId).Values) { var objModule = new ModuleInfo(); objModule.Initialize(portalSettings.PortalId); objModule.PortalID = portalSettings.PortalId; objModule.TabID = tabId; objModule.ModuleOrder = position; objModule.ModuleTitle = string.IsNullOrEmpty(title) ? objModuleDefinition.FriendlyName : title; objModule.PaneName = paneName; objModule.ModuleDefID = objModuleDefinition.ModuleDefID; if (objModuleDefinition.DefaultCacheTime > 0) { objModule.CacheTime = objModuleDefinition.DefaultCacheTime; if (portalSettings.DefaultModuleId > Null.NullInteger && portalSettings.DefaultTabId > Null.NullInteger) { var defaultModule = ModuleController.Instance.GetModule(portalSettings.DefaultModuleId, portalSettings.DefaultTabId, true); if (defaultModule != null) { objModule.CacheTime = defaultModule.CacheTime; } } } ModuleController.Instance.InitialModulePermission(objModule, objModule.TabID, permissionType); if (portalSettings.ContentLocalizationEnabled) { var defaultLocale = LocaleController.Instance.GetDefaultLocale(portalSettings.PortalId); //check whether original tab is exists, if true then set culture code to default language, //otherwise set culture code to current. objModule.CultureCode = TabController.Instance.GetTabByCulture(objModule.TabID, portalSettings.PortalId, defaultLocale) != null ? defaultLocale.Code : portalSettings.CultureCode; } else { objModule.CultureCode = Null.NullString; } objModule.AllTabs = false; objModule.Alignment = align; ModuleController.Instance.AddModule(objModule); moduleList.Add(objModule); // Set position so future additions to page can operate correctly position = ModuleController.Instance.GetTabModule(objModule.TabModuleID).ModuleOrder + 1; } return moduleList; } public ModuleInfo CopyModule(PortalSettings portalSettings, int moduleId, int sourcePageId, int targetPageId, string pane, bool includeSettings, out KeyValuePair<HttpStatusCode, string> message, bool moveBahaviour = false) { var sourceModule = GetModule(portalSettings, moduleId, sourcePageId, out message); if (sourceModule == null) { return null; } var targetPage = TabController.Instance.GetTab(targetPageId, portalSettings.PortalId); message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.NotFound, string.Format(Localization.GetString("Prompt_PageNotFound", Constants.LocalResourcesFile), targetPageId)); if (targetPage == null) { return null; } var currentPortalSetting = PortalController.Instance.GetCurrentPortalSettings(); if (_contentVerifier.IsContentExistsForRequestedPortal(targetPage.PortalID, portalSettings)) { try { if (moveBahaviour) ModuleController.Instance.MoveModule(sourceModule.ModuleID, sourceModule.TabID, targetPage.TabID, pane); else ModuleController.Instance.CopyModule(sourceModule, targetPage, pane, includeSettings); ModuleController.Instance.ClearCache(targetPageId); } catch (Exception ex) { Logger.Error(ex); message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.InternalServerError, Localization.GetString(moveBahaviour ? "Prompt_ErrorWhileMoving" : "Prompt_ErrorWhileCopying")); } // get the new module return ModuleController.Instance.GetModule(sourceModule.ModuleID, targetPageId, true); } else { return null; } } public void DeleteModule(PortalSettings portalSettings, int moduleId, int pageId, out KeyValuePair<HttpStatusCode, string> message) { var module = GetModule(portalSettings,moduleId,pageId,out message); if (module != null) { try { ModuleController.Instance.DeleteTabModule(pageId, moduleId, true); ModuleController.Instance.ClearCache(pageId); } catch (Exception ex) { Logger.Error(ex); message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.InternalServerError, string.Format(Localization.GetString("Prompt_FailedtoDeleteModule", Constants.LocalResourcesFile), moduleId)); } } } public ModuleInfo GetModule(PortalSettings portalSettings, int moduleId, int? pageId, out KeyValuePair<HttpStatusCode, string> message) { message = new KeyValuePair<HttpStatusCode, string>(); if (pageId.HasValue) { var module = ModuleController.Instance.GetModule(moduleId, pageId.Value, true); if (module != null) { var currentPortal = PortalController.Instance.GetCurrentPortalSettings(); if (_contentVerifier.IsContentExistsForRequestedPortal(module.PortalID, portalSettings, true)) { return module; } } else { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.NotFound, string.Format(Localization.GetString("Prompt_ModuleNotFound", Constants.LocalResourcesFile), moduleId, pageId)); return null; } } else { var modules = ModuleController.Instance.GetAllTabsModulesByModuleID(moduleId); if (modules != null && modules.Count != 0) { return modules[0] as ModuleInfo; } } message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.NotFound, string.Format(Localization.GetString("Prompt_NoModule", Constants.LocalResourcesFile), moduleId)); return null; } public IEnumerable<ModuleInfo> GetModules(PortalSettings portalSettings, bool? deleted, out int total, string moduleName = null, string moduleTitle = null, int? pageId = null, int pageIndex = 0, int pageSize = 10) { pageIndex = pageIndex < 0 ? 0 : pageIndex; pageSize = pageSize > 0 && pageSize <= 100 ? pageSize : 10; moduleName = moduleName?.Replace("*", ""); moduleTitle = moduleTitle?.Replace("*", ""); var modules = ModuleController.Instance.GetModules(portalSettings.PortalId) .Cast<ModuleInfo>().Where(ModulePermissionController.CanViewModule); if (!string.IsNullOrEmpty(moduleName)) modules = modules.Where(module => module.DesktopModule.ModuleName.IndexOf(moduleName, StringComparison.OrdinalIgnoreCase) >= 0); if (!string.IsNullOrEmpty(moduleTitle)) modules = modules.Where(module => module.ModuleTitle.IndexOf(moduleTitle, StringComparison.OrdinalIgnoreCase) >= 0); //Return only deleted modules with matching criteria. if (pageId.HasValue && pageId.Value > 0) { modules = modules.Where(x => x.TabID == pageId.Value); } if (deleted.HasValue) { modules = modules.Where(module => module.IsDeleted == deleted); } //Get distincts. modules = modules.GroupBy(x => x.ModuleID).Select(group => group.First()).OrderBy(x => x.ModuleID); var moduleInfos = modules as IList<ModuleInfo> ?? modules.ToList(); total = moduleInfos.Count; return moduleInfos.Skip(pageIndex * pageSize).Take(pageSize); } } }
{ "content_hash": "a90cd7e0ec1683926108fc10676a17a0", "timestamp": "", "source": "github", "line_count": 238, "max_line_length": 236, "avg_line_length": 47.05042016806723, "alnum_prop": 0.5937667440614396, "repo_name": "robsiera/Dnn.Platform", "id": "b0b3b430be02dcb285100f4df6224e2b43951d6a", "size": "11200", "binary": false, "copies": "3", "ref": "refs/heads/development", "path": "Dnn.AdminExperience/Library/Dnn.PersonaBar.Library/Controllers/ModulesController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "572469" }, { "name": "Batchfile", "bytes": "405" }, { "name": "C#", "bytes": "21903627" }, { "name": "CSS", "bytes": "1653926" }, { "name": "HTML", "bytes": "528314" }, { "name": "JavaScript", "bytes": "8361433" }, { "name": "PLpgSQL", "bytes": "53478" }, { "name": "PowerShell", "bytes": "10762" }, { "name": "Smalltalk", "bytes": "2410" }, { "name": "TSQL", "bytes": "56906" }, { "name": "Visual Basic", "bytes": "139195" }, { "name": "XSLT", "bytes": "11388" } ], "symlink_target": "" }