code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
# frozen_string_literal: true
begin
require 'ripper'
require 'test/unit'
ripper_test = true
module TestRipper; end
rescue LoadError
end
class TestRipper::Filter < Test::Unit::TestCase
class Filter < Ripper::Filter
def on_default(event, token, data)
if data.empty?
data[:filename] = filename rescue nil
data[:lineno] = lineno
data[:column] = column
data[:state] = state
data[:token] = token
end
data
end
end
def filename
File.expand_path(__FILE__)
end
def test_filter_filename_unset
data = {}
filter = Filter.new(File.read(filename))
filter.parse(data)
assert_equal('-', data[:filename], "[ruby-dev:37856]")
assert_equal('-', filter.filename)
end
def test_filter_filename
data = {}
filter = Filter.new(File.read(filename), filename)
assert_equal(filename, filter.filename)
filter.parse(data)
assert_equal(filename, data[:filename])
assert_equal(filename, filter.filename)
end
def test_filter_lineno
data = {}
src = File.read(filename)
src_lines = src.count("\n")
filter = Filter.new(src)
assert_equal(nil, filter.lineno)
filter.parse(data)
assert_equal(1, data[:lineno])
assert_equal(src_lines, filter.lineno)
end
def test_filter_lineno_set
data = {}
src = File.read(filename)
src_lines = src.count("\n")
filter = Filter.new(src, '-', 100)
assert_equal(nil, filter.lineno)
filter.parse(data)
assert_equal(100, data[:lineno])
assert_equal(src_lines+100-1, filter.lineno)
end
def test_filter_column
data = {}
src = File.read(filename)
last_columns = src[/(.*)\Z/].size
filter = Filter.new(src)
assert_equal(nil, filter.column)
filter.parse(data)
assert_equal(0, data[:column])
assert_equal(last_columns, filter.column)
end
def test_filter_state
data = {}
src = File.read(filename)
filter = Filter.new(src)
assert_equal(nil, filter.state)
filter.parse(data)
assert_not_nil(data[:state])
assert_not_nil(filter.state)
end
def test_filter_token
data = {}
filter = Filter.new("begin; puts 1; end")
filter.parse(data)
assert_equal("begin", data[:token])
end
end if ripper_test
| pmq20/ruby-compiler | ruby/test/ripper/test_filter.rb | Ruby | mit | 2,276 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>Uses of Class org.apache.poi.ss.formula.ptg.DeletedArea3DPtg (POI API Documentation)</title>
<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.poi.ss.formula.ptg.DeletedArea3DPtg (POI API Documentation)";
}
//-->
</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/poi/ss/formula/ptg/DeletedArea3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">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/poi/ss/formula/ptg/class-use/DeletedArea3DPtg.html" target="_top">Frames</a></li>
<li><a href="DeletedArea3DPtg.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.poi.ss.formula.ptg.DeletedArea3DPtg" class="title">Uses of Class<br>org.apache.poi.ss.formula.ptg.DeletedArea3DPtg</h2>
</div>
<div class="classUseContainer">No usage of org.apache.poi.ss.formula.ptg.DeletedArea3DPtg</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/poi/ss/formula/ptg/DeletedArea3DPtg.html" title="class in org.apache.poi.ss.formula.ptg">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/poi/ss/formula/ptg/class-use/DeletedArea3DPtg.html" target="_top">Frames</a></li>
<li><a href="DeletedArea3DPtg.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>
<i>Copyright 2015 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html>
| misuqian/ExcelTool | eclipse/poi-3.12/docs/apidocs/org/apache/poi/ss/formula/ptg/class-use/DeletedArea3DPtg.html | HTML | mit | 4,526 |
package de.tuberlin.dima.ti.analysis;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple7;
import org.apache.flink.api.java.tuple.Tuple8;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.util.Collector;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
public class MIDTCapacityEmitter extends RichFlatMapFunction<String, Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> {
private HashMap<String, String> APToRegion;
private HashMap<String, String> APToCountry;
private HashMap<String, String> APToState;
private boolean noPartition;
private boolean DIPartition;
private boolean fullPartition;
public MIDTCapacityEmitter(boolean noPartition, boolean DIPartition, boolean fullPartition) {
this.noPartition = noPartition;
this.DIPartition = DIPartition;
this.fullPartition = fullPartition;
}
@Override
public void open(Configuration parameters) {
Collection<Tuple8<String, String, String, String, String, Double, Double, String>> broadcastSet =
this.getRuntimeContext().getBroadcastVariable(TrafficAnalysis.AP_GEO_DATA);
this.APToRegion = new HashMap<String, String>(broadcastSet.size());
this.APToCountry = new HashMap<String, String>(broadcastSet.size());
this.APToState = new HashMap<String, String>(200);
for(Tuple8<String, String, String, String, String, Double, Double, String> t : broadcastSet) {
this.APToRegion.put(t.f0, t.f4);
this.APToCountry.put(t.f0, t.f3);
if(TrafficAnalysis.countriesWithStates.contains(t.f3)) {
this.APToState.put(t.f0, t.f2);
}
}
}
@Override
public void flatMap(String s, Collector<Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>> out) throws Exception {
if(s.startsWith("$")) {
return;
}
String[] tmp = s.split(";");
if(tmp.length < 15) {
return;
}
int pax = Integer.parseInt(tmp[2].trim());
int segmentCount = Integer.parseInt(tmp[3].trim());
long departureDay = Long.parseLong(tmp[11].trim())-1;
long departureTimestamp = TrafficAnalysis.firstPossibleTimestamp + (departureDay*24L*60L*60L*1000L);
Date date = new Date(departureTimestamp);
String dayString = TrafficAnalysis.dayFormat.format(date);
if(departureDay > 6) {
throw new Exception("Value error: " + s);
}
boolean isIntercontinental = false;
boolean isInternational = false;
boolean isInterstate = true;
int offset = 9;
int counter = 0;
int index = 6;
while(counter < segmentCount) {
String apOut = tmp[index].trim();
String apIn = tmp[index+1].trim();
index += offset;
counter++;
String outRegion = APToRegion.get(apOut);
String inRegion = APToRegion.get(apIn);
String outCountry = APToCountry.get(apOut);
String inCountry = APToCountry.get(apIn);
if(outCountry != null && inCountry != null) {
isIntercontinental = !outRegion.equals(inRegion);
isInternational = !outCountry.equals(inCountry);
isInterstate = true;
if(!isInternational && TrafficAnalysis.countriesWithStates.contains(outCountry)) {
String outState = APToState.get(apOut);
String inState = APToState.get(apIn);
isInterstate = !outState.equals(inState);
}
} else {
continue;
}
if(noPartition) {
isIntercontinental = false;
isInternational = false;
isInterstate = false;
}
if(DIPartition) {
isIntercontinental = false;
isInternational = isInternational;
isInterstate = false;
}
Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> tOut =
new Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>(apOut, dayString, isIntercontinental, isInternational, isInterstate, pax, 0);
Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer> tIn =
new Tuple7<String, String, Boolean, Boolean, Boolean, Integer, Integer>(apIn, dayString, isIntercontinental, isInternational, isInterstate, 0, pax);
out.collect(tOut);
out.collect(tIn);
}
}
} | rwaury/pcb | src/main/java/de/tuberlin/dima/ti/analysis/MIDTCapacityEmitter.java | Java | mit | 4,721 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>D3 Append</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
</head>
<body>
<p>Here is a paragraph.</p>
<p>And one more.</p>
<p>Third one.</p>
<p>Fourth one.</p>
<script>
var p = d3.selectAll("p");
p.append("span").text(" New text in span.");
</script>
</body>
</html> | CS171/CS171.github.io | 2016_Spring/lectures/lecture-d3/d3_append.html | HTML | mit | 413 |
Yet another post
[meta:author]: <> (Jonas Colmsjo)
[meta:title]: <> (Development-architecture.md)
[meta:date]: <> (2012-01-01)
[meta:nested:key]: <> (Metadata value)
##!!truncate
[[wiki]] > [[Technical Architecture]]
h1. Development Architecture
h2. Overview
The development architecture consists of the following tools:
* This Redmine portal
** Issues
** Wiki
** Functional and Technical Design Documents
* DokuWiki - for system documentation
* Testlink - for documentation of tests
* Source Code Management system (SCM) based on Subversion and shell scripts
* PHP/MySQL environments for vTiger etc.
** Sandbox
** Development
** Test
** QA
** Production environments
h2. Coding standards
phpdoc is used to create documentation:
* http://www.phpdoc.org/docs/latest/for-users/anatomy-of-a-docblock.html
* http://phpmaster.com/introduction-to-phpdoc/
These coding standards should be followed:
* http://pear.php.net/manual/en/standards.php
h3. phpdoc
phpdoc is automatically executed on the vtigertest repository. The documentation can be found here:
* http://phpdoc.gizurcloud.com/
h3. About PHPUnit
Unit testing is “is a method of testing that verifies the individual units of source code are working properly”
Unit Testing in short is a
1. unit: the smallest testable code of an app
- procedural: function or procedure
- OOP: a method
2. Test: code that checks code on
- functional behavior
- expected results
- unexpected failures
PHPUnit is a set of tools to test PHP pages for errors.. The difference is between testing, that is, checking that program behaves as expected, and performing a battery of tests, runnable code-fragments that automatically test the correctness of parts (units) of the software. These runnable code-fragments are called unit tests
See PHPUnit.docx below for more details.
h2. SCM
Subversion is used for configuration management. Code that is commited to subversion is automatically deployed on the application servers. There are separate subversion repositories for development, test and producttion. Access to the reposirotiers are controlled via the subversion configuration file (s2.gizur.com:/etc/svn-access-control)
If you're new to subversion, check-out some introduction like this (or just Google):
* Short - http://www.froihofer.net/en/students/svn-intro.html
* In depth - http://svnbook.red-bean.com/
Subversion can be used from the prompt and there are also GUI:s
* For windows Tortoise is commonly used - http://tortoisesvn.tigris.org/
* For Linux there is not single given GUI, Google or give this a try http://rabbitvcs.org/
Repositories:
* Development - https://s2.gizur.com/svn/gom-dev
* Test - https://s2.gizur.com/svn/gom-test
* Production - https://s2.gizur.com/svn/gom-prod
The structure of the root-dir directory in the repositories is the same as the dicrectory structure of the linux application servers.
Directory structure of the gom-dev repository:
* root-dir
** etc
** root
*** scripts
** var
*** www
**** html
***** vtigersbx
****** The vTigerCRM structure
***** vtigerdev
****** The vTigerCRM structure
* setup
* tests
* developers
** jonas
** essindia
** ...
Directory structure of the gom-test repository:
* root-dir
** etc
** root
*** scripts
** var
*** www
**** html
***** vtigertest
****** The vTigerCRM structure
* setup
Directory structure of the gom-prod repository:
* root-dir
** etc
** root
*** scripts
** var
*** www
**** html
***** vitger<client>
****** The vTigerCRM structure
***** vtigerbase
****** The vTigerCRM structure
* setup
h2. Deployment of code
h3. Development and Sandbox environments
The directory /root-dir/var/www/html/vtigerdev is used for deploying in the development environment. This environment is used during development and unit testing.
The directory /root-dir/var/www/html/vtigersbx is used for "playing around". This environment is "reset" periodically by copying the contents of vtigerdev.
h3. Test environment
Deployment from the development environment to test is performed using a shell script. This script simply copies file by file from vtigerdev to vtigertest.
Each Change Request must contain a list of the files that have been modified. The deployment script is developed by the Configuration Manager (currently at Gizur).
Deployment to test:
# Copy the file gom-test/setup/issues/template-deployment-descriptor to gom-test/setup/issues/deployment-descriptor-issue<NUMBER>
# Edit the new file
## Enter the files to de be deployed in the template (make sure the spelling is correct, file names are case sensitive)
## Also enter the directories that need to be created in the template
# Test the deployment descriptor running: deploy-issues-to-test.sh deployment-descriptor-issue<NUMBER>
# NOW, check that the files have been copied from the gom-dev repository ti gom-test as expected
# This deployment descriptor should be attached to the issue
h3. Production environment
Deployment to the production environment is performed in the same way as to the test environment. The same deployment script is used.
| colmsjo/myblog.old | migration/output/Development-architecture.md | Markdown | mit | 5,059 |
$client = new Paymill\Models\Request\Client();
$client->setId('client_88a388d9dd48f86c3136')
->setEmail('updated-client@example.com')
->setDescription('Updated Client');
$response = $request->update($client);
| paymill/paymill-php | samples/clients/update_client.php | PHP | mit | 224 |
FactoryGirl.define do
# Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them.
#
# Example adding this to your spec_helper will load these Factories for use:
# require 'spree_rtl/factories'
end
| mshirdel/spree_rtl | lib/spree_rtl/factories.rb | Ruby | mit | 274 |
Deployment guide
================
JARVIS is a [Flask](http://flask.pocoo.org) application, see the
[uWSGI docs](https://uwsgi-docs.readthedocs.org/en/latest/WSGIquickstart.html)
for a more detailed uWSGI deployment guide or check out the other deployment
options described in the [Flask docs](http://flask.pocoo.org/docs/deploying)
This guide assumes Debian or Ubuntu, but most steps should work for other
distros.
Clone repo:
export APP_PATH=/path/to/jarvis2
git clone https://github.com/mpolden/jarvis2.git $APP_PATH
Create virtualenv and install dependencies:
cd $APP_PATH
virtualenv venv
source venv/bin/activate
pip install -r requirements.txt
Copy sample config and edit it to suit your needs:
cp $APP_PATH/jarvis/config.py.sample $APP_PATH/jarvis/config.py
Create cache directories (needs to be writable by uwsgi process):
mkdir -p $APP_PATH/jarvis/static/{.webassets-cache,gen}
chown www-data:www-data $APP_PATH/jarvis/static/{.webassets-cache,gen}
Install nginx and uwsgi:
aptitude install nginx uwsgi uwsgi-plugin-python
Configure app config in `/etc/uwsgi/apps-available/jarvis.ini`:
[uwsgi]
workers = 1
threads = 20
plugin = python
chdir = /path/to/jarvis2/jarvis
home = /path/to/jarvis2/venv
env = JARVIS_SETTINGS=config.py
module = app
callable = app
Enable uwsgi app and start uwsgi:
ln -s /etc/uwsgi/apps-available/jarvis.ini /etc/uwsgi/apps-enabled/jarvis.ini
systemctl restart uwsgi
Configure nginx site in `/etc/nginx/sites-available/jarvis`:
server {
location /static/ {
alias /path/to/jarvis2/jarvis/static/;
}
location / {
include uwsgi_params;
uwsgi_buffering off;
uwsgi_pass unix:/run/uwsgi/app/jarvis/socket;
}
}
Enable nginx site and (re)start nginx:
ln -s /etc/nginx/sites-available/jarvis /etc/nginx/sites-enabled/jarvis
systemctl restart nginx
| mpolden/jarvis2 | docs/INSTALL.md | Markdown | mit | 1,972 |
using System.Drawing.Imaging;
using Aspose.BarCode.Generation;
/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.BarCode for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.BarCode for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/
namespace Aspose.BarCode.Examples.CSharp.ManageBarCodes
{
class SetSupplementData
{
public static void Run()
{
// ExStart:SetSupplementData
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_ManageBarCodes();
// Instantiate barcode object
BarcodeGenerator generator = new BarcodeGenerator (EncodeTypes.EAN13, "123456789123");
// Set the supplement data (5 Digit)
generator.Parameters.Barcode.Supplement.SupplementData = "12345";
generator.Parameters.Barcode.Supplement.SupplementSpace.Millimeters = 2.0f;
generator.Save(dataDir + "SetSupplementData_out.jpg", BarCodeImageFormat.Jpeg);
// ExEnd:SetSupplementData
}
}
} | asposebarcode/Aspose_BarCode_NET | Examples/CSharp/ManageBarCodes/SetSupplementData.cs | C# | mit | 1,413 |
/**
* Interface C4BoardIntf specifies the interface for an object that implements
* the Connect Four game board. The methods in this interface are queried to
* display the game board.
*
* @author Alan Kaminsky
* @version 13-Oct-2014
*/
public interface C4BoardIntf
{
/**
* Number of rows.
*/
public static final int ROWS = 6;
/**
* Number of columns.
*/
public static final int COLS = 7;
/**
* Determine if the given row and column contains player 1's marker.
*
* @param r Row.
* @param c Column.
*
* @return True if (r, c) contains player 1's marker, false otherwise.
*/
public boolean hasPlayer1Marker
(int r,
int c);
/**
* Determine if the given row and column contains player 2's marker.
*
* @param r Row.
* @param c Column.
*
* @return True if (r, c) contains player 2's marker, false otherwise.
*/
public boolean hasPlayer2Marker
(int r,
int c);
/**
* Determine if one player or the other has won; that is, has four markers
* in a row horizontally, vertically, or diagonally. If so, an array of four
* integers (r1, c1, r2, c2) is returned, where (r1, c1) is the row/column
* of the first of the four markers and (r2, c2) is the row/column of the
* last of the four markers. If neither player has won, null is returned.
*
* @return Array of (r1, c1, r2, c2), or null.
*/
public int[] hasWon();
}
| mooman219/CSCI251 | project4-c4server/src/C4BoardIntf.java | Java | mit | 1,401 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Storm</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="ExDoc">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/elixir.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="row row-offcanvas row-offcanvas-left">
<section id="sidebar" class="col-xs-6 col-sm-3 sidebar-offcanvas">
<p class="pull-right visible-xs">
<button type="button" class="btn btn-default btn-sm" data-toggle="offcanvas">
<span class="glyphicon glyphicon-search"></span>
</button>
</p>
<h1 id="full_list_header">
storm v0.0.1
</h1>
<h2 id="sub_list_header">
<a href="overview.html">Overview</a>
</h2>
<div class="nav">
<span><a id="modules_list" href="#full_list">Modules</a></span>
<span role="presentation" class="disabled">Exceptions</span>
<span role="presentation" class="disabled">Protocols</span>
</div>
<div id="search" class="row">
<div class="col-xs-10">
<div class="input-group input-group-sm">
<label for="search_field" class="sr-only">Search</label>
<input type="text" id="search_field" class="form-control" placeholder="Search" autocomplete="off" autofocus="autofocus" results="0">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><span class="glyphicon glyphicon-search"></span></button>
</span>
</div><!-- /input-group -->
</div><!-- /.col-xs-10 -->
<div class="col-xs-2" id="spinning">
<span></span>
</div><!-- /.col-xs-2 -->
</div><!-- /#search .row -->
<script src="sidebar_items.js" defer></script>
<ul id="full_list">
</ul>
<div id="no_results"></div>
</section><!--/.sidebar-offcanvas -->
<section id="content" class="col-xs-12 col-sm-9">
<div class="breadcrumbs">
<button type="button" class="btn btn-default btn-sm" data-toggle="offcanvas">
<span class="glyphicon glyphicon-menu-hamburger"></span>
</button>
storm v0.0.1 → <a href="overview.html">Overview</a> → <a href="Storm.html#content">Storm</a>
</div>
<h1>
Storm
</h1>
<ul class="summary_links">
<li><a href="#summary_details">Summary</a></li>
<li><a href="#functions_details">Functions</a></li>
</ul>
<section id="summary_details" class="details_list">
<h1>Summary</h1>
<table class="summary">
<tr>
<td class="summary_signature"><a href="#config_change/3">config_change(changed, new, removed)</a></td>
<td class="summary_synopsis"></td>
</tr>
<tr>
<td class="summary_signature"><a href="#start/2">start(type, args)</a></td>
<td class="summary_synopsis"><p>Callback implementation for <code class="inline">c::application.start/2</code></p>
</td>
</tr>
</table>
</section>
<section id="functions_details" class="details_list">
<h1>Functions</h1>
<section class="detail">
<div class="detail_header" id="config_change/3">
<span class="signature"><strong>config_change(changed, new, removed)</strong></span>
<div class="detail_header_links">
<span class="detail_type">(function)</span>
<a href="#config_change/3" class="detail_link" title="Link to this function">#</a>
<a class="to_top_link" href="#content" title="To the top of the page">↑</a>
</div>
</div>
<section class="docstring">
</section>
</section>
<section class="detail">
<div class="detail_header" id="start/2">
<span class="signature"><strong>start(type, args)</strong></span>
<div class="detail_header_links">
<span class="detail_type">(function)</span>
<a href="#start/2" class="detail_link" title="Link to this function">#</a>
<a class="to_top_link" href="#content" title="To the top of the page">↑</a>
</div>
</div>
<section class="docstring">
<p>Callback implementation for <code class="inline">c::application.start/2</code>.</p>
</section>
</section>
</section>
</section> <!--/content -->
</div><!--/row -->
<!-- Scripts -->
<script>
relpath = '';
if (relpath != '') relpath += '/';
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery.js"><\/script>')</script>
<script src="js/highlight.pack.js"></script>
<script src="js/app.js"></script>
</body>
</html>
| nsarno/storm | doc/Storm.html | HTML | mit | 4,983 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Series Evaluation</title>
<link rel="stylesheet" href="../../math.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Math Toolkit 1.9.0">
<link rel="up" href="../internals1.html" title="Utilities & internals">
<link rel="prev" href="../internals1.html" title="Utilities & internals">
<link rel="next" href="cf.html" title="Continued Fraction Evaluation">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../internals1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../internals1.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="cf.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="math_toolkit.internals1.series_evaluation"></a><a class="link" href="series_evaluation.html" title="Series Evaluation">Series Evaluation</a>
</h3></div></div></div>
<h5>
<a name="math_toolkit.internals1.series_evaluation.h0"></a>
<span class="phrase"><a name="math_toolkit.internals1.series_evaluation.synopsis"></a></span><a class="link" href="series_evaluation.html#math_toolkit.internals1.series_evaluation.synopsis">Synopsis</a>
</h5>
<pre class="programlisting"><span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">math</span><span class="special">/</span><span class="identifier">tools</span><span class="special">/</span><span class="identifier">series</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
</pre>
<pre class="programlisting"><span class="keyword">namespace</span> <span class="identifier">boost</span><span class="special">{</span> <span class="keyword">namespace</span> <span class="identifier">math</span><span class="special">{</span> <span class="keyword">namespace</span> <span class="identifier">tools</span><span class="special">{</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Functor</span><span class="special">,</span> <span class="keyword">class</span> <span class="identifier">U</span><span class="special">,</span> <span class="keyword">class</span> <span class="identifier">V</span><span class="special">></span>
<span class="keyword">inline</span> <span class="keyword">typename</span> <span class="identifier">Functor</span><span class="special">::</span><span class="identifier">result_type</span> <span class="identifier">sum_series</span><span class="special">(</span><span class="identifier">Functor</span><span class="special">&</span> <span class="identifier">func</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">U</span><span class="special">&</span> <span class="identifier">tolerance</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uintmax_t</span><span class="special">&</span> <span class="identifier">max_terms</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">V</span><span class="special">&</span> <span class="identifier">init_value</span><span class="special">);</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Functor</span><span class="special">,</span> <span class="keyword">class</span> <span class="identifier">U</span><span class="special">,</span> <span class="keyword">class</span> <span class="identifier">V</span><span class="special">></span>
<span class="keyword">inline</span> <span class="keyword">typename</span> <span class="identifier">Functor</span><span class="special">::</span><span class="identifier">result_type</span> <span class="identifier">sum_series</span><span class="special">(</span><span class="identifier">Functor</span><span class="special">&</span> <span class="identifier">func</span><span class="special">,</span> <span class="keyword">const</span> <span class="identifier">U</span><span class="special">&</span> <span class="identifier">tolerance</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uintmax_t</span><span class="special">&</span> <span class="identifier">max_terms</span><span class="special">);</span>
<span class="comment">//</span>
<span class="comment">// The following interfaces are now deprecated:</span>
<span class="comment">// </span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Functor</span><span class="special">></span>
<span class="keyword">typename</span> <span class="identifier">Functor</span><span class="special">::</span><span class="identifier">result_type</span> <span class="identifier">sum_series</span><span class="special">(</span><span class="identifier">Functor</span><span class="special">&</span> <span class="identifier">func</span><span class="special">,</span> <span class="keyword">int</span> <span class="identifier">bits</span><span class="special">);</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Functor</span><span class="special">></span>
<span class="keyword">typename</span> <span class="identifier">Functor</span><span class="special">::</span><span class="identifier">result_type</span> <span class="identifier">sum_series</span><span class="special">(</span><span class="identifier">Functor</span><span class="special">&</span> <span class="identifier">func</span><span class="special">,</span> <span class="keyword">int</span> <span class="identifier">bits</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uintmax_t</span><span class="special">&</span> <span class="identifier">max_terms</span><span class="special">);</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Functor</span><span class="special">,</span> <span class="keyword">class</span> <span class="identifier">U</span><span class="special">></span>
<span class="keyword">typename</span> <span class="identifier">Functor</span><span class="special">::</span><span class="identifier">result_type</span> <span class="identifier">sum_series</span><span class="special">(</span><span class="identifier">Functor</span><span class="special">&</span> <span class="identifier">func</span><span class="special">,</span> <span class="keyword">int</span> <span class="identifier">bits</span><span class="special">,</span> <span class="identifier">U</span> <span class="identifier">init_value</span><span class="special">);</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Functor</span><span class="special">,</span> <span class="keyword">class</span> <span class="identifier">U</span><span class="special">></span>
<span class="keyword">typename</span> <span class="identifier">Functor</span><span class="special">::</span><span class="identifier">result_type</span> <span class="identifier">sum_series</span><span class="special">(</span><span class="identifier">Functor</span><span class="special">&</span> <span class="identifier">func</span><span class="special">,</span> <span class="keyword">int</span> <span class="identifier">bits</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uintmax_t</span><span class="special">&</span> <span class="identifier">max_terms</span><span class="special">,</span> <span class="identifier">U</span> <span class="identifier">init_value</span><span class="special">);</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Functor</span><span class="special">></span>
<span class="keyword">typename</span> <span class="identifier">Functor</span><span class="special">::</span><span class="identifier">result_type</span> <span class="identifier">kahan_sum_series</span><span class="special">(</span><span class="identifier">Functor</span><span class="special">&</span> <span class="identifier">func</span><span class="special">,</span> <span class="keyword">int</span> <span class="identifier">bits</span><span class="special">);</span>
<span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">Functor</span><span class="special">></span>
<span class="keyword">typename</span> <span class="identifier">Functor</span><span class="special">::</span><span class="identifier">result_type</span> <span class="identifier">kahan_sum_series</span><span class="special">(</span><span class="identifier">Functor</span><span class="special">&</span> <span class="identifier">func</span><span class="special">,</span> <span class="keyword">int</span> <span class="identifier">bits</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">uintmax_t</span><span class="special">&</span> <span class="identifier">max_terms</span><span class="special">);</span>
<span class="special">}}}</span> <span class="comment">// namespaces</span>
</pre>
<h5>
<a name="math_toolkit.internals1.series_evaluation.h1"></a>
<span class="phrase"><a name="math_toolkit.internals1.series_evaluation.description"></a></span><a class="link" href="series_evaluation.html#math_toolkit.internals1.series_evaluation.description">Description</a>
</h5>
<p>
These algorithms are intended for the <a href="http://en.wikipedia.org/wiki/Series_%28mathematics%29" target="_top">summation
of infinite series</a>.
</p>
<p>
Each of the algorithms takes a nullary-function object as the first argument:
the function object will be repeatedly invoked to pull successive terms from
the series being summed.
</p>
<p>
The second argument is the precision required, summation will stop when the
next term is less than <span class="emphasis"><em>tolerance</em></span> times the result. The
deprecated versions of sum_series take an integer number of bits here - internally
they just convert this to a tolerance and forward the call.
</p>
<p>
The third argument <span class="emphasis"><em>max_terms</em></span> sets an upper limit on
the number of terms of the series to evaluate. In addition, on exit the function
will set <span class="emphasis"><em>max_terms</em></span> to the actual number of terms of
the series that were evaluated: this is particularly useful for profiling
the convergence properties of a new series.
</p>
<p>
The final optional argument <span class="emphasis"><em>init_value</em></span> is the initial
value of the sum to which the terms of the series should be added. This is
useful in two situations:
</p>
<div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; ">
<li class="listitem">
Where the first value of the series has a different formula to successive
terms. In this case the first value in the series can be passed as the
last argument and the logic of the function object can then be simplified
to return subsequent terms.
</li>
<li class="listitem">
Where the series is being added (or subtracted) from some other value:
termination of the series will likely occur much more rapidly if that
other value is passed as the last argument. For example, there are several
functions that can be expressed as <span class="emphasis"><em>1 - S(z)</em></span> where
S(z) is an infinite series. In this case, pass -1 as the last argument
and then negate the result of the summation to get the result of <span class="emphasis"><em>1
- S(z)</em></span>.
</li>
</ul></div>
<p>
The two <span class="emphasis"><em>kahan_sum_series</em></span> variants of these algorithms
maintain a carry term that corrects for roundoff error during summation.
They are inspired by the <a href="http://en.wikipedia.org/wiki/Kahan_Summation_Algorithm" target="_top"><span class="emphasis"><em>Kahan
Summation Formula</em></span></a> that appears in <a href="http://docs.sun.com/source/806-3568/ncg_goldberg.html" target="_top">What
Every Computer Scientist Should Know About Floating-Point Arithmetic</a>.
However, it should be pointed out that there are very few series that require
summation in this way.
</p>
<h5>
<a name="math_toolkit.internals1.series_evaluation.h2"></a>
<span class="phrase"><a name="math_toolkit.internals1.series_evaluation.example"></a></span><a class="link" href="series_evaluation.html#math_toolkit.internals1.series_evaluation.example">Example</a>
</h5>
<p>
Let's suppose we want to implement <span class="emphasis"><em>log(1+x)</em></span> via its
infinite series,
</p>
<p>
<span class="inlinemediaobject"><img src="../../../equations/log1pseries.png"></span>
</p>
<p>
We begin by writing a small function object to return successive terms of
the series:
</p>
<pre class="programlisting"><span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">T</span><span class="special">></span>
<span class="keyword">struct</span> <span class="identifier">log1p_series</span>
<span class="special">{</span>
<span class="comment">// we must define a result_type typedef:</span>
<span class="keyword">typedef</span> <span class="identifier">T</span> <span class="identifier">result_type</span><span class="special">;</span>
<span class="identifier">log1p_series</span><span class="special">(</span><span class="identifier">T</span> <span class="identifier">x</span><span class="special">)</span>
<span class="special">:</span> <span class="identifier">k</span><span class="special">(</span><span class="number">0</span><span class="special">),</span> <span class="identifier">m_mult</span><span class="special">(-</span><span class="identifier">x</span><span class="special">),</span> <span class="identifier">m_prod</span><span class="special">(-</span><span class="number">1</span><span class="special">){}</span>
<span class="identifier">T</span> <span class="keyword">operator</span><span class="special">()()</span>
<span class="special">{</span>
<span class="comment">// This is the function operator invoked by the summation</span>
<span class="comment">// algorithm, the first call to this operator should return</span>
<span class="comment">// the first term of the series, the second call the second </span>
<span class="comment">// term and so on.</span>
<span class="identifier">m_prod</span> <span class="special">*=</span> <span class="identifier">m_mult</span><span class="special">;</span>
<span class="keyword">return</span> <span class="identifier">m_prod</span> <span class="special">/</span> <span class="special">++</span><span class="identifier">k</span><span class="special">;</span>
<span class="special">}</span>
<span class="keyword">private</span><span class="special">:</span>
<span class="keyword">int</span> <span class="identifier">k</span><span class="special">;</span>
<span class="keyword">const</span> <span class="identifier">T</span> <span class="identifier">m_mult</span><span class="special">;</span>
<span class="identifier">T</span> <span class="identifier">m_prod</span><span class="special">;</span>
<span class="special">};</span>
</pre>
<p>
Implementing log(1+x) is now fairly trivial:
</p>
<pre class="programlisting"><span class="keyword">template</span> <span class="special"><</span><span class="keyword">class</span> <span class="identifier">T</span><span class="special">></span>
<span class="identifier">T</span> <span class="identifier">log1p</span><span class="special">(</span><span class="identifier">T</span> <span class="identifier">x</span><span class="special">)</span>
<span class="special">{</span>
<span class="comment">// We really should add some error checking on x here!</span>
<span class="identifier">assert</span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">fabs</span><span class="special">(</span><span class="identifier">x</span><span class="special">)</span> <span class="special"><</span> <span class="number">1</span><span class="special">);</span>
<span class="comment">// Construct the series functor:</span>
<span class="identifier">log1p_series</span><span class="special"><</span><span class="identifier">T</span><span class="special">></span> <span class="identifier">s</span><span class="special">(</span><span class="identifier">x</span><span class="special">);</span>
<span class="comment">// Set a limit on how many iterations we permit:</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">uintmax_t</span> <span class="identifier">max_iter</span> <span class="special">=</span> <span class="number">1000</span><span class="special">;</span>
<span class="comment">// Add it up, with enough precision for full machine precision:</span>
<span class="keyword">return</span> <span class="identifier">tools</span><span class="special">::</span><span class="identifier">sum_series</span><span class="special">(</span><span class="identifier">s</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">numeric_limits</span><span class="special"><</span><span class="identifier">T</span><span class="special">>::</span><span class="identifier">epsilon</span><span class="special">(),</span> <span class="identifier">max_iter</span><span class="special">);</span>
<span class="special">}</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2006-2010, 2012, 2013 Nikhar Agrawal, Anton Bikineev,
Paul A. Bristow, Christopher Kormanyos, Hubert Holin, Bruno Lalande, John Maddock,
Johan Råde, Gautam Sewani, Benjamin Sobotta, Thijs van den Berg, Daryle Walker
and Xiaogang Zhang<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../internals1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../internals1.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="cf.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| rkq/cxxexp | third-party/src/boost_1_56_0/libs/math/doc/html/math_toolkit/internals1/series_evaluation.html | HTML | mit | 20,787 |
using System;
using System.Threading;
using JetBrains.Annotations;
namespace Jasily.Extensions.System.Threading
{
public static class SynchronizationContextExtensions
{
public static void Send([NotNull] this SynchronizationContext context, [NotNull] Action action)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (action == null) throw new ArgumentNullException(nameof(action));
context.Send(_ => action(), null);
}
public static void Send<T>([NotNull] this SynchronizationContext context, [NotNull] Action<T> action, T state)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (action == null) throw new ArgumentNullException(nameof(action));
context.Send(_ => action(state), null);
}
public static void Send([NotNull] this SynchronizationContext context, [NotNull] EventHandler handler,
object sender, EventArgs e)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (handler == null) throw new ArgumentNullException(nameof(handler));
context.Send(_ => handler(sender, e), null);
}
public static void Send<T>([NotNull] this SynchronizationContext context, [NotNull] EventHandler<T> handler,
object sender, T state)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (handler == null) throw new ArgumentNullException(nameof(handler));
context.Send(_ => handler(sender, state), null);
}
public static void Post([NotNull] this SynchronizationContext context, [NotNull] Action action)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (action == null) throw new ArgumentNullException(nameof(action));
context.Post(_ => action(), null);
}
public static void Post<T>([NotNull] this SynchronizationContext context, [NotNull] Action<T> action, T state)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (action == null) throw new ArgumentNullException(nameof(action));
context.Post(_ => action(state), null);
}
public static void Post([NotNull] this SynchronizationContext context, [NotNull] EventHandler handler,
object sender, EventArgs e)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (handler == null) throw new ArgumentNullException(nameof(handler));
context.Post(_ => handler(sender, e), null);
}
public static void Post<T>([NotNull] this SynchronizationContext context, [NotNull] EventHandler<T> handler,
object sender, T state)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (handler == null) throw new ArgumentNullException(nameof(handler));
context.Post(_ => handler(sender, state), null);
}
}
} | Jasily/jasily-csharp | Jasily.Extensions.System/Threading/SynchronizationContextExtensions.cs | C# | mit | 3,171 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>API documentation</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="css/highlight.github.css" />
<link rel="stylesheet" type="text/css" href="custom.css" />
</head>
<body class="antialiased hide-extras">
<div class="sidebar-top">
<div class="logo"></div>
API documentation
</div>
<div class="sidebar">
<form>
<input tabindex="1" id="autocomplete" type="search"
placeholder="search" autocomplete="off" />
</form>
<nav>
<ul class="side-nav">
<li class="divider"></li>
<li class="heading">
<a href="index.html">Intro</a>
</li>
<li>
<a href="index.html#event-information" data-search="Event information">
Event information
</a>
</li>
<li>
<a href="index.html#authenticated-calls" data-search="Authenticated calls">
Authenticated calls
</a>
</li>
<li class="divider"></li>
<li class="heading">
<a href="admin.html">Admin</a>
</li>
<li>
<a href="admin.html#reporting" data-search="Reporting">
Reporting
<span class="label">1</span>
</a>
</li>
<li class="divider"></li>
<li class="heading">
<a href="events.html">Events</a>
</li>
<li>
<a href="events.html#competitions" data-search="Competitions">
Competitions
<span class="label">2</span>
</a>
</li>
<li>
<a href="events.html#sports" data-search="Sports">
Sports
<span class="label">1</span>
</a>
</li>
<li class="divider"></li>
<li class="heading">
<a href="user.html">User</a>
</li>
<li>
<a href="user.html#tickets" data-search="Tickets">
Tickets
<span class="label">3</span>
</a>
</li>
</ul>
</nav>
</div>
<div class="content-top"></div>
<div class="content">
<h1>Admin</h1>
<div class="group">
<a name="reporting"></a>
<h2>Reporting</h2>
<ul class="samples">
<li>
<div class="summary">
<p>Status check</p>
<p>Health check route to check the status of all downstreams system.</p>
</div>
<div class="operation">
<div class="method color-GET">
GET
</div>
<div class="request">
<div class="url">
GET
<pre><code>/status</code></pre>
</div>
Sample request
<div class="expanders">
<a href="#sample3-url">url</a><span>
<a href="#sample3-request-headers">headers</a><span>
<a href="#sample3-request-curl">curl</a><span>
</div>
</div>
<div id="sample3-url" class="collapsible">
<pre><code>/status</code></pre>
</div>
<div id="sample3-request-headers" class="collapsible">
<pre><code><span class="hljs-attribute">accept</span>: <span class="hljs-string">application/json</span>
</code></pre>
</div>
<div id="sample3-request-payload" class="collapsible">
</div>
<div id="sample3-request-attachments" class="collapsible">
</div>
<div id="sample3-request-curl" class="collapsible">
<pre><code class="wrap">curl <span class="hljs-attribute">-X</span> GET <span class="hljs-attribute">-H</span> <span class="hljs-string">"accept: application/json"</span> <span class="hljs-string">"http://my-api.com/status"</span></code></pre>
</div>
<div class="response">
Response 200 OK
<div class="expanders">
<a href="#sample3-response-headers">headers</a>
<a href="#sample3-response-body">body</a>
</div>
</div>
<div id="sample3-response-headers" class="collapsible">
<pre><code><span class="hljs-attribute">content-type</span>: <span class="hljs-string">application/json</span>
</code></pre>
</div>
<div id="sample3-response-body" class="collapsible">
<pre><code>{
"<span class="hljs-attribute">status</span>": <span class="hljs-value"><span class="hljs-string">"OK"</span>
</span>}</code></pre>
</div>
</div>
</li>
</ul>
</div>
</div>
<footer>
<div class="row">
<div class="medium-8 columns">
<ul class="no-bullet">
<li>
Documentation generated on May 27th 2014, 3:18 pm
</li>
<li>
<a href="http://github.com/rprieto/supersamples">
Powered by supersamples
<div class="logo">
<div class="swatch color-GET"></div>
<div class="swatch color-POST"></div>
<div class="swatch color-PUT"></div>
<div class="swatch color-DELETE"></div>
</div>
</a>
</li>
</ul>
</div>
</div>
</footer>
<script src="scripts/zepto.min.js"></script>
<script src="scripts/scripts.js"></script>
</body>
</html>
| vickvu/supersamples | example-docs/admin.html | HTML | mit | 5,856 |
<HTML>
<BODY BGCOLOR="white">
<PRE>
<FONT color="green">001</FONT> /*<a name="line.1"></a>
<FONT color="green">002</FONT> * Licensed to the Apache Software Foundation (ASF) under one or more<a name="line.2"></a>
<FONT color="green">003</FONT> * contributor license agreements. See the NOTICE file distributed with<a name="line.3"></a>
<FONT color="green">004</FONT> * this work for additional information regarding copyright ownership.<a name="line.4"></a>
<FONT color="green">005</FONT> * The ASF licenses this file to You under the Apache License, Version 2.0<a name="line.5"></a>
<FONT color="green">006</FONT> * (the "License"); you may not use this file except in compliance with<a name="line.6"></a>
<FONT color="green">007</FONT> * the License. You may obtain a copy of the License at<a name="line.7"></a>
<FONT color="green">008</FONT> *<a name="line.8"></a>
<FONT color="green">009</FONT> * http://www.apache.org/licenses/LICENSE-2.0<a name="line.9"></a>
<FONT color="green">010</FONT> *<a name="line.10"></a>
<FONT color="green">011</FONT> * Unless required by applicable law or agreed to in writing, software<a name="line.11"></a>
<FONT color="green">012</FONT> * distributed under the License is distributed on an "AS IS" BASIS,<a name="line.12"></a>
<FONT color="green">013</FONT> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<a name="line.13"></a>
<FONT color="green">014</FONT> * See the License for the specific language governing permissions and<a name="line.14"></a>
<FONT color="green">015</FONT> * limitations under the License.<a name="line.15"></a>
<FONT color="green">016</FONT> */<a name="line.16"></a>
<FONT color="green">017</FONT> package org.apache.commons.jexl2.internal.introspection;<a name="line.17"></a>
<FONT color="green">018</FONT> <a name="line.18"></a>
<FONT color="green">019</FONT> import java.lang.reflect.Method;<a name="line.19"></a>
<FONT color="green">020</FONT> import java.lang.reflect.Constructor;<a name="line.20"></a>
<FONT color="green">021</FONT> import java.lang.reflect.Field;<a name="line.21"></a>
<FONT color="green">022</FONT> import java.util.Map;<a name="line.22"></a>
<FONT color="green">023</FONT> import java.util.HashMap;<a name="line.23"></a>
<FONT color="green">024</FONT> import java.util.Iterator;<a name="line.24"></a>
<FONT color="green">025</FONT> import java.util.LinkedList;<a name="line.25"></a>
<FONT color="green">026</FONT> import java.util.List;<a name="line.26"></a>
<FONT color="green">027</FONT> <a name="line.27"></a>
<FONT color="green">028</FONT> import org.apache.commons.logging.Log;<a name="line.28"></a>
<FONT color="green">029</FONT> <a name="line.29"></a>
<FONT color="green">030</FONT> /**<a name="line.30"></a>
<FONT color="green">031</FONT> * This basic function of this class is to return a Method object for a<a name="line.31"></a>
<FONT color="green">032</FONT> * particular class given the name of a method and the parameters to the method<a name="line.32"></a>
<FONT color="green">033</FONT> * in the form of an Object[]<a name="line.33"></a>
<FONT color="green">034</FONT> * <p/><a name="line.34"></a>
<FONT color="green">035</FONT> * The first time the Introspector sees a class it creates a class method map<a name="line.35"></a>
<FONT color="green">036</FONT> * for the class in question. Basically the class method map is a Hastable where<a name="line.36"></a>
<FONT color="green">037</FONT> * Method objects are keyed by a concatenation of the method name and the names<a name="line.37"></a>
<FONT color="green">038</FONT> * of classes that make up the parameters.<a name="line.38"></a>
<FONT color="green">039</FONT> *<a name="line.39"></a>
<FONT color="green">040</FONT> * For example, a method with the following signature:<a name="line.40"></a>
<FONT color="green">041</FONT> *<a name="line.41"></a>
<FONT color="green">042</FONT> * public void method(String a, StringBuffer b)<a name="line.42"></a>
<FONT color="green">043</FONT> *<a name="line.43"></a>
<FONT color="green">044</FONT> * would be mapped by the key:<a name="line.44"></a>
<FONT color="green">045</FONT> *<a name="line.45"></a>
<FONT color="green">046</FONT> * "method" + "java.lang.String" + "java.lang.StringBuffer"<a name="line.46"></a>
<FONT color="green">047</FONT> *<a name="line.47"></a>
<FONT color="green">048</FONT> * This mapping is performed for all the methods in a class and stored.<a name="line.48"></a>
<FONT color="green">049</FONT> * @since 1.0<a name="line.49"></a>
<FONT color="green">050</FONT> */<a name="line.50"></a>
<FONT color="green">051</FONT> public class IntrospectorBase {<a name="line.51"></a>
<FONT color="green">052</FONT> /** the logger. */<a name="line.52"></a>
<FONT color="green">053</FONT> protected final Log rlog;<a name="line.53"></a>
<FONT color="green">054</FONT> /**<a name="line.54"></a>
<FONT color="green">055</FONT> * Holds the method maps for the classes we know about, keyed by Class.<a name="line.55"></a>
<FONT color="green">056</FONT> */<a name="line.56"></a>
<FONT color="green">057</FONT> private final Map<Class<?>, ClassMap> classMethodMaps = new HashMap<Class<?>, ClassMap>();<a name="line.57"></a>
<FONT color="green">058</FONT> /**<a name="line.58"></a>
<FONT color="green">059</FONT> * The class loader used to solve constructors if needed.<a name="line.59"></a>
<FONT color="green">060</FONT> */<a name="line.60"></a>
<FONT color="green">061</FONT> private ClassLoader loader;<a name="line.61"></a>
<FONT color="green">062</FONT> /**<a name="line.62"></a>
<FONT color="green">063</FONT> * Holds the map of classes ctors we know about as well as unknown ones.<a name="line.63"></a>
<FONT color="green">064</FONT> */<a name="line.64"></a>
<FONT color="green">065</FONT> private final Map<MethodKey, Constructor<?>> constructorsMap = new HashMap<MethodKey, Constructor<?>>();<a name="line.65"></a>
<FONT color="green">066</FONT> /**<a name="line.66"></a>
<FONT color="green">067</FONT> * Holds the set of classes we have introspected.<a name="line.67"></a>
<FONT color="green">068</FONT> */<a name="line.68"></a>
<FONT color="green">069</FONT> private final Map<String, Class<?>> constructibleClasses = new HashMap<String, Class<?>>();<a name="line.69"></a>
<FONT color="green">070</FONT> <a name="line.70"></a>
<FONT color="green">071</FONT> /**<a name="line.71"></a>
<FONT color="green">072</FONT> * Create the introspector.<a name="line.72"></a>
<FONT color="green">073</FONT> * @param log the logger to use<a name="line.73"></a>
<FONT color="green">074</FONT> */<a name="line.74"></a>
<FONT color="green">075</FONT> public IntrospectorBase(Log log) {<a name="line.75"></a>
<FONT color="green">076</FONT> this.rlog = log;<a name="line.76"></a>
<FONT color="green">077</FONT> loader = getClass().getClassLoader();<a name="line.77"></a>
<FONT color="green">078</FONT> }<a name="line.78"></a>
<FONT color="green">079</FONT> <a name="line.79"></a>
<FONT color="green">080</FONT> /**<a name="line.80"></a>
<FONT color="green">081</FONT> * Gets a class by name through this introspector class loader.<a name="line.81"></a>
<FONT color="green">082</FONT> * @param className the class name<a name="line.82"></a>
<FONT color="green">083</FONT> * @return the class instance or null if it could not be found<a name="line.83"></a>
<FONT color="green">084</FONT> */<a name="line.84"></a>
<FONT color="green">085</FONT> public Class<?> getClassByName(String className) {<a name="line.85"></a>
<FONT color="green">086</FONT> try {<a name="line.86"></a>
<FONT color="green">087</FONT> return Class.forName(className, false, loader);<a name="line.87"></a>
<FONT color="green">088</FONT> } catch (ClassNotFoundException xignore) {<a name="line.88"></a>
<FONT color="green">089</FONT> return null;<a name="line.89"></a>
<FONT color="green">090</FONT> }<a name="line.90"></a>
<FONT color="green">091</FONT> }<a name="line.91"></a>
<FONT color="green">092</FONT> <a name="line.92"></a>
<FONT color="green">093</FONT> /**<a name="line.93"></a>
<FONT color="green">094</FONT> * Gets the method defined by the <code>MethodKey</code> for the class <code>c</code>.<a name="line.94"></a>
<FONT color="green">095</FONT> *<a name="line.95"></a>
<FONT color="green">096</FONT> * @param c Class in which the method search is taking place<a name="line.96"></a>
<FONT color="green">097</FONT> * @param key Key of the method being searched for<a name="line.97"></a>
<FONT color="green">098</FONT> * @return The desired method object<a name="line.98"></a>
<FONT color="green">099</FONT> * @throws MethodKey.AmbiguousException if no unambiguous method could be found through introspection<a name="line.99"></a>
<FONT color="green">100</FONT> */<a name="line.100"></a>
<FONT color="green">101</FONT> public Method getMethod(Class<?> c, MethodKey key) {<a name="line.101"></a>
<FONT color="green">102</FONT> try {<a name="line.102"></a>
<FONT color="green">103</FONT> ClassMap classMap = getMap(c);<a name="line.103"></a>
<FONT color="green">104</FONT> return classMap.findMethod(key);<a name="line.104"></a>
<FONT color="green">105</FONT> } catch (MethodKey.AmbiguousException xambiguous) {<a name="line.105"></a>
<FONT color="green">106</FONT> // whoops. Ambiguous. Make a nice log message and return null...<a name="line.106"></a>
<FONT color="green">107</FONT> if (rlog != null && rlog.isInfoEnabled()) {<a name="line.107"></a>
<FONT color="green">108</FONT> rlog.info("ambiguous method invocation: "<a name="line.108"></a>
<FONT color="green">109</FONT> + c.getName() + "."<a name="line.109"></a>
<FONT color="green">110</FONT> + key.debugString(), xambiguous);<a name="line.110"></a>
<FONT color="green">111</FONT> }<a name="line.111"></a>
<FONT color="green">112</FONT> return null;<a name="line.112"></a>
<FONT color="green">113</FONT> }<a name="line.113"></a>
<FONT color="green">114</FONT> }<a name="line.114"></a>
<FONT color="green">115</FONT> <a name="line.115"></a>
<FONT color="green">116</FONT> /**<a name="line.116"></a>
<FONT color="green">117</FONT> * Gets the field named by <code>key</code> for the class <code>c</code>.<a name="line.117"></a>
<FONT color="green">118</FONT> *<a name="line.118"></a>
<FONT color="green">119</FONT> * @param c Class in which the field search is taking place<a name="line.119"></a>
<FONT color="green">120</FONT> * @param key Name of the field being searched for<a name="line.120"></a>
<FONT color="green">121</FONT> * @return the desired field or null if it does not exist or is not accessible<a name="line.121"></a>
<FONT color="green">122</FONT> * */<a name="line.122"></a>
<FONT color="green">123</FONT> public Field getField(Class<?> c, String key) {<a name="line.123"></a>
<FONT color="green">124</FONT> ClassMap classMap = getMap(c);<a name="line.124"></a>
<FONT color="green">125</FONT> return classMap.findField(c, key);<a name="line.125"></a>
<FONT color="green">126</FONT> }<a name="line.126"></a>
<FONT color="green">127</FONT> <a name="line.127"></a>
<FONT color="green">128</FONT> /**<a name="line.128"></a>
<FONT color="green">129</FONT> * Gets the array of accessible field names known for a given class.<a name="line.129"></a>
<FONT color="green">130</FONT> * @param c the class<a name="line.130"></a>
<FONT color="green">131</FONT> * @return the class field names<a name="line.131"></a>
<FONT color="green">132</FONT> */<a name="line.132"></a>
<FONT color="green">133</FONT> public String[] getFieldNames(Class<?> c) {<a name="line.133"></a>
<FONT color="green">134</FONT> if (c == null) {<a name="line.134"></a>
<FONT color="green">135</FONT> return new String[0];<a name="line.135"></a>
<FONT color="green">136</FONT> }<a name="line.136"></a>
<FONT color="green">137</FONT> ClassMap classMap = getMap(c);<a name="line.137"></a>
<FONT color="green">138</FONT> return classMap.getFieldNames();<a name="line.138"></a>
<FONT color="green">139</FONT> }<a name="line.139"></a>
<FONT color="green">140</FONT> <a name="line.140"></a>
<FONT color="green">141</FONT> /**<a name="line.141"></a>
<FONT color="green">142</FONT> * Gets the array of accessible methods names known for a given class.<a name="line.142"></a>
<FONT color="green">143</FONT> * @param c the class<a name="line.143"></a>
<FONT color="green">144</FONT> * @return the class method names<a name="line.144"></a>
<FONT color="green">145</FONT> */<a name="line.145"></a>
<FONT color="green">146</FONT> public String[] getMethodNames(Class<?> c) {<a name="line.146"></a>
<FONT color="green">147</FONT> if (c == null) {<a name="line.147"></a>
<FONT color="green">148</FONT> return new String[0];<a name="line.148"></a>
<FONT color="green">149</FONT> }<a name="line.149"></a>
<FONT color="green">150</FONT> ClassMap classMap = getMap(c);<a name="line.150"></a>
<FONT color="green">151</FONT> return classMap.getMethodNames();<a name="line.151"></a>
<FONT color="green">152</FONT> }<a name="line.152"></a>
<FONT color="green">153</FONT> <a name="line.153"></a>
<FONT color="green">154</FONT> /**<a name="line.154"></a>
<FONT color="green">155</FONT> * Gets the array of accessible method known for a given class.<a name="line.155"></a>
<FONT color="green">156</FONT> * @param c the class<a name="line.156"></a>
<FONT color="green">157</FONT> * @param methodName the method name<a name="line.157"></a>
<FONT color="green">158</FONT> * @return the array of methods (null or not empty)<a name="line.158"></a>
<FONT color="green">159</FONT> */<a name="line.159"></a>
<FONT color="green">160</FONT> public Method[] getMethods(Class<?> c, String methodName) {<a name="line.160"></a>
<FONT color="green">161</FONT> if (c == null) {<a name="line.161"></a>
<FONT color="green">162</FONT> return null;<a name="line.162"></a>
<FONT color="green">163</FONT> }<a name="line.163"></a>
<FONT color="green">164</FONT> ClassMap classMap = getMap(c);<a name="line.164"></a>
<FONT color="green">165</FONT> return classMap.get(methodName);<a name="line.165"></a>
<FONT color="green">166</FONT> }<a name="line.166"></a>
<FONT color="green">167</FONT> <a name="line.167"></a>
<FONT color="green">168</FONT> /**<a name="line.168"></a>
<FONT color="green">169</FONT> * A Constructor get cache-miss.<a name="line.169"></a>
<FONT color="green">170</FONT> */<a name="line.170"></a>
<FONT color="green">171</FONT> private static class CacheMiss {<a name="line.171"></a>
<FONT color="green">172</FONT> /** The constructor used as cache-miss. */<a name="line.172"></a>
<FONT color="green">173</FONT> @SuppressWarnings("unused")<a name="line.173"></a>
<FONT color="green">174</FONT> public CacheMiss() {}<a name="line.174"></a>
<FONT color="green">175</FONT> }<a name="line.175"></a>
<FONT color="green">176</FONT> <a name="line.176"></a>
<FONT color="green">177</FONT> /** The cache-miss marker for the constructors map. */<a name="line.177"></a>
<FONT color="green">178</FONT> private static final Constructor<?> CTOR_MISS = CacheMiss.class.getConstructors()[0];<a name="line.178"></a>
<FONT color="green">179</FONT> <a name="line.179"></a>
<FONT color="green">180</FONT> /**<a name="line.180"></a>
<FONT color="green">181</FONT> * Sets the class loader used to solve constructors.<a name="line.181"></a>
<FONT color="green">182</FONT> * <p>Also cleans the constructors and methods caches.</p><a name="line.182"></a>
<FONT color="green">183</FONT> * @param cloader the class loader; if null, use this instance class loader<a name="line.183"></a>
<FONT color="green">184</FONT> */<a name="line.184"></a>
<FONT color="green">185</FONT> public void setLoader(ClassLoader cloader) {<a name="line.185"></a>
<FONT color="green">186</FONT> ClassLoader previous = loader;<a name="line.186"></a>
<FONT color="green">187</FONT> if (cloader == null) {<a name="line.187"></a>
<FONT color="green">188</FONT> cloader = getClass().getClassLoader();<a name="line.188"></a>
<FONT color="green">189</FONT> }<a name="line.189"></a>
<FONT color="green">190</FONT> if (!cloader.equals(loader)) {<a name="line.190"></a>
<FONT color="green">191</FONT> // clean up constructor and class maps<a name="line.191"></a>
<FONT color="green">192</FONT> synchronized (constructorsMap) {<a name="line.192"></a>
<FONT color="green">193</FONT> Iterator<Map.Entry<MethodKey, Constructor<?>>> entries = constructorsMap.entrySet().iterator();<a name="line.193"></a>
<FONT color="green">194</FONT> while (entries.hasNext()) {<a name="line.194"></a>
<FONT color="green">195</FONT> Map.Entry<MethodKey, Constructor<?>> entry = entries.next();<a name="line.195"></a>
<FONT color="green">196</FONT> Class<?> clazz = entry.getValue().getDeclaringClass();<a name="line.196"></a>
<FONT color="green">197</FONT> if (isLoadedBy(previous, clazz)) {<a name="line.197"></a>
<FONT color="green">198</FONT> entries.remove();<a name="line.198"></a>
<FONT color="green">199</FONT> // the method name is the name of the class<a name="line.199"></a>
<FONT color="green">200</FONT> constructibleClasses.remove(entry.getKey().getMethod());<a name="line.200"></a>
<FONT color="green">201</FONT> }<a name="line.201"></a>
<FONT color="green">202</FONT> }<a name="line.202"></a>
<FONT color="green">203</FONT> }<a name="line.203"></a>
<FONT color="green">204</FONT> // clean up method maps<a name="line.204"></a>
<FONT color="green">205</FONT> synchronized (classMethodMaps) {<a name="line.205"></a>
<FONT color="green">206</FONT> Iterator<Map.Entry<Class<?>, ClassMap>> entries = classMethodMaps.entrySet().iterator();<a name="line.206"></a>
<FONT color="green">207</FONT> while (entries.hasNext()) {<a name="line.207"></a>
<FONT color="green">208</FONT> Map.Entry<Class<?>, ClassMap> entry = entries.next();<a name="line.208"></a>
<FONT color="green">209</FONT> Class<?> clazz = entry.getKey();<a name="line.209"></a>
<FONT color="green">210</FONT> if (isLoadedBy(previous, clazz)) {<a name="line.210"></a>
<FONT color="green">211</FONT> entries.remove();<a name="line.211"></a>
<FONT color="green">212</FONT> }<a name="line.212"></a>
<FONT color="green">213</FONT> }<a name="line.213"></a>
<FONT color="green">214</FONT> }<a name="line.214"></a>
<FONT color="green">215</FONT> loader = cloader;<a name="line.215"></a>
<FONT color="green">216</FONT> }<a name="line.216"></a>
<FONT color="green">217</FONT> }<a name="line.217"></a>
<FONT color="green">218</FONT> <a name="line.218"></a>
<FONT color="green">219</FONT> /**<a name="line.219"></a>
<FONT color="green">220</FONT> * Checks whether a class is loaded through a given class loader or one of its ascendants.<a name="line.220"></a>
<FONT color="green">221</FONT> * @param loader the class loader<a name="line.221"></a>
<FONT color="green">222</FONT> * @param clazz the class to check<a name="line.222"></a>
<FONT color="green">223</FONT> * @return true if clazz was loaded through the loader, false otherwise<a name="line.223"></a>
<FONT color="green">224</FONT> */<a name="line.224"></a>
<FONT color="green">225</FONT> private static boolean isLoadedBy(ClassLoader loader, Class<?> clazz) {<a name="line.225"></a>
<FONT color="green">226</FONT> if (loader != null) {<a name="line.226"></a>
<FONT color="green">227</FONT> ClassLoader cloader = clazz.getClassLoader();<a name="line.227"></a>
<FONT color="green">228</FONT> while (cloader != null) {<a name="line.228"></a>
<FONT color="green">229</FONT> if (cloader.equals(loader)) {<a name="line.229"></a>
<FONT color="green">230</FONT> return true;<a name="line.230"></a>
<FONT color="green">231</FONT> } else {<a name="line.231"></a>
<FONT color="green">232</FONT> cloader = cloader.getParent();<a name="line.232"></a>
<FONT color="green">233</FONT> }<a name="line.233"></a>
<FONT color="green">234</FONT> }<a name="line.234"></a>
<FONT color="green">235</FONT> }<a name="line.235"></a>
<FONT color="green">236</FONT> return false;<a name="line.236"></a>
<FONT color="green">237</FONT> }<a name="line.237"></a>
<FONT color="green">238</FONT> <a name="line.238"></a>
<FONT color="green">239</FONT> /**<a name="line.239"></a>
<FONT color="green">240</FONT> * Gets the constructor defined by the <code>MethodKey</code>.<a name="line.240"></a>
<FONT color="green">241</FONT> *<a name="line.241"></a>
<FONT color="green">242</FONT> * @param key Key of the constructor being searched for<a name="line.242"></a>
<FONT color="green">243</FONT> * @return The desired constructor object<a name="line.243"></a>
<FONT color="green">244</FONT> * or null if no unambiguous constructor could be found through introspection.<a name="line.244"></a>
<FONT color="green">245</FONT> */<a name="line.245"></a>
<FONT color="green">246</FONT> public Constructor<?> getConstructor(final MethodKey key) {<a name="line.246"></a>
<FONT color="green">247</FONT> return getConstructor(null, key);<a name="line.247"></a>
<FONT color="green">248</FONT> }<a name="line.248"></a>
<FONT color="green">249</FONT> <a name="line.249"></a>
<FONT color="green">250</FONT> /**<a name="line.250"></a>
<FONT color="green">251</FONT> * Gets the constructor defined by the <code>MethodKey</code>.<a name="line.251"></a>
<FONT color="green">252</FONT> * @param c the class we want to instantiate<a name="line.252"></a>
<FONT color="green">253</FONT> * @param key Key of the constructor being searched for<a name="line.253"></a>
<FONT color="green">254</FONT> * @return The desired constructor object<a name="line.254"></a>
<FONT color="green">255</FONT> * or null if no unambiguous constructor could be found through introspection.<a name="line.255"></a>
<FONT color="green">256</FONT> */<a name="line.256"></a>
<FONT color="green">257</FONT> public Constructor<?> getConstructor(final Class<?> c, final MethodKey key) {<a name="line.257"></a>
<FONT color="green">258</FONT> Constructor<?> ctor = null;<a name="line.258"></a>
<FONT color="green">259</FONT> synchronized (constructorsMap) {<a name="line.259"></a>
<FONT color="green">260</FONT> ctor = constructorsMap.get(key);<a name="line.260"></a>
<FONT color="green">261</FONT> // that's a clear miss<a name="line.261"></a>
<FONT color="green">262</FONT> if (CTOR_MISS.equals(ctor)) {<a name="line.262"></a>
<FONT color="green">263</FONT> return null;<a name="line.263"></a>
<FONT color="green">264</FONT> }<a name="line.264"></a>
<FONT color="green">265</FONT> // let's introspect...<a name="line.265"></a>
<FONT color="green">266</FONT> if (ctor == null) {<a name="line.266"></a>
<FONT color="green">267</FONT> final String cname = key.getMethod();<a name="line.267"></a>
<FONT color="green">268</FONT> // do we know about this class?<a name="line.268"></a>
<FONT color="green">269</FONT> Class<?> clazz = constructibleClasses.get(cname);<a name="line.269"></a>
<FONT color="green">270</FONT> try {<a name="line.270"></a>
<FONT color="green">271</FONT> // do find the most specific ctor<a name="line.271"></a>
<FONT color="green">272</FONT> if (clazz == null) {<a name="line.272"></a>
<FONT color="green">273</FONT> if (c != null && c.getName().equals(key.getMethod())) {<a name="line.273"></a>
<FONT color="green">274</FONT> clazz = c;<a name="line.274"></a>
<FONT color="green">275</FONT> } else {<a name="line.275"></a>
<FONT color="green">276</FONT> clazz = loader.loadClass(cname);<a name="line.276"></a>
<FONT color="green">277</FONT> }<a name="line.277"></a>
<FONT color="green">278</FONT> // add it to list of known loaded classes<a name="line.278"></a>
<FONT color="green">279</FONT> constructibleClasses.put(cname, clazz);<a name="line.279"></a>
<FONT color="green">280</FONT> }<a name="line.280"></a>
<FONT color="green">281</FONT> List<Constructor<?>> l = new LinkedList<Constructor<?>>();<a name="line.281"></a>
<FONT color="green">282</FONT> for (Constructor<?> ictor : clazz.getConstructors()) {<a name="line.282"></a>
<FONT color="green">283</FONT> l.add(ictor);<a name="line.283"></a>
<FONT color="green">284</FONT> }<a name="line.284"></a>
<FONT color="green">285</FONT> // try to find one<a name="line.285"></a>
<FONT color="green">286</FONT> ctor = key.getMostSpecificConstructor(l);<a name="line.286"></a>
<FONT color="green">287</FONT> if (ctor != null) {<a name="line.287"></a>
<FONT color="green">288</FONT> constructorsMap.put(key, ctor);<a name="line.288"></a>
<FONT color="green">289</FONT> } else {<a name="line.289"></a>
<FONT color="green">290</FONT> constructorsMap.put(key, CTOR_MISS);<a name="line.290"></a>
<FONT color="green">291</FONT> }<a name="line.291"></a>
<FONT color="green">292</FONT> } catch (ClassNotFoundException xnotfound) {<a name="line.292"></a>
<FONT color="green">293</FONT> if (rlog != null && rlog.isInfoEnabled()) {<a name="line.293"></a>
<FONT color="green">294</FONT> rlog.info("unable to find class: "<a name="line.294"></a>
<FONT color="green">295</FONT> + cname + "."<a name="line.295"></a>
<FONT color="green">296</FONT> + key.debugString(), xnotfound);<a name="line.296"></a>
<FONT color="green">297</FONT> }<a name="line.297"></a>
<FONT color="green">298</FONT> ctor = null;<a name="line.298"></a>
<FONT color="green">299</FONT> } catch (MethodKey.AmbiguousException xambiguous) {<a name="line.299"></a>
<FONT color="green">300</FONT> if (rlog != null && rlog.isInfoEnabled()) {<a name="line.300"></a>
<FONT color="green">301</FONT> rlog.info("ambiguous constructor invocation: "<a name="line.301"></a>
<FONT color="green">302</FONT> + cname + "."<a name="line.302"></a>
<FONT color="green">303</FONT> + key.debugString(), xambiguous);<a name="line.303"></a>
<FONT color="green">304</FONT> }<a name="line.304"></a>
<FONT color="green">305</FONT> ctor = null;<a name="line.305"></a>
<FONT color="green">306</FONT> }<a name="line.306"></a>
<FONT color="green">307</FONT> }<a name="line.307"></a>
<FONT color="green">308</FONT> return ctor;<a name="line.308"></a>
<FONT color="green">309</FONT> }<a name="line.309"></a>
<FONT color="green">310</FONT> }<a name="line.310"></a>
<FONT color="green">311</FONT> <a name="line.311"></a>
<FONT color="green">312</FONT> /**<a name="line.312"></a>
<FONT color="green">313</FONT> * Gets the ClassMap for a given class.<a name="line.313"></a>
<FONT color="green">314</FONT> * @param c the class<a name="line.314"></a>
<FONT color="green">315</FONT> * @return the class map<a name="line.315"></a>
<FONT color="green">316</FONT> */<a name="line.316"></a>
<FONT color="green">317</FONT> private ClassMap getMap(Class<?> c) {<a name="line.317"></a>
<FONT color="green">318</FONT> synchronized (classMethodMaps) {<a name="line.318"></a>
<FONT color="green">319</FONT> ClassMap classMap = classMethodMaps.get(c);<a name="line.319"></a>
<FONT color="green">320</FONT> if (classMap == null) {<a name="line.320"></a>
<FONT color="green">321</FONT> classMap = new ClassMap(c, rlog);<a name="line.321"></a>
<FONT color="green">322</FONT> classMethodMaps.put(c, classMap);<a name="line.322"></a>
<FONT color="green">323</FONT> }<a name="line.323"></a>
<FONT color="green">324</FONT> return classMap;<a name="line.324"></a>
<FONT color="green">325</FONT> }<a name="line.325"></a>
<FONT color="green">326</FONT> }<a name="line.326"></a>
<FONT color="green">327</FONT> }<a name="line.327"></a>
</PRE>
</BODY>
</HTML>
| azyobuzin/JexlSample | assets/commons-jexl-2.1.1/apidocs/src-html/org/apache/commons/jexl2/internal/introspection/IntrospectorBase.html | HTML | mit | 31,155 |
/* Tomorrow Night Theme */
/* https://jmblog.github.com/color-themes-for-google-code-highlightjs */
/* Original theme - https://github.com/chriskempson/tomorrow-theme */
/* https://jmblog.github.com/color-themes-for-google-code-highlightjs */
/* Tomorrow Comment */
.hljs-comment {
color: #969896;
}
/* Tomorrow Red */
.hljs-variable,
.hljs-attribute,
.hljs-tag,
.hljs-regexp,
.ruby .hljs-constant,
.xml .hljs-tag .hljs-title,
.xml .hljs-pi,
.xml .hljs-doctype,
.html .hljs-doctype,
.css .hljs-id,
.css .hljs-class,
.css .hljs-pseudo {
color: #cc6666;
}
/* Tomorrow Orange */
.hljs-number,
.hljs-preprocessor,
.hljs-pragma,
.hljs-built_in,
.hljs-literal,
.hljs-params,
.hljs-constant {
color: #de935f;
}
/* Tomorrow Yellow */
.ruby .hljs-class .hljs-title,
.css .hljs-rule .hljs-attribute {
color: #f0c674;
}
/* Tomorrow Green */
.hljs-string,
.hljs-value,
.hljs-inheritance,
.hljs-header,
.hljs-name,
.ruby .hljs-symbol,
.xml .hljs-cdata {
color: #b5bd68;
}
/* Tomorrow Aqua */
.hljs-title,
.css .hljs-hexcolor {
color: #8abeb7;
}
/* Tomorrow Blue */
.hljs-function,
.python .hljs-decorator,
.python .hljs-title,
.ruby .hljs-function .hljs-title,
.ruby .hljs-title .hljs-keyword,
.perl .hljs-sub,
.javascript .hljs-title,
.coffeescript .hljs-title {
color: #81a2be;
}
/* Tomorrow Purple */
.hljs-keyword,
.javascript .hljs-function {
color: #b294bb;
}
.hljs {
display: block;
overflow-x: auto;
background: #1d1f21;
color: #c5c8c6;
padding: 0.5em;
-webkit-text-size-adjust: none;
}
.coffeescript .javascript,
.javascript .xml,
.tex .hljs-formula,
.xml .javascript,
.xml .vbscript,
.xml .css,
.xml .hljs-cdata {
opacity: 0.5;
}
| narcan/narcan.github.io | assets/vendor/highlight/styles/tomorrow-night.css | CSS | mit | 1,667 |
'use strict';
describe('Suite', function suiteName() {
it('should finish immediately', function testCase1Name() {});
it('should finish after 100ms', function testCase2Name(done) { setTimeout(done, 100); });
it('should fail', function testCase3Name() { throw new Error('foo'); });
});
| mmotkina/mocha-parallel-tests | test/reporter-custom-mochawesome/suite.js | JavaScript | mit | 297 |
THIS_SRCS = longjmp.s setjmp.s
include $(MENUET_LIBC_TOPDIR)/Make.rules
| devlato/kolibrios-llvm | programs/develop/libraries/menuetlibc/src/libc/ansi/setjmp/Makefile | Makefile | mit | 73 |
/****************************************************************************
*
* Open Watcom Project
*
* Portions Copyright (c) 1983-2002 Sybase, Inc. All Rights Reserved.
*
* ========================================================================
*
* This file contains Original Code and/or Modifications of Original
* Code as defined in and that are subject to the Sybase Open Watcom
* Public License version 1.0 (the 'License'). You may not use this file
* except in compliance with the License. BY USING THIS FILE YOU AGREE TO
* ALL TERMS AND CONDITIONS OF THE LICENSE. A copy of the License is
* provided with the Original Code and Modifications, and is also
* available at www.sybase.com/developer/opensource.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND SYBASE AND ALL CONTRIBUTORS HEREBY DISCLAIM
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR
* NON-INFRINGEMENT. Please see the License for the specific language
* governing rights and limitations under the License.
*
* ========================================================================
*
* Description: WHEN YOU FIGURE OUT WHAT THIS FILE DOES, PLEASE
* DESCRIBE IT HERE!
*
****************************************************************************/
#include "variety.h"
#include <mbstring.h>
#include "rtinit.h"
_WCRTLINKD int __IsDBCS;
| devlato/kolibrios-llvm | programs/develop/open watcom/trunk/clib/mbyte/mbisdbcs.c | C | mit | 1,638 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Profile extends CI_Controller {
public function __construct()
{
parent::__construct();
{
//inlcude a better hashing library
include('./resources/password/password.php');
if($this->session->userdata('isloggedin')=='1')
{
$this->load->model('Stuff_permissions');
$pass = $this->Stuff_permissions->has_permission("profile");
if($pass != true)
{
redirect('admin/dashboard','refresh');
}
}
else
{
redirect('admin/installer','refresh');
}
}
}
/**
* @Description: Save first and last name and password reset
* @Params: params
*
* @returns: returns
*/
public function index()
{
$userid = $this->session->userdata('userid');
$this->db->select('*');
$this->db->from('user');
$this->db->where('id', $userid);
$this->db->limit(1);
$query = $this->db->get();
$data['query'] = $query;
$this->load->view('admin/header');
$this->load->view('admin/body');
$this->load->view('admin/profile/profile-view', $data);
$this->load->view('admin/footer');
}
public function save_profile()
{
$id = $this->session->userdata('userid');
//save the details to the database
$fullname = $this->input->post('fullname');
//to check email is not duplicated
$email = $this->input->post('email');
$password = $this->input->post('password');
//doesn't require a password change
if(strlen($password) == 0)
{
$object = array('fullname' => $fullname, 'email' => $email );
$this->db->where('id', $id);
$this->db->update('user', $object);
redirect("admin/profile","refresh");
}
else{
if($this->check_password($password) == true)
{
//password is ok
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
$object2 = array('password' => $hashed_password,'fullname' => $fullname, 'email' => $email );
$this->db->where('id', $id);
$this->db->update('user', $object2);
$this->session->set_flashdata('type', '1');
$this->session->set_flashdata('msg', '<strong>Success</strong> Password updated!');
redirect("admin/profile","refresh");
}
else
{
$errors =
'Password is too simple <br/>
Password must contain a number and Uppercase letter!<br/>
Password must be at least 6 characters long';
$this->session->set_flashdata('type', '0');
$this->session->set_flashdata('msg', "<strong>Failed</strong> $errors");
redirect("admin/profile","refresh");
}
}
}
/**
* @Description: make sure password is secure
* One number and Upper case letter
* @Params: params
*
* @returns: returns
*/
public function check_password($pwd)
{
$error ="";
if( strlen($pwd) < 6 )
{
$error .= "Password too short! ";
}
if( !preg_match("#[0-9]+#", $pwd) )
{
$error .= "Password must include at least one number! ";
}
if( !preg_match("#[a-zA-z]+#", $pwd) )
{
$error .= "Password must include at least one letter! ";
}
if($error)
{
return false;
}
else
{
return true;
}
}
}
/* End of file profile.php */
/* Location: ./application/controllers/profile.php */ | ignitedcms/ignitedcms | application/controllers/admin/Profile.php | PHP | mit | 3,581 |
<div class="mat-calendar-header">
<div class="mat-calendar-controls">
<button mat-button type="button" class="mat-calendar-period-button"
(click)="currentPeriodClicked()" [attr.aria-label]="periodButtonLabel"
[attr.aria-describedby]="_buttonDescriptionId"
cdkAriaLive="polite">
<span [attr.id]="_buttonDescriptionId">{{periodButtonText}}</span>
<svg class="mat-calendar-arrow" [class.mat-calendar-invert]="calendar.currentView !== 'month'"
viewBox="0 0 10 5" focusable="false">
<polygon points="0,0 5,5 10,0"/>
</svg>
</button>
<div class="mat-calendar-spacer"></div>
<ng-content></ng-content>
<button mat-icon-button type="button" class="mat-calendar-previous-button"
[disabled]="!previousEnabled()" (click)="previousClicked()"
[attr.aria-label]="prevButtonLabel">
</button>
<button mat-icon-button type="button" class="mat-calendar-next-button"
[disabled]="!nextEnabled()" (click)="nextClicked()"
[attr.aria-label]="nextButtonLabel">
</button>
</div>
</div>
| josephperrott/material2 | src/material/datepicker/calendar-header.html | HTML | mit | 1,124 |
<?php
declare(strict_types=1);
/**
* This file is part of Narrowspark Framework.
*
* (c) Daniel Bannert <d.bannert@anolilab.de>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Viserio\Contract\Cookie;
interface Factory
{
/**
* Create a new cookie instance.
*
* @param string $name
* @param null|string $value
* @param int $second
* @param null|string $path
* @param null|string $domain
* @param bool $secure
* @param bool $httpOnly
* @param null|bool|string $sameSite
*
* @return \Viserio\Contract\Cookie\Cookie
*/
public function create(
string $name,
?string $value = null,
int $second = 0,
?string $path = null,
?string $domain = null,
bool $secure = false,
bool $httpOnly = true,
$sameSite = false
): Cookie;
/**
* Create a cookie that lasts "forever" (five years).
*
* @param string $name
* @param null|string $value
* @param null|string $path
* @param null|string $domain
* @param bool $secure
* @param bool $httpOnly
* @param null|bool|string $sameSite
*
* @return \Viserio\Contract\Cookie\Cookie
*/
public function forever(
string $name,
?string $value = null,
?string $path = null,
?string $domain = null,
bool $secure = false,
bool $httpOnly = true,
$sameSite = false
): Cookie;
/**
* Expire the given cookie.
*
* @param string $name
* @param null|string $path
* @param null|string $domain
*
* @return \Viserio\Contract\Cookie\Cookie
*/
public function delete(string $name, ?string $path = null, ?string $domain = null): Cookie;
}
| narrowspark/framework | src/Viserio/Contract/Cookie/Factory.php | PHP | mit | 1,964 |
<?php
/**
* @package framework
* @copyright Copyright 2005-2019 HUBzero Foundation, LLC.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Hubzero\Config\Tests\Processor;
use Hubzero\Test\Basic;
use Hubzero\Config\Processor\Ini;
use stdClass;
/**
* Ini Processor tests
*/
class IniTest extends Basic
{
/**
* Format processor
*
* @var object
*/
private $processor = null;
/**
* Expected data as an object
*
* @var object
*/
private $obj = null;
/**
* Expected data as an array
*
* @var array
*/
private $arr = null;
/**
* Expected data as a string
*
* @var string
*/
private $str = '
[app]
application_env="development"
editor="ckeditor"
list_limit=25
helpurl="English (GB) - HUBzero help"
debug=1
debug_lang=0
sef=1
sef_rewrite=1
sef_suffix=0
sef_groups=0
feed_limit=10
feed_email="author"
gzip=true
unicodeslugs=false
version=2.2
[seo]
sef=1
sef_groups=0
sef_rewrite=1
sef_suffix=0
unicodeslugs=0
sitename_pagetitles=0';
/**
* Test setup
*
* @return void
**/
protected function setUp()
{
$data = new stdClass();
$data->app = new stdClass();
$data->app->application_env = "development";
$data->app->editor = "ckeditor";
$data->app->list_limit = 25;
$data->app->helpurl = "English (GB) - HUBzero help";
$data->app->debug = 1;
$data->app->debug_lang = 0;
$data->app->sef = 1;
$data->app->sef_rewrite = 1;
$data->app->sef_suffix = 0;
$data->app->sef_groups = 0;
$data->app->feed_limit = 10;
$data->app->feed_email = "author";
$data->app->gzip = true;
$data->app->unicodeslugs = false;
$data->app->version = 2.2;
$data->seo = new stdClass();
$data->seo->sef = 1;
$data->seo->sef_groups = 0;
$data->seo->sef_rewrite = 1;
$data->seo->sef_suffix = 0;
$data->seo->unicodeslugs = 0;
$data->seo->sitename_pagetitles = 0;
$this->obj = $data;
$this->arr = array(
'app' => (array)$data->app,
'seo' => (array)$data->seo
);
$this->processor = new Ini();
parent::setUp();
}
/**
* Tests the getSupportedExtensions() method.
*
* @covers \Hubzero\Config\Processor\Ini::getSupportedExtensions
* @return void
**/
public function testGetSupportedExtensions()
{
$extensions = $this->processor->getSupportedExtensions();
$this->assertTrue(is_array($extensions));
$this->assertCount(1, $extensions);
$this->assertTrue(in_array('ini', $extensions));
}
/**
* Tests the canParse() method.
*
* @covers \Hubzero\Config\Processor\Ini::canParse
* @return void
**/
public function testCanParse()
{
$this->assertFalse($this->processor->canParse('Cras justo odio, dapibus ac facilisis in, egestas eget quam.'));
$this->assertFalse($this->processor->canParse('{"application_env":"development","editor":"ck = editor","list_limit":"25"}'));
$this->assertFalse($this->processor->canParse('<foo att=="val">Cras justo odio dapibus ac facilisis in, egestas eget quam.</foo>'));
$this->assertTrue($this->processor->canParse($this->str));
}
/**
* Tests the parse() method.
*
* @covers \Hubzero\Config\Processor\Ini::parse
* @return void
**/
public function testParse()
{
$result = $this->processor->parse(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Files' . DIRECTORY_SEPARATOR . 'test.ini');
$this->assertEquals($this->arr, $result);
$this->setExpectedException('Hubzero\Config\Exception\ParseException');
$result = $this->processor->parse(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Files' . DIRECTORY_SEPARATOR . 'test.xml');
}
/**
* Tests the objectToString() method.
*
* @covers \Hubzero\Config\Processor\Ini::objectToString
* @covers \Hubzero\Config\Processor\Ini::getValueAsINI
* @return void
**/
public function testObjectToString()
{
// Test that a string is returned as-is
$result = $this->processor->objectToString($this->str);
$this->assertEquals($this->str, $result);
// Test object to string conversion
$result = $this->processor->objectToString($this->obj);
$this->assertEquals($this->str, $result);
}
/**
* Tests the stringToObject() method.
*
* @covers \Hubzero\Config\Processor\Ini::stringToObject
* @return void
**/
public function testStringToObject()
{
// Test that an object is returned as-is
$result = $this->processor->stringToObject($this->obj, array('processSections' => true));
$this->assertEquals($this->obj, $result);
// Test that an empty string returns an empty stdClass object
$result = $this->processor->stringToObject('', array('processSections' => true));
$this->assertEquals(new stdClass, $result);
// Test that a string gets converted as expected
$result = $this->processor->stringToObject($this->str, array('processSections' => true));
$this->assertEquals($this->obj, $result);
// Test that a string gets converted as expected
$result = $this->processor->stringToObject($this->str, array('processSections' => false));
$data = new stdClass();
$data->application_env = "development";
$data->editor = "ckeditor";
$data->list_limit = 25;
$data->helpurl = "English (GB) - HUBzero help";
$data->debug = 1;
$data->debug_lang = 0;
$data->sef = 1;
$data->sef_rewrite = 1;
$data->sef_suffix = 0;
$data->sef_groups = 0;
$data->feed_limit = 10;
$data->feed_email = "author";
$data->gzip = true;
$data->unicodeslugs = false;
$data->version = 2.2;
$data->sef = 1;
$data->sef_groups = 0;
$data->sef_rewrite = 1;
$data->sef_suffix = 0;
$data->unicodeslugs = 0;
$data->sitename_pagetitles = 0;
$this->assertEquals($data, $result);
}
}
| zweidner/framework | src/Config/Tests/Processor/IniTest.php | PHP | mit | 5,575 |
/**
* TagController
*
* @description :: Server-side logic for managing Tags
*/
module.exports = {
find: (req,res) => {
Tag.findAll({
where: ActionUtil.parseWhere(req),
limit: ActionUtil.parseLimit(req),
offset: ActionUtil.parseSkip(req),
order: ActionUtil.parseSort(req),
include: [],
}).then((recordsFound) => {
return res.ok(recordsFound)
}).catch((err) => {
return res.serverError(err)
});
},
findOne: function(req,res){
const pk = ActionUtil.requirePk(req)
Tag.findById(pk, {
include: ActionUtil.parsePopulate(req)
}).then((recordFound) => {
if(!recordFound) return res.notFound('No record found with the specified `id`.')
res.ok(recordFound);
}).catch((err) => {
return res.serverError(err)
})
},
};
| badfuture/huoshui-backend-api | api/controllers/TagController.js | JavaScript | mit | 821 |
<?php
/**
* Hoa
*
*
* @license
*
* New BSD License
*
* Copyright © 2007-2015, Hoa community. 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 the Hoa 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 HOLDERS AND 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.
*/
namespace Hoa\Compiler\Llk\Rule;
/**
* Class \Hoa\Compiler\Llk\Rule\Invocation.
*
* Parent of entry and ekzit rules.
*
* @copyright Copyright © 2007-2015 Hoa community
* @license New BSD License
*/
abstract class Invocation
{
/**
* Rule.
*
* @var string
*/
protected $_rule = null;
/**
* Data.
*
* @var mixed
*/
protected $_data = null;
/**
* Piece of todo sequence.
*
* @var array
*/
protected $_todo = null;
/**
* Depth in the trace.
*
* @var int
*/
protected $_depth = -1;
/**
* Whether the rule is transitional or not (i.e. not declared in the grammar
* but created by the analyzer).
*
* @var bool
*/
protected $_transitional = false;
/**
* Constructor.
*
* @param string $rule Rule name.
* @param mixed $data Data.
* @param array $todo Todo.
* @param int $depth Depth.
* @return void
*/
public function __construct(
$rule,
$data,
Array $todo = null,
$depth = -1
) {
$this->_rule = $rule;
$this->_data = $data;
$this->_todo = $todo;
$this->_depth = $depth;
$this->_transitional = is_numeric($rule);
return;
}
/**
* Get rule name.
*
* @return string
*/
public function getRule()
{
return $this->_rule;
}
/**
* Get data.
*
* @return mixed
*/
public function getData()
{
return $this->_data;
}
/**
* Get todo sequence.
*
* @return array
*/
public function getTodo()
{
return $this->_todo;
}
/**
* Set depth in trace.
*
* @parma int $depth Depth.
* @return int
*/
public function setDepth($depth)
{
$old = $this->_depth;
$this->_depth = $depth;
return $old;
}
/**
* Get depth in trace.
*
* @return int
*/
public function getDepth()
{
return $this->_depth;
}
/**
* Check whether the rule is transitional or not.
*
* @return bool
*/
public function isTransitional()
{
return $this->_transitional;
}
}
| Halleck45/PhpMetricsZendServer | zray/vendor/hoa/compiler/Llk/Rule/Invocation.php | PHP | mit | 4,064 |
define(['angular'], function (ng) {
'use strict';
return ng.module('app.directives', []);
});
| prolativ/simulConf | public/js/directives/module.js | JavaScript | mit | 103 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Code Coverage for /Applications/XAMPP/xamppfiles/htdocs/printpbw/application/views/user/login.php</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-responsive.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="span12">
<ul class="breadcrumb">
<li><a href="index.html">/Applications/XAMPP/xamppfiles/htdocs/printpbw/application</a> <span class="divider">/</span></li>
<li><a href="views.html">views</a> <span class="divider">/</span></li>
<li><a href="views_user.html">user</a> <span class="divider">/</span></li>
<li class="active">login.php</li>
</ul>
</div>
</div>
</div>
</header>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<td> </td>
<td colspan="10"><div align="center"><strong>Code Coverage</strong></div></td>
</tr>
<tr>
<td> </td>
<td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
<td colspan="4"><div align="center"><strong>Functions and Methods</strong></div></td>
<td colspan="3"><div align="center"><strong>Lines</strong></div></td>
</tr>
</thead>
<tbody>
<tr>
<td class="None">Total</td>
<td class="None big"> </td>
<td class="None small"><div align="right"></div></td>
<td class="None small"><div align="right"> </div></td>
<td class="None big"> </td>
<td class="None small"><div align="right"></div></td>
<td class="None small"><div align="right"> </div></td>
<td class="None small"><acronym title="Change Risk Anti-Patterns (CRAP) Index">CRAP</acronym></td>
<td class="success big"> <div class="progress progress-success" style="width: 100px;">
<div class="bar" style="width: 100.00%;"></div>
</div>
</td>
<td class="success small"><div align="right">100.00%</div></td>
<td class="success small"><div align="right">1 / 1</div></td>
</tr>
</tbody>
</table>
<table class="table table-borderless table-condensed">
<tbody>
<tr class="success popin" data-title="1 test covers line 1" data-content="<ul><li class="success">Welcome_test::test_indexlogin</li></ul>" data-placement="bottom" data-html="true"><td><div align="right"><a name="1"></a><a href="#1">1</a></div></td><td class="codeLine"><!doctype html></td></tr>
<tr><td><div align="right"><a name="2"></a><a href="#2">2</a></div></td><td class="codeLine"><html></td></tr>
<tr><td><div align="right"><a name="3"></a><a href="#3">3</a></div></td><td class="codeLine"> <head></td></tr>
<tr><td><div align="right"><a name="4"></a><a href="#4">4</a></div></td><td class="codeLine"> <meta charset="utf-8"></td></tr>
<tr><td><div align="right"><a name="5"></a><a href="#5">5</a></div></td><td class="codeLine"> <meta name="viewport" content="width=device-width, maximum-scale=1"></td></tr>
<tr><td><div align="right"><a name="6"></a><a href="#6">6</a></div></td><td class="codeLine"> <title>Print-in - Log In</title></td></tr>
<tr><td><div align="right"><a name="7"></a><a href="#7">7</a></div></td><td class="codeLine"> <link rel="icon" href="favicon.png" type="image/png"></td></tr>
<tr><td><div align="right"><a name="8"></a><a href="#8">8</a></div></td><td class="codeLine"> <link href="<?php echo base_url ('assets/css/bootstrap.css') ?>" rel="stylesheet" type="text/css"></td></tr>
<tr><td><div align="right"><a name="9"></a><a href="#9">9</a></div></td><td class="codeLine"> <link href="<?php echo base_url ('assets/css/style.css') ?>" rel="stylesheet" type="text/css"></td></tr>
<tr><td><div align="right"><a name="10"></a><a href="#10">10</a></div></td><td class="codeLine"> <link href="<?php echo base_url ('assets/css/linecons.css') ?>" rel="stylesheet" type="text/css"></td></tr>
<tr><td><div align="right"><a name="11"></a><a href="#11">11</a></div></td><td class="codeLine"> <link href="<?php echo base_url ('assets/css/font-awesome.css') ?>" rel="stylesheet" type="text/css"></td></tr>
<tr><td><div align="right"><a name="12"></a><a href="#12">12</a></div></td><td class="codeLine"> <link href="<?php echo base_url ('assets/css/responsive.css') ?>" rel="stylesheet" type="text/css"></td></tr>
<tr><td><div align="right"><a name="13"></a><a href="#13">13</a></div></td><td class="codeLine"> <link href="<?php echo base_url ('assets/css/animate.css') ?>" rel="stylesheet" type="text/css"></td></tr>
<tr><td><div align="right"><a name="14"></a><a href="#14">14</a></div></td><td class="codeLine"> <link href='https://fonts.googleapis.com/css?family=Lato:400,900,700,700italic,400italic,300italic,300,100italic,100,900italic' rel='stylesheet' type='text/css'></td></tr>
<tr><td><div align="right"><a name="15"></a><a href="#15">15</a></div></td><td class="codeLine"> <link href='https://fonts.googleapis.com/css?family=Dosis:400,500,700,800,600,300,200' rel='stylesheet' type='text/css'></td></tr>
<tr><td><div align="right"><a name="16"></a><a href="#16">16</a></div></td><td class="codeLine"> <!-- =======================================================</td></tr>
<tr><td><div align="right"><a name="17"></a><a href="#17">17</a></div></td><td class="codeLine"> Theme Name: Butterfly</td></tr>
<tr><td><div align="right"><a name="18"></a><a href="#18">18</a></div></td><td class="codeLine"> Theme URL: https://bootstrapmade.com/butterfly-free-bootstrap-theme/</td></tr>
<tr><td><div align="right"><a name="19"></a><a href="#19">19</a></div></td><td class="codeLine"> Author: BootstrapMade</td></tr>
<tr><td><div align="right"><a name="20"></a><a href="#20">20</a></div></td><td class="codeLine"> Author URL: https://bootstrapmade.com</td></tr>
<tr><td><div align="right"><a name="21"></a><a href="#21">21</a></div></td><td class="codeLine"> ======================================================= --></td></tr>
<tr><td><div align="right"><a name="22"></a><a href="#22">22</a></div></td><td class="codeLine"> <script type="text/javascript" src="js/jquery.1.8.3.min.js"></script></td></tr>
<tr><td><div align="right"><a name="23"></a><a href="#23">23</a></div></td><td class="codeLine"> <script type="text/javascript" src="js/bootstrap.js"></script></td></tr>
<tr><td><div align="right"><a name="24"></a><a href="#24">24</a></div></td><td class="codeLine"> <script type="text/javascript" src="js/jquery-scrolltofixed.js"></script></td></tr>
<tr><td><div align="right"><a name="25"></a><a href="#25">25</a></div></td><td class="codeLine"> <script type="text/javascript" src="js/jquery.easing.1.3.js"></script></td></tr>
<tr><td><div align="right"><a name="26"></a><a href="#26">26</a></div></td><td class="codeLine"> <script type="text/javascript" src="js/jquery.isotope.js"></script></td></tr>
<tr><td><div align="right"><a name="27"></a><a href="#27">27</a></div></td><td class="codeLine"> <script type="text/javascript" src="js/wow.js"></script></td></tr>
<tr><td><div align="right"><a name="28"></a><a href="#28">28</a></div></td><td class="codeLine"> <script type="text/javascript" src="js/classie.js"></script></td></tr>
<tr><td><div align="right"><a name="29"></a><a href="#29">29</a></div></td><td class="codeLine"> <script type="text/javascript"></td></tr>
<tr><td><div align="right"><a name="30"></a><a href="#30">30</a></div></td><td class="codeLine"> $(document).ready(function(e) {</td></tr>
<tr><td><div align="right"><a name="31"></a><a href="#31">31</a></div></td><td class="codeLine"> $('.res-nav_click').click(function(){</td></tr>
<tr><td><div align="right"><a name="32"></a><a href="#32">32</a></div></td><td class="codeLine"> $('ul.toggle').slideToggle(600)</td></tr>
<tr><td><div align="right"><a name="33"></a><a href="#33">33</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="34"></a><a href="#34">34</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="35"></a><a href="#35">35</a></div></td><td class="codeLine"> $(document).ready(function() {</td></tr>
<tr><td><div align="right"><a name="36"></a><a href="#36">36</a></div></td><td class="codeLine">$(window).bind('scroll', function() {</td></tr>
<tr><td><div align="right"><a name="37"></a><a href="#37">37</a></div></td><td class="codeLine"> if ($(window).scrollTop() > 0) {</td></tr>
<tr><td><div align="right"><a name="38"></a><a href="#38">38</a></div></td><td class="codeLine"> $('#header_outer').addClass('fixed');</td></tr>
<tr><td><div align="right"><a name="39"></a><a href="#39">39</a></div></td><td class="codeLine"> }</td></tr>
<tr><td><div align="right"><a name="40"></a><a href="#40">40</a></div></td><td class="codeLine"> else {</td></tr>
<tr><td><div align="right"><a name="41"></a><a href="#41">41</a></div></td><td class="codeLine"> $('#header_outer').removeClass('fixed');</td></tr>
<tr><td><div align="right"><a name="42"></a><a href="#42">42</a></div></td><td class="codeLine"> }</td></tr>
<tr><td><div align="right"><a name="43"></a><a href="#43">43</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="44"></a><a href="#44">44</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="45"></a><a href="#45">45</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="46"></a><a href="#46">46</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="47"></a><a href="#47">47</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="48"></a><a href="#48">48</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="49"></a><a href="#49">49</a></div></td><td class="codeLine">function resizeText() {</td></tr>
<tr><td><div align="right"><a name="50"></a><a href="#50">50</a></div></td><td class="codeLine"> var preferredWidth = 767;</td></tr>
<tr><td><div align="right"><a name="51"></a><a href="#51">51</a></div></td><td class="codeLine"> var displayWidth = window.innerWidth;</td></tr>
<tr><td><div align="right"><a name="52"></a><a href="#52">52</a></div></td><td class="codeLine"> var percentage = displayWidth / preferredWidth;</td></tr>
<tr><td><div align="right"><a name="53"></a><a href="#53">53</a></div></td><td class="codeLine"> var fontsizetitle = 25;</td></tr>
<tr><td><div align="right"><a name="54"></a><a href="#54">54</a></div></td><td class="codeLine"> var newFontSizeTitle = Math.floor(fontsizetitle * percentage);</td></tr>
<tr><td><div align="right"><a name="55"></a><a href="#55">55</a></div></td><td class="codeLine"> $(".divclass").css("font-size", newFontSizeTitle)</td></tr>
<tr><td><div align="right"><a name="56"></a><a href="#56">56</a></div></td><td class="codeLine">}</td></tr>
<tr><td><div align="right"><a name="57"></a><a href="#57">57</a></div></td><td class="codeLine"></script></td></tr>
<tr><td><div align="right"><a name="58"></a><a href="#58">58</a></div></td><td class="codeLine"> </head></td></tr>
<tr><td><div align="right"><a name="59"></a><a href="#59">59</a></div></td><td class="codeLine"> <body></td></tr>
<tr><td><div align="right"><a name="60"></a><a href="#60">60</a></div></td><td class="codeLine"> <!--Header_section--></td></tr>
<tr><td><div align="right"><a name="61"></a><a href="#61">61</a></div></td><td class="codeLine"> <header style="padding-top:30px"></td></tr>
<tr><td><div align="right"><a name="62"></a><a href="#62">62</a></div></td><td class="codeLine"> <div class="container"></td></tr>
<tr><td><div align="right"><a name="63"></a><a href="#63">63</a></div></td><td class="codeLine"> <div class="header_section"></td></tr>
<tr><td><div align="right"><a name="64"></a><a href="#64">64</a></div></td><td class="codeLine"> <div class="logo"></td></tr>
<tr><td><div align="right"><a name="65"></a><a href="#65">65</a></div></td><td class="codeLine"> <a href="javascript:void(0)"></td></tr>
<tr><td><div align="right"><a name="66"></a><a href="#66">66</a></div></td><td class="codeLine"> <img src="img/logob.png" alt=""></td></tr>
<tr><td><div align="right"><a name="67"></a><a href="#67">67</a></div></td><td class="codeLine"> </a></td></tr>
<tr><td><div align="right"><a name="68"></a><a href="#68">68</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="69"></a><a href="#69">69</a></div></td><td class="codeLine"> <nav class="nav" id="nav"></td></tr>
<tr><td><div align="right"><a name="70"></a><a href="#70">70</a></div></td><td class="codeLine"> <ul></td></tr>
<tr><td><div align="right"><a name="71"></a><a href="#71">71</a></div></td><td class="codeLine"> <li></td></tr>
<tr><td><div align="right"><a name="72"></a><a href="#72">72</a></div></td><td class="codeLine"> <a href="<?php echo site_url('display/index')?>">Home</a></td></tr>
<tr><td><div align="right"><a name="73"></a><a href="#73">73</a></div></td><td class="codeLine"> </li></td></tr>
<tr><td><div align="right"><a name="74"></a><a href="#74">74</a></div></td><td class="codeLine"> <li></td></tr>
<tr><td><div align="right"><a name="75"></a><a href="#75">75</a></div></td><td class="codeLine"> <a href="<?php echo site_url('display/register')?>">Register</a></td></tr>
<tr><td><div align="right"><a name="76"></a><a href="#76">76</a></div></td><td class="codeLine"> </li></td></tr>
<tr><td><div align="right"><a name="77"></a><a href="#77">77</a></div></td><td class="codeLine"> </ul></td></tr>
<tr><td><div align="right"><a name="78"></a><a href="#78">78</a></div></td><td class="codeLine"> </nav></td></tr>
<tr><td><div align="right"><a name="79"></a><a href="#79">79</a></div></td><td class="codeLine"> <a class="res-nav_click animated wobble wow" href="javascript:void(0)"><i class="fa-bars"></i></a></td></tr>
<tr><td><div align="right"><a name="80"></a><a href="#80">80</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="81"></a><a href="#81">81</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="82"></a><a href="#82">82</a></div></td><td class="codeLine"> <div class="container"></td></tr>
<tr><td><div align="right"><a name="83"></a><a href="#83">83</a></div></td><td class="codeLine"></div></td></tr>
<tr><td><div align="right"><a name="84"></a><a href="#84">84</a></div></td><td class="codeLine"> <div class="container"></td></tr>
<tr><td><div align="right"><a name="85"></a><a href="#85">85</a></div></td><td class="codeLine"> <div style="padding:20px;" class="text-center"></td></tr>
<tr><td><div align="right"><a name="86"></a><a href="#86">86</a></div></td><td class="codeLine"> <div class="col-md-4"></td></tr>
<tr><td><div align="right"><a name="87"></a><a href="#87">87</a></div></td><td class="codeLine"></div></td></tr>
<tr><td><div align="right"><a name="88"></a><a href="#88">88</a></div></td><td class="codeLine"> <div class="col-md-4 text-center"></td></tr>
<tr><td><div align="right"><a name="89"></a><a href="#89">89</a></div></td><td class="codeLine"> <div class="page-header"></td></tr>
<tr><td><div align="right"><a name="90"></a><a href="#90">90</a></div></td><td class="codeLine"> <h1>Log In</h1></td></tr>
<tr><td><div align="right"><a name="91"></a><a href="#91">91</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="92"></a><a href="#92">92</a></div></td><td class="codeLine"> <form role="form" class="form-normal" method="post" action="<?php echo site_url('user/login')?>"></td></tr>
<tr><td><div align="right"><a name="93"></a><a href="#93">93</a></div></td><td class="codeLine"> <div class="form-group" style="padding-left:30px;"></td></tr>
<tr><td><div align="right"><a name="94"></a><a href="#94">94</a></div></td><td class="codeLine"> <label class="control-label " for="exampleInputEmail1">Email address</label></td></tr>
<tr><td><div align="right"><a name="95"></a><a href="#95">95</a></div></td><td class="codeLine"> <div></td></tr>
<tr><td><div align="right"><a name="96"></a><a href="#96">96</a></div></td><td class="codeLine"> <input type="email" class="form-control" id="email" placeholder="Enter email" name="email"></td></tr>
<tr><td><div align="right"><a name="97"></a><a href="#97">97</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="98"></a><a href="#98">98</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="99"></a><a href="#99">99</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="100"></a><a href="#100">100</a></div></td><td class="codeLine"> <div class="form-group" style="padding-left:30px;"></td></tr>
<tr><td><div align="right"><a name="101"></a><a href="#101">101</a></div></td><td class="codeLine"> <label class="control-label " for="exampleInputPassword1">Password</label></td></tr>
<tr><td><div align="right"><a name="102"></a><a href="#102">102</a></div></td><td class="codeLine"> <div></td></tr>
<tr><td><div align="right"><a name="103"></a><a href="#103">103</a></div></td><td class="codeLine"> <input type="password" class="form-control" id="password" placeholder="Password" name="pass"></td></tr>
<tr><td><div align="right"><a name="104"></a><a href="#104">104</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="105"></a><a href="#105">105</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="106"></a><a href="#106">106</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="107"></a><a href="#107">107</a></div></td><td class="codeLine"> <div class="form-group"></td></tr>
<tr><td><div align="right"><a name="108"></a><a href="#108">108</a></div></td><td class="codeLine"> <div></td></tr>
<tr><td><div align="right"><a name="109"></a><a href="#109">109</a></div></td><td class="codeLine"> <button type="submit" class="btn">Log In</button></td></tr>
<tr><td><div align="right"><a name="110"></a><a href="#110">110</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="111"></a><a href="#111">111</a></div></td><td class="codeLine"> <div></td></tr>
<tr><td><div align="right"><a name="112"></a><a href="#112">112</a></div></td><td class="codeLine"> <p><br></td></tr>
<tr><td><div align="right"><a name="113"></a><a href="#113">113</a></div></td><td class="codeLine"> Tidak Punya Akun ? &nbsp;<span><a href="<?php echo site_url('display/register')?>">Register</a></span></p></td></tr>
<tr><td><div align="right"><a name="114"></a><a href="#114">114</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="115"></a><a href="#115">115</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="116"></a><a href="#116">116</a></div></td><td class="codeLine"> </form></td></tr>
<tr><td><div align="right"><a name="117"></a><a href="#117">117</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="118"></a><a href="#118">118</a></div></td><td class="codeLine"> <div class="col-md-4"></td></tr>
<tr><td><div align="right"><a name="119"></a><a href="#119">119</a></div></td><td class="codeLine"></div></td></tr>
<tr><td><div align="right"><a name="120"></a><a href="#120">120</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="121"></a><a href="#121">121</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="122"></a><a href="#122">122</a></div></td><td class="codeLine"> </header></td></tr>
<tr><td><div align="right"><a name="123"></a><a href="#123">123</a></div></td><td class="codeLine"> <!--Header_section--></td></tr>
<tr><td><div align="right"><a name="124"></a><a href="#124">124</a></div></td><td class="codeLine"> <!--Top_content--></td></tr>
<tr><td><div align="right"><a name="125"></a><a href="#125">125</a></div></td><td class="codeLine"> <!--Top_content--></td></tr>
<tr><td><div align="right"><a name="126"></a><a href="#126">126</a></div></td><td class="codeLine"> <!--Service--></td></tr>
<tr><td><div align="right"><a name="127"></a><a href="#127">127</a></div></td><td class="codeLine"> <!--Service--></td></tr>
<tr><td><div align="right"><a name="128"></a><a href="#128">128</a></div></td><td class="codeLine"> <!--main-section-end--></td></tr>
<tr><td><div align="right"><a name="129"></a><a href="#129">129</a></div></td><td class="codeLine"> <!--new_portfolio--></td></tr>
<tr><td><div align="right"><a name="130"></a><a href="#130">130</a></div></td><td class="codeLine"> <!-- Portfolio --></td></tr>
<tr><td><div align="right"><a name="131"></a><a href="#131">131</a></div></td><td class="codeLine"> <!--/Portfolio --></td></tr>
<tr><td><div align="right"><a name="132"></a><a href="#132">132</a></div></td><td class="codeLine"> <!--new_portfolio--></td></tr>
<tr><td><div align="right"><a name="133"></a><a href="#133">133</a></div></td><td class="codeLine"> <!--</td></tr>
<tr><td><div align="right"><a name="134"></a><a href="#134">134</a></div></td><td class="codeLine"><section class="main-section paddind" id="Portfolio"></td></tr>
<tr><td><div align="right"><a name="135"></a><a href="#135">135</a></div></td><td class="codeLine"> <div class="container"></td></tr>
<tr><td><div align="right"><a name="136"></a><a href="#136">136</a></div></td><td class="codeLine"> <h2>Portfolio</h2></td></tr>
<tr><td><div align="right"><a name="137"></a><a href="#137">137</a></div></td><td class="codeLine"> <h6>Fresh portfolio of designs that will keep you wanting more.</h6></td></tr>
<tr><td><div align="right"><a name="138"></a><a href="#138">138</a></div></td><td class="codeLine"> </div></td></tr>
<tr><td><div align="right"><a name="139"></a><a href="#139">139</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="140"></a><a href="#140">140</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="141"></a><a href="#141">141</a></div></td><td class="codeLine"></section></td></tr>
<tr><td><div align="right"><a name="142"></a><a href="#142">142</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="143"></a><a href="#143">143</a></div></td><td class="codeLine">--></td></tr>
<tr><td><div align="right"><a name="144"></a><a href="#144">144</a></div></td><td class="codeLine"> <!--main-section client-part-end--></td></tr>
<tr><td><div align="right"><a name="145"></a><a href="#145">145</a></div></td><td class="codeLine"> <!--c-logo-part-end--></td></tr>
<tr><td><div align="right"><a name="146"></a><a href="#146">146</a></div></td><td class="codeLine"> <!--main-section team-end--></td></tr>
<tr><td><div align="right"><a name="147"></a><a href="#147">147</a></div></td><td class="codeLine"> <!--twitter-feed-end--></td></tr>
<tr><td><div align="right"><a name="148"></a><a href="#148">148</a></div></td><td class="codeLine"> <script type="text/javascript"></td></tr>
<tr><td><div align="right"><a name="149"></a><a href="#149">149</a></div></td><td class="codeLine"> $(document).ready(function(e) {</td></tr>
<tr><td><div align="right"><a name="150"></a><a href="#150">150</a></div></td><td class="codeLine"> $('#header_outer').scrollToFixed();</td></tr>
<tr><td><div align="right"><a name="151"></a><a href="#151">151</a></div></td><td class="codeLine"> $('.res-nav_click').click(function(){</td></tr>
<tr><td><div align="right"><a name="152"></a><a href="#152">152</a></div></td><td class="codeLine"> $('.main-nav').slideToggle();</td></tr>
<tr><td><div align="right"><a name="153"></a><a href="#153">153</a></div></td><td class="codeLine"> return false</td></tr>
<tr><td><div align="right"><a name="154"></a><a href="#154">154</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="155"></a><a href="#155">155</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="156"></a><a href="#156">156</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="157"></a><a href="#157">157</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="158"></a><a href="#158">158</a></div></td><td class="codeLine"></script></td></tr>
<tr><td><div align="right"><a name="159"></a><a href="#159">159</a></div></td><td class="codeLine"> <script></td></tr>
<tr><td><div align="right"><a name="160"></a><a href="#160">160</a></div></td><td class="codeLine"> wow = new WOW(</td></tr>
<tr><td><div align="right"><a name="161"></a><a href="#161">161</a></div></td><td class="codeLine"> {</td></tr>
<tr><td><div align="right"><a name="162"></a><a href="#162">162</a></div></td><td class="codeLine"> animateClass: 'animated',</td></tr>
<tr><td><div align="right"><a name="163"></a><a href="#163">163</a></div></td><td class="codeLine"> offset: 100</td></tr>
<tr><td><div align="right"><a name="164"></a><a href="#164">164</a></div></td><td class="codeLine"> }</td></tr>
<tr><td><div align="right"><a name="165"></a><a href="#165">165</a></div></td><td class="codeLine"> );</td></tr>
<tr><td><div align="right"><a name="166"></a><a href="#166">166</a></div></td><td class="codeLine"> wow.init();</td></tr>
<tr><td><div align="right"><a name="167"></a><a href="#167">167</a></div></td><td class="codeLine"> document.getElementById('').onclick = function() {</td></tr>
<tr><td><div align="right"><a name="168"></a><a href="#168">168</a></div></td><td class="codeLine"> var section = document.createElement('section');</td></tr>
<tr><td><div align="right"><a name="169"></a><a href="#169">169</a></div></td><td class="codeLine"> section.className = 'wow fadeInDown';</td></tr>
<tr><td><div align="right"><a name="170"></a><a href="#170">170</a></div></td><td class="codeLine"> section.className = 'wow shake';</td></tr>
<tr><td><div align="right"><a name="171"></a><a href="#171">171</a></div></td><td class="codeLine"> section.className = 'wow zoomIn';</td></tr>
<tr><td><div align="right"><a name="172"></a><a href="#172">172</a></div></td><td class="codeLine"> section.className = 'wow lightSpeedIn';</td></tr>
<tr><td><div align="right"><a name="173"></a><a href="#173">173</a></div></td><td class="codeLine"> this.parentNode.insertBefore(section, this);</td></tr>
<tr><td><div align="right"><a name="174"></a><a href="#174">174</a></div></td><td class="codeLine"> };</td></tr>
<tr><td><div align="right"><a name="175"></a><a href="#175">175</a></div></td><td class="codeLine"> </script></td></tr>
<tr><td><div align="right"><a name="176"></a><a href="#176">176</a></div></td><td class="codeLine"> <script type="text/javascript"></td></tr>
<tr><td><div align="right"><a name="177"></a><a href="#177">177</a></div></td><td class="codeLine"> $(window).load(function(){</td></tr>
<tr><td><div align="right"><a name="178"></a><a href="#178">178</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="179"></a><a href="#179">179</a></div></td><td class="codeLine"> $('a').bind('click',function(event){</td></tr>
<tr><td><div align="right"><a name="180"></a><a href="#180">180</a></div></td><td class="codeLine"> var $anchor = $(this);</td></tr>
<tr><td><div align="right"><a name="181"></a><a href="#181">181</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="182"></a><a href="#182">182</a></div></td><td class="codeLine"> $('html, body').stop().animate({</td></tr>
<tr><td><div align="right"><a name="183"></a><a href="#183">183</a></div></td><td class="codeLine"> scrollTop: $($anchor.attr('href')).offset().top - 91</td></tr>
<tr><td><div align="right"><a name="184"></a><a href="#184">184</a></div></td><td class="codeLine"> }, 1500,'easeInOutExpo');</td></tr>
<tr><td><div align="right"><a name="185"></a><a href="#185">185</a></div></td><td class="codeLine"> /*</td></tr>
<tr><td><div align="right"><a name="186"></a><a href="#186">186</a></div></td><td class="codeLine"> if you don't want to use the easing effects:</td></tr>
<tr><td><div align="right"><a name="187"></a><a href="#187">187</a></div></td><td class="codeLine"> $('html, body').stop().animate({</td></tr>
<tr><td><div align="right"><a name="188"></a><a href="#188">188</a></div></td><td class="codeLine"> scrollTop: $($anchor.attr('href')).offset().top</td></tr>
<tr><td><div align="right"><a name="189"></a><a href="#189">189</a></div></td><td class="codeLine"> }, 1000);</td></tr>
<tr><td><div align="right"><a name="190"></a><a href="#190">190</a></div></td><td class="codeLine"> */</td></tr>
<tr><td><div align="right"><a name="191"></a><a href="#191">191</a></div></td><td class="codeLine"> event.preventDefault();</td></tr>
<tr><td><div align="right"><a name="192"></a><a href="#192">192</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="193"></a><a href="#193">193</a></div></td><td class="codeLine"> })</td></tr>
<tr><td><div align="right"><a name="194"></a><a href="#194">194</a></div></td><td class="codeLine"></script></td></tr>
<tr><td><div align="right"><a name="195"></a><a href="#195">195</a></div></td><td class="codeLine"> <script type="text/javascript"></td></tr>
<tr><td><div align="right"><a name="196"></a><a href="#196">196</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="197"></a><a href="#197">197</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="198"></a><a href="#198">198</a></div></td><td class="codeLine"> jQuery(document).ready(function($){</td></tr>
<tr><td><div align="right"><a name="199"></a><a href="#199">199</a></div></td><td class="codeLine">// Portfolio Isotope</td></tr>
<tr><td><div align="right"><a name="200"></a><a href="#200">200</a></div></td><td class="codeLine"> var container = $('#portfolio-wrap');</td></tr>
<tr><td><div align="right"><a name="201"></a><a href="#201">201</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="202"></a><a href="#202">202</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="203"></a><a href="#203">203</a></div></td><td class="codeLine"> container.isotope({</td></tr>
<tr><td><div align="right"><a name="204"></a><a href="#204">204</a></div></td><td class="codeLine"> animationEngine : 'best-available',</td></tr>
<tr><td><div align="right"><a name="205"></a><a href="#205">205</a></div></td><td class="codeLine"> animationOptions: {</td></tr>
<tr><td><div align="right"><a name="206"></a><a href="#206">206</a></div></td><td class="codeLine"> duration: 200,</td></tr>
<tr><td><div align="right"><a name="207"></a><a href="#207">207</a></div></td><td class="codeLine"> queue: false</td></tr>
<tr><td><div align="right"><a name="208"></a><a href="#208">208</a></div></td><td class="codeLine"> },</td></tr>
<tr><td><div align="right"><a name="209"></a><a href="#209">209</a></div></td><td class="codeLine"> layoutMode: 'fitRows'</td></tr>
<tr><td><div align="right"><a name="210"></a><a href="#210">210</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="211"></a><a href="#211">211</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="212"></a><a href="#212">212</a></div></td><td class="codeLine"> $('#filters a').click(function(){</td></tr>
<tr><td><div align="right"><a name="213"></a><a href="#213">213</a></div></td><td class="codeLine"> $('#filters a').removeClass('active');</td></tr>
<tr><td><div align="right"><a name="214"></a><a href="#214">214</a></div></td><td class="codeLine"> $(this).addClass('active');</td></tr>
<tr><td><div align="right"><a name="215"></a><a href="#215">215</a></div></td><td class="codeLine"> var selector = $(this).attr('data-filter');</td></tr>
<tr><td><div align="right"><a name="216"></a><a href="#216">216</a></div></td><td class="codeLine"> container.isotope({ filter: selector });</td></tr>
<tr><td><div align="right"><a name="217"></a><a href="#217">217</a></div></td><td class="codeLine"> setProjects();</td></tr>
<tr><td><div align="right"><a name="218"></a><a href="#218">218</a></div></td><td class="codeLine"> return false;</td></tr>
<tr><td><div align="right"><a name="219"></a><a href="#219">219</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="220"></a><a href="#220">220</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="221"></a><a href="#221">221</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="222"></a><a href="#222">222</a></div></td><td class="codeLine"> function splitColumns() {</td></tr>
<tr><td><div align="right"><a name="223"></a><a href="#223">223</a></div></td><td class="codeLine"> var winWidth = $(window).width(),</td></tr>
<tr><td><div align="right"><a name="224"></a><a href="#224">224</a></div></td><td class="codeLine"> columnNumb = 1;</td></tr>
<tr><td><div align="right"><a name="225"></a><a href="#225">225</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="226"></a><a href="#226">226</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="227"></a><a href="#227">227</a></div></td><td class="codeLine"> if (winWidth > 1024) {</td></tr>
<tr><td><div align="right"><a name="228"></a><a href="#228">228</a></div></td><td class="codeLine"> columnNumb = 4;</td></tr>
<tr><td><div align="right"><a name="229"></a><a href="#229">229</a></div></td><td class="codeLine"> } else if (winWidth > 900) {</td></tr>
<tr><td><div align="right"><a name="230"></a><a href="#230">230</a></div></td><td class="codeLine"> columnNumb = 2;</td></tr>
<tr><td><div align="right"><a name="231"></a><a href="#231">231</a></div></td><td class="codeLine"> } else if (winWidth > 479) {</td></tr>
<tr><td><div align="right"><a name="232"></a><a href="#232">232</a></div></td><td class="codeLine"> columnNumb = 2;</td></tr>
<tr><td><div align="right"><a name="233"></a><a href="#233">233</a></div></td><td class="codeLine"> } else if (winWidth < 479) {</td></tr>
<tr><td><div align="right"><a name="234"></a><a href="#234">234</a></div></td><td class="codeLine"> columnNumb = 1;</td></tr>
<tr><td><div align="right"><a name="235"></a><a href="#235">235</a></div></td><td class="codeLine"> }</td></tr>
<tr><td><div align="right"><a name="236"></a><a href="#236">236</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="237"></a><a href="#237">237</a></div></td><td class="codeLine"> return columnNumb;</td></tr>
<tr><td><div align="right"><a name="238"></a><a href="#238">238</a></div></td><td class="codeLine"> }</td></tr>
<tr><td><div align="right"><a name="239"></a><a href="#239">239</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="240"></a><a href="#240">240</a></div></td><td class="codeLine"> function setColumns() {</td></tr>
<tr><td><div align="right"><a name="241"></a><a href="#241">241</a></div></td><td class="codeLine"> var winWidth = $(window).width(),</td></tr>
<tr><td><div align="right"><a name="242"></a><a href="#242">242</a></div></td><td class="codeLine"> columnNumb = splitColumns(),</td></tr>
<tr><td><div align="right"><a name="243"></a><a href="#243">243</a></div></td><td class="codeLine"> postWidth = Math.floor(winWidth / columnNumb);</td></tr>
<tr><td><div align="right"><a name="244"></a><a href="#244">244</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="245"></a><a href="#245">245</a></div></td><td class="codeLine"> container.find('.portfolio-item').each(function () {</td></tr>
<tr><td><div align="right"><a name="246"></a><a href="#246">246</a></div></td><td class="codeLine"> $(this).css( {</td></tr>
<tr><td><div align="right"><a name="247"></a><a href="#247">247</a></div></td><td class="codeLine"> width : postWidth + 'px'</td></tr>
<tr><td><div align="right"><a name="248"></a><a href="#248">248</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="249"></a><a href="#249">249</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="250"></a><a href="#250">250</a></div></td><td class="codeLine"> }</td></tr>
<tr><td><div align="right"><a name="251"></a><a href="#251">251</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="252"></a><a href="#252">252</a></div></td><td class="codeLine"> function setProjects() {</td></tr>
<tr><td><div align="right"><a name="253"></a><a href="#253">253</a></div></td><td class="codeLine"> setColumns();</td></tr>
<tr><td><div align="right"><a name="254"></a><a href="#254">254</a></div></td><td class="codeLine"> container.isotope('reLayout');</td></tr>
<tr><td><div align="right"><a name="255"></a><a href="#255">255</a></div></td><td class="codeLine"> }</td></tr>
<tr><td><div align="right"><a name="256"></a><a href="#256">256</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="257"></a><a href="#257">257</a></div></td><td class="codeLine"> container.imagesLoaded(function () {</td></tr>
<tr><td><div align="right"><a name="258"></a><a href="#258">258</a></div></td><td class="codeLine"> setColumns();</td></tr>
<tr><td><div align="right"><a name="259"></a><a href="#259">259</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="260"></a><a href="#260">260</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="261"></a><a href="#261">261</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="262"></a><a href="#262">262</a></div></td><td class="codeLine"> $(window).bind('resize', function () {</td></tr>
<tr><td><div align="right"><a name="263"></a><a href="#263">263</a></div></td><td class="codeLine"> setProjects();</td></tr>
<tr><td><div align="right"><a name="264"></a><a href="#264">264</a></div></td><td class="codeLine"> });</td></tr>
<tr><td><div align="right"><a name="265"></a><a href="#265">265</a></div></td><td class="codeLine"></td></tr>
<tr><td><div align="right"><a name="266"></a><a href="#266">266</a></div></td><td class="codeLine">});</td></tr>
<tr><td><div align="right"><a name="267"></a><a href="#267">267</a></div></td><td class="codeLine">$( window ).load(function() {</td></tr>
<tr><td><div align="right"><a name="268"></a><a href="#268">268</a></div></td><td class="codeLine"> jQuery('#all').click();</td></tr>
<tr><td><div align="right"><a name="269"></a><a href="#269">269</a></div></td><td class="codeLine"> return false;</td></tr>
<tr><td><div align="right"><a name="270"></a><a href="#270">270</a></div></td><td class="codeLine">});</td></tr>
<tr><td><div align="right"><a name="271"></a><a href="#271">271</a></div></td><td class="codeLine"></script></td></tr>
<tr><td><div align="right"><a name="272"></a><a href="#272">272</a></div></td><td class="codeLine"> <script src="contactform/contactform.js"></script></td></tr>
<tr><td><div align="right"><a name="273"></a><a href="#273">273</a></div></td><td class="codeLine"> </body></td></tr>
</tbody>
</table>
<footer>
<h4>Legend</h4>
<p>
<span class="success"><strong>Executed</strong></span>
<span class="danger"><strong>Not Executed</strong></span>
<span class="warning"><strong>Dead Code</strong></span>
</p>
<p>
<small>Generated by <a href="http://github.com/sebastianbergmann/php-code-coverage" target="_top">PHP_CodeCoverage 1.2.11</a> using <a href="http://www.php.net/" target="_top">PHP 7.0.23</a> and <a href="http://phpunit.de/">PHPUnit 3.7.21</a> at Tue Oct 17 12:51:41 UTC 2017.</small>
</p>
</footer>
</div>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">$('.popin').popover({trigger: 'hover'});</script>
</body>
</html>
| faiqpurnomo/kppl | tests/build/coverage/views_user_login.php.html | HTML | mit | 45,925 |
input {
outline: none;
padding: 10px;
font-size: 18px;
}
| gilbox/elegant-react | examples/form-validation/app.css | CSS | mit | 63 |
# -*- coding: utf-8 -*-
"""
handler base
~~~~~~~~~~~~
Presents a reasonable base class for a ``Handler`` object, which handles
responding to an arbitrary "request" for action. For example, ``Handler``
is useful for responding to HTTP requests *or* noncyclical realtime-style
requests, and acts as a base class for ``Page`` and ``ServiceHandler``.
:author: Sam Gammon <sg@samgammon.com>
:copyright: (c) Sam Gammon, 2014
:license: This software makes use of the MIT Open Source License.
A copy of this license is included as ``LICENSE.md`` in
the root of the project.
"""
# stdlib
import itertools
# canteen core, util, logic
from ..core import injection
# noinspection PyUnresolvedReferences
class Handler(object):
""" Base class structure for a ``Handler`` of some request or desired action.
Specifies basic machinery for tracking a ``request`` alongside some form
of ``response``.
Also keeps track of relevant ``environ`` (potentially from WSGI) and sets
up a jump off point for DI-provided tools like logging, config, caching,
template rendering, etc. """
# @TODO(sgammon): HTTPify, convert to decorator
config = property(lambda self: {})
__agent__ = None # current `agent` details
__status__ = 200 # it's a glass-half-full kind of day, why not
__routes__ = None # route map adapter from werkzeug
__context__ = None # holds current runtime context, if any
__logging__ = None # internal logging slot
__runtime__ = None # reference up to the runtime
__environ__ = None # original WSGI environment
__request__ = None # lazy-loaded request object
__headers__ = None # buffer HTTP header access
__response__ = None # lazy-loaded response object
__callback__ = None # callback to send data (sync or async)
__content_type__ = None # response content type
# set owner and injection side
__owner__, __metaclass__ = "Handler", injection.Compound
def __init__(self, environ=None,
start_response=None,
runtime=None,
request=None,
response=None, **context):
""" Initialize a new ``Handler`` object with proper ``environ`` details and
inform it of larger world around it.
``Handler`` objects (much like ``Runtime`` objects) are designed to be
usable independently as a WSGI-style callable. Note that the first two
position parameters of this ``__init__`` are the venerable ``environ``
and ``start_response`` - dispatching this way is totally possible, but
providing ``runtime``, ``request`` and ``response`` allow tighter
integration with the underlying runtime.
Current execution details (internal to Canteen) are passed as ``kwargs``
and compounded as new context items are added.
:param environ: WSGI environment, provided by active runtime. ``dict``
in standard WSGI format.
:param start_response: Callable to begin the response cycle. Usually a
vanilla ``function``.
:param runtime: Currently-active Canteen runtime. Always an instance of
:py:class:`canteen.core.runtime.Runtime` or a subclass thereof.
:param request: Object to use for ``self.request``. Usually an instance
of :py:class:`werkzeug.wrappers.Request`.
:param response: Object to use for ``self.response``. Usually an
instance of :py:class:`werkzeug.wrappers.Response`. """
# startup/assign internals
self.__runtime__, self.__environ__, self.__callback__ = (
runtime, # reference to the active runtime
environ, # reference to WSGI environment
start_response) # reference to WSGI callback
# setup HTTP/dispatch stuff
self.__status__, self.__headers__, self.__content_type__ = (
200, # default response status
{}, # default repsonse headers
'text/html; charset=utf-8') # default content type
# request, response & context
self.__request__, self.__response__, self.__context__ = (
request, response, context)
# expose internals, but write-protect
routes = property(lambda self: self.__runtime__.routes)
status = property(lambda self: self.__status__)
headers = property(lambda self: self.__headers__)
content_type = property(lambda self: self.__content_type__)
# shortcuts & utilities
url_for = link = lambda self, end, **args: self.routes.build(end, args)
# WSGI internals
app = runtime = property(lambda self: self.__runtime__)
environment = environ = property(lambda self: self.__environ__)
start_response = callback = property(lambda self: self.__callback__)
# Context
session = property(lambda self: ( # session is tuple of (session, engine)
self.request.session[0] if self.request.session else None))
# Agent
agent = property(lambda self: (
self.__agent__ if self.__agent__ else (
setattr(self, '__agent__', self.http.agent.scan(self.request)) or (
self.__agent__))))
# Request & Response
request = property(lambda self: (
self.__request__ if self.__request__ else (
setattr(self, '__request__', self.http.new_request(self.__environ__)) or (
self.__request__))))
response = property(lambda self: (
self.__response__ if self.__response__ else (
setattr(self, '__response__', self.http.new_response()) or (
self.__response__))))
@property
def template_context(self):
""" Generate template context to be used in rendering source templates. The
``template_context`` accessor is expected to return a ``dict`` of
``name=>value`` pairs to present to the template API.
:returns: ``dict`` of template context. """
# for javascript context
from canteen.rpc import ServiceHandler
return {
# Default Context
'handler': self,
'config': getattr(self, 'config', {}),
'runtime': self.runtime,
# HTTP Context
'http': {
'agent': getattr(self, 'agent', None),
'request': self.request,
'response': self.response
},
# WSGI internals
'wsgi': {
'environ': self.environ,
'callback': self.callback,
'start_response': self.start_response
},
# Cache API
'cache': {
'get': self.cache.get,
'get_multi': self.cache.get_multi,
'set': self.cache.set,
'set_multi': self.cache.set_multi,
'delete': self.cache.delete,
'delete_multi': self.cache.delete_multi,
'clear': self.cache.clear,
'flush': self.cache.flush
},
# Assets API
'asset': {
'image': self.assets.image_url,
'style': self.assets.style_url,
'script': self.assets.script_url
},
# Service API
'services': {
'list': ServiceHandler.services,
'describe': ServiceHandler.describe
},
# Output API
'output': {
'render': self.template.render,
'environment': self.template.environment
},
# Routing
'link': self.url_for,
'route': {
'build': self.url_for,
'resolve': self.http.resolve_route
}
}
def respond(self, content=None, direct=False):
""" Respond to this ``Handler``'s request with raw ``str`` or ``unicode``
content. UTF-8 encoding happens if necessary.
:param content: Content to respond to. Must be ``str``, ``unicode``, or
a similar string buffer object.
:param direct: Flag indicating that ``self`` should be returned, rather
than ``self.response``. Bool, defaults to ``False`` as this
technically breaks WSGI.
:returns: Generated (filled-in) ``self.response`` object. """
# today is a good day
if not self.status: self.__status__ = 200
if content: self.response.response = content
# set status code and return
return setattr(self.response,
('status_code' if isinstance(self.status, int) else 'status'),
self.status) or (
(i.encode('utf-8').strip() for i in self.response.response),
self.response) if not direct else self
def render(self, template,
headers=None,
content_type='text/html; charset=utf-8',
context=None,
_direct=False, **kwargs):
""" Render a source ``template`` for the purpose of responding to this
``Handler``'s request, given ``context`` and proper ``headers`` for
return.
``kwargs`` are taken as extra template context and overlayed onto
``context`` before render.
:param template: Path to template file to serve. ``str`` or ``unicode``
file path.
:param headers: Extra headers to send with response. ``dict`` or iter of
``(name, value)`` tuples.
:param content_type: Value to send for ``Content-Type`` header. ``str``,
defaults to ``text/html; charset=utf-8``.
:param context: Extra template context to include during render.
``dict`` of items, with keys as names that values are bound to in the
resulting template context.
:param _direct: Flag indicating that ``self`` should be returned, rather
than ``self.response``. Bool, defaults to ``False`` as this
technically breaks WSGI.
:param kwargs: Additional items to add to the template context.
Overrides all other sources of context.
:returns: Rendered template content, added to ``self.response``. """
from canteen.util import config
# set mime type
if content_type: self.response.mimetype = content_type
# collapse and merge HTTP headers (base headers first)
self.response.headers.extend(itertools.chain(
iter(self.http.base_headers),
self.config.get('http', {}).get('headers', {}).iteritems(),
self.headers.iteritems(),
(headers or {}).iteritems()))
# merge template context
_merged_context = dict(itertools.chain(*(i.iteritems() for i in (
self.template.base_context,
self.template_context,
context or {},
kwargs))))
# render template and set as response data
self.response.response, self.response.direct_passthrough = (
self.template.render(
self,
getattr(self.runtime, 'config', None) or config.Config(),
template,
_merged_context)), True
return self.respond(direct=_direct)
def dispatch(self, **url_args):
""" Dispatch a WSGI request through this ``Handler``. Expected to be an
HTTP-style (cyclical) dispatch flow.
:param url_args: Arguments provided from the URI that should be passed
along to any resulting handler calls.
:returns: After filling the local response object (at ``self.response``)
returns it for inspection or reply. """
self.__response__ = (
getattr(self, self.request.method)(**url_args)) or self.__response__
return self.__response__
def __call__(self, url_args, direct=False):
""" Kick off the local response dispatch process, and run any necessary
pre/post hooks (named ``prepare`` and ``destroy``, respectively).
:param url_args: Arguments parsed from URL according to matched route.
``dict`` of ``{param: value}`` pairs.
:param direct: Flag to indicate 'direct' mode, whereby a handler is
returned instead of a response. Bool, defaults to ``False``, as this
technically breaks WSGI.
:returns: ``self.response`` if ``direct`` mode is not active, otherwise
``self`` for chainability. """
# run prepare hook, if specified
if hasattr(self, 'prepare'): self.prepare(url_args, direct=direct)
self.dispatch(**url_args) # dispatch local handler, fills `__response__`
# run destroy hook, if specified
if hasattr(self, 'destroy'): self.destroy(self.__response__)
return self.__response__ if not direct else self
# noinspection PyUnresolvedReferences
class RealtimeHandler(Handler):
""" Provides structure for an acyclically-dispatched web handler, meant for
use in scenarios like WebSockets. Instead of handling things with
methods like ``GET`` or ``POST``, a ``RealtimeHandler`` can specify
hooks for two events - ``on_connect`` and ``on_message``.
The first, ``on_connect``, is dispatched when a realtime connection has
just been successfully negotiated. It is executed once the application
is ready to return an ``HTTP/1.1 Upgrade`` response, so that the
developer has a chance to specify subprotocols/extensions/etc.
The second hook, ``on_message``, is dispatched each time an established
connection receives a message from the client. It takes two parameters -
the ``message`` itself and whether it is ``binary`` or not. """
__socket__ = None # space for currently-active realtime socket
def dispatch(self, **url_args): # pragma: no cover
""" Adapt regular handler dispatch to support an acyclic/realtime-style
dispatch scheme. Accepts same arguments as ``super`` definition, but
dispatches *realtime*-style messages like ``on_connect`` and
``on_message``, so long as the request looks like a WebSocket upgrade.
:param url_args: Arguments provided from the URI that should be passed
along to any resulting handler calls.
:returns: After filling the local response object (at ``self.response``)
returns it for inspection or reply. """
# fallback to standard dispatch
if self.realtime.hint not in self.environ:
return super(RealtimeHandler, self).dispatch(**url_args)
try:
# websocket upgrade and session
self.__socket__ = self.realtime.on_connect(self)
self.realtime.on_message(self, self.__socket__)
except NotImplementedError:
return self.error(400) # raised when a non-websocket handler is hit
@staticmethod
def terminate(graceful=True): # pragma: no cover
""" Terminate the currently-active ``RealtimeSocket`` communication
channel.
:param graceful: ``bool`` parameter, whether to end the connection
gracefully or not.
:returns: ``TERMINATE`` sentinel, to be yielded so the connection can be
terminated. """
from canteen.logic import realtime
if graceful: return realtime.TERMINATE
raise realtime.TerminateSocket(graceful=False)
@staticmethod
def on_connect(): # pragma: no cover
""" Hook function that is dispatched upon successful handshake for a
realtime-style connection between a client and this server. Local
handler should be prepared by this point with all information necessary
to satisfy messages.
Implementors are expected to provide a method that makes use of object-
level context (i.e. not a static or classmethod).
:returns: ``NotImplemented`` by default, which simply indicates that
the implementor elects not to run code ``on_connect``. """
return NotImplemented
def on_message(self, message, binary): # pragma: no cover
""" Hook that is dispatched per message sent from a live client. Called
subsequent to a connection being properly established from a previous
call to ``on_connect``.
:param message: WebSocket message passed from the client.
:param binary: ``bool`` flag - ``True`` if ``message`` is binary,
``False`` otherwise.
:raises NotImplementedError: By default, since not many people use
WebSockets and there's no such thing as a ``400`` without HTTP. :)
:returns: Not expected to return anything. If a return is used, any
value or iterable of values will be collapsed and sent to the client.
Optionally, the developer may implement ``on_message`` as a coroutine-
style Python generator, in which case new messages will be ``sent``
in from the client and messages to the client can be yielded upwards
to be sent. """
raise NotImplementedError('Handler "%s" fails to implement hook'
' `on_message` so it does not support'
' realtime-style communications.' % repr(self))
# noinspection PyUnusedLocal
@staticmethod
def on_close(graceful): # pragma: no cover
""" Hook function that is dispatched upon closure of an existing realtime
communications session.
:param graceful: ``bool`` parameter indicating whether the connection
was closed gracefully (i.e. electively) or because of some error
condition.
:returns: ``NotImplemented`` by default, which simply indicates that
the implementor elects not to run code ``on_connect``. """
return NotImplemented
__all__ = ('Handler',)
| momentum/canteen | canteen/base/handler.py | Python | mit | 17,022 |
#pragma once
#include <xenon/ict/unit.h>
class itu_unit {
public:
void register_tests(ict::unit_test<itu_unit> &ut) {
ut.add(&itu_unit::host);
ut.add(&itu_unit::bit_lengths);
ut.add(&itu_unit::splits);
ut.add(&itu_unit::sanity);
}
/* Tests */
void host();
void bit_lengths();
void splits();
void sanity();
};
| intrig/xenon | unit/itu/ituunit.h | C | mit | 373 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LionFire.ObjectBus
{
public class CannotOverwriteException : OBusException // REVIEW: Should this be OBaseException?
{
public CannotOverwriteException() { }
public CannotOverwriteException(string message) : base(message) { }
public CannotOverwriteException(string message, Exception inner) : base(message, inner) { }
}
}
| jaredthirsk/Core | src/LionFire.ObjectBus.Abstractions/OBus/CannotOverwriteException.cs | C# | mit | 467 |
# -*-coding: utf-8 -*-
import math
import numpy as np
import relations
def _avg_difference(npiece, side):
if side == relations.LEFT:
difference = npiece[:, 0] - npiece[:, 1]
elif side == relations.RIGHT:
difference = npiece[:, -1] - npiece[:, -2]
elif side == relations.UP:
difference = npiece[0, :] - npiece[1, :]
else:
difference = npiece[-1, :] - npiece[-2, :]
return sum(difference)/float(len(difference))
def _gradient(pieces_difference, average_side_difference):
grad = pieces_difference - average_side_difference
grad_t = np.transpose(grad)
cov = np.cov(grad_t)
try:
cov_inv = np.linalg.inv(cov)
except np.linalg.LinAlgError as e:
cov_inv = np.ones((3, 3))
return grad.dot(cov_inv).dot(grad_t)
def mgc(np1, np2, relation):
if relation == relations.LEFT:
grad_12 = _gradient(np2[:, 0] - np1[:, -1], _avg_difference(np1, relations.RIGHT))
grad_21 = _gradient(np1[:, -1] - np2[:, 0], _avg_difference(np2, relations.LEFT))
else:
grad_12 = _gradient(np2[0, :] - np1[-1, :], _avg_difference(np1, relations.DOWN))
grad_21 = _gradient(np1[-1, :] - np2[0, :], _avg_difference(np2, relations.UP))
return np.sum(grad_12 + grad_21)
def rgb(np1, np2, relation):
if relation == relations.LEFT:
difference = np1[:, -1] - np2[:, 0]
else:
difference = np1[-1, :] - np2[0, :]
exponent = np.vectorize(lambda x: math.pow(x, 2))
dissimilarity = np.sum(exponent(difference))
return math.sqrt(dissimilarity)
def rgb_mgc(*args):
return rgb(*args)*mgc(*args) | typeinference/jigsaw-puzzle | src/measures.py | Python | mit | 1,631 |
import RPi.GPIO as GPIO
import os
import time
import datetime
import glob
import MySQLdb
from time import strftime
import serial
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter = 0
GPIO.setmode(GPIO.BOARD)
GPIO.setup(15,GPIO.IN)
# Variables for MySQL
db = MySQLdb.connect(host="localhost", user="root",passwd="deb280794", db="temp_database")
cur = db.cursor()
while True:
x = ser.readline()
f=x.split()
moisture = f[1]
humidity = f[4]
temp = f[7]
print("Moisture: ")
print moisture
print("Humidity: ")
print humidity
print("Temperature: ")
print temp
datetimeWrite = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
sql = ("""INSERT INTO tempLog (datetime,temperature,humidity,moisture) VALUES (%s,%s,%s,%s)""",(datetimeWrite,temp,humidity,moisture))
try:
print "Writing to database..."
# Execute the SQL command
cur.execute(*sql)
# Commit your changes in the database
db.commit()
print "Write Complete"
except:
# Rollback in case there is any error
db.rollback()
print "Failed writing to database"
time.sleep(0.5)
| Shashank95/Intellifarm | logdata.py | Python | mit | 1,310 |
#!/usr/bin/env node
require("./proof")(1, function (step, parse, deepEqual) {
step(function () {
parse("CancelSpotInstanceRequests", step());
}, function (object) {
var expected =
{ requestId: "59dbff89-35bd-4eac-99ed-be587ed81825"
, spotInstanceRequestSet: [ { spotInstanceRequestId: 'sir-e95fae02', state: "cancelled" } ]
};
deepEqual(object, expected, "parse cancel spot instance requests");
});
});
| defunct/node-ec2 | t/response/cancel-spot-instance-requests.t.js | JavaScript | mit | 434 |
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
overflow-x: hidden;
}
span {
height: 100%;
width: 100%;
position: fixed;
bottom: 0px;
right: 0px;
background: rgba(255,0,0,0.2);
}
</style>
</head>
<body class="home">
<div style="height:3000px;width:100%">Try tap-and-scrolling this page; doesn't work in Firefox, does in Chrome.</div>
<span></span>
</body></html> | bokand/bokand.github.io | bugs/1017748/testcase2.html | HTML | mit | 605 |
# frozen_string_literal: true
require 'rails_helper'
require "#{Rails.root}/lib/importers/article_importer"
describe ArticleImporter do
before { stub_wiki_validation }
let(:en_wiki) { Wiki.default_wiki }
let(:es_wiki) { create(:wiki, language: 'es', project: 'wikipedia') }
describe '.import_articles' do
it 'creates an Article from a English Wikipedia page_id' do
ArticleImporter.new(en_wiki).import_articles [46349871]
article = Article.find_by(mw_page_id: 46349871)
expect(article.title).to eq('Kostanay')
end
it 'works for a language besides the default' do
ArticleImporter.new(es_wiki).import_articles [100]
article = Article.find_by(mw_page_id: 100)
expect(article.title).to eq('Alnus')
end
end
describe '.import_articles_by_title' do
it 'creates an Article from a title with the correct mw_page_id' do
titles = %w[Selfie Bombus_hortorum Kostanay]
VCR.use_cassette 'article_importer/existing_titles' do
ArticleImporter.new(en_wiki).import_articles_by_title(titles)
end
expect(Article.find_by(title: 'Kostanay').mw_page_id).to eq(46349871)
end
it 'does not create an article if there is no matching title' do
titles = ['There_is_no_article_with_this_title']
VCR.use_cassette 'article_importer/nonexistent_title' do
ArticleImporter.new(en_wiki).import_articles_by_title(titles)
end
expect(Article.find_by(title: titles[0])).to be_nil
end
it 'works for a language besides the default' do
VCR.use_cassette 'article_importer/existing_titles' do
titles = %w[Selfie Bombus_hortorum]
ArticleImporter.new(es_wiki).import_articles_by_title(titles)
expect(Article.find_by(title: 'Selfie').mw_page_id).to eq(6210294)
end
end
end
end
| alpha721/WikiEduDashboard | spec/lib/importers/article_importer_spec.rb | Ruby | mit | 1,824 |
<?php
class Exception {
protected $message;
protected $code;
protected $file;
protected $line;
public function __construct($message = "", $code = 0, $previous = NULL) {
$this->message = $message;
$this->line = 1;
}
final public function getMessage() {
return $this->message;
}
final public function getPrevious() {
}
final public function getCode() {
}
final public function getFile() {
}
final public function getLine() {
return $this->line;
}
final public function getTrace() {
return array(
array("function" => "Error2Exception"),
array("function" => "fopen")
);
}
final public function getTraceAsString() {
}
public function __toString() {
}
final private function __clone() {
}
}
?>
| niklasvh/php.js | templates/classes/Exception.php | PHP | mit | 925 |
# Copyright 2016 The TensorFlow Authors. 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.
# ==============================================================================
# TODO(ptucker,ipolosukhin): Improve descriptions.
"""High level API for learning. See the @{$python/contrib.learn} guide.
@@BaseEstimator
@@Estimator
@@Trainable
@@Evaluable
@@KMeansClustering
@@ModeKeys
@@ModelFnOps
@@MetricSpec
@@PredictionKey
@@DNNClassifier
@@DNNRegressor
@@DNNLinearCombinedRegressor
@@DNNLinearCombinedClassifier
@@LinearClassifier
@@LinearRegressor
@@LogisticRegressor
@@Experiment
@@ExportStrategy
@@TaskType
@@NanLossDuringTrainingError
@@RunConfig
@@evaluate
@@infer
@@run_feeds
@@run_n
@@train
@@extract_dask_data
@@extract_dask_labels
@@extract_pandas_data
@@extract_pandas_labels
@@extract_pandas_matrix
@@infer_real_valued_columns_from_input
@@infer_real_valued_columns_from_input_fn
@@read_batch_examples
@@read_batch_features
@@read_batch_record_features
@@InputFnOps
@@ProblemType
@@build_parsing_serving_input_fn
@@ProblemType
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=wildcard-import
from tensorflow.contrib.learn.python.learn import *
# pylint: enable=wildcard-import
from tensorflow.python.util.all_util import remove_undocumented
_allowed_symbols = ['datasets', 'head', 'io', 'models',
'monitors', 'NotFittedError', 'ops', 'preprocessing',
'utils', 'graph_actions']
remove_undocumented(__name__, _allowed_symbols)
| jjas0nn/solvem | tensorflow/lib/python2.7/site-packages/tensorflow/contrib/learn/__init__.py | Python | mit | 2,083 |
<?php
// MyCompanyMyProjectSysBundle:AdminLocale:admin_locale.html.twig
return array (
);
| ithone/pam | app/cache/test/assetic/config/7/7ea99c7a54cfc2c514ed659b03d8764f.php | PHP | mit | 91 |
#include "f2c.h"
#include "blaswrap.h"
/* Table of constant values */
static doublecomplex c_b1 = {0.,0.};
static doublecomplex c_b2 = {1.,0.};
static integer c__1 = 1;
/* Subroutine */ int zlabrd_(integer *m, integer *n, integer *nb,
doublecomplex *a, integer *lda, doublereal *d__, doublereal *e,
doublecomplex *tauq, doublecomplex *taup, doublecomplex *x, integer *
ldx, doublecomplex *y, integer *ldy)
{
/* System generated locals */
integer a_dim1, a_offset, x_dim1, x_offset, y_dim1, y_offset, i__1, i__2,
i__3;
doublecomplex z__1;
/* Local variables */
integer i__;
doublecomplex alpha;
extern /* Subroutine */ int zscal_(integer *, doublecomplex *,
doublecomplex *, integer *), zgemv_(char *, integer *, integer *,
doublecomplex *, doublecomplex *, integer *, doublecomplex *,
integer *, doublecomplex *, doublecomplex *, integer *),
zlarfg_(integer *, doublecomplex *, doublecomplex *, integer *,
doublecomplex *), zlacgv_(integer *, doublecomplex *, integer *);
/* -- LAPACK auxiliary routine (version 3.1) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* ZLABRD reduces the first NB rows and columns of a complex general */
/* m by n matrix A to upper or lower real bidiagonal form by a unitary */
/* transformation Q' * A * P, and returns the matrices X and Y which */
/* are needed to apply the transformation to the unreduced part of A. */
/* If m >= n, A is reduced to upper bidiagonal form; if m < n, to lower */
/* bidiagonal form. */
/* This is an auxiliary routine called by ZGEBRD */
/* Arguments */
/* ========= */
/* M (input) INTEGER */
/* The number of rows in the matrix A. */
/* N (input) INTEGER */
/* The number of columns in the matrix A. */
/* NB (input) INTEGER */
/* The number of leading rows and columns of A to be reduced. */
/* A (input/output) COMPLEX*16 array, dimension (LDA,N) */
/* On entry, the m by n general matrix to be reduced. */
/* On exit, the first NB rows and columns of the matrix are */
/* overwritten; the rest of the array is unchanged. */
/* If m >= n, elements on and below the diagonal in the first NB */
/* columns, with the array TAUQ, represent the unitary */
/* matrix Q as a product of elementary reflectors; and */
/* elements above the diagonal in the first NB rows, with the */
/* array TAUP, represent the unitary matrix P as a product */
/* of elementary reflectors. */
/* If m < n, elements below the diagonal in the first NB */
/* columns, with the array TAUQ, represent the unitary */
/* matrix Q as a product of elementary reflectors, and */
/* elements on and above the diagonal in the first NB rows, */
/* with the array TAUP, represent the unitary matrix P as */
/* a product of elementary reflectors. */
/* See Further Details. */
/* LDA (input) INTEGER */
/* The leading dimension of the array A. LDA >= max(1,M). */
/* D (output) DOUBLE PRECISION array, dimension (NB) */
/* The diagonal elements of the first NB rows and columns of */
/* the reduced matrix. D(i) = A(i,i). */
/* E (output) DOUBLE PRECISION array, dimension (NB) */
/* The off-diagonal elements of the first NB rows and columns of */
/* the reduced matrix. */
/* TAUQ (output) COMPLEX*16 array dimension (NB) */
/* The scalar factors of the elementary reflectors which */
/* represent the unitary matrix Q. See Further Details. */
/* TAUP (output) COMPLEX*16 array, dimension (NB) */
/* The scalar factors of the elementary reflectors which */
/* represent the unitary matrix P. See Further Details. */
/* X (output) COMPLEX*16 array, dimension (LDX,NB) */
/* The m-by-nb matrix X required to update the unreduced part */
/* of A. */
/* LDX (input) INTEGER */
/* The leading dimension of the array X. LDX >= max(1,M). */
/* Y (output) COMPLEX*16 array, dimension (LDY,NB) */
/* The n-by-nb matrix Y required to update the unreduced part */
/* of A. */
/* LDY (input) INTEGER */
/* The leading dimension of the array Y. LDY >= max(1,N). */
/* Further Details */
/* =============== */
/* The matrices Q and P are represented as products of elementary */
/* reflectors: */
/* Q = H(1) H(2) . . . H(nb) and P = G(1) G(2) . . . G(nb) */
/* Each H(i) and G(i) has the form: */
/* H(i) = I - tauq * v * v' and G(i) = I - taup * u * u' */
/* where tauq and taup are complex scalars, and v and u are complex */
/* vectors. */
/* If m >= n, v(1:i-1) = 0, v(i) = 1, and v(i:m) is stored on exit in */
/* A(i:m,i); u(1:i) = 0, u(i+1) = 1, and u(i+1:n) is stored on exit in */
/* A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). */
/* If m < n, v(1:i) = 0, v(i+1) = 1, and v(i+1:m) is stored on exit in */
/* A(i+2:m,i); u(1:i-1) = 0, u(i) = 1, and u(i:n) is stored on exit in */
/* A(i,i+1:n); tauq is stored in TAUQ(i) and taup in TAUP(i). */
/* The elements of the vectors v and u together form the m-by-nb matrix */
/* V and the nb-by-n matrix U' which are needed, with X and Y, to apply */
/* the transformation to the unreduced part of the matrix, using a block */
/* update of the form: A := A - V*Y' - X*U'. */
/* The contents of A on exit are illustrated by the following examples */
/* with nb = 2: */
/* m = 6 and n = 5 (m > n): m = 5 and n = 6 (m < n): */
/* ( 1 1 u1 u1 u1 ) ( 1 u1 u1 u1 u1 u1 ) */
/* ( v1 1 1 u2 u2 ) ( 1 1 u2 u2 u2 u2 ) */
/* ( v1 v2 a a a ) ( v1 1 a a a a ) */
/* ( v1 v2 a a a ) ( v1 v2 a a a a ) */
/* ( v1 v2 a a a ) ( v1 v2 a a a a ) */
/* ( v1 v2 a a a ) */
/* where a denotes an element of the original matrix which is unchanged, */
/* vi denotes an element of the vector defining H(i), and ui an element */
/* of the vector defining G(i). */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Quick return if possible */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1;
a -= a_offset;
--d__;
--e;
--tauq;
--taup;
x_dim1 = *ldx;
x_offset = 1 + x_dim1;
x -= x_offset;
y_dim1 = *ldy;
y_offset = 1 + y_dim1;
y -= y_offset;
/* Function Body */
if (*m <= 0 || *n <= 0) {
return 0;
}
if (*m >= *n) {
/* Reduce to upper bidiagonal form */
i__1 = *nb;
for (i__ = 1; i__ <= i__1; ++i__) {
/* Update A(i:m,i) */
i__2 = i__ - 1;
zlacgv_(&i__2, &y[i__ + y_dim1], ldy);
i__2 = *m - i__ + 1;
i__3 = i__ - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__3, &z__1, &a[i__ + a_dim1], lda,
&y[i__ + y_dim1], ldy, &c_b2, &a[i__ + i__ * a_dim1], &
c__1);
i__2 = i__ - 1;
zlacgv_(&i__2, &y[i__ + y_dim1], ldy);
i__2 = *m - i__ + 1;
i__3 = i__ - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__3, &z__1, &x[i__ + x_dim1], ldx,
&a[i__ * a_dim1 + 1], &c__1, &c_b2, &a[i__ + i__ *
a_dim1], &c__1);
/* Generate reflection Q(i) to annihilate A(i+1:m,i) */
i__2 = i__ + i__ * a_dim1;
alpha.r = a[i__2].r, alpha.i = a[i__2].i;
i__2 = *m - i__ + 1;
/* Computing MIN */
i__3 = i__ + 1;
zlarfg_(&i__2, &alpha, &a[min(i__3, *m)+ i__ * a_dim1], &c__1, &
tauq[i__]);
i__2 = i__;
d__[i__2] = alpha.r;
if (i__ < *n) {
i__2 = i__ + i__ * a_dim1;
a[i__2].r = 1., a[i__2].i = 0.;
/* Compute Y(i+1:n,i) */
i__2 = *m - i__ + 1;
i__3 = *n - i__;
zgemv_("Conjugate transpose", &i__2, &i__3, &c_b2, &a[i__ + (
i__ + 1) * a_dim1], lda, &a[i__ + i__ * a_dim1], &
c__1, &c_b1, &y[i__ + 1 + i__ * y_dim1], &c__1);
i__2 = *m - i__ + 1;
i__3 = i__ - 1;
zgemv_("Conjugate transpose", &i__2, &i__3, &c_b2, &a[i__ +
a_dim1], lda, &a[i__ + i__ * a_dim1], &c__1, &c_b1, &
y[i__ * y_dim1 + 1], &c__1);
i__2 = *n - i__;
i__3 = i__ - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__3, &z__1, &y[i__ + 1 +
y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b2, &y[
i__ + 1 + i__ * y_dim1], &c__1);
i__2 = *m - i__ + 1;
i__3 = i__ - 1;
zgemv_("Conjugate transpose", &i__2, &i__3, &c_b2, &x[i__ +
x_dim1], ldx, &a[i__ + i__ * a_dim1], &c__1, &c_b1, &
y[i__ * y_dim1 + 1], &c__1);
i__2 = i__ - 1;
i__3 = *n - i__;
z__1.r = -1., z__1.i = -0.;
zgemv_("Conjugate transpose", &i__2, &i__3, &z__1, &a[(i__ +
1) * a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, &
c_b2, &y[i__ + 1 + i__ * y_dim1], &c__1);
i__2 = *n - i__;
zscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1);
/* Update A(i,i+1:n) */
i__2 = *n - i__;
zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda);
zlacgv_(&i__, &a[i__ + a_dim1], lda);
i__2 = *n - i__;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__, &z__1, &y[i__ + 1 +
y_dim1], ldy, &a[i__ + a_dim1], lda, &c_b2, &a[i__ + (
i__ + 1) * a_dim1], lda);
zlacgv_(&i__, &a[i__ + a_dim1], lda);
i__2 = i__ - 1;
zlacgv_(&i__2, &x[i__ + x_dim1], ldx);
i__2 = i__ - 1;
i__3 = *n - i__;
z__1.r = -1., z__1.i = -0.;
zgemv_("Conjugate transpose", &i__2, &i__3, &z__1, &a[(i__ +
1) * a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b2, &
a[i__ + (i__ + 1) * a_dim1], lda);
i__2 = i__ - 1;
zlacgv_(&i__2, &x[i__ + x_dim1], ldx);
/* Generate reflection P(i) to annihilate A(i,i+2:n) */
i__2 = i__ + (i__ + 1) * a_dim1;
alpha.r = a[i__2].r, alpha.i = a[i__2].i;
i__2 = *n - i__;
/* Computing MIN */
i__3 = i__ + 2;
zlarfg_(&i__2, &alpha, &a[i__ + min(i__3, *n)* a_dim1], lda, &
taup[i__]);
i__2 = i__;
e[i__2] = alpha.r;
i__2 = i__ + (i__ + 1) * a_dim1;
a[i__2].r = 1., a[i__2].i = 0.;
/* Compute X(i+1:m,i) */
i__2 = *m - i__;
i__3 = *n - i__;
zgemv_("No transpose", &i__2, &i__3, &c_b2, &a[i__ + 1 + (i__
+ 1) * a_dim1], lda, &a[i__ + (i__ + 1) * a_dim1],
lda, &c_b1, &x[i__ + 1 + i__ * x_dim1], &c__1);
i__2 = *n - i__;
zgemv_("Conjugate transpose", &i__2, &i__, &c_b2, &y[i__ + 1
+ y_dim1], ldy, &a[i__ + (i__ + 1) * a_dim1], lda, &
c_b1, &x[i__ * x_dim1 + 1], &c__1);
i__2 = *m - i__;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__, &z__1, &a[i__ + 1 +
a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b2, &x[
i__ + 1 + i__ * x_dim1], &c__1);
i__2 = i__ - 1;
i__3 = *n - i__;
zgemv_("No transpose", &i__2, &i__3, &c_b2, &a[(i__ + 1) *
a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, &
c_b1, &x[i__ * x_dim1 + 1], &c__1);
i__2 = *m - i__;
i__3 = i__ - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__3, &z__1, &x[i__ + 1 +
x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b2, &x[
i__ + 1 + i__ * x_dim1], &c__1);
i__2 = *m - i__;
zscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1);
i__2 = *n - i__;
zlacgv_(&i__2, &a[i__ + (i__ + 1) * a_dim1], lda);
}
/* L10: */
}
} else {
/* Reduce to lower bidiagonal form */
i__1 = *nb;
for (i__ = 1; i__ <= i__1; ++i__) {
/* Update A(i,i:n) */
i__2 = *n - i__ + 1;
zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda);
i__2 = i__ - 1;
zlacgv_(&i__2, &a[i__ + a_dim1], lda);
i__2 = *n - i__ + 1;
i__3 = i__ - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__3, &z__1, &y[i__ + y_dim1], ldy,
&a[i__ + a_dim1], lda, &c_b2, &a[i__ + i__ * a_dim1],
lda);
i__2 = i__ - 1;
zlacgv_(&i__2, &a[i__ + a_dim1], lda);
i__2 = i__ - 1;
zlacgv_(&i__2, &x[i__ + x_dim1], ldx);
i__2 = i__ - 1;
i__3 = *n - i__ + 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("Conjugate transpose", &i__2, &i__3, &z__1, &a[i__ *
a_dim1 + 1], lda, &x[i__ + x_dim1], ldx, &c_b2, &a[i__ +
i__ * a_dim1], lda);
i__2 = i__ - 1;
zlacgv_(&i__2, &x[i__ + x_dim1], ldx);
/* Generate reflection P(i) to annihilate A(i,i+1:n) */
i__2 = i__ + i__ * a_dim1;
alpha.r = a[i__2].r, alpha.i = a[i__2].i;
i__2 = *n - i__ + 1;
/* Computing MIN */
i__3 = i__ + 1;
zlarfg_(&i__2, &alpha, &a[i__ + min(i__3, *n)* a_dim1], lda, &
taup[i__]);
i__2 = i__;
d__[i__2] = alpha.r;
if (i__ < *m) {
i__2 = i__ + i__ * a_dim1;
a[i__2].r = 1., a[i__2].i = 0.;
/* Compute X(i+1:m,i) */
i__2 = *m - i__;
i__3 = *n - i__ + 1;
zgemv_("No transpose", &i__2, &i__3, &c_b2, &a[i__ + 1 + i__ *
a_dim1], lda, &a[i__ + i__ * a_dim1], lda, &c_b1, &x[
i__ + 1 + i__ * x_dim1], &c__1);
i__2 = *n - i__ + 1;
i__3 = i__ - 1;
zgemv_("Conjugate transpose", &i__2, &i__3, &c_b2, &y[i__ +
y_dim1], ldy, &a[i__ + i__ * a_dim1], lda, &c_b1, &x[
i__ * x_dim1 + 1], &c__1);
i__2 = *m - i__;
i__3 = i__ - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__3, &z__1, &a[i__ + 1 +
a_dim1], lda, &x[i__ * x_dim1 + 1], &c__1, &c_b2, &x[
i__ + 1 + i__ * x_dim1], &c__1);
i__2 = i__ - 1;
i__3 = *n - i__ + 1;
zgemv_("No transpose", &i__2, &i__3, &c_b2, &a[i__ * a_dim1 +
1], lda, &a[i__ + i__ * a_dim1], lda, &c_b1, &x[i__ *
x_dim1 + 1], &c__1);
i__2 = *m - i__;
i__3 = i__ - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__3, &z__1, &x[i__ + 1 +
x_dim1], ldx, &x[i__ * x_dim1 + 1], &c__1, &c_b2, &x[
i__ + 1 + i__ * x_dim1], &c__1);
i__2 = *m - i__;
zscal_(&i__2, &taup[i__], &x[i__ + 1 + i__ * x_dim1], &c__1);
i__2 = *n - i__ + 1;
zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda);
/* Update A(i+1:m,i) */
i__2 = i__ - 1;
zlacgv_(&i__2, &y[i__ + y_dim1], ldy);
i__2 = *m - i__;
i__3 = i__ - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__3, &z__1, &a[i__ + 1 +
a_dim1], lda, &y[i__ + y_dim1], ldy, &c_b2, &a[i__ +
1 + i__ * a_dim1], &c__1);
i__2 = i__ - 1;
zlacgv_(&i__2, &y[i__ + y_dim1], ldy);
i__2 = *m - i__;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__, &z__1, &x[i__ + 1 +
x_dim1], ldx, &a[i__ * a_dim1 + 1], &c__1, &c_b2, &a[
i__ + 1 + i__ * a_dim1], &c__1);
/* Generate reflection Q(i) to annihilate A(i+2:m,i) */
i__2 = i__ + 1 + i__ * a_dim1;
alpha.r = a[i__2].r, alpha.i = a[i__2].i;
i__2 = *m - i__;
/* Computing MIN */
i__3 = i__ + 2;
zlarfg_(&i__2, &alpha, &a[min(i__3, *m)+ i__ * a_dim1], &c__1,
&tauq[i__]);
i__2 = i__;
e[i__2] = alpha.r;
i__2 = i__ + 1 + i__ * a_dim1;
a[i__2].r = 1., a[i__2].i = 0.;
/* Compute Y(i+1:n,i) */
i__2 = *m - i__;
i__3 = *n - i__;
zgemv_("Conjugate transpose", &i__2, &i__3, &c_b2, &a[i__ + 1
+ (i__ + 1) * a_dim1], lda, &a[i__ + 1 + i__ * a_dim1]
, &c__1, &c_b1, &y[i__ + 1 + i__ * y_dim1], &c__1);
i__2 = *m - i__;
i__3 = i__ - 1;
zgemv_("Conjugate transpose", &i__2, &i__3, &c_b2, &a[i__ + 1
+ a_dim1], lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &
c_b1, &y[i__ * y_dim1 + 1], &c__1);
i__2 = *n - i__;
i__3 = i__ - 1;
z__1.r = -1., z__1.i = -0.;
zgemv_("No transpose", &i__2, &i__3, &z__1, &y[i__ + 1 +
y_dim1], ldy, &y[i__ * y_dim1 + 1], &c__1, &c_b2, &y[
i__ + 1 + i__ * y_dim1], &c__1);
i__2 = *m - i__;
zgemv_("Conjugate transpose", &i__2, &i__, &c_b2, &x[i__ + 1
+ x_dim1], ldx, &a[i__ + 1 + i__ * a_dim1], &c__1, &
c_b1, &y[i__ * y_dim1 + 1], &c__1);
i__2 = *n - i__;
z__1.r = -1., z__1.i = -0.;
zgemv_("Conjugate transpose", &i__, &i__2, &z__1, &a[(i__ + 1)
* a_dim1 + 1], lda, &y[i__ * y_dim1 + 1], &c__1, &
c_b2, &y[i__ + 1 + i__ * y_dim1], &c__1);
i__2 = *n - i__;
zscal_(&i__2, &tauq[i__], &y[i__ + 1 + i__ * y_dim1], &c__1);
} else {
i__2 = *n - i__ + 1;
zlacgv_(&i__2, &a[i__ + i__ * a_dim1], lda);
}
/* L20: */
}
}
return 0;
/* End of ZLABRD */
} /* zlabrd_ */
| dacap/loseface | third_party/clapack/SRC/zlabrd.c | C | mit | 16,657 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Qt 4.8: Slider.qml Example File (demos/declarative/flickr/qml/flickr/common/Slider.qml)</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style/superfish.css" />
<link rel="stylesheet" type="text/css" href="style/narrow.css" />
<!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->
<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>
</head>
<body class="" onload="CheckEmptyAndLoadList();">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="narrowsearch"></div>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
<li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul>
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul>
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="supported-platforms.html">Supported Platforms</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul>
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search" id="sidebarsearch">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
<div id="resultdialog">
<a href="#" id="resultclose">Close</a>
<p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p>
<p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p>
<ul id="resultlist" class="all">
</ul>
</div>
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content mainContent">
<h1 class="title">Slider.qml Example File</h1>
<span class="small-subtitle">demos/declarative/flickr/qml/flickr/common/Slider.qml</span>
<!-- $$$demos/declarative/flickr/qml/flickr/common/Slider.qml-description -->
<div class="descr"> <a name="details"></a>
<pre class="qml"> <span class="comment">/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/</span>
import QtQuick 1.0
<span class="type"><a href="qml-item.html">Item</a></span> {
<span class="name">id</span>: <span class="name">slider</span>; <span class="name">width</span>: <span class="number">400</span>; <span class="name">height</span>: <span class="number">16</span>
<span class="comment">// value is read/write.</span>
property <span class="type">real</span> <span class="name">value</span>: <span class="number">1</span>
<span class="name">onValueChanged</span>: <span class="name">updatePos</span>();
property <span class="type">real</span> <span class="name">maximum</span>: <span class="number">1</span>
property <span class="type">real</span> <span class="name">minimum</span>: <span class="number">1</span>
property <span class="type">int</span> <span class="name">xMax</span>: <span class="name">width</span> <span class="operator">-</span> <span class="name">handle</span>.<span class="name">width</span> <span class="operator">-</span> <span class="number">4</span>
<span class="name">onXMaxChanged</span>: <span class="name">updatePos</span>();
<span class="name">onMinimumChanged</span>: <span class="name">updatePos</span>();
<span class="keyword">function</span> <span class="name">updatePos</span>() {
<span class="keyword">if</span> (<span class="name">maximum</span> <span class="operator">></span> <span class="name">minimum</span>) {
var <span class="name">pos</span> = <span class="number">2</span> <span class="operator">+</span> (<span class="name">value</span> <span class="operator">-</span> <span class="name">minimum</span>) <span class="operator">*</span> <span class="name">slider</span>.<span class="name">xMax</span> <span class="operator">/</span> (<span class="name">maximum</span> <span class="operator">-</span> <span class="name">minimum</span>);
<span class="name">pos</span> <span class="operator">=</span> <span class="name">Math</span>.<span class="name">min</span>(<span class="name">pos</span>, <span class="name">width</span> <span class="operator">-</span> <span class="name">handle</span>.<span class="name">width</span> <span class="operator">-</span> <span class="number">2</span>);
<span class="name">pos</span> <span class="operator">=</span> <span class="name">Math</span>.<span class="name">max</span>(<span class="name">pos</span>, <span class="number">2</span>);
<span class="name">handle</span>.<span class="name">x</span> <span class="operator">=</span> <span class="name">pos</span>;
} else {
<span class="name">handle</span>.<span class="name">x</span> <span class="operator">=</span> <span class="number">2</span>;
}
}
<span class="type"><a href="qml-rectangle.html">Rectangle</a></span> {
<span class="name">anchors</span>.fill: <span class="name">parent</span>
<span class="name">border</span>.color: <span class="string">"white"</span>; <span class="name">border</span>.width: <span class="number">0</span>; <span class="name">radius</span>: <span class="number">8</span>
<span class="name">gradient</span>: <span class="name">Gradient</span> {
<span class="type"><a href="qml-gradientstop.html">GradientStop</a></span> { <span class="name">position</span>: <span class="number">0.0</span>; <span class="name">color</span>: <span class="string">"#66343434"</span> }
<span class="type"><a href="qml-gradientstop.html">GradientStop</a></span> { <span class="name">position</span>: <span class="number">1.0</span>; <span class="name">color</span>: <span class="string">"#66000000"</span> }
}
}
<span class="type"><a href="qml-rectangle.html">Rectangle</a></span> {
<span class="name">id</span>: <span class="name">handle</span>; <span class="name">smooth</span>: <span class="number">true</span>
<span class="name">y</span>: <span class="number">2</span>; <span class="name">width</span>: <span class="number">30</span>; <span class="name">height</span>: <span class="name">slider</span>.<span class="name">height</span><span class="operator">-</span><span class="number">4</span>; <span class="name">radius</span>: <span class="number">6</span>
<span class="name">gradient</span>: <span class="name">Gradient</span> {
<span class="type"><a href="qml-gradientstop.html">GradientStop</a></span> { <span class="name">position</span>: <span class="number">0.0</span>; <span class="name">color</span>: <span class="string">"lightgray"</span> }
<span class="type"><a href="qml-gradientstop.html">GradientStop</a></span> { <span class="name">position</span>: <span class="number">1.0</span>; <span class="name">color</span>: <span class="string">"gray"</span> }
}
<span class="type"><a href="qml-mousearea.html">MouseArea</a></span> {
<span class="name">id</span>: <span class="name">mouse</span>
<span class="name">anchors</span>.fill: <span class="name">parent</span>; <span class="name">drag</span>.target: <span class="name">parent</span>
<span class="name">drag</span>.axis: <span class="name">Drag</span>.<span class="name">XAxis</span>; <span class="name">drag</span>.minimumX: <span class="number">2</span>; <span class="name">drag</span>.maximumX: <span class="name">slider</span>.<span class="name">xMax</span><span class="operator">+</span><span class="number">2</span>
<span class="name">onPositionChanged</span>: { <span class="name">value</span> <span class="operator">=</span> (<span class="name">maximum</span> <span class="operator">-</span> <span class="name">minimum</span>) <span class="operator">*</span> (<span class="name">handle</span>.<span class="name">x</span><span class="operator">-</span><span class="number">2</span>) <span class="operator">/</span> <span class="name">slider</span>.<span class="name">xMax</span> <span class="operator">+</span> <span class="name">minimum</span>; }
}
}
}</pre>
</div>
<!-- @@@demos/declarative/flickr/qml/flickr/common/Slider.qml -->
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Digia, Qt and their respective logos are trademarks of Digia Plc
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
<script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>
| stephaneAG/PengPod700 | QtEsrc/qt-everywhere-opensource-src-4.8.5/doc/html/demos-declarative-flickr-qml-flickr-common-slider-qml.html | HTML | mit | 17,496 |
---
layout: post
title: 【译】主动阅读:评注的艺术
category: [思考]
tags: [阅读, 评注, 学习]
published: true
---
# Active Reading: The Art of Annotation | 主动阅读:评注的艺术
> We do not read books in this class; we study literature! At an academic level, it is not enough for you to passively read the words on a page. You must think about words, question ideas, interact with the text, engage with the author, hold conversations and CREATE...
我们已经不再是学生在课堂里读书了,而是研究文学!从学术层面来说,只是被动地阅读书本上的文字是远远不够的。你必须要去思考这些文字的内容,质疑其中的想法,与文字交互,与作者互动,保持交流以及**创造**……
> To succeed in life, you will need to be a proficient reader. One way to strengthen your reading skills is to closely read the texts we study. Reading is not a race -- slow down. The next step is to **annotate the text**. I expect you to annotate EVERY text that we read! But, what is annotation? Dictionary.com states that to annotate means “to supply with critical or explanatory notes; comment upon in notes.” This means that while you are reading, you will be taking notes within the text.
为了成为人生赢家,你需要变成一个阅读的行家。加强阅读技能的一种方式就是仔细阅读我们所学习的内容。阅读不是一场比赛 —— 慢下来。下一步就是**给文字作评注**。我期望你尽可能给阅读的每一处文字都打上评注!但是评注是什么东东?Dictionary.com 上面显示,评注指的是「作重点或者说明性注解」。这就意味着当你阅读的时候,你将会在文本里面做笔记。
> No more curling up on the couch or lying in bed, passively reading; you should have a pen/pencil in hand and be free from other distractions. Unlike "highlighting” alone, which is a passive activity, the process of annotating text helps you to stay focused and involved with the text. Soon you will be concentrating as you read and retaining more information, which will help to improve your comprehension and analysis. **It would be a good idea to purchase the texts each time we read a new book!** If you do not purchase the books, you will need to find a different way to annotate in the school’s books, perhaps by using small **post-it notes**. Occasionally, I may conduct an “annotation check” which will be counted as a quiz grade.
不要再蜷缩在沙发上或躺在床上被动地去阅读,你应该手拿一只钢笔或者铅笔,而且不受其他干扰。不再只是简单地「高亮」,那只是一种被动的行为,评注内容的过程可以帮你保持专注,并让你沉浸到到文字当中去。很快你就会专心于你的阅读并吸收更多的信息,这会有助于提高你的理解和分析能力。**在我们每次阅读一本新书的时候这会是一个好主意!**如果你不买书的话,你就需要用另外一种方式来标注学校里面的书,也许就可以用上小的**便利贴**。有的时候,我可能还会进行「评注检查」来算作测验的分数。
### Becoming an Active Reader Through Annotation | 通过评注成为一个主动的阅读者
> Three main things to consider: decide on the author’s most important points, identify how they fit together, and show how you feel about them.
值得考虑的三大事情:确定作者最重要的见解,理解它们如何相互配合,并且描述你对其感觉如何。
> - To annotate: _underline_, highlight, or flag passages that stand out to you in some way. Make written notes in the margins to connect ideas or make note of important passages. Also make note of specific details that support a main idea or literary theme, and identify your reactions to specific passages (if applicable).
> - Although the more specific your marks, the better it will be when you write your essays, the downfall to annotating is that many people underline or highlight too much! Try to avoid this pitfall. **Remember, annotate according to your purpose!**
- 评注的方式:_下划线_,高亮,或者标记那些在某方面吸引你注意力的段落。在边缘处写下备注,用来关联想法,或者标记重要段落。也可以标注支持某个中心思想或者文学主题的具体细节,或者记下你对于某个段落的反应(如果可以的话)。
- 虽然你标记得越特别,在你写论文的时候就会越好,然而评注不起作用的原因却是很多人的下划线或者高亮太多了!尽量避免这个陷阱。**记住,评注要取决于你的目标!**
> **Consider the following questions as you read:**
**在阅读的时候思考以下问题:**
> > Landsberger, Joe. “Reading Critically.” Study Guides and Strategies. Web. 20 Aug. 2010.
> Landsberger, Joe. “Reading Critically.” Study Guides and Strategies. Web. 20 Aug. 2010.
> - What initial topics or questions are raised for me, the reader?
> - What issues are addressed in the reading?
> - What conclusions does the author reach about the issue(s)?
> - What are the author’s reasons for his or her assertions?
> - Are there passages that stick out in the reading selection? Why does this passage stickout (ask this question for each passage)?
- 最初的主题是什么?我,即读者最开始所提出的问题是什么?
- 阅读材料所提及的问题是什么?
- 作者对于这个(些)问题达成了什么结论?
- 他或她的主张背后的原因是什么?
- 阅读选集的这些段落是否突出了重点?为什么这个段落有所着重(每个段落都要提出这个问题)?
> **Suggestions for annotating include the following:**
**以下是作评注的一些建议:**
> - Label and interpret literary devices (metaphor, simile, imagery, personification, symbol, alliteration, metonymy, synecdoche, etc.) and elements of style (tone, diction, syntax, narrative pace, use of figurative language, etc.)
> - Identify themes, main ideas, supportive details and/or evidence that lead the reader to a conclusion about the text
> - Summarize what you read (minimally)
> - Write questions
> - Converse with the author
> - Make connections to other texts or experiences
- 标签和解释性文学元素(暗喻、明喻、意象、象征、符号、头韵、转喻、提喻,等等)和元素风格(语气、措辞、语法、叙事节奏、比喻性语言的使用,等等)
- 确定主题,主要观点,支持论点的细节以及/或者是引导读者得出内容结论的论据
- 总结所阅读的内容(最小化)
- 写下问题或疑虑
- 与作者谈话
- 跟其他内容或经验建立连接
> **Sample annotated text:**
**评注内容样例:**

| JimmyLv/jimmylv.github.io | 思考/2016-07-20-active-reading-the-art-of-annotation.md | Markdown | mit | 6,929 |
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const ResearchBlochSphere16: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default ResearchBlochSphere16;
| mcliment/DefinitelyTyped | types/carbon__icons-react/lib/research--bloch-sphere/16.d.ts | TypeScript | mit | 240 |
//----------------------------------------------------------------------
// Copyright 2011 Ciaran McHale.
//
// 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.
//----------------------------------------------------------------------
#include "A.h"
#include "Logger.h"
A::A(const FooConfiguration * cfg)
{
m_logLevelOp1 = cfg->getLogLevel("A::op1");
m_logLevelOp2 = cfg->getLogLevel("A::op2");
m_logLevelOp3 = cfg->getLogLevel("A::op3");
}
void
A::op1()
{
log.error(m_logLevelOp1, "A::op1(): this is an error message");
log.info(m_logLevelOp1, "A::op1(): this is an information message");
log.warn(m_logLevelOp1, "A::op1(): this is a warning message");
log.debug(m_logLevelOp1, "A::op1(): this is a debug message");
}
void
A::op2()
{
log.error(m_logLevelOp2, "A::op2(): this is an error message");
log.info(m_logLevelOp2, "A::op2(): this is an information message");
log.warn(m_logLevelOp2, "A::op2(): this is a warning message");
log.debug(m_logLevelOp2, "A::op2(): this is a debug message");
}
void
A::op3()
{
log.error(m_logLevelOp3, "A::op3(): this is an error message");
log.info(m_logLevelOp3, "A::op3(): this is an information message");
log.warn(m_logLevelOp3, "A::op3(): this is a warning message");
log.debug(m_logLevelOp3, "A::op3(): this is a debug message");
}
| offa/config4cpp | demos/log-level/A.cpp | C++ | mit | 2,337 |
/**
* Display warning messages in console to discover potential errors
*/
(function(seajs) {
var uriCache = {}
var RE_VERSION = /\/(?:\d+\.){1,2}\d+\/|\D(?:\d+\.){1,2}\d+[^/]*\.(?:js|css)\W?/
seajs.on("fetch", checkMultiVersion)
// Only support this version style:
// `zz/1.2.3/xx`
// `zz/xx-1.2.3-beta.js`
// `zz/xx.1.2.3.rc2.js`
function checkMultiVersion(data) {
var uri = data.uri
if (!RE_VERSION.test(uri)) return
var key = uri.replace(RE_VERSION, "{version}")
var versions = uriCache[key] || (uriCache[key] = [])
if (indexOf(versions, uri) === -1) {
versions.push(uri)
}
if (versions.length > 1) {
seajs.log("This module has multiple versions:\n" +
versions.join("\n"), "warn")
}
}
// Helpers
var indexOf = [].indexOf ?
function(arr, item) {
return arr.indexOf(item)
} :
function(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) {
return i
}
}
return -1
}
define(seajs.dir + "plugin-warning", [], {})
})(seajs);
| 007slm/seajs | src/plugins/plugin-warning.js | JavaScript | mit | 1,124 |
<?php
/*
* This file is part of the Jirro package.
*
* (c) Rendy Eko Prastiyo <rendyekoprastiyo@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
// login
[
'path' => '/account/login',
'method' => 'GET',
'target' => 'Jirro\Bundle\AccountBundle\Controllers\AuthenticationController::loginAction',
'anonymous' => true,
],
[
'path' => '/account/login',
'method' => 'POST',
'target' => 'Jirro\Bundle\AccountBundle\Controllers\AuthenticationController::loginAction',
'anonymous' => true,
],
// logout
[
'path' => '/account/logout',
'method' => 'GET',
'target' => 'Jirro\Bundle\AccountBundle\Controllers\AuthenticationController::logoutAction',
'anonymous' => true,
],
];
| jirro/jirro | src/Jirro/Bundle/AccountBundle/Resources/config/routes.php | PHP | mit | 937 |
//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Decl subclasses.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/Decl.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/ASTMutationListener.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
using namespace clang;
Decl *clang::getPrimaryMergedDecl(Decl *D) {
return D->getASTContext().getPrimaryMergedDecl(D);
}
// Defined here so that it can be inlined into its direct callers.
bool Decl::isOutOfLine() const {
return !getLexicalDeclContext()->Equals(getDeclContext());
}
TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
: Decl(TranslationUnit, nullptr, SourceLocation()),
DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
}
//===----------------------------------------------------------------------===//
// NamedDecl Implementation
//===----------------------------------------------------------------------===//
// Visibility rules aren't rigorously externally specified, but here
// are the basic principles behind what we implement:
//
// 1. An explicit visibility attribute is generally a direct expression
// of the user's intent and should be honored. Only the innermost
// visibility attribute applies. If no visibility attribute applies,
// global visibility settings are considered.
//
// 2. There is one caveat to the above: on or in a template pattern,
// an explicit visibility attribute is just a default rule, and
// visibility can be decreased by the visibility of template
// arguments. But this, too, has an exception: an attribute on an
// explicit specialization or instantiation causes all the visibility
// restrictions of the template arguments to be ignored.
//
// 3. A variable that does not otherwise have explicit visibility can
// be restricted by the visibility of its type.
//
// 4. A visibility restriction is explicit if it comes from an
// attribute (or something like it), not a global visibility setting.
// When emitting a reference to an external symbol, visibility
// restrictions are ignored unless they are explicit.
//
// 5. When computing the visibility of a non-type, including a
// non-type member of a class, only non-type visibility restrictions
// are considered: the 'visibility' attribute, global value-visibility
// settings, and a few special cases like __private_extern.
//
// 6. When computing the visibility of a type, including a type member
// of a class, only type visibility restrictions are considered:
// the 'type_visibility' attribute and global type-visibility settings.
// However, a 'visibility' attribute counts as a 'type_visibility'
// attribute on any declaration that only has the former.
//
// The visibility of a "secondary" entity, like a template argument,
// is computed using the kind of that entity, not the kind of the
// primary entity for which we are computing visibility. For example,
// the visibility of a specialization of either of these templates:
// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
// template <class T, bool (&compare)(T, X)> class matcher;
// is restricted according to the type visibility of the argument 'T',
// the type visibility of 'bool(&)(T,X)', and the value visibility of
// the argument function 'compare'. That 'has_match' is a value
// and 'matcher' is a type only matters when looking for attributes
// and settings from the immediate context.
const unsigned IgnoreExplicitVisibilityBit = 2;
const unsigned IgnoreAllVisibilityBit = 4;
/// Kinds of LV computation. The linkage side of the computation is
/// always the same, but different things can change how visibility is
/// computed.
enum LVComputationKind {
/// Do an LV computation for, ultimately, a type.
/// Visibility may be restricted by type visibility settings and
/// the visibility of template arguments.
LVForType = NamedDecl::VisibilityForType,
/// Do an LV computation for, ultimately, a non-type declaration.
/// Visibility may be restricted by value visibility settings and
/// the visibility of template arguments.
LVForValue = NamedDecl::VisibilityForValue,
/// Do an LV computation for, ultimately, a type that already has
/// some sort of explicit visibility. Visibility may only be
/// restricted by the visibility of template arguments.
LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
/// Do an LV computation for, ultimately, a non-type declaration
/// that already has some sort of explicit visibility. Visibility
/// may only be restricted by the visibility of template arguments.
LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
/// Do an LV computation when we only care about the linkage.
LVForLinkageOnly =
LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
};
/// Does this computation kind permit us to consider additional
/// visibility settings from attributes and the like?
static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
}
/// Given an LVComputationKind, return one of the same type/value sort
/// that records that it already has explicit visibility.
static LVComputationKind
withExplicitVisibilityAlready(LVComputationKind oldKind) {
LVComputationKind newKind =
static_cast<LVComputationKind>(unsigned(oldKind) |
IgnoreExplicitVisibilityBit);
assert(oldKind != LVForType || newKind == LVForExplicitType);
assert(oldKind != LVForValue || newKind == LVForExplicitValue);
assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
return newKind;
}
static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
LVComputationKind kind) {
assert(!hasExplicitVisibilityAlready(kind) &&
"asking for explicit visibility when we shouldn't be");
return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
}
/// Is the given declaration a "type" or a "value" for the purposes of
/// visibility computation?
static bool usesTypeVisibility(const NamedDecl *D) {
return isa<TypeDecl>(D) ||
isa<ClassTemplateDecl>(D) ||
isa<ObjCInterfaceDecl>(D);
}
/// Does the given declaration have member specialization information,
/// and if so, is it an explicit specialization?
template <class T> static typename
std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
isExplicitMemberSpecialization(const T *D) {
if (const MemberSpecializationInfo *member =
D->getMemberSpecializationInfo()) {
return member->isExplicitSpecialization();
}
return false;
}
/// For templates, this question is easier: a member template can't be
/// explicitly instantiated, so there's a single bit indicating whether
/// or not this is an explicit member specialization.
static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
return D->isMemberSpecialization();
}
/// Given a visibility attribute, return the explicit visibility
/// associated with it.
template <class T>
static Visibility getVisibilityFromAttr(const T *attr) {
switch (attr->getVisibility()) {
case T::Default:
return DefaultVisibility;
case T::Hidden:
return HiddenVisibility;
case T::Protected:
return ProtectedVisibility;
}
llvm_unreachable("bad visibility kind");
}
/// Return the explicit visibility of the given declaration.
static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
NamedDecl::ExplicitVisibilityKind kind) {
// If we're ultimately computing the visibility of a type, look for
// a 'type_visibility' attribute before looking for 'visibility'.
if (kind == NamedDecl::VisibilityForType) {
if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
return getVisibilityFromAttr(A);
}
}
// If this declaration has an explicit visibility attribute, use it.
if (const auto *A = D->getAttr<VisibilityAttr>()) {
return getVisibilityFromAttr(A);
}
// If we're on Mac OS X, an 'availability' for Mac OS X attribute
// implies visibility(default).
if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
for (const auto *A : D->specific_attrs<AvailabilityAttr>())
if (A->getPlatform()->getName().equals("macos"))
return DefaultVisibility;
}
return None;
}
static LinkageInfo
getLVForType(const Type &T, LVComputationKind computation) {
if (computation == LVForLinkageOnly)
return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
return T.getLinkageAndVisibility();
}
/// \brief Get the most restrictive linkage for the types in the given
/// template parameter list. For visibility purposes, template
/// parameters are part of the signature of a template.
static LinkageInfo
getLVForTemplateParameterList(const TemplateParameterList *Params,
LVComputationKind computation) {
LinkageInfo LV;
for (const NamedDecl *P : *Params) {
// Template type parameters are the most common and never
// contribute to visibility, pack or not.
if (isa<TemplateTypeParmDecl>(P))
continue;
// Non-type template parameters can be restricted by the value type, e.g.
// template <enum X> class A { ... };
// We have to be careful here, though, because we can be dealing with
// dependent types.
if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
// Handle the non-pack case first.
if (!NTTP->isExpandedParameterPack()) {
if (!NTTP->getType()->isDependentType()) {
LV.merge(getLVForType(*NTTP->getType(), computation));
}
continue;
}
// Look at all the types in an expanded pack.
for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
QualType type = NTTP->getExpansionType(i);
if (!type->isDependentType())
LV.merge(type->getLinkageAndVisibility());
}
continue;
}
// Template template parameters can be restricted by their
// template parameters, recursively.
const auto *TTP = cast<TemplateTemplateParmDecl>(P);
// Handle the non-pack case first.
if (!TTP->isExpandedParameterPack()) {
LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
computation));
continue;
}
// Look at all expansions in an expanded pack.
for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
i != n; ++i) {
LV.merge(getLVForTemplateParameterList(
TTP->getExpansionTemplateParameters(i), computation));
}
}
return LV;
}
/// getLVForDecl - Get the linkage and visibility for the given declaration.
static LinkageInfo getLVForDecl(const NamedDecl *D,
LVComputationKind computation);
static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
const Decl *Ret = nullptr;
const DeclContext *DC = D->getDeclContext();
while (DC->getDeclKind() != Decl::TranslationUnit) {
if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
Ret = cast<Decl>(DC);
DC = DC->getParent();
}
return Ret;
}
/// \brief Get the most restrictive linkage for the types and
/// declarations in the given template argument list.
///
/// Note that we don't take an LVComputationKind because we always
/// want to honor the visibility of template arguments in the same way.
static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
LVComputationKind computation) {
LinkageInfo LV;
for (const TemplateArgument &Arg : Args) {
switch (Arg.getKind()) {
case TemplateArgument::Null:
case TemplateArgument::Integral:
case TemplateArgument::Expression:
continue;
case TemplateArgument::Type:
LV.merge(getLVForType(*Arg.getAsType(), computation));
continue;
case TemplateArgument::Declaration:
if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
assert(!usesTypeVisibility(ND));
LV.merge(getLVForDecl(ND, computation));
}
continue;
case TemplateArgument::NullPtr:
LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
continue;
case TemplateArgument::Template:
case TemplateArgument::TemplateExpansion:
if (TemplateDecl *Template =
Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
LV.merge(getLVForDecl(Template, computation));
continue;
case TemplateArgument::Pack:
LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
continue;
}
llvm_unreachable("bad template argument kind");
}
return LV;
}
static LinkageInfo
getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
LVComputationKind computation) {
return getLVForTemplateArgumentList(TArgs.asArray(), computation);
}
static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
const FunctionTemplateSpecializationInfo *specInfo) {
// Include visibility from the template parameters and arguments
// only if this is not an explicit instantiation or specialization
// with direct explicit visibility. (Implicit instantiations won't
// have a direct attribute.)
if (!specInfo->isExplicitInstantiationOrSpecialization())
return true;
return !fn->hasAttr<VisibilityAttr>();
}
/// Merge in template-related linkage and visibility for the given
/// function template specialization.
///
/// We don't need a computation kind here because we can assume
/// LVForValue.
///
/// \param[out] LV the computation to use for the parent
static void
mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
const FunctionTemplateSpecializationInfo *specInfo,
LVComputationKind computation) {
bool considerVisibility =
shouldConsiderTemplateVisibility(fn, specInfo);
// Merge information from the template parameters.
FunctionTemplateDecl *temp = specInfo->getTemplate();
LinkageInfo tempLV =
getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
// Merge information from the template arguments.
const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
}
/// Does the given declaration have a direct visibility attribute
/// that would match the given rules?
static bool hasDirectVisibilityAttribute(const NamedDecl *D,
LVComputationKind computation) {
switch (computation) {
case LVForType:
case LVForExplicitType:
if (D->hasAttr<TypeVisibilityAttr>())
return true;
// fallthrough
case LVForValue:
case LVForExplicitValue:
if (D->hasAttr<VisibilityAttr>())
return true;
return false;
case LVForLinkageOnly:
return false;
}
llvm_unreachable("bad visibility computation kind");
}
/// Should we consider visibility associated with the template
/// arguments and parameters of the given class template specialization?
static bool shouldConsiderTemplateVisibility(
const ClassTemplateSpecializationDecl *spec,
LVComputationKind computation) {
// Include visibility from the template parameters and arguments
// only if this is not an explicit instantiation or specialization
// with direct explicit visibility (and note that implicit
// instantiations won't have a direct attribute).
//
// Furthermore, we want to ignore template parameters and arguments
// for an explicit specialization when computing the visibility of a
// member thereof with explicit visibility.
//
// This is a bit complex; let's unpack it.
//
// An explicit class specialization is an independent, top-level
// declaration. As such, if it or any of its members has an
// explicit visibility attribute, that must directly express the
// user's intent, and we should honor it. The same logic applies to
// an explicit instantiation of a member of such a thing.
// Fast path: if this is not an explicit instantiation or
// specialization, we always want to consider template-related
// visibility restrictions.
if (!spec->isExplicitInstantiationOrSpecialization())
return true;
// This is the 'member thereof' check.
if (spec->isExplicitSpecialization() &&
hasExplicitVisibilityAlready(computation))
return false;
return !hasDirectVisibilityAttribute(spec, computation);
}
/// Merge in template-related linkage and visibility for the given
/// class template specialization.
static void mergeTemplateLV(LinkageInfo &LV,
const ClassTemplateSpecializationDecl *spec,
LVComputationKind computation) {
bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
// Merge information from the template parameters, but ignore
// visibility if we're only considering template arguments.
ClassTemplateDecl *temp = spec->getSpecializedTemplate();
LinkageInfo tempLV =
getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
LV.mergeMaybeWithVisibility(tempLV,
considerVisibility && !hasExplicitVisibilityAlready(computation));
// Merge information from the template arguments. We ignore
// template-argument visibility if we've got an explicit
// instantiation with a visibility attribute.
const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
if (considerVisibility)
LV.mergeVisibility(argsLV);
LV.mergeExternalVisibility(argsLV);
}
/// Should we consider visibility associated with the template
/// arguments and parameters of the given variable template
/// specialization? As usual, follow class template specialization
/// logic up to initialization.
static bool shouldConsiderTemplateVisibility(
const VarTemplateSpecializationDecl *spec,
LVComputationKind computation) {
// Include visibility from the template parameters and arguments
// only if this is not an explicit instantiation or specialization
// with direct explicit visibility (and note that implicit
// instantiations won't have a direct attribute).
if (!spec->isExplicitInstantiationOrSpecialization())
return true;
// An explicit variable specialization is an independent, top-level
// declaration. As such, if it has an explicit visibility attribute,
// that must directly express the user's intent, and we should honor
// it.
if (spec->isExplicitSpecialization() &&
hasExplicitVisibilityAlready(computation))
return false;
return !hasDirectVisibilityAttribute(spec, computation);
}
/// Merge in template-related linkage and visibility for the given
/// variable template specialization. As usual, follow class template
/// specialization logic up to initialization.
static void mergeTemplateLV(LinkageInfo &LV,
const VarTemplateSpecializationDecl *spec,
LVComputationKind computation) {
bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
// Merge information from the template parameters, but ignore
// visibility if we're only considering template arguments.
VarTemplateDecl *temp = spec->getSpecializedTemplate();
LinkageInfo tempLV =
getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
LV.mergeMaybeWithVisibility(tempLV,
considerVisibility && !hasExplicitVisibilityAlready(computation));
// Merge information from the template arguments. We ignore
// template-argument visibility if we've got an explicit
// instantiation with a visibility attribute.
const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
if (considerVisibility)
LV.mergeVisibility(argsLV);
LV.mergeExternalVisibility(argsLV);
}
static bool useInlineVisibilityHidden(const NamedDecl *D) {
// FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
const LangOptions &Opts = D->getASTContext().getLangOpts();
if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
return false;
const auto *FD = dyn_cast<FunctionDecl>(D);
if (!FD)
return false;
TemplateSpecializationKind TSK = TSK_Undeclared;
if (FunctionTemplateSpecializationInfo *spec
= FD->getTemplateSpecializationInfo()) {
TSK = spec->getTemplateSpecializationKind();
} else if (MemberSpecializationInfo *MSI =
FD->getMemberSpecializationInfo()) {
TSK = MSI->getTemplateSpecializationKind();
}
const FunctionDecl *Def = nullptr;
// InlineVisibilityHidden only applies to definitions, and
// isInlined() only gives meaningful answers on definitions
// anyway.
return TSK != TSK_ExplicitInstantiationDeclaration &&
TSK != TSK_ExplicitInstantiationDefinition &&
FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
}
template <typename T> static bool isFirstInExternCContext(T *D) {
const T *First = D->getFirstDecl();
return First->isInExternCContext();
}
static bool isSingleLineLanguageLinkage(const Decl &D) {
if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
if (!SD->hasBraces())
return true;
return false;
}
static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
LVComputationKind computation) {
assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
"Not a name having namespace scope");
ASTContext &Context = D->getASTContext();
// C++ [basic.link]p3:
// A name having namespace scope (3.3.6) has internal linkage if it
// is the name of
// - an object, reference, function or function template that is
// explicitly declared static; or,
// (This bullet corresponds to C99 6.2.2p3.)
if (const auto *Var = dyn_cast<VarDecl>(D)) {
// Explicitly declared static.
if (Var->getStorageClass() == SC_Static)
return LinkageInfo::internal();
// - a non-inline, non-volatile object or reference that is explicitly
// declared const or constexpr and neither explicitly declared extern
// nor previously declared to have external linkage; or (there is no
// equivalent in C99)
if (Context.getLangOpts().CPlusPlus &&
Var->getType().isConstQualified() &&
!Var->getType().isVolatileQualified() &&
!Var->isInline()) {
const VarDecl *PrevVar = Var->getPreviousDecl();
if (PrevVar)
return getLVForDecl(PrevVar, computation);
if (Var->getStorageClass() != SC_Extern &&
Var->getStorageClass() != SC_PrivateExtern &&
!isSingleLineLanguageLinkage(*Var))
return LinkageInfo::internal();
}
for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
PrevVar = PrevVar->getPreviousDecl()) {
if (PrevVar->getStorageClass() == SC_PrivateExtern &&
Var->getStorageClass() == SC_None)
return PrevVar->getLinkageAndVisibility();
// Explicitly declared static.
if (PrevVar->getStorageClass() == SC_Static)
return LinkageInfo::internal();
}
} else if (const FunctionDecl *Function = D->getAsFunction()) {
// C++ [temp]p4:
// A non-member function template can have internal linkage; any
// other template name shall have external linkage.
// Explicitly declared static.
if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
return LinkageInfo(InternalLinkage, DefaultVisibility, false);
} else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
// - a data member of an anonymous union.
const VarDecl *VD = IFD->getVarDecl();
assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
return getLVForNamespaceScopeDecl(VD, computation);
}
assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
if (D->isInAnonymousNamespace()) {
const auto *Var = dyn_cast<VarDecl>(D);
const auto *Func = dyn_cast<FunctionDecl>(D);
// FIXME: In C++11 onwards, anonymous namespaces should give decls
// within them internal linkage, not unique external linkage.
if ((!Var || !isFirstInExternCContext(Var)) &&
(!Func || !isFirstInExternCContext(Func)))
return LinkageInfo::uniqueExternal();
}
// Set up the defaults.
// C99 6.2.2p5:
// If the declaration of an identifier for an object has file
// scope and no storage-class specifier, its linkage is
// external.
LinkageInfo LV;
if (!hasExplicitVisibilityAlready(computation)) {
if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
LV.mergeVisibility(*Vis, true);
} else {
// If we're declared in a namespace with a visibility attribute,
// use that namespace's visibility, and it still counts as explicit.
for (const DeclContext *DC = D->getDeclContext();
!isa<TranslationUnitDecl>(DC);
DC = DC->getParent()) {
const auto *ND = dyn_cast<NamespaceDecl>(DC);
if (!ND) continue;
if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
LV.mergeVisibility(*Vis, true);
break;
}
}
}
// Add in global settings if the above didn't give us direct visibility.
if (!LV.isVisibilityExplicit()) {
// Use global type/value visibility as appropriate.
Visibility globalVisibility;
if (computation == LVForValue) {
globalVisibility = Context.getLangOpts().getValueVisibilityMode();
} else {
assert(computation == LVForType);
globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
}
LV.mergeVisibility(globalVisibility, /*explicit*/ false);
// If we're paying attention to global visibility, apply
// -finline-visibility-hidden if this is an inline method.
if (useInlineVisibilityHidden(D))
LV.mergeVisibility(HiddenVisibility, true);
}
}
// C++ [basic.link]p4:
// A name having namespace scope has external linkage if it is the
// name of
//
// - an object or reference, unless it has internal linkage; or
if (const auto *Var = dyn_cast<VarDecl>(D)) {
// GCC applies the following optimization to variables and static
// data members, but not to functions:
//
// Modify the variable's LV by the LV of its type unless this is
// C or extern "C". This follows from [basic.link]p9:
// A type without linkage shall not be used as the type of a
// variable or function with external linkage unless
// - the entity has C language linkage, or
// - the entity is declared within an unnamed namespace, or
// - the entity is not used or is defined in the same
// translation unit.
// and [basic.link]p10:
// ...the types specified by all declarations referring to a
// given variable or function shall be identical...
// C does not have an equivalent rule.
//
// Ignore this if we've got an explicit attribute; the user
// probably knows what they're doing.
//
// Note that we don't want to make the variable non-external
// because of this, but unique-external linkage suits us.
if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
if (TypeLV.getLinkage() != ExternalLinkage)
return LinkageInfo::uniqueExternal();
if (!LV.isVisibilityExplicit())
LV.mergeVisibility(TypeLV);
}
if (Var->getStorageClass() == SC_PrivateExtern)
LV.mergeVisibility(HiddenVisibility, true);
// Note that Sema::MergeVarDecl already takes care of implementing
// C99 6.2.2p4 and propagating the visibility attribute, so we don't have
// to do it here.
// As per function and class template specializations (below),
// consider LV for the template and template arguments. We're at file
// scope, so we do not need to worry about nested specializations.
if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
mergeTemplateLV(LV, spec, computation);
}
// - a function, unless it has internal linkage; or
} else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
// In theory, we can modify the function's LV by the LV of its
// type unless it has C linkage (see comment above about variables
// for justification). In practice, GCC doesn't do this, so it's
// just too painful to make work.
if (Function->getStorageClass() == SC_PrivateExtern)
LV.mergeVisibility(HiddenVisibility, true);
// Note that Sema::MergeCompatibleFunctionDecls already takes care of
// merging storage classes and visibility attributes, so we don't have to
// look at previous decls in here.
// In C++, then if the type of the function uses a type with
// unique-external linkage, it's not legally usable from outside
// this translation unit. However, we should use the C linkage
// rules instead for extern "C" declarations.
if (Context.getLangOpts().CPlusPlus &&
!Function->isInExternCContext()) {
// Only look at the type-as-written. If this function has an auto-deduced
// return type, we can't compute the linkage of that type because it could
// require looking at the linkage of this function, and we don't need this
// for correctness because the type is not part of the function's
// signature.
// FIXME: This is a hack. We should be able to solve this circularity and
// the one in getLVForClassMember for Functions some other way.
QualType TypeAsWritten = Function->getType();
if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
TypeAsWritten = TSI->getType();
if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
return LinkageInfo::uniqueExternal();
}
// Consider LV from the template and the template arguments.
// We're at file scope, so we do not need to worry about nested
// specializations.
if (FunctionTemplateSpecializationInfo *specInfo
= Function->getTemplateSpecializationInfo()) {
mergeTemplateLV(LV, Function, specInfo, computation);
}
// - a named class (Clause 9), or an unnamed class defined in a
// typedef declaration in which the class has the typedef name
// for linkage purposes (7.1.3); or
// - a named enumeration (7.2), or an unnamed enumeration
// defined in a typedef declaration in which the enumeration
// has the typedef name for linkage purposes (7.1.3); or
} else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
// Unnamed tags have no linkage.
if (!Tag->hasNameForLinkage())
return LinkageInfo::none();
// If this is a class template specialization, consider the
// linkage of the template and template arguments. We're at file
// scope, so we do not need to worry about nested specializations.
if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
mergeTemplateLV(LV, spec, computation);
}
// - an enumerator belonging to an enumeration with external linkage;
} else if (isa<EnumConstantDecl>(D)) {
LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
computation);
if (!isExternalFormalLinkage(EnumLV.getLinkage()))
return LinkageInfo::none();
LV.merge(EnumLV);
// - a template, unless it is a function template that has
// internal linkage (Clause 14);
} else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
bool considerVisibility = !hasExplicitVisibilityAlready(computation);
LinkageInfo tempLV =
getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
// - a namespace (7.3), unless it is declared within an unnamed
// namespace.
} else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
return LV;
// By extension, we assign external linkage to Objective-C
// interfaces.
} else if (isa<ObjCInterfaceDecl>(D)) {
// fallout
} else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
// A typedef declaration has linkage if it gives a type a name for
// linkage purposes.
if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
return LinkageInfo::none();
// Everything not covered here has no linkage.
} else {
return LinkageInfo::none();
}
// If we ended up with non-external linkage, visibility should
// always be default.
if (LV.getLinkage() != ExternalLinkage)
return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
return LV;
}
static LinkageInfo getLVForClassMember(const NamedDecl *D,
LVComputationKind computation) {
// Only certain class members have linkage. Note that fields don't
// really have linkage, but it's convenient to say they do for the
// purposes of calculating linkage of pointer-to-data-member
// template arguments.
//
// Templates also don't officially have linkage, but since we ignore
// the C++ standard and look at template arguments when determining
// linkage and visibility of a template specialization, we might hit
// a template template argument that way. If we do, we need to
// consider its linkage.
if (!(isa<CXXMethodDecl>(D) ||
isa<VarDecl>(D) ||
isa<FieldDecl>(D) ||
isa<IndirectFieldDecl>(D) ||
isa<TagDecl>(D) ||
isa<TemplateDecl>(D)))
return LinkageInfo::none();
LinkageInfo LV;
// If we have an explicit visibility attribute, merge that in.
if (!hasExplicitVisibilityAlready(computation)) {
if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
LV.mergeVisibility(*Vis, true);
// If we're paying attention to global visibility, apply
// -finline-visibility-hidden if this is an inline method.
//
// Note that we do this before merging information about
// the class visibility.
if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
LV.mergeVisibility(HiddenVisibility, true);
}
// If this class member has an explicit visibility attribute, the only
// thing that can change its visibility is the template arguments, so
// only look for them when processing the class.
LVComputationKind classComputation = computation;
if (LV.isVisibilityExplicit())
classComputation = withExplicitVisibilityAlready(computation);
LinkageInfo classLV =
getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
// If the class already has unique-external linkage, we can't improve.
if (classLV.getLinkage() == UniqueExternalLinkage)
return LinkageInfo::uniqueExternal();
if (!isExternallyVisible(classLV.getLinkage()))
return LinkageInfo::none();
// Otherwise, don't merge in classLV yet, because in certain cases
// we need to completely ignore the visibility from it.
// Specifically, if this decl exists and has an explicit attribute.
const NamedDecl *explicitSpecSuppressor = nullptr;
if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
// If the type of the function uses a type with unique-external
// linkage, it's not legally usable from outside this translation unit.
// But only look at the type-as-written. If this function has an
// auto-deduced return type, we can't compute the linkage of that type
// because it could require looking at the linkage of this function, and we
// don't need this for correctness because the type is not part of the
// function's signature.
// FIXME: This is a hack. We should be able to solve this circularity and
// the one in getLVForNamespaceScopeDecl for Functions some other way.
{
QualType TypeAsWritten = MD->getType();
if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
TypeAsWritten = TSI->getType();
if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
return LinkageInfo::uniqueExternal();
}
// If this is a method template specialization, use the linkage for
// the template parameters and arguments.
if (FunctionTemplateSpecializationInfo *spec
= MD->getTemplateSpecializationInfo()) {
mergeTemplateLV(LV, MD, spec, computation);
if (spec->isExplicitSpecialization()) {
explicitSpecSuppressor = MD;
} else if (isExplicitMemberSpecialization(spec->getTemplate())) {
explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
}
} else if (isExplicitMemberSpecialization(MD)) {
explicitSpecSuppressor = MD;
}
} else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
mergeTemplateLV(LV, spec, computation);
if (spec->isExplicitSpecialization()) {
explicitSpecSuppressor = spec;
} else {
const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
if (isExplicitMemberSpecialization(temp)) {
explicitSpecSuppressor = temp->getTemplatedDecl();
}
}
} else if (isExplicitMemberSpecialization(RD)) {
explicitSpecSuppressor = RD;
}
// Static data members.
} else if (const auto *VD = dyn_cast<VarDecl>(D)) {
if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
mergeTemplateLV(LV, spec, computation);
// Modify the variable's linkage by its type, but ignore the
// type's visibility unless it's a definition.
LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
LV.mergeVisibility(typeLV);
LV.mergeExternalVisibility(typeLV);
if (isExplicitMemberSpecialization(VD)) {
explicitSpecSuppressor = VD;
}
// Template members.
} else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
bool considerVisibility =
(!LV.isVisibilityExplicit() &&
!classLV.isVisibilityExplicit() &&
!hasExplicitVisibilityAlready(computation));
LinkageInfo tempLV =
getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
if (isExplicitMemberSpecialization(redeclTemp)) {
explicitSpecSuppressor = temp->getTemplatedDecl();
}
}
}
// We should never be looking for an attribute directly on a template.
assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
// If this member is an explicit member specialization, and it has
// an explicit attribute, ignore visibility from the parent.
bool considerClassVisibility = true;
if (explicitSpecSuppressor &&
// optimization: hasDVA() is true only with explicit visibility.
LV.isVisibilityExplicit() &&
classLV.getVisibility() != DefaultVisibility &&
hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
considerClassVisibility = false;
}
// Finally, merge in information from the class.
LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
return LV;
}
void NamedDecl::anchor() { }
static LinkageInfo computeLVForDecl(const NamedDecl *D,
LVComputationKind computation);
bool NamedDecl::isLinkageValid() const {
if (!hasCachedLinkage())
return true;
return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
getCachedLinkage();
}
ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
StringRef name = getName();
if (name.empty()) return SFF_None;
if (name.front() == 'C')
if (name == "CFStringCreateWithFormat" ||
name == "CFStringCreateWithFormatAndArguments" ||
name == "CFStringAppendFormat" ||
name == "CFStringAppendFormatAndArguments")
return SFF_CFString;
return SFF_None;
}
Linkage NamedDecl::getLinkageInternal() const {
// We don't care about visibility here, so ask for the cheapest
// possible visibility analysis.
return getLVForDecl(this, LVForLinkageOnly).getLinkage();
}
LinkageInfo NamedDecl::getLinkageAndVisibility() const {
LVComputationKind computation =
(usesTypeVisibility(this) ? LVForType : LVForValue);
return getLVForDecl(this, computation);
}
static Optional<Visibility>
getExplicitVisibilityAux(const NamedDecl *ND,
NamedDecl::ExplicitVisibilityKind kind,
bool IsMostRecent) {
assert(!IsMostRecent || ND == ND->getMostRecentDecl());
// Check the declaration itself first.
if (Optional<Visibility> V = getVisibilityOf(ND, kind))
return V;
// If this is a member class of a specialization of a class template
// and the corresponding decl has explicit visibility, use that.
if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
if (InstantiatedFrom)
return getVisibilityOf(InstantiatedFrom, kind);
}
// If there wasn't explicit visibility there, and this is a
// specialization of a class template, check for visibility
// on the pattern.
if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
kind);
// Use the most recent declaration.
if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
const NamedDecl *MostRecent = ND->getMostRecentDecl();
if (MostRecent != ND)
return getExplicitVisibilityAux(MostRecent, kind, true);
}
if (const auto *Var = dyn_cast<VarDecl>(ND)) {
if (Var->isStaticDataMember()) {
VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
if (InstantiatedFrom)
return getVisibilityOf(InstantiatedFrom, kind);
}
if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
kind);
return None;
}
// Also handle function template specializations.
if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
// If the function is a specialization of a template with an
// explicit visibility attribute, use that.
if (FunctionTemplateSpecializationInfo *templateInfo
= fn->getTemplateSpecializationInfo())
return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
kind);
// If the function is a member of a specialization of a class template
// and the corresponding decl has explicit visibility, use that.
FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
if (InstantiatedFrom)
return getVisibilityOf(InstantiatedFrom, kind);
return None;
}
// The visibility of a template is stored in the templated decl.
if (const auto *TD = dyn_cast<TemplateDecl>(ND))
return getVisibilityOf(TD->getTemplatedDecl(), kind);
return None;
}
Optional<Visibility>
NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
return getExplicitVisibilityAux(this, kind, false);
}
static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
LVComputationKind computation) {
// This lambda has its linkage/visibility determined by its owner.
if (ContextDecl) {
if (isa<ParmVarDecl>(ContextDecl))
DC = ContextDecl->getDeclContext()->getRedeclContext();
else
return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
}
if (const auto *ND = dyn_cast<NamedDecl>(DC))
return getLVForDecl(ND, computation);
return LinkageInfo::external();
}
static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
LVComputationKind computation) {
if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
if (Function->isInAnonymousNamespace() &&
!Function->isInExternCContext())
return LinkageInfo::uniqueExternal();
// This is a "void f();" which got merged with a file static.
if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
return LinkageInfo::internal();
LinkageInfo LV;
if (!hasExplicitVisibilityAlready(computation)) {
if (Optional<Visibility> Vis =
getExplicitVisibility(Function, computation))
LV.mergeVisibility(*Vis, true);
}
// Note that Sema::MergeCompatibleFunctionDecls already takes care of
// merging storage classes and visibility attributes, so we don't have to
// look at previous decls in here.
return LV;
}
if (const auto *Var = dyn_cast<VarDecl>(D)) {
if (Var->hasExternalStorage()) {
if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
return LinkageInfo::uniqueExternal();
LinkageInfo LV;
if (Var->getStorageClass() == SC_PrivateExtern)
LV.mergeVisibility(HiddenVisibility, true);
else if (!hasExplicitVisibilityAlready(computation)) {
if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
LV.mergeVisibility(*Vis, true);
}
if (const VarDecl *Prev = Var->getPreviousDecl()) {
LinkageInfo PrevLV = getLVForDecl(Prev, computation);
if (PrevLV.getLinkage())
LV.setLinkage(PrevLV.getLinkage());
LV.mergeVisibility(PrevLV);
}
return LV;
}
if (!Var->isStaticLocal())
return LinkageInfo::none();
}
ASTContext &Context = D->getASTContext();
if (!Context.getLangOpts().CPlusPlus)
return LinkageInfo::none();
const Decl *OuterD = getOutermostFuncOrBlockContext(D);
if (!OuterD || OuterD->isInvalidDecl())
return LinkageInfo::none();
LinkageInfo LV;
if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
if (!BD->getBlockManglingNumber())
return LinkageInfo::none();
LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
BD->getBlockManglingContextDecl(), computation);
} else {
const auto *FD = cast<FunctionDecl>(OuterD);
if (!FD->isInlined() &&
!isTemplateInstantiation(FD->getTemplateSpecializationKind()))
return LinkageInfo::none();
LV = getLVForDecl(FD, computation);
}
if (!isExternallyVisible(LV.getLinkage()))
return LinkageInfo::none();
return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
LV.isVisibilityExplicit());
}
static inline const CXXRecordDecl*
getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
const CXXRecordDecl *Ret = Record;
while (Record && Record->isLambda()) {
Ret = Record;
if (!Record->getParent()) break;
// Get the Containing Class of this Lambda Class
Record = dyn_cast_or_null<CXXRecordDecl>(
Record->getParent()->getParent());
}
return Ret;
}
static LinkageInfo computeLVForDecl(const NamedDecl *D,
LVComputationKind computation) {
// Internal_linkage attribute overrides other considerations.
if (D->hasAttr<InternalLinkageAttr>())
return LinkageInfo::internal();
// Objective-C: treat all Objective-C declarations as having external
// linkage.
switch (D->getKind()) {
default:
break;
// Per C++ [basic.link]p2, only the names of objects, references,
// functions, types, templates, namespaces, and values ever have linkage.
//
// Note that the name of a typedef, namespace alias, using declaration,
// and so on are not the name of the corresponding type, namespace, or
// declaration, so they do *not* have linkage.
case Decl::ImplicitParam:
case Decl::Label:
case Decl::NamespaceAlias:
case Decl::ParmVar:
case Decl::Using:
case Decl::UsingShadow:
case Decl::UsingDirective:
return LinkageInfo::none();
case Decl::EnumConstant:
// C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
case Decl::Typedef:
case Decl::TypeAlias:
// A typedef declaration has linkage if it gives a type a name for
// linkage purposes.
if (!D->getASTContext().getLangOpts().CPlusPlus ||
!cast<TypedefNameDecl>(D)
->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
return LinkageInfo::none();
break;
case Decl::TemplateTemplateParm: // count these as external
case Decl::NonTypeTemplateParm:
case Decl::ObjCAtDefsField:
case Decl::ObjCCategory:
case Decl::ObjCCategoryImpl:
case Decl::ObjCCompatibleAlias:
case Decl::ObjCImplementation:
case Decl::ObjCMethod:
case Decl::ObjCProperty:
case Decl::ObjCPropertyImpl:
case Decl::ObjCProtocol:
return LinkageInfo::external();
case Decl::CXXRecord: {
const auto *Record = cast<CXXRecordDecl>(D);
if (Record->isLambda()) {
if (!Record->getLambdaManglingNumber()) {
// This lambda has no mangling number, so it's internal.
return LinkageInfo::internal();
}
// This lambda has its linkage/visibility determined:
// - either by the outermost lambda if that lambda has no mangling
// number.
// - or by the parent of the outer most lambda
// This prevents infinite recursion in settings such as nested lambdas
// used in NSDMI's, for e.g.
// struct L {
// int t{};
// int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
// };
const CXXRecordDecl *OuterMostLambda =
getOutermostEnclosingLambda(Record);
if (!OuterMostLambda->getLambdaManglingNumber())
return LinkageInfo::internal();
return getLVForClosure(
OuterMostLambda->getDeclContext()->getRedeclContext(),
OuterMostLambda->getLambdaContextDecl(), computation);
}
break;
}
}
// Handle linkage for namespace-scope names.
if (D->getDeclContext()->getRedeclContext()->isFileContext())
return getLVForNamespaceScopeDecl(D, computation);
// C++ [basic.link]p5:
// In addition, a member function, static data member, a named
// class or enumeration of class scope, or an unnamed class or
// enumeration defined in a class-scope typedef declaration such
// that the class or enumeration has the typedef name for linkage
// purposes (7.1.3), has external linkage if the name of the class
// has external linkage.
if (D->getDeclContext()->isRecord())
return getLVForClassMember(D, computation);
// C++ [basic.link]p6:
// The name of a function declared in block scope and the name of
// an object declared by a block scope extern declaration have
// linkage. If there is a visible declaration of an entity with
// linkage having the same name and type, ignoring entities
// declared outside the innermost enclosing namespace scope, the
// block scope declaration declares that same entity and receives
// the linkage of the previous declaration. If there is more than
// one such matching entity, the program is ill-formed. Otherwise,
// if no matching entity is found, the block scope entity receives
// external linkage.
if (D->getDeclContext()->isFunctionOrMethod())
return getLVForLocalDecl(D, computation);
// C++ [basic.link]p6:
// Names not covered by these rules have no linkage.
return LinkageInfo::none();
}
namespace clang {
class LinkageComputer {
public:
static LinkageInfo getLVForDecl(const NamedDecl *D,
LVComputationKind computation) {
// Internal_linkage attribute overrides other considerations.
if (D->hasAttr<InternalLinkageAttr>())
return LinkageInfo::internal();
if (computation == LVForLinkageOnly && D->hasCachedLinkage())
return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
LinkageInfo LV = computeLVForDecl(D, computation);
if (D->hasCachedLinkage())
assert(D->getCachedLinkage() == LV.getLinkage());
D->setCachedLinkage(LV.getLinkage());
#ifndef NDEBUG
// In C (because of gnu inline) and in c++ with microsoft extensions an
// static can follow an extern, so we can have two decls with different
// linkages.
const LangOptions &Opts = D->getASTContext().getLangOpts();
if (!Opts.CPlusPlus || Opts.MicrosoftExt)
return LV;
// We have just computed the linkage for this decl. By induction we know
// that all other computed linkages match, check that the one we just
// computed also does.
NamedDecl *Old = nullptr;
for (auto I : D->redecls()) {
auto *T = cast<NamedDecl>(I);
if (T == D)
continue;
if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Old = T;
break;
}
}
assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
#endif
return LV;
}
};
}
static LinkageInfo getLVForDecl(const NamedDecl *D,
LVComputationKind computation) {
return clang::LinkageComputer::getLVForDecl(D, computation);
}
void NamedDecl::printName(raw_ostream &os) const {
os << Name;
}
std::string NamedDecl::getQualifiedNameAsString() const {
std::string QualName;
llvm::raw_string_ostream OS(QualName);
printQualifiedName(OS, getASTContext().getPrintingPolicy());
return OS.str();
}
void NamedDecl::printQualifiedName(raw_ostream &OS) const {
printQualifiedName(OS, getASTContext().getPrintingPolicy());
}
void NamedDecl::printQualifiedName(raw_ostream &OS,
const PrintingPolicy &P) const {
const DeclContext *Ctx = getDeclContext();
if (Ctx->isFunctionOrMethod()) {
printName(OS);
return;
}
typedef SmallVector<const DeclContext *, 8> ContextsTy;
ContextsTy Contexts;
// Collect contexts.
while (Ctx && isa<NamedDecl>(Ctx)) {
Contexts.push_back(Ctx);
Ctx = Ctx->getParent();
}
for (const DeclContext *DC : reverse(Contexts)) {
if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
OS << Spec->getName();
const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
TemplateSpecializationType::PrintTemplateArgumentList(
OS, TemplateArgs.asArray(), P);
} else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
if (P.SuppressUnwrittenScope &&
(ND->isAnonymousNamespace() || ND->isInline()))
continue;
if (ND->isAnonymousNamespace()) {
OS << (P.MSVCFormatting ? "`anonymous namespace\'"
: "(anonymous namespace)");
}
else
OS << *ND;
} else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
if (!RD->getIdentifier())
OS << "(anonymous " << RD->getKindName() << ')';
else
OS << *RD;
} else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
const FunctionProtoType *FT = nullptr;
if (FD->hasWrittenPrototype())
FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
OS << *FD << '(';
if (FT) {
unsigned NumParams = FD->getNumParams();
for (unsigned i = 0; i < NumParams; ++i) {
if (i)
OS << ", ";
OS << FD->getParamDecl(i)->getType().stream(P);
}
if (FT->isVariadic()) {
if (NumParams > 0)
OS << ", ";
OS << "...";
}
}
OS << ')';
} else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
// C++ [dcl.enum]p10: Each enum-name and each unscoped
// enumerator is declared in the scope that immediately contains
// the enum-specifier. Each scoped enumerator is declared in the
// scope of the enumeration.
if (ED->isScoped() || ED->getIdentifier())
OS << *ED;
else
continue;
} else {
OS << *cast<NamedDecl>(DC);
}
OS << "::";
}
if (getDeclName() || isa<DecompositionDecl>(this))
OS << *this;
else
OS << "(anonymous)";
}
void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
const PrintingPolicy &Policy,
bool Qualified) const {
if (Qualified)
printQualifiedName(OS, Policy);
else
printName(OS);
}
template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
return true;
}
static bool isRedeclarableImpl(...) { return false; }
static bool isRedeclarable(Decl::Kind K) {
switch (K) {
#define DECL(Type, Base) \
case Decl::Type: \
return isRedeclarableImpl((Type##Decl *)nullptr);
#define ABSTRACT_DECL(DECL)
#include "clang/AST/DeclNodes.inc"
}
llvm_unreachable("unknown decl kind");
}
bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
// Never replace one imported declaration with another; we need both results
// when re-exporting.
if (OldD->isFromASTFile() && isFromASTFile())
return false;
// A kind mismatch implies that the declaration is not replaced.
if (OldD->getKind() != getKind())
return false;
// For method declarations, we never replace. (Why?)
if (isa<ObjCMethodDecl>(this))
return false;
// For parameters, pick the newer one. This is either an error or (in
// Objective-C) permitted as an extension.
if (isa<ParmVarDecl>(this))
return true;
// Inline namespaces can give us two declarations with the same
// name and kind in the same scope but different contexts; we should
// keep both declarations in this case.
if (!this->getDeclContext()->getRedeclContext()->Equals(
OldD->getDeclContext()->getRedeclContext()))
return false;
// Using declarations can be replaced if they import the same name from the
// same context.
if (auto *UD = dyn_cast<UsingDecl>(this)) {
ASTContext &Context = getASTContext();
return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Context.getCanonicalNestedNameSpecifier(
cast<UsingDecl>(OldD)->getQualifier());
}
if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
ASTContext &Context = getASTContext();
return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Context.getCanonicalNestedNameSpecifier(
cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
}
// UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
// They can be replaced if they nominate the same namespace.
// FIXME: Is this true even if they have different module visibility?
if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
return UD->getNominatedNamespace()->getOriginalNamespace() ==
cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
->getOriginalNamespace();
if (isRedeclarable(getKind())) {
if (getCanonicalDecl() != OldD->getCanonicalDecl())
return false;
if (IsKnownNewer)
return true;
// Check whether this is actually newer than OldD. We want to keep the
// newer declaration. This loop will usually only iterate once, because
// OldD is usually the previous declaration.
for (auto D : redecls()) {
if (D == OldD)
break;
// If we reach the canonical declaration, then OldD is not actually older
// than this one.
//
// FIXME: In this case, we should not add this decl to the lookup table.
if (D->isCanonicalDecl())
return false;
}
// It's a newer declaration of the same kind of declaration in the same
// scope: we want this decl instead of the existing one.
return true;
}
// In all other cases, we need to keep both declarations in case they have
// different visibility. Any attempt to use the name will result in an
// ambiguity if more than one is visible.
return false;
}
bool NamedDecl::hasLinkage() const {
return getFormalLinkage() != NoLinkage;
}
NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
NamedDecl *ND = this;
while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
ND = UD->getTargetDecl();
if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
return AD->getClassInterface();
if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
return AD->getNamespace();
return ND;
}
bool NamedDecl::isCXXInstanceMember() const {
if (!isCXXClassMember())
return false;
const NamedDecl *D = this;
if (isa<UsingShadowDecl>(D))
D = cast<UsingShadowDecl>(D)->getTargetDecl();
if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
return true;
if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
return MD->isInstance();
return false;
}
//===----------------------------------------------------------------------===//
// DeclaratorDecl Implementation
//===----------------------------------------------------------------------===//
template <typename DeclT>
static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
if (decl->getNumTemplateParameterLists() > 0)
return decl->getTemplateParameterList(0)->getTemplateLoc();
else
return decl->getInnerLocStart();
}
SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
TypeSourceInfo *TSI = getTypeSourceInfo();
if (TSI) return TSI->getTypeLoc().getBeginLoc();
return SourceLocation();
}
void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
if (QualifierLoc) {
// Make sure the extended decl info is allocated.
if (!hasExtInfo()) {
// Save (non-extended) type source info pointer.
auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
// Allocate external info struct.
DeclInfo = new (getASTContext()) ExtInfo;
// Restore savedTInfo into (extended) decl info.
getExtInfo()->TInfo = savedTInfo;
}
// Set qualifier info.
getExtInfo()->QualifierLoc = QualifierLoc;
} else {
// Here Qualifier == 0, i.e., we are removing the qualifier (if any).
if (hasExtInfo()) {
if (getExtInfo()->NumTemplParamLists == 0) {
// Save type source info pointer.
TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
// Deallocate the extended decl info.
getASTContext().Deallocate(getExtInfo());
// Restore savedTInfo into (non-extended) decl info.
DeclInfo = savedTInfo;
}
else
getExtInfo()->QualifierLoc = QualifierLoc;
}
}
}
void DeclaratorDecl::setTemplateParameterListsInfo(
ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
assert(!TPLists.empty());
// Make sure the extended decl info is allocated.
if (!hasExtInfo()) {
// Save (non-extended) type source info pointer.
auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
// Allocate external info struct.
DeclInfo = new (getASTContext()) ExtInfo;
// Restore savedTInfo into (extended) decl info.
getExtInfo()->TInfo = savedTInfo;
}
// Set the template parameter lists info.
getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
}
SourceLocation DeclaratorDecl::getOuterLocStart() const {
return getTemplateOrInnerLocStart(this);
}
namespace {
// Helper function: returns true if QT is or contains a type
// having a postfix component.
bool typeIsPostfix(clang::QualType QT) {
while (true) {
const Type* T = QT.getTypePtr();
switch (T->getTypeClass()) {
default:
return false;
case Type::Pointer:
QT = cast<PointerType>(T)->getPointeeType();
break;
case Type::BlockPointer:
QT = cast<BlockPointerType>(T)->getPointeeType();
break;
case Type::MemberPointer:
QT = cast<MemberPointerType>(T)->getPointeeType();
break;
case Type::LValueReference:
case Type::RValueReference:
QT = cast<ReferenceType>(T)->getPointeeType();
break;
case Type::PackExpansion:
QT = cast<PackExpansionType>(T)->getPattern();
break;
case Type::Paren:
case Type::ConstantArray:
case Type::DependentSizedArray:
case Type::IncompleteArray:
case Type::VariableArray:
case Type::FunctionProto:
case Type::FunctionNoProto:
return true;
}
}
}
} // namespace
SourceRange DeclaratorDecl::getSourceRange() const {
SourceLocation RangeEnd = getLocation();
if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
// If the declaration has no name or the type extends past the name take the
// end location of the type.
if (!getDeclName() || typeIsPostfix(TInfo->getType()))
RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
}
return SourceRange(getOuterLocStart(), RangeEnd);
}
void QualifierInfo::setTemplateParameterListsInfo(
ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
// Free previous template parameters (if any).
if (NumTemplParamLists > 0) {
Context.Deallocate(TemplParamLists);
TemplParamLists = nullptr;
NumTemplParamLists = 0;
}
// Set info on matched template parameter lists (if any).
if (!TPLists.empty()) {
TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
NumTemplParamLists = TPLists.size();
std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
}
}
//===----------------------------------------------------------------------===//
// VarDecl Implementation
//===----------------------------------------------------------------------===//
const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
switch (SC) {
case SC_None: break;
case SC_Auto: return "auto";
case SC_Extern: return "extern";
case SC_PrivateExtern: return "__private_extern__";
case SC_Register: return "register";
case SC_Static: return "static";
}
llvm_unreachable("Invalid storage class");
}
VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
StorageClass SC)
: DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
redeclarable_base(C), Init() {
static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
"VarDeclBitfields too large!");
static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
"ParmVarDeclBitfields too large!");
static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
"NonParmVarDeclBitfields too large!");
AllBits = 0;
VarDeclBits.SClass = SC;
// Everything else is implicitly initialized to false.
}
VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation StartL, SourceLocation IdL,
IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
StorageClass S) {
return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
}
VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID)
VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
QualType(), nullptr, SC_None);
}
void VarDecl::setStorageClass(StorageClass SC) {
assert(isLegalForVariable(SC));
VarDeclBits.SClass = SC;
}
VarDecl::TLSKind VarDecl::getTLSKind() const {
switch (VarDeclBits.TSCSpec) {
case TSCS_unspecified:
if (!hasAttr<ThreadAttr>() &&
!(getASTContext().getLangOpts().OpenMPUseTLS &&
getASTContext().getTargetInfo().isTLSSupported() &&
hasAttr<OMPThreadPrivateDeclAttr>()))
return TLS_None;
return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
LangOptions::MSVC2015)) ||
hasAttr<OMPThreadPrivateDeclAttr>())
? TLS_Dynamic
: TLS_Static;
case TSCS___thread: // Fall through.
case TSCS__Thread_local:
return TLS_Static;
case TSCS_thread_local:
return TLS_Dynamic;
}
llvm_unreachable("Unknown thread storage class specifier!");
}
SourceRange VarDecl::getSourceRange() const {
if (const Expr *Init = getInit()) {
SourceLocation InitEnd = Init->getLocEnd();
// If Init is implicit, ignore its source range and fallback on
// DeclaratorDecl::getSourceRange() to handle postfix elements.
if (InitEnd.isValid() && InitEnd != getLocation())
return SourceRange(getOuterLocStart(), InitEnd);
}
return DeclaratorDecl::getSourceRange();
}
template<typename T>
static LanguageLinkage getDeclLanguageLinkage(const T &D) {
// C++ [dcl.link]p1: All function types, function names with external linkage,
// and variable names with external linkage have a language linkage.
if (!D.hasExternalFormalLinkage())
return NoLanguageLinkage;
// Language linkage is a C++ concept, but saying that everything else in C has
// C language linkage fits the implementation nicely.
ASTContext &Context = D.getASTContext();
if (!Context.getLangOpts().CPlusPlus)
return CLanguageLinkage;
// C++ [dcl.link]p4: A C language linkage is ignored in determining the
// language linkage of the names of class members and the function type of
// class member functions.
const DeclContext *DC = D.getDeclContext();
if (DC->isRecord())
return CXXLanguageLinkage;
// If the first decl is in an extern "C" context, any other redeclaration
// will have C language linkage. If the first one is not in an extern "C"
// context, we would have reported an error for any other decl being in one.
if (isFirstInExternCContext(&D))
return CLanguageLinkage;
return CXXLanguageLinkage;
}
template<typename T>
static bool isDeclExternC(const T &D) {
// Since the context is ignored for class members, they can only have C++
// language linkage or no language linkage.
const DeclContext *DC = D.getDeclContext();
if (DC->isRecord()) {
assert(D.getASTContext().getLangOpts().CPlusPlus);
return false;
}
return D.getLanguageLinkage() == CLanguageLinkage;
}
LanguageLinkage VarDecl::getLanguageLinkage() const {
return getDeclLanguageLinkage(*this);
}
bool VarDecl::isExternC() const {
return isDeclExternC(*this);
}
bool VarDecl::isInExternCContext() const {
return getLexicalDeclContext()->isExternCContext();
}
bool VarDecl::isInExternCXXContext() const {
return getLexicalDeclContext()->isExternCXXContext();
}
VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
VarDecl::DefinitionKind
VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
// C++ [basic.def]p2:
// A declaration is a definition unless [...] it contains the 'extern'
// specifier or a linkage-specification and neither an initializer [...],
// it declares a non-inline static data member in a class declaration [...],
// it declares a static data member outside a class definition and the variable
// was defined within the class with the constexpr specifier [...],
// C++1y [temp.expl.spec]p15:
// An explicit specialization of a static data member or an explicit
// specialization of a static data member template is a definition if the
// declaration includes an initializer; otherwise, it is a declaration.
//
// FIXME: How do you declare (but not define) a partial specialization of
// a static data member template outside the containing class?
if (isThisDeclarationADemotedDefinition())
return DeclarationOnly;
if (isStaticDataMember()) {
if (isOutOfLine() &&
!(getCanonicalDecl()->isInline() &&
getCanonicalDecl()->isConstexpr()) &&
(hasInit() ||
// If the first declaration is out-of-line, this may be an
// instantiation of an out-of-line partial specialization of a variable
// template for which we have not yet instantiated the initializer.
(getFirstDecl()->isOutOfLine()
? getTemplateSpecializationKind() == TSK_Undeclared
: getTemplateSpecializationKind() !=
TSK_ExplicitSpecialization) ||
isa<VarTemplatePartialSpecializationDecl>(this)))
return Definition;
else if (!isOutOfLine() && isInline())
return Definition;
else
return DeclarationOnly;
}
// C99 6.7p5:
// A definition of an identifier is a declaration for that identifier that
// [...] causes storage to be reserved for that object.
// Note: that applies for all non-file-scope objects.
// C99 6.9.2p1:
// If the declaration of an identifier for an object has file scope and an
// initializer, the declaration is an external definition for the identifier
if (hasInit())
return Definition;
if (hasDefiningAttr())
return Definition;
if (const auto *SAA = getAttr<SelectAnyAttr>())
if (!SAA->isInherited())
return Definition;
// A variable template specialization (other than a static data member
// template or an explicit specialization) is a declaration until we
// instantiate its initializer.
if (isa<VarTemplateSpecializationDecl>(this) &&
getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
return DeclarationOnly;
if (hasExternalStorage())
return DeclarationOnly;
// [dcl.link] p7:
// A declaration directly contained in a linkage-specification is treated
// as if it contains the extern specifier for the purpose of determining
// the linkage of the declared name and whether it is a definition.
if (isSingleLineLanguageLinkage(*this))
return DeclarationOnly;
// C99 6.9.2p2:
// A declaration of an object that has file scope without an initializer,
// and without a storage class specifier or the scs 'static', constitutes
// a tentative definition.
// No such thing in C++.
if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
return TentativeDefinition;
// What's left is (in C, block-scope) declarations without initializers or
// external storage. These are definitions.
return Definition;
}
VarDecl *VarDecl::getActingDefinition() {
DefinitionKind Kind = isThisDeclarationADefinition();
if (Kind != TentativeDefinition)
return nullptr;
VarDecl *LastTentative = nullptr;
VarDecl *First = getFirstDecl();
for (auto I : First->redecls()) {
Kind = I->isThisDeclarationADefinition();
if (Kind == Definition)
return nullptr;
else if (Kind == TentativeDefinition)
LastTentative = I;
}
return LastTentative;
}
VarDecl *VarDecl::getDefinition(ASTContext &C) {
VarDecl *First = getFirstDecl();
for (auto I : First->redecls()) {
if (I->isThisDeclarationADefinition(C) == Definition)
return I;
}
return nullptr;
}
VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
DefinitionKind Kind = DeclarationOnly;
const VarDecl *First = getFirstDecl();
for (auto I : First->redecls()) {
Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
if (Kind == Definition)
break;
}
return Kind;
}
const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
for (auto I : redecls()) {
if (auto Expr = I->getInit()) {
D = I;
return Expr;
}
}
return nullptr;
}
bool VarDecl::hasInit() const {
if (auto *P = dyn_cast<ParmVarDecl>(this))
if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
return false;
return !Init.isNull();
}
Expr *VarDecl::getInit() {
if (!hasInit())
return nullptr;
if (auto *S = Init.dyn_cast<Stmt *>())
return cast<Expr>(S);
return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
}
Stmt **VarDecl::getInitAddress() {
if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
return &ES->Value;
return Init.getAddrOfPtr1();
}
bool VarDecl::isOutOfLine() const {
if (Decl::isOutOfLine())
return true;
if (!isStaticDataMember())
return false;
// If this static data member was instantiated from a static data member of
// a class template, check whether that static data member was defined
// out-of-line.
if (VarDecl *VD = getInstantiatedFromStaticDataMember())
return VD->isOutOfLine();
return false;
}
void VarDecl::setInit(Expr *I) {
if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Eval->~EvaluatedStmt();
getASTContext().Deallocate(Eval);
}
Init = I;
}
bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
const LangOptions &Lang = C.getLangOpts();
if (!Lang.CPlusPlus)
return false;
// In C++11, any variable of reference type can be used in a constant
// expression if it is initialized by a constant expression.
if (Lang.CPlusPlus11 && getType()->isReferenceType())
return true;
// Only const objects can be used in constant expressions in C++. C++98 does
// not require the variable to be non-volatile, but we consider this to be a
// defect.
if (!getType().isConstQualified() || getType().isVolatileQualified())
return false;
// In C++, const, non-volatile variables of integral or enumeration types
// can be used in constant expressions.
if (getType()->isIntegralOrEnumerationType())
return true;
// Additionally, in C++11, non-volatile constexpr variables can be used in
// constant expressions.
return Lang.CPlusPlus11 && isConstexpr();
}
/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
/// form, which contains extra information on the evaluated value of the
/// initializer.
EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
if (!Eval) {
// Note: EvaluatedStmt contains an APValue, which usually holds
// resources not allocated from the ASTContext. We need to do some
// work to avoid leaking those, but we do so in VarDecl::evaluateValue
// where we can detect whether there's anything to clean up or not.
Eval = new (getASTContext()) EvaluatedStmt;
Eval->Value = Init.get<Stmt *>();
Init = Eval;
}
return Eval;
}
APValue *VarDecl::evaluateValue() const {
SmallVector<PartialDiagnosticAt, 8> Notes;
return evaluateValue(Notes);
}
namespace {
// Destroy an APValue that was allocated in an ASTContext.
void DestroyAPValue(void* UntypedValue) {
static_cast<APValue*>(UntypedValue)->~APValue();
}
} // namespace
APValue *VarDecl::evaluateValue(
SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
EvaluatedStmt *Eval = ensureEvaluatedStmt();
// We only produce notes indicating why an initializer is non-constant the
// first time it is evaluated. FIXME: The notes won't always be emitted the
// first time we try evaluation, so might not be produced at all.
if (Eval->WasEvaluated)
return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
const auto *Init = cast<Expr>(Eval->Value);
assert(!Init->isValueDependent());
if (Eval->IsEvaluating) {
// FIXME: Produce a diagnostic for self-initialization.
Eval->CheckedICE = true;
Eval->IsICE = false;
return nullptr;
}
Eval->IsEvaluating = true;
bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
this, Notes);
// Ensure the computed APValue is cleaned up later if evaluation succeeded,
// or that it's empty (so that there's nothing to clean up) if evaluation
// failed.
if (!Result)
Eval->Evaluated = APValue();
else if (Eval->Evaluated.needsCleanup())
getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Eval->IsEvaluating = false;
Eval->WasEvaluated = true;
// In C++11, we have determined whether the initializer was a constant
// expression as a side-effect.
if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Eval->CheckedICE = true;
Eval->IsICE = Result && Notes.empty();
}
return Result ? &Eval->Evaluated : nullptr;
}
APValue *VarDecl::getEvaluatedValue() const {
if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
if (Eval->WasEvaluated)
return &Eval->Evaluated;
return nullptr;
}
bool VarDecl::isInitKnownICE() const {
if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
return Eval->CheckedICE;
return false;
}
bool VarDecl::isInitICE() const {
assert(isInitKnownICE() &&
"Check whether we already know that the initializer is an ICE");
return Init.get<EvaluatedStmt *>()->IsICE;
}
bool VarDecl::checkInitIsICE() const {
// Initializers of weak variables are never ICEs.
if (isWeak())
return false;
EvaluatedStmt *Eval = ensureEvaluatedStmt();
if (Eval->CheckedICE)
// We have already checked whether this subexpression is an
// integral constant expression.
return Eval->IsICE;
const auto *Init = cast<Expr>(Eval->Value);
assert(!Init->isValueDependent());
// In C++11, evaluate the initializer to check whether it's a constant
// expression.
if (getASTContext().getLangOpts().CPlusPlus11) {
SmallVector<PartialDiagnosticAt, 8> Notes;
evaluateValue(Notes);
return Eval->IsICE;
}
// It's an ICE whether or not the definition we found is
// out-of-line. See DR 721 and the discussion in Clang PR
// 6206 for details.
if (Eval->CheckingICE)
return false;
Eval->CheckingICE = true;
Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
Eval->CheckingICE = false;
Eval->CheckedICE = true;
return Eval->IsICE;
}
VarDecl *VarDecl::getTemplateInstantiationPattern() const {
// If it's a variable template specialization, find the template or partial
// specialization from which it was instantiated.
if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
auto From = VDTemplSpec->getInstantiatedFrom();
if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
if (NewVTD->isMemberSpecialization())
break;
VTD = NewVTD;
}
return VTD->getTemplatedDecl()->getDefinition();
}
if (auto *VTPSD =
From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
if (NewVTPSD->isMemberSpecialization())
break;
VTPSD = NewVTPSD;
}
return VTPSD->getDefinition();
}
}
if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
VarDecl *VD = getInstantiatedFromStaticDataMember();
while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
VD = NewVD;
return VD->getDefinition();
}
}
if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
while (VarTemplate->getInstantiatedFromMemberTemplate()) {
if (VarTemplate->isMemberSpecialization())
break;
VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
}
assert((!VarTemplate->getTemplatedDecl() ||
!isTemplateInstantiation(getTemplateSpecializationKind())) &&
"couldn't find pattern for variable instantiation");
return VarTemplate->getTemplatedDecl();
}
return nullptr;
}
VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
return cast<VarDecl>(MSI->getInstantiatedFrom());
return nullptr;
}
TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
return Spec->getSpecializationKind();
if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
return MSI->getTemplateSpecializationKind();
return TSK_Undeclared;
}
SourceLocation VarDecl::getPointOfInstantiation() const {
if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
return Spec->getPointOfInstantiation();
if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
return MSI->getPointOfInstantiation();
return SourceLocation();
}
VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
return getASTContext().getTemplateOrSpecializationInfo(this)
.dyn_cast<VarTemplateDecl *>();
}
void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
getASTContext().setTemplateOrSpecializationInfo(this, Template);
}
MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
if (isStaticDataMember())
// FIXME: Remove ?
// return getASTContext().getInstantiatedFromStaticDataMember(this);
return getASTContext().getTemplateOrSpecializationInfo(this)
.dyn_cast<MemberSpecializationInfo *>();
return nullptr;
}
void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
SourceLocation PointOfInstantiation) {
assert((isa<VarTemplateSpecializationDecl>(this) ||
getMemberSpecializationInfo()) &&
"not a variable or static data member template specialization");
if (VarTemplateSpecializationDecl *Spec =
dyn_cast<VarTemplateSpecializationDecl>(this)) {
Spec->setSpecializationKind(TSK);
if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Spec->getPointOfInstantiation().isInvalid())
Spec->setPointOfInstantiation(PointOfInstantiation);
}
if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
MSI->setTemplateSpecializationKind(TSK);
if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
MSI->getPointOfInstantiation().isInvalid())
MSI->setPointOfInstantiation(PointOfInstantiation);
}
}
void
VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
TemplateSpecializationKind TSK) {
assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
"Previous template or instantiation?");
getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
}
//===----------------------------------------------------------------------===//
// ParmVarDecl Implementation
//===----------------------------------------------------------------------===//
ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
QualType T, TypeSourceInfo *TInfo,
StorageClass S, Expr *DefArg) {
return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
S, DefArg);
}
QualType ParmVarDecl::getOriginalType() const {
TypeSourceInfo *TSI = getTypeSourceInfo();
QualType T = TSI ? TSI->getType() : getType();
if (const auto *DT = dyn_cast<DecayedType>(T))
return DT->getOriginalType();
return T;
}
ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID)
ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
nullptr, QualType(), nullptr, SC_None, nullptr);
}
SourceRange ParmVarDecl::getSourceRange() const {
if (!hasInheritedDefaultArg()) {
SourceRange ArgRange = getDefaultArgRange();
if (ArgRange.isValid())
return SourceRange(getOuterLocStart(), ArgRange.getEnd());
}
// DeclaratorDecl considers the range of postfix types as overlapping with the
// declaration name, but this is not the case with parameters in ObjC methods.
if (isa<ObjCMethodDecl>(getDeclContext()))
return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
return DeclaratorDecl::getSourceRange();
}
Expr *ParmVarDecl::getDefaultArg() {
assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
assert(!hasUninstantiatedDefaultArg() &&
"Default argument is not yet instantiated!");
Expr *Arg = getInit();
if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
return E->getSubExpr();
return Arg;
}
void ParmVarDecl::setDefaultArg(Expr *defarg) {
ParmVarDeclBits.DefaultArgKind = DAK_Normal;
Init = defarg;
}
SourceRange ParmVarDecl::getDefaultArgRange() const {
switch (ParmVarDeclBits.DefaultArgKind) {
case DAK_None:
case DAK_Unparsed:
// Nothing we can do here.
return SourceRange();
case DAK_Uninstantiated:
return getUninstantiatedDefaultArg()->getSourceRange();
case DAK_Normal:
if (const Expr *E = getInit())
return E->getSourceRange();
// Missing an actual expression, may be invalid.
return SourceRange();
}
llvm_unreachable("Invalid default argument kind.");
}
void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
Init = arg;
}
Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
assert(hasUninstantiatedDefaultArg() &&
"Wrong kind of initialization expression!");
return cast_or_null<Expr>(Init.get<Stmt *>());
}
bool ParmVarDecl::hasDefaultArg() const {
// FIXME: We should just return false for DAK_None here once callers are
// prepared for the case that we encountered an invalid default argument and
// were unable to even build an invalid expression.
return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
!Init.isNull();
}
bool ParmVarDecl::isParameterPack() const {
return isa<PackExpansionType>(getType());
}
void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
getASTContext().setParameterIndex(this, parameterIndex);
ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
}
unsigned ParmVarDecl::getParameterIndexLarge() const {
return getASTContext().getParameterIndex(this);
}
//===----------------------------------------------------------------------===//
// FunctionDecl Implementation
//===----------------------------------------------------------------------===//
void FunctionDecl::getNameForDiagnostic(
raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
if (TemplateArgs)
TemplateSpecializationType::PrintTemplateArgumentList(
OS, TemplateArgs->asArray(), Policy);
}
bool FunctionDecl::isVariadic() const {
if (const auto *FT = getType()->getAs<FunctionProtoType>())
return FT->isVariadic();
return false;
}
bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
for (auto I : redecls()) {
if (I->Body || I->IsLateTemplateParsed) {
Definition = I;
return true;
}
}
return false;
}
bool FunctionDecl::hasTrivialBody() const
{
Stmt *S = getBody();
if (!S) {
// Since we don't have a body for this function, we don't know if it's
// trivial or not.
return false;
}
if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
return true;
return false;
}
bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
for (auto I : redecls()) {
if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
I->hasDefiningAttr()) {
Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
return true;
}
}
return false;
}
Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
if (!hasBody(Definition))
return nullptr;
if (Definition->Body)
return Definition->Body.get(getASTContext().getExternalSource());
return nullptr;
}
void FunctionDecl::setBody(Stmt *B) {
Body = B;
if (B)
EndRangeLoc = B->getLocEnd();
}
void FunctionDecl::setPure(bool P) {
IsPure = P;
if (P)
if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Parent->markedVirtualFunctionPure();
}
template<std::size_t Len>
static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
IdentifierInfo *II = ND->getIdentifier();
return II && II->isStr(Str);
}
bool FunctionDecl::isMain() const {
const TranslationUnitDecl *tunit =
dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
return tunit &&
!tunit->getASTContext().getLangOpts().Freestanding &&
isNamed(this, "main");
}
bool FunctionDecl::isMSVCRTEntryPoint() const {
const TranslationUnitDecl *TUnit =
dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
if (!TUnit)
return false;
// Even though we aren't really targeting MSVCRT if we are freestanding,
// semantic analysis for these functions remains the same.
// MSVCRT entry points only exist on MSVCRT targets.
if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
return false;
// Nameless functions like constructors cannot be entry points.
if (!getIdentifier())
return false;
return llvm::StringSwitch<bool>(getName())
.Cases("main", // an ANSI console app
"wmain", // a Unicode console App
"WinMain", // an ANSI GUI app
"wWinMain", // a Unicode GUI app
"DllMain", // a DLL
true)
.Default(false);
}
bool FunctionDecl::isReservedGlobalPlacementOperator() const {
assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
getDeclName().getCXXOverloadedOperator() == OO_Delete ||
getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
return false;
const auto *proto = getType()->castAs<FunctionProtoType>();
if (proto->getNumParams() != 2 || proto->isVariadic())
return false;
ASTContext &Context =
cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
->getASTContext();
// The result type and first argument type are constant across all
// these operators. The second argument must be exactly void*.
return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
}
bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
return false;
if (getDeclName().getCXXOverloadedOperator() != OO_New &&
getDeclName().getCXXOverloadedOperator() != OO_Delete &&
getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
return false;
if (isa<CXXRecordDecl>(getDeclContext()))
return false;
// This can only fail for an invalid 'operator new' declaration.
if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
return false;
const auto *FPT = getType()->castAs<FunctionProtoType>();
if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
return false;
// If this is a single-parameter function, it must be a replaceable global
// allocation or deallocation function.
if (FPT->getNumParams() == 1)
return true;
unsigned Params = 1;
QualType Ty = FPT->getParamType(Params);
ASTContext &Ctx = getASTContext();
auto Consume = [&] {
++Params;
Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
};
// In C++14, the next parameter can be a 'std::size_t' for sized delete.
bool IsSizedDelete = false;
if (Ctx.getLangOpts().SizedDeallocation &&
(getDeclName().getCXXOverloadedOperator() == OO_Delete ||
getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
Ctx.hasSameType(Ty, Ctx.getSizeType())) {
IsSizedDelete = true;
Consume();
}
// In C++17, the next parameter can be a 'std::align_val_t' for aligned
// new/delete.
if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT())
Consume();
// Finally, if this is not a sized delete, the final parameter can
// be a 'const std::nothrow_t&'.
if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
Ty = Ty->getPointeeType();
if (Ty.getCVRQualifiers() != Qualifiers::Const)
return false;
const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
Consume();
}
return Params == FPT->getNumParams();
}
LanguageLinkage FunctionDecl::getLanguageLinkage() const {
return getDeclLanguageLinkage(*this);
}
bool FunctionDecl::isExternC() const {
return isDeclExternC(*this);
}
bool FunctionDecl::isInExternCContext() const {
return getLexicalDeclContext()->isExternCContext();
}
bool FunctionDecl::isInExternCXXContext() const {
return getLexicalDeclContext()->isExternCXXContext();
}
bool FunctionDecl::isGlobal() const {
if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
return Method->isStatic();
if (getCanonicalDecl()->getStorageClass() == SC_Static)
return false;
for (const DeclContext *DC = getDeclContext();
DC->isNamespace();
DC = DC->getParent()) {
if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
if (!Namespace->getDeclName())
return false;
break;
}
}
return true;
}
bool FunctionDecl::isNoReturn() const {
if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
hasAttr<C11NoReturnAttr>())
return true;
if (auto *FnTy = getType()->getAs<FunctionType>())
return FnTy->getNoReturnAttr();
return false;
}
void
FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
redeclarable_base::setPreviousDecl(PrevDecl);
if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
FunctionTemplateDecl *PrevFunTmpl
= PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
FunTmpl->setPreviousDecl(PrevFunTmpl);
}
if (PrevDecl && PrevDecl->IsInline)
IsInline = true;
}
FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
/// \brief Returns a value indicating whether this function
/// corresponds to a builtin function.
///
/// The function corresponds to a built-in function if it is
/// declared at translation scope or within an extern "C" block and
/// its name matches with the name of a builtin. The returned value
/// will be 0 for functions that do not correspond to a builtin, a
/// value of type \c Builtin::ID if in the target-independent range
/// \c [1,Builtin::First), or a target-specific builtin value.
unsigned FunctionDecl::getBuiltinID() const {
if (!getIdentifier())
return 0;
unsigned BuiltinID = getIdentifier()->getBuiltinID();
if (!BuiltinID)
return 0;
ASTContext &Context = getASTContext();
if (Context.getLangOpts().CPlusPlus) {
const auto *LinkageDecl =
dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
// In C++, the first declaration of a builtin is always inside an implicit
// extern "C".
// FIXME: A recognised library function may not be directly in an extern "C"
// declaration, for instance "extern "C" { namespace std { decl } }".
if (!LinkageDecl) {
if (BuiltinID == Builtin::BI__GetExceptionInfo &&
Context.getTargetInfo().getCXXABI().isMicrosoft())
return Builtin::BI__GetExceptionInfo;
return 0;
}
if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
return 0;
}
// If the function is marked "overloadable", it has a different mangled name
// and is not the C library function.
if (hasAttr<OverloadableAttr>())
return 0;
if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
return BuiltinID;
// This function has the name of a known C library
// function. Determine whether it actually refers to the C library
// function or whether it just has the same name.
// If this is a static function, it's not a builtin.
if (getStorageClass() == SC_Static)
return 0;
// OpenCL v1.2 s6.9.f - The library functions defined in
// the C99 standard headers are not available.
if (Context.getLangOpts().OpenCL &&
Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
return 0;
return BuiltinID;
}
/// getNumParams - Return the number of parameters this function must have
/// based on its FunctionType. This is the length of the ParamInfo array
/// after it has been created.
unsigned FunctionDecl::getNumParams() const {
const auto *FPT = getType()->getAs<FunctionProtoType>();
return FPT ? FPT->getNumParams() : 0;
}
void FunctionDecl::setParams(ASTContext &C,
ArrayRef<ParmVarDecl *> NewParamInfo) {
assert(!ParamInfo && "Already has param info!");
assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
// Zero params -> null pointer.
if (!NewParamInfo.empty()) {
ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
}
}
/// getMinRequiredArguments - Returns the minimum number of arguments
/// needed to call this function. This may be fewer than the number of
/// function parameters, if some of the parameters have default
/// arguments (in C++) or are parameter packs (C++11).
unsigned FunctionDecl::getMinRequiredArguments() const {
if (!getASTContext().getLangOpts().CPlusPlus)
return getNumParams();
unsigned NumRequiredArgs = 0;
for (auto *Param : parameters())
if (!Param->isParameterPack() && !Param->hasDefaultArg())
++NumRequiredArgs;
return NumRequiredArgs;
}
/// \brief The combination of the extern and inline keywords under MSVC forces
/// the function to be required.
///
/// Note: This function assumes that we will only get called when isInlined()
/// would return true for this FunctionDecl.
bool FunctionDecl::isMSExternInline() const {
assert(isInlined() && "expected to get called on an inlined function!");
const ASTContext &Context = getASTContext();
if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
!hasAttr<DLLExportAttr>())
return false;
for (const FunctionDecl *FD = getMostRecentDecl(); FD;
FD = FD->getPreviousDecl())
if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
return true;
return false;
}
static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
if (Redecl->getStorageClass() != SC_Extern)
return false;
for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
FD = FD->getPreviousDecl())
if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
return false;
return true;
}
static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
// Only consider file-scope declarations in this test.
if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
return false;
// Only consider explicit declarations; the presence of a builtin for a
// libcall shouldn't affect whether a definition is externally visible.
if (Redecl->isImplicit())
return false;
if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
return true; // Not an inline definition
return false;
}
/// \brief For a function declaration in C or C++, determine whether this
/// declaration causes the definition to be externally visible.
///
/// For instance, this determines if adding the current declaration to the set
/// of redeclarations of the given functions causes
/// isInlineDefinitionExternallyVisible to change from false to true.
bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
assert(!doesThisDeclarationHaveABody() &&
"Must have a declaration without a body.");
ASTContext &Context = getASTContext();
if (Context.getLangOpts().MSVCCompat) {
const FunctionDecl *Definition;
if (hasBody(Definition) && Definition->isInlined() &&
redeclForcesDefMSVC(this))
return true;
}
if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
// With GNU inlining, a declaration with 'inline' but not 'extern', forces
// an externally visible definition.
//
// FIXME: What happens if gnu_inline gets added on after the first
// declaration?
if (!isInlineSpecified() || getStorageClass() == SC_Extern)
return false;
const FunctionDecl *Prev = this;
bool FoundBody = false;
while ((Prev = Prev->getPreviousDecl())) {
FoundBody |= Prev->Body.isValid();
if (Prev->Body) {
// If it's not the case that both 'inline' and 'extern' are
// specified on the definition, then it is always externally visible.
if (!Prev->isInlineSpecified() ||
Prev->getStorageClass() != SC_Extern)
return false;
} else if (Prev->isInlineSpecified() &&
Prev->getStorageClass() != SC_Extern) {
return false;
}
}
return FoundBody;
}
if (Context.getLangOpts().CPlusPlus)
return false;
// C99 6.7.4p6:
// [...] If all of the file scope declarations for a function in a
// translation unit include the inline function specifier without extern,
// then the definition in that translation unit is an inline definition.
if (isInlineSpecified() && getStorageClass() != SC_Extern)
return false;
const FunctionDecl *Prev = this;
bool FoundBody = false;
while ((Prev = Prev->getPreviousDecl())) {
FoundBody |= Prev->Body.isValid();
if (RedeclForcesDefC99(Prev))
return false;
}
return FoundBody;
}
SourceRange FunctionDecl::getReturnTypeSourceRange() const {
const TypeSourceInfo *TSI = getTypeSourceInfo();
if (!TSI)
return SourceRange();
FunctionTypeLoc FTL =
TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
if (!FTL)
return SourceRange();
// Skip self-referential return types.
const SourceManager &SM = getASTContext().getSourceManager();
SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
SourceLocation Boundary = getNameInfo().getLocStart();
if (RTRange.isInvalid() || Boundary.isInvalid() ||
!SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
return SourceRange();
return RTRange;
}
SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
const TypeSourceInfo *TSI = getTypeSourceInfo();
if (!TSI)
return SourceRange();
FunctionTypeLoc FTL =
TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
if (!FTL)
return SourceRange();
return FTL.getExceptionSpecRange();
}
const Attr *FunctionDecl::getUnusedResultAttr() const {
QualType RetType = getReturnType();
if (RetType->isRecordType()) {
const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
const auto *MD = dyn_cast<CXXMethodDecl>(this);
if (Ret && !(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
return R;
}
} else if (const auto *ET = RetType->getAs<EnumType>()) {
if (const EnumDecl *ED = ET->getDecl()) {
if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
return R;
}
}
return getAttr<WarnUnusedResultAttr>();
}
/// \brief For an inline function definition in C, or for a gnu_inline function
/// in C++, determine whether the definition will be externally visible.
///
/// Inline function definitions are always available for inlining optimizations.
/// However, depending on the language dialect, declaration specifiers, and
/// attributes, the definition of an inline function may or may not be
/// "externally" visible to other translation units in the program.
///
/// In C99, inline definitions are not externally visible by default. However,
/// if even one of the global-scope declarations is marked "extern inline", the
/// inline definition becomes externally visible (C99 6.7.4p6).
///
/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
/// definition, we use the GNU semantics for inline, which are nearly the
/// opposite of C99 semantics. In particular, "inline" by itself will create
/// an externally visible symbol, but "extern inline" will not create an
/// externally visible symbol.
bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
"Must be a function definition");
assert(isInlined() && "Function must be inline");
ASTContext &Context = getASTContext();
if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
// Note: If you change the logic here, please change
// doesDeclarationForceExternallyVisibleDefinition as well.
//
// If it's not the case that both 'inline' and 'extern' are
// specified on the definition, then this inline definition is
// externally visible.
if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
return true;
// If any declaration is 'inline' but not 'extern', then this definition
// is externally visible.
for (auto Redecl : redecls()) {
if (Redecl->isInlineSpecified() &&
Redecl->getStorageClass() != SC_Extern)
return true;
}
return false;
}
// The rest of this function is C-only.
assert(!Context.getLangOpts().CPlusPlus &&
"should not use C inline rules in C++");
// C99 6.7.4p6:
// [...] If all of the file scope declarations for a function in a
// translation unit include the inline function specifier without extern,
// then the definition in that translation unit is an inline definition.
for (auto Redecl : redecls()) {
if (RedeclForcesDefC99(Redecl))
return true;
}
// C99 6.7.4p6:
// An inline definition does not provide an external definition for the
// function, and does not forbid an external definition in another
// translation unit.
return false;
}
/// getOverloadedOperator - Which C++ overloaded operator this
/// function represents, if any.
OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
return getDeclName().getCXXOverloadedOperator();
else
return OO_None;
}
/// getLiteralIdentifier - The literal suffix identifier this function
/// represents, if any.
const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
return getDeclName().getCXXLiteralIdentifier();
else
return nullptr;
}
FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
if (TemplateOrSpecialization.isNull())
return TK_NonTemplate;
if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
return TK_FunctionTemplate;
if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
return TK_MemberSpecialization;
if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
return TK_FunctionTemplateSpecialization;
if (TemplateOrSpecialization.is
<DependentFunctionTemplateSpecializationInfo*>())
return TK_DependentFunctionTemplateSpecialization;
llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
}
FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
return cast<FunctionDecl>(Info->getInstantiatedFrom());
return nullptr;
}
MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
}
void
FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
FunctionDecl *FD,
TemplateSpecializationKind TSK) {
assert(TemplateOrSpecialization.isNull() &&
"Member function is already a specialization");
MemberSpecializationInfo *Info
= new (C) MemberSpecializationInfo(FD, TSK);
TemplateOrSpecialization = Info;
}
FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
}
void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
TemplateOrSpecialization = Template;
}
bool FunctionDecl::isImplicitlyInstantiable() const {
// If the function is invalid, it can't be implicitly instantiated.
if (isInvalidDecl())
return false;
switch (getTemplateSpecializationKind()) {
case TSK_Undeclared:
case TSK_ExplicitInstantiationDefinition:
return false;
case TSK_ImplicitInstantiation:
return true;
// It is possible to instantiate TSK_ExplicitSpecialization kind
// if the FunctionDecl has a class scope specialization pattern.
case TSK_ExplicitSpecialization:
return getClassScopeSpecializationPattern() != nullptr;
case TSK_ExplicitInstantiationDeclaration:
// Handled below.
break;
}
// Find the actual template from which we will instantiate.
const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
bool HasPattern = false;
if (PatternDecl)
HasPattern = PatternDecl->hasBody(PatternDecl);
// C++0x [temp.explicit]p9:
// Except for inline functions, other explicit instantiation declarations
// have the effect of suppressing the implicit instantiation of the entity
// to which they refer.
if (!HasPattern || !PatternDecl)
return true;
return PatternDecl->isInlined();
}
bool FunctionDecl::isTemplateInstantiation() const {
switch (getTemplateSpecializationKind()) {
case TSK_Undeclared:
case TSK_ExplicitSpecialization:
return false;
case TSK_ImplicitInstantiation:
case TSK_ExplicitInstantiationDeclaration:
case TSK_ExplicitInstantiationDefinition:
return true;
}
llvm_unreachable("All TSK values handled.");
}
FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
// Handle class scope explicit specialization special case.
if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
return getClassScopeSpecializationPattern();
// If this is a generic lambda call operator specialization, its
// instantiation pattern is always its primary template's pattern
// even if its primary template was instantiated from another
// member template (which happens with nested generic lambdas).
// Since a lambda's call operator's body is transformed eagerly,
// we don't have to go hunting for a prototype definition template
// (i.e. instantiated-from-member-template) to use as an instantiation
// pattern.
if (isGenericLambdaCallOperatorSpecialization(
dyn_cast<CXXMethodDecl>(this))) {
assert(getPrimaryTemplate() && "A generic lambda specialization must be "
"generated from a primary call operator "
"template");
assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
"A generic lambda call operator template must always have a body - "
"even if instantiated from a prototype (i.e. as written) member "
"template");
return getPrimaryTemplate()->getTemplatedDecl();
}
if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
while (Primary->getInstantiatedFromMemberTemplate()) {
// If we have hit a point where the user provided a specialization of
// this template, we're done looking.
if (Primary->isMemberSpecialization())
break;
Primary = Primary->getInstantiatedFromMemberTemplate();
}
return Primary->getTemplatedDecl();
}
return getInstantiatedFromMemberFunction();
}
FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
if (FunctionTemplateSpecializationInfo *Info
= TemplateOrSpecialization
.dyn_cast<FunctionTemplateSpecializationInfo*>()) {
return Info->Template.getPointer();
}
return nullptr;
}
FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
return getASTContext().getClassScopeSpecializationPattern(this);
}
FunctionTemplateSpecializationInfo *
FunctionDecl::getTemplateSpecializationInfo() const {
return TemplateOrSpecialization
.dyn_cast<FunctionTemplateSpecializationInfo *>();
}
const TemplateArgumentList *
FunctionDecl::getTemplateSpecializationArgs() const {
if (FunctionTemplateSpecializationInfo *Info
= TemplateOrSpecialization
.dyn_cast<FunctionTemplateSpecializationInfo*>()) {
return Info->TemplateArguments;
}
return nullptr;
}
const ASTTemplateArgumentListInfo *
FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
if (FunctionTemplateSpecializationInfo *Info
= TemplateOrSpecialization
.dyn_cast<FunctionTemplateSpecializationInfo*>()) {
return Info->TemplateArgumentsAsWritten;
}
return nullptr;
}
void
FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
FunctionTemplateDecl *Template,
const TemplateArgumentList *TemplateArgs,
void *InsertPos,
TemplateSpecializationKind TSK,
const TemplateArgumentListInfo *TemplateArgsAsWritten,
SourceLocation PointOfInstantiation) {
assert(TSK != TSK_Undeclared &&
"Must specify the type of function template specialization");
FunctionTemplateSpecializationInfo *Info
= TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
if (!Info)
Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
TemplateArgs,
TemplateArgsAsWritten,
PointOfInstantiation);
TemplateOrSpecialization = Info;
Template->addSpecialization(Info, InsertPos);
}
void
FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
const UnresolvedSetImpl &Templates,
const TemplateArgumentListInfo &TemplateArgs) {
assert(TemplateOrSpecialization.isNull());
DependentFunctionTemplateSpecializationInfo *Info =
DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
TemplateArgs);
TemplateOrSpecialization = Info;
}
DependentFunctionTemplateSpecializationInfo *
FunctionDecl::getDependentSpecializationInfo() const {
return TemplateOrSpecialization
.dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
}
DependentFunctionTemplateSpecializationInfo *
DependentFunctionTemplateSpecializationInfo::Create(
ASTContext &Context, const UnresolvedSetImpl &Ts,
const TemplateArgumentListInfo &TArgs) {
void *Buffer = Context.Allocate(
totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
TArgs.size(), Ts.size()));
return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
}
DependentFunctionTemplateSpecializationInfo::
DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
const TemplateArgumentListInfo &TArgs)
: AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
NumTemplates = Ts.size();
NumArgs = TArgs.size();
FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
for (unsigned I = 0, E = Ts.size(); I != E; ++I)
TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
}
TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
// For a function template specialization, query the specialization
// information object.
FunctionTemplateSpecializationInfo *FTSInfo
= TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
if (FTSInfo)
return FTSInfo->getTemplateSpecializationKind();
MemberSpecializationInfo *MSInfo
= TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
if (MSInfo)
return MSInfo->getTemplateSpecializationKind();
return TSK_Undeclared;
}
void
FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
SourceLocation PointOfInstantiation) {
if (FunctionTemplateSpecializationInfo *FTSInfo
= TemplateOrSpecialization.dyn_cast<
FunctionTemplateSpecializationInfo*>()) {
FTSInfo->setTemplateSpecializationKind(TSK);
if (TSK != TSK_ExplicitSpecialization &&
PointOfInstantiation.isValid() &&
FTSInfo->getPointOfInstantiation().isInvalid())
FTSInfo->setPointOfInstantiation(PointOfInstantiation);
} else if (MemberSpecializationInfo *MSInfo
= TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
MSInfo->setTemplateSpecializationKind(TSK);
if (TSK != TSK_ExplicitSpecialization &&
PointOfInstantiation.isValid() &&
MSInfo->getPointOfInstantiation().isInvalid())
MSInfo->setPointOfInstantiation(PointOfInstantiation);
} else
llvm_unreachable("Function cannot have a template specialization kind");
}
SourceLocation FunctionDecl::getPointOfInstantiation() const {
if (FunctionTemplateSpecializationInfo *FTSInfo
= TemplateOrSpecialization.dyn_cast<
FunctionTemplateSpecializationInfo*>())
return FTSInfo->getPointOfInstantiation();
else if (MemberSpecializationInfo *MSInfo
= TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
return MSInfo->getPointOfInstantiation();
return SourceLocation();
}
bool FunctionDecl::isOutOfLine() const {
if (Decl::isOutOfLine())
return true;
// If this function was instantiated from a member function of a
// class template, check whether that member function was defined out-of-line.
if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
const FunctionDecl *Definition;
if (FD->hasBody(Definition))
return Definition->isOutOfLine();
}
// If this function was instantiated from a function template,
// check whether that function template was defined out-of-line.
if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
const FunctionDecl *Definition;
if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
return Definition->isOutOfLine();
}
return false;
}
SourceRange FunctionDecl::getSourceRange() const {
return SourceRange(getOuterLocStart(), EndRangeLoc);
}
unsigned FunctionDecl::getMemoryFunctionKind() const {
IdentifierInfo *FnInfo = getIdentifier();
if (!FnInfo)
return 0;
// Builtin handling.
switch (getBuiltinID()) {
case Builtin::BI__builtin_memset:
case Builtin::BI__builtin___memset_chk:
case Builtin::BImemset:
return Builtin::BImemset;
case Builtin::BI__builtin_memcpy:
case Builtin::BI__builtin___memcpy_chk:
case Builtin::BImemcpy:
return Builtin::BImemcpy;
case Builtin::BI__builtin_memmove:
case Builtin::BI__builtin___memmove_chk:
case Builtin::BImemmove:
return Builtin::BImemmove;
case Builtin::BIstrlcpy:
case Builtin::BI__builtin___strlcpy_chk:
return Builtin::BIstrlcpy;
case Builtin::BIstrlcat:
case Builtin::BI__builtin___strlcat_chk:
return Builtin::BIstrlcat;
case Builtin::BI__builtin_memcmp:
case Builtin::BImemcmp:
return Builtin::BImemcmp;
case Builtin::BI__builtin_strncpy:
case Builtin::BI__builtin___strncpy_chk:
case Builtin::BIstrncpy:
return Builtin::BIstrncpy;
case Builtin::BI__builtin_strncmp:
case Builtin::BIstrncmp:
return Builtin::BIstrncmp;
case Builtin::BI__builtin_strncasecmp:
case Builtin::BIstrncasecmp:
return Builtin::BIstrncasecmp;
case Builtin::BI__builtin_strncat:
case Builtin::BI__builtin___strncat_chk:
case Builtin::BIstrncat:
return Builtin::BIstrncat;
case Builtin::BI__builtin_strndup:
case Builtin::BIstrndup:
return Builtin::BIstrndup;
case Builtin::BI__builtin_strlen:
case Builtin::BIstrlen:
return Builtin::BIstrlen;
case Builtin::BI__builtin_bzero:
case Builtin::BIbzero:
return Builtin::BIbzero;
default:
if (isExternC()) {
if (FnInfo->isStr("memset"))
return Builtin::BImemset;
else if (FnInfo->isStr("memcpy"))
return Builtin::BImemcpy;
else if (FnInfo->isStr("memmove"))
return Builtin::BImemmove;
else if (FnInfo->isStr("memcmp"))
return Builtin::BImemcmp;
else if (FnInfo->isStr("strncpy"))
return Builtin::BIstrncpy;
else if (FnInfo->isStr("strncmp"))
return Builtin::BIstrncmp;
else if (FnInfo->isStr("strncasecmp"))
return Builtin::BIstrncasecmp;
else if (FnInfo->isStr("strncat"))
return Builtin::BIstrncat;
else if (FnInfo->isStr("strndup"))
return Builtin::BIstrndup;
else if (FnInfo->isStr("strlen"))
return Builtin::BIstrlen;
else if (FnInfo->isStr("bzero"))
return Builtin::BIbzero;
}
break;
}
return 0;
}
//===----------------------------------------------------------------------===//
// FieldDecl Implementation
//===----------------------------------------------------------------------===//
FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, QualType T,
TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
InClassInitStyle InitStyle) {
return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
BW, Mutable, InitStyle);
}
FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
SourceLocation(), nullptr, QualType(), nullptr,
nullptr, false, ICIS_NoInit);
}
bool FieldDecl::isAnonymousStructOrUnion() const {
if (!isImplicit() || getDeclName())
return false;
if (const auto *Record = getType()->getAs<RecordType>())
return Record->getDecl()->isAnonymousStructOrUnion();
return false;
}
unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
assert(isBitField() && "not a bitfield");
auto *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
}
unsigned FieldDecl::getFieldIndex() const {
const FieldDecl *Canonical = getCanonicalDecl();
if (Canonical != this)
return Canonical->getFieldIndex();
if (CachedFieldIndex) return CachedFieldIndex - 1;
unsigned Index = 0;
const RecordDecl *RD = getParent();
for (auto *Field : RD->fields()) {
Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
++Index;
}
assert(CachedFieldIndex && "failed to find field in parent");
return CachedFieldIndex - 1;
}
SourceRange FieldDecl::getSourceRange() const {
switch (InitStorage.getInt()) {
// All three of these cases store an optional Expr*.
case ISK_BitWidthOrNothing:
case ISK_InClassCopyInit:
case ISK_InClassListInit:
if (const auto *E = static_cast<const Expr *>(InitStorage.getPointer()))
return SourceRange(getInnerLocStart(), E->getLocEnd());
// FALLTHROUGH
case ISK_CapturedVLAType:
return DeclaratorDecl::getSourceRange();
}
llvm_unreachable("bad init storage kind");
}
void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
"capturing type in non-lambda or captured record.");
assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
InitStorage.getPointer() == nullptr &&
"bit width, initializer or captured type already set");
InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
ISK_CapturedVLAType);
}
//===----------------------------------------------------------------------===//
// TagDecl Implementation
//===----------------------------------------------------------------------===//
SourceLocation TagDecl::getOuterLocStart() const {
return getTemplateOrInnerLocStart(this);
}
SourceRange TagDecl::getSourceRange() const {
SourceLocation RBraceLoc = BraceRange.getEnd();
SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
return SourceRange(getOuterLocStart(), E);
}
TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
TypedefNameDeclOrQualifier = TDD;
if (const Type *T = getTypeForDecl()) {
(void)T;
assert(T->isLinkageValid());
}
assert(isLinkageValid());
}
void TagDecl::startDefinition() {
IsBeingDefined = true;
if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
struct CXXRecordDecl::DefinitionData *Data =
new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
for (auto I : redecls())
cast<CXXRecordDecl>(I)->DefinitionData = Data;
}
}
void TagDecl::completeDefinition() {
assert((!isa<CXXRecordDecl>(this) ||
cast<CXXRecordDecl>(this)->hasDefinition()) &&
"definition completed but not started");
IsCompleteDefinition = true;
IsBeingDefined = false;
if (ASTMutationListener *L = getASTMutationListener())
L->CompletedTagDefinition(this);
}
TagDecl *TagDecl::getDefinition() const {
if (isCompleteDefinition())
return const_cast<TagDecl *>(this);
// If it's possible for us to have an out-of-date definition, check now.
if (MayHaveOutOfDateDef) {
if (IdentifierInfo *II = getIdentifier()) {
if (II->isOutOfDate()) {
updateOutOfDate(*II);
}
}
}
if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
return CXXRD->getDefinition();
for (auto R : redecls())
if (R->isCompleteDefinition())
return R;
return nullptr;
}
void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
if (QualifierLoc) {
// Make sure the extended qualifier info is allocated.
if (!hasExtInfo())
TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
// Set qualifier info.
getExtInfo()->QualifierLoc = QualifierLoc;
} else {
// Here Qualifier == 0, i.e., we are removing the qualifier (if any).
if (hasExtInfo()) {
if (getExtInfo()->NumTemplParamLists == 0) {
getASTContext().Deallocate(getExtInfo());
TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
}
else
getExtInfo()->QualifierLoc = QualifierLoc;
}
}
}
void TagDecl::setTemplateParameterListsInfo(
ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
assert(!TPLists.empty());
// Make sure the extended decl info is allocated.
if (!hasExtInfo())
// Allocate external info struct.
TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
// Set the template parameter lists info.
getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
}
//===----------------------------------------------------------------------===//
// EnumDecl Implementation
//===----------------------------------------------------------------------===//
void EnumDecl::anchor() { }
EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id,
EnumDecl *PrevDecl, bool IsScoped,
bool IsScopedUsingClassTag, bool IsFixed) {
auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
IsScoped, IsScopedUsingClassTag, IsFixed);
Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
C.getTypeDeclType(Enum, PrevDecl);
return Enum;
}
EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
EnumDecl *Enum =
new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
nullptr, nullptr, false, false, false);
Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
return Enum;
}
SourceRange EnumDecl::getIntegerTypeRange() const {
if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
return TI->getTypeLoc().getSourceRange();
return SourceRange();
}
void EnumDecl::completeDefinition(QualType NewType,
QualType NewPromotionType,
unsigned NumPositiveBits,
unsigned NumNegativeBits) {
assert(!isCompleteDefinition() && "Cannot redefine enums!");
if (!IntegerType)
IntegerType = NewType.getTypePtr();
PromotionType = NewPromotionType;
setNumPositiveBits(NumPositiveBits);
setNumNegativeBits(NumNegativeBits);
TagDecl::completeDefinition();
}
TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
return MSI->getTemplateSpecializationKind();
return TSK_Undeclared;
}
void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
SourceLocation PointOfInstantiation) {
MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
assert(MSI && "Not an instantiated member enumeration?");
MSI->setTemplateSpecializationKind(TSK);
if (TSK != TSK_ExplicitSpecialization &&
PointOfInstantiation.isValid() &&
MSI->getPointOfInstantiation().isInvalid())
MSI->setPointOfInstantiation(PointOfInstantiation);
}
EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
EnumDecl *ED = getInstantiatedFromMemberEnum();
while (auto *NewED = ED->getInstantiatedFromMemberEnum())
ED = NewED;
return ED;
}
}
assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
"couldn't find pattern for enum instantiation");
return nullptr;
}
EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
if (SpecializationInfo)
return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
return nullptr;
}
void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
TemplateSpecializationKind TSK) {
assert(!SpecializationInfo && "Member enum is already a specialization");
SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
}
//===----------------------------------------------------------------------===//
// RecordDecl Implementation
//===----------------------------------------------------------------------===//
RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
DeclContext *DC, SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
RecordDecl *PrevDecl)
: TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
HasFlexibleArrayMember = false;
AnonymousStructOrUnion = false;
HasObjectMember = false;
HasVolatileMember = false;
LoadedFieldsFromExternalStorage = false;
assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
}
RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, RecordDecl* PrevDecl) {
RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
StartLoc, IdLoc, Id, PrevDecl);
R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
C.getTypeDeclType(R, PrevDecl);
return R;
}
RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
RecordDecl *R =
new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
SourceLocation(), nullptr, nullptr);
R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
return R;
}
bool RecordDecl::isInjectedClassName() const {
return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
}
bool RecordDecl::isLambda() const {
if (auto RD = dyn_cast<CXXRecordDecl>(this))
return RD->isLambda();
return false;
}
bool RecordDecl::isCapturedRecord() const {
return hasAttr<CapturedRecordAttr>();
}
void RecordDecl::setCapturedRecord() {
addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
}
RecordDecl::field_iterator RecordDecl::field_begin() const {
if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
LoadFieldsFromExternalStorage();
return field_iterator(decl_iterator(FirstDecl));
}
/// completeDefinition - Notes that the definition of this type is now
/// complete.
void RecordDecl::completeDefinition() {
assert(!isCompleteDefinition() && "Cannot redefine record!");
TagDecl::completeDefinition();
}
/// isMsStruct - Get whether or not this record uses ms_struct layout.
/// This which can be turned on with an attribute, pragma, or the
/// -mms-bitfields command-line option.
bool RecordDecl::isMsStruct(const ASTContext &C) const {
return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
}
void RecordDecl::LoadFieldsFromExternalStorage() const {
ExternalASTSource *Source = getASTContext().getExternalSource();
assert(hasExternalLexicalStorage() && Source && "No external storage?");
// Notify that we have a RecordDecl doing some initialization.
ExternalASTSource::Deserializing TheFields(Source);
SmallVector<Decl*, 64> Decls;
LoadedFieldsFromExternalStorage = true;
Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
}, Decls);
#ifndef NDEBUG
// Check that all decls we got were FieldDecls.
for (unsigned i=0, e=Decls.size(); i != e; ++i)
assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
#endif
if (Decls.empty())
return;
std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
/*FieldsAlreadyLoaded=*/false);
}
bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
ASTContext &Context = getASTContext();
if (!Context.getLangOpts().Sanitize.hasOneOf(
SanitizerKind::Address | SanitizerKind::KernelAddress) ||
!Context.getLangOpts().SanitizeAddressFieldPadding)
return false;
const auto &Blacklist = Context.getSanitizerBlacklist();
const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
// We may be able to relax some of these requirements.
int ReasonToReject = -1;
if (!CXXRD || CXXRD->isExternCContext())
ReasonToReject = 0; // is not C++.
else if (CXXRD->hasAttr<PackedAttr>())
ReasonToReject = 1; // is packed.
else if (CXXRD->isUnion())
ReasonToReject = 2; // is a union.
else if (CXXRD->isTriviallyCopyable())
ReasonToReject = 3; // is trivially copyable.
else if (CXXRD->hasTrivialDestructor())
ReasonToReject = 4; // has trivial destructor.
else if (CXXRD->isStandardLayout())
ReasonToReject = 5; // is standard layout.
else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
ReasonToReject = 6; // is in a blacklisted file.
else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
"field-padding"))
ReasonToReject = 7; // is blacklisted.
if (EmitRemark) {
if (ReasonToReject >= 0)
Context.getDiagnostics().Report(
getLocation(),
diag::remark_sanitize_address_insert_extra_padding_rejected)
<< getQualifiedNameAsString() << ReasonToReject;
else
Context.getDiagnostics().Report(
getLocation(),
diag::remark_sanitize_address_insert_extra_padding_accepted)
<< getQualifiedNameAsString();
}
return ReasonToReject < 0;
}
const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
for (const auto *I : fields()) {
if (I->getIdentifier())
return I;
if (const auto *RT = I->getType()->getAs<RecordType>())
if (const FieldDecl *NamedDataMember =
RT->getDecl()->findFirstNamedDataMember())
return NamedDataMember;
}
// We didn't find a named data member.
return nullptr;
}
//===----------------------------------------------------------------------===//
// BlockDecl Implementation
//===----------------------------------------------------------------------===//
void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
assert(!ParamInfo && "Already has param info!");
// Zero params -> null pointer.
if (!NewParamInfo.empty()) {
NumParams = NewParamInfo.size();
ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
}
}
void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
bool CapturesCXXThis) {
this->CapturesCXXThis = CapturesCXXThis;
this->NumCaptures = Captures.size();
if (Captures.empty()) {
this->Captures = nullptr;
return;
}
this->Captures = Captures.copy(Context).data();
}
bool BlockDecl::capturesVariable(const VarDecl *variable) const {
for (const auto &I : captures())
// Only auto vars can be captured, so no redeclaration worries.
if (I.getVariable() == variable)
return true;
return false;
}
SourceRange BlockDecl::getSourceRange() const {
return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
}
//===----------------------------------------------------------------------===//
// Other Decl Allocation/Deallocation Method Implementations
//===----------------------------------------------------------------------===//
void TranslationUnitDecl::anchor() { }
TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
}
void PragmaCommentDecl::anchor() { }
PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
TranslationUnitDecl *DC,
SourceLocation CommentLoc,
PragmaMSCommentKind CommentKind,
StringRef Arg) {
PragmaCommentDecl *PCD =
new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
PragmaCommentDecl(DC, CommentLoc, CommentKind);
memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
return PCD;
}
PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
unsigned ID,
unsigned ArgSize) {
return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
}
void PragmaDetectMismatchDecl::anchor() { }
PragmaDetectMismatchDecl *
PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
SourceLocation Loc, StringRef Name,
StringRef Value) {
size_t ValueStart = Name.size() + 1;
PragmaDetectMismatchDecl *PDMD =
new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
PragmaDetectMismatchDecl(DC, Loc, ValueStart);
memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
Value.size());
PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
return PDMD;
}
PragmaDetectMismatchDecl *
PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
unsigned NameValueSize) {
return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
}
void ExternCContextDecl::anchor() { }
ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
TranslationUnitDecl *DC) {
return new (C, DC) ExternCContextDecl(DC);
}
void LabelDecl::anchor() { }
LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation IdentL, IdentifierInfo *II) {
return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
}
LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation IdentL, IdentifierInfo *II,
SourceLocation GnuLabelL) {
assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
}
LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
SourceLocation());
}
void LabelDecl::setMSAsmLabel(StringRef Name) {
char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
memcpy(Buffer, Name.data(), Name.size());
Buffer[Name.size()] = '\0';
MSAsmName = Buffer;
}
void ValueDecl::anchor() { }
bool ValueDecl::isWeak() const {
for (const auto *I : attrs())
if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
return true;
return isWeakImported();
}
void ImplicitParamDecl::anchor() { }
ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation IdLoc,
IdentifierInfo *Id,
QualType Type) {
return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
}
ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
unsigned ID) {
return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
QualType());
}
FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
StorageClass SC,
bool isInlineSpecified,
bool hasWrittenPrototype,
bool isConstexprSpecified) {
FunctionDecl *New =
new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
SC, isInlineSpecified, isConstexprSpecified);
New->HasWrittenPrototype = hasWrittenPrototype;
return New;
}
FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
DeclarationNameInfo(), QualType(), nullptr,
SC_None, false, false);
}
BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
return new (C, DC) BlockDecl(DC, L);
}
BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID) BlockDecl(nullptr, SourceLocation());
}
CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
: Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
unsigned NumParams) {
return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
CapturedDecl(DC, NumParams);
}
CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
unsigned NumParams) {
return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
CapturedDecl(nullptr, NumParams);
}
Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
SourceLocation L,
IdentifierInfo *Id, QualType T,
Expr *E, const llvm::APSInt &V) {
return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
}
EnumConstantDecl *
EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
QualType(), nullptr, llvm::APSInt());
}
void IndirectFieldDecl::anchor() { }
IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
SourceLocation L, DeclarationName N,
QualType T,
MutableArrayRef<NamedDecl *> CH)
: ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
ChainingSize(CH.size()) {
// In C++, indirect field declarations conflict with tag declarations in the
// same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
if (C.getLangOpts().CPlusPlus)
IdentifierNamespace |= IDNS_Tag;
}
IndirectFieldDecl *
IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
IdentifierInfo *Id, QualType T,
llvm::MutableArrayRef<NamedDecl *> CH) {
return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
}
IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
unsigned ID) {
return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
DeclarationName(), QualType(), None);
}
SourceRange EnumConstantDecl::getSourceRange() const {
SourceLocation End = getLocation();
if (Init)
End = Init->getLocEnd();
return SourceRange(getLocation(), End);
}
void TypeDecl::anchor() { }
TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, TypeSourceInfo *TInfo) {
return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
}
void TypedefNameDecl::anchor() { }
TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
auto *ThisTypedef = this;
if (AnyRedecl && OwningTypedef) {
OwningTypedef = OwningTypedef->getCanonicalDecl();
ThisTypedef = ThisTypedef->getCanonicalDecl();
}
if (OwningTypedef == ThisTypedef)
return TT->getDecl();
}
return nullptr;
}
TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
nullptr, nullptr);
}
TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
TypeSourceInfo *TInfo) {
return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
}
TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
SourceLocation(), nullptr, nullptr);
}
SourceRange TypedefDecl::getSourceRange() const {
SourceLocation RangeEnd = getLocation();
if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
if (typeIsPostfix(TInfo->getType()))
RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
}
return SourceRange(getLocStart(), RangeEnd);
}
SourceRange TypeAliasDecl::getSourceRange() const {
SourceLocation RangeEnd = getLocStart();
if (TypeSourceInfo *TInfo = getTypeSourceInfo())
RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
return SourceRange(getLocStart(), RangeEnd);
}
void FileScopeAsmDecl::anchor() { }
FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
StringLiteral *Str,
SourceLocation AsmLoc,
SourceLocation RParenLoc) {
return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
}
FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
unsigned ID) {
return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
SourceLocation());
}
void EmptyDecl::anchor() {}
EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
return new (C, DC) EmptyDecl(DC, L);
}
EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID) EmptyDecl(nullptr, SourceLocation());
}
//===----------------------------------------------------------------------===//
// ImportDecl Implementation
//===----------------------------------------------------------------------===//
/// \brief Retrieve the number of module identifiers needed to name the given
/// module.
static unsigned getNumModuleIdentifiers(Module *Mod) {
unsigned Result = 1;
while (Mod->Parent) {
Mod = Mod->Parent;
++Result;
}
return Result;
}
ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Module *Imported,
ArrayRef<SourceLocation> IdentifierLocs)
: Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
NextLocalImport()
{
assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
auto *StoredLocs = getTrailingObjects<SourceLocation>();
std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
StoredLocs);
}
ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Module *Imported, SourceLocation EndLoc)
: Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
NextLocalImport()
{
*getTrailingObjects<SourceLocation>() = EndLoc;
}
ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, Module *Imported,
ArrayRef<SourceLocation> IdentifierLocs) {
return new (C, DC,
additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
}
ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc,
Module *Imported,
SourceLocation EndLoc) {
ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
ImportDecl(DC, StartLoc, Imported, EndLoc);
Import->setImplicit();
return Import;
}
ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
unsigned NumLocations) {
return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
ImportDecl(EmptyShell());
}
ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
if (!ImportedAndComplete.getInt())
return None;
const auto *StoredLocs = getTrailingObjects<SourceLocation>();
return llvm::makeArrayRef(StoredLocs,
getNumModuleIdentifiers(getImportedModule()));
}
SourceRange ImportDecl::getSourceRange() const {
if (!ImportedAndComplete.getInt())
return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
return SourceRange(getLocation(), getIdentifierLocs().back());
}
//===----------------------------------------------------------------------===//
// ExportDecl Implementation
//===----------------------------------------------------------------------===//
void ExportDecl::anchor() {}
ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
SourceLocation ExportLoc) {
return new (C, DC) ExportDecl(DC, ExportLoc);
}
ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (C, ID) ExportDecl(nullptr, SourceLocation());
}
| ensemblr/llvm-project-boilerplate | include/llvm/tools/clang/lib/AST/Decl.cpp | C++ | mit | 159,341 |
/******************************************************************************
* The MIT License
*
* Copyright (c) 2010 LeafLabs LLC.
*
* 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.
*****************************************************************************/
/**
* @brief Wire library, ported from Arduino. Provides a lean
* interface to I2C (two-wire) communication.
*/
#include "wirish.h"
#ifndef _WIRE_H_
#define _WIRE_H_
#define uint8_t uint8
typedef struct {
uint8 scl;
uint8 sda;
} Port;
/* You must update the online docs if you change this value. */
#define WIRE_BUFSIZ 32
/* return codes from endTransmission() */
#define SUCCESS 0 /* transmission was successful */
#define EDATA 1 /* too much data */
#define ENACKADDR 2 /* readd nack on transmit of address */
#define ENACKTRNS 3 /* readd nack on transmit of data */
#define EOTHER 4 /* other error */
#define SDA 20
#define SCL 21
#define I2C_WRITE 0
#define I2C_READ 1
#define I2C_DELAY do{for(int i=0;i<40;i++) {asm volatile("nop");}}while(0)
class TwoWire {
private:
uint8 rx_buf[WIRE_BUFSIZ]; /* read buffer */
uint8 rx_buf_idx; /* first unread idx in rx_buf */
uint8 rx_buf_len; /* number of bytes read */
uint8 tx_addr; /* address transmitting to */
uint8 tx_buf[WIRE_BUFSIZ]; /* transmit buffer */
uint8 tx_buf_idx; /* next idx available in tx_buf, -1 overflow */
boolean tx_buf_overflow;
Port port;
uint8 writeOneByte(uint8);
uint8 readOneByte(uint8, uint8*);
public:
TwoWire();
void begin();
void begin(uint8, uint8);
void beginTransmission(uint8);
void beginTransmission(int);
uint8 endTransmission(void);
uint8 requestFrom(uint8, int);
uint8 requestFrom(int, int);
void write(uint8);
void write(uint8*, int);
void write(int);
void write(int*, int);
void write(char*);
uint8 available();
uint8 read();
};
void i2c_start(Port port);
void i2c_stop(Port port);
boolean i2c_get_ack(Port port);
void i2c_write_ack(Port port);
void i2c_write_nack(Port port);
uint8 i2c_shift_in(Port port);
void i2c_shift_out(Port port, uint8 val);
extern TwoWire Wire;
#endif // _WIRE_H_
| chcbaram/OpenCM9.04_IDE_1.5 | hardware/robotis/OpenCM9.04/libraries/Wire/Wire.h | C | mit | 3,322 |
body {
margin: 0.5em 0.5em 0.5em 0.5em;
}
body h1:nth-child(1) {
margin: 0 0 0.5em 0;
}
h1 {
margin: 2em 0 1em 0;
padding: 0.2em;
font-size: 200%;
font-weight: bold;
}
h2 {
margin: 2em 0 1em 0;
padding: 0.2em;
font-size: 150%;
font-weight: bold;
}
h3 {
margin: 2em 0 1em 0;
padding: 0.2em;
font-size: 125%;
font-weight: bold;
}
h4 {
margin: 2em 0 1em 0;
padding: 0.2em;
font-size: 100%;
font-weight: bold;
}
h5 {
margin: 2em 0.5em 1em 0.5em;
padding: 0.2em;
font-size: 100%;
font-weight: bold;
}
h6 {
margin: 2em 1em 1em 1em;
padding: 0.2em;
font-size: 100%;
font-weight: bold;
}
p {
margin: 1em 1em 1em 1em;
}
em {
font-weight: normal;
font-decoration: italic;
}
storng {
font-weight: bold;
font-decoration: none;
}
code {
margin: 0;
padding: 0.3em;
}
pre {
margin: 1em 1em 1em 1em;
padding: 1em;
font-size: 100%;
}
a {
color: #2020a0;
}
a:visited {
color: #202080;
}
blockquote {
margin: 1em 1em 1em 1em;
padding: 0.2em;
}
table {
margin: 1em 1em 1em 1em;
}
th {
padding: 0.2em;
font-weight: normal;
text-align: center;
}
td {
padding: 0.2em;
background-color: white;
}
caption {
padding: 0.3em;
font-weight: normal;
}
hr {
margin: 2em 0 2em 0;
padding: 1px 0 1px 0;
border: solid 1px #c0c0c0;
border-radius: 1px;
background-color: #c0c0c0;
}
li {
}
| keisuken/caffemarkdown | styles/default_with_HTML/style.css | CSS | mit | 1,375 |
// @flow
import net from 'net'
import get from 'lodash/get'
import path from 'path'
// TODO: Remove this in favor of a non-overkill incremental port checker package
const getPort = options =>
new Promise((resolve, reject) => {
const server = net.createServer()
server.unref()
server.on('error', reject)
server.listen(options, () => {
const { port } = server.address()
server.close(() => {
resolve(port)
})
})
})
export function getNextPort(port: number, host: string): Promise<number> {
return getPort({ port, host }).catch(() => getPort({ port: port + 1, host }))
}
export function getStaticMappings(pundle: $FlowFixMe, config: Object): Array<{ local: string, remote: string }> {
const mappings = []
const configStatic = [].concat(get(config, 'dev.static', []))
configStatic.forEach(function(item) {
if (typeof item !== 'string') {
console.error(`Error: --dev.static expects an array or string. Got ${typeof item}`)
return
}
const chunks = item.split('::')
if (chunks.length !== 2) {
console.error(
`Error: Invalid dev.static path: '${item}'. Expected format is localPath::serverPath eg. ./static::/assets`,
)
return
}
const resolved = path.resolve(pundle.context.config.rootDirectory, chunks[0])
mappings.push({ local: resolved, remote: chunks[1] })
})
return mappings
}
| steelbrain/pundle | packages/pundle-cli/src/helpers.js | JavaScript | mit | 1,410 |
---
layout: default
---
{% include wrap.html %}
<div class="container mtb">
<div class="row">
<!-- SINGLE POST -->
<div class="col-lg-10">
<!-- Blog Post -->
<a href="{{ page.url | prepend: site.baseurl }}"><h3 class="ctitle">{{ page.title }}</h3></a>
<p><csmall>{{ page.date | date: "%b %-d, %Y" }}. | By: {{ page.author }}</csmall></p>
<span class="label label-primary">2-4 Players</span>
<span class="label label-primary">Hexagonal Board</span>
<span class="label label-primary">Turn Based</span>
<span class="label label-primary">Strategy and Resource Management</span>
{{ content }}
<div class="spacing"></div>
<!-- <h6>SHARE:</h6>
<p class="share">
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-tumblr"></i></a>
<a href="#"><i class="fa fa-google-plus"></i></a>
</p> -->
</div><!--/col-lg-10 -->
{% include sidebar.html %}
</div><! --/row -->
</div><! --/container --> | ChibiCritters/empiria-card-game | _layouts/post.html | HTML | mit | 1,234 |
# <gaia-property-inspector> [](https://travis-ci.org/gaia-components/gaia-property-inspector)
## Installation
```bash
$ bower install gaia-components/gaia-property-inspector
```
## Examples
- [Example](http://gaia-components.github.io/gaia-property-inspector/)
## Tests
1. Ensure Firefox Nightly is installed on your machine.
2. `$ npm install`
3. `$ npm test`
If your would like tests to run on file change use:
`$ npm run test-dev`
| fxos-components/gaia-property-inspector | README.md | Markdown | mit | 518 |
<?xml version="1.0" encoding="utf-8"?>
<!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" xml:lang="en" lang="en">
<head>
<title>base.rb</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../css/github.css" type="text/css" media="screen" />
<script src="../../../../../../../../../../../../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../../../../../../../../../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.1.6</span><br />
<h1>
base.rb
</h1>
<ul class="files">
<li>
../../.rbenv/versions/2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.1.6/lib/active_record/base.rb
</li>
<li>Last modified: 2014-10-25 21:54:03 +1100</li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<!-- File only: requires -->
<div class="sectiontitle">Required Files</div>
<ul>
<li>yaml</li>
<li>set</li>
<li>active_support/benchmarkable</li>
<li>active_support/dependencies</li>
<li>active_support/descendants_tracker</li>
<li>active_support/time</li>
<li>active_support/core_ext/module/attribute_accessors</li>
<li>active_support/core_ext/class/delegating_attributes</li>
<li>active_support/core_ext/array/extract_options</li>
<li>active_support/core_ext/hash/deep_merge</li>
<li>active_support/core_ext/hash/slice</li>
<li>active_support/core_ext/string/behavior</li>
<li>active_support/core_ext/kernel/singleton_class</li>
<li>active_support/core_ext/module/introspection</li>
<li>active_support/core_ext/object/duplicable</li>
<li>active_support/core_ext/class/subclasses</li>
<li>arel</li>
<li>active_record/errors</li>
<li>active_record/log_subscriber</li>
<li>active_record/explain_subscriber</li>
<li>active_record/relation/delegation</li>
</ul>
<!-- Namespace -->
<div class="sectiontitle">Namespace</div>
<ul>
<li>
<span class="type">MODULE</span>
<a href="../../../../../../../../../../../../../../classes/ActiveRecord.html">ActiveRecord</a>
</li>
<li>
<span class="type">CLASS</span>
<a href="../../../../../../../../../../../../../../classes/ActiveRecord/Base.html">ActiveRecord::Base</a>
</li>
</ul>
<!-- Methods -->
</div>
</div>
</body>
</html> | SeanYamaguchi/circle | doc/api/files/__/__/_rbenv/versions/2_1_0/lib/ruby/gems/2_1_0/gems/activerecord-4_1_6/lib/active_record/base_rb.html | HTML | mit | 3,616 |
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_mapify_session'
| jbarrieault/mapify | config/initializers/session_store.rb | Ruby | mit | 138 |
Clazz.declarePackage ("J.adapter.readers.xtal");
Clazz.load (["J.adapter.smarter.AtomSetCollectionReader"], "J.adapter.readers.xtal.CastepReader", ["java.lang.Double", "$.Float", "JU.DF", "$.Lst", "$.P3", "$.PT", "$.V3", "J.adapter.smarter.Atom", "JU.Escape", "$.Logger", "$.Tensor"], function () {
c$ = Clazz.decorateAsClass (function () {
this.tokens = null;
this.isPhonon = false;
this.isTS = false;
this.isOutput = false;
this.isCell = false;
this.a = 0;
this.b = 0;
this.c = 0;
this.alpha = 0;
this.beta = 0;
this.gamma = 0;
this.abc = null;
this.ac = 0;
this.atomPts = null;
this.havePhonons = false;
this.lastQPt = null;
this.qpt2 = 0;
this.desiredQpt = null;
this.desiredQ = null;
this.chargeType = "MULL";
this.isAllQ = false;
this.haveCharges = false;
this.tsType = null;
Clazz.instantialize (this, arguments);
}, J.adapter.readers.xtal, "CastepReader", J.adapter.smarter.AtomSetCollectionReader);
Clazz.prepareFields (c$, function () {
this.abc = new Array (3);
});
Clazz.overrideMethod (c$, "initializeReader",
function () {
if (this.filter != null) {
this.chargeType = this.getFilter ("CHARGE=");
if (this.chargeType != null && this.chargeType.length > 4) this.chargeType = this.chargeType.substring (0, 4);
this.filter = this.filter.$replace ('(', '{').$replace (')', '}');
this.filter = JU.PT.rep (this.filter, " ", " ");
this.isAllQ = this.checkFilterKey ("Q=ALL");
this.tsType = this.getFilter ("TSTYPE=");
if (!this.isAllQ && this.filter.indexOf ("{") >= 0) this.setDesiredQpt (this.filter.substring (this.filter.indexOf ("{")));
this.filter = JU.PT.rep (this.filter, "-PT", "");
}this.continuing = this.readFileData ();
});
Clazz.defineMethod (c$, "setDesiredQpt",
function (s) {
this.desiredQpt = new JU.V3 ();
this.desiredQ = "";
var num = 1;
var denom = 1;
var ipt = 0;
var xyz = 0;
var useSpace = (s.indexOf (',') < 0);
for (var i = 0; i < s.length; i++) {
var c = s.charAt (i);
switch (c) {
case '{':
ipt = i + 1;
num = 1;
denom = 1;
break;
case '/':
num = this.parseFloatStr (s.substring (ipt, i));
ipt = i + 1;
denom = 0;
break;
case ',':
case ' ':
case '}':
if (c == '}') this.desiredQ = s.substring (0, i + 1);
else if ((c == ' ') != useSpace) break;
if (denom == 0) {
denom = this.parseFloatStr (s.substring (ipt, i));
} else {
num = this.parseFloatStr (s.substring (ipt, i));
}num /= denom;
switch (xyz++) {
case 0:
this.desiredQpt.x = num;
break;
case 1:
this.desiredQpt.y = num;
break;
case 2:
this.desiredQpt.z = num;
break;
}
denom = 1;
if (c == '}') i = s.length;
ipt = i + 1;
break;
}
}
JU.Logger.info ("Looking for q-pt=" + this.desiredQpt);
}, "~S");
Clazz.defineMethod (c$, "readFileData",
function () {
while (this.tokenizeCastepCell () > 0) if (this.tokens.length >= 2 && this.tokens[0].equalsIgnoreCase ("%BLOCK")) {
JU.Logger.info (this.line);
if (this.tokens[1].equalsIgnoreCase ("LATTICE_ABC")) {
this.readLatticeAbc ();
continue;
}if (this.tokens[1].equalsIgnoreCase ("LATTICE_CART")) {
this.readLatticeCart ();
continue;
}if (this.tokens[1].equalsIgnoreCase ("POSITIONS_FRAC")) {
this.setFractionalCoordinates (true);
this.readPositionsFrac ();
continue;
}if (this.tokens[1].equalsIgnoreCase ("POSITIONS_ABS")) {
this.setFractionalCoordinates (false);
this.readPositionsAbs ();
continue;
}}
if (this.isPhonon || this.isOutput || this.isTS) {
if (this.isPhonon) {
this.isTrajectory = (this.desiredVibrationNumber <= 0);
this.asc.allowMultiple = false;
}return true;
}return false;
});
Clazz.overrideMethod (c$, "checkLine",
function () {
if (this.isOutput) {
if (this.line.contains ("Real Lattice(A)")) {
this.readOutputUnitCell ();
} else if (this.line.contains ("Fractional coordinates of atoms")) {
if (this.doGetModel (++this.modelNumber, null)) {
this.readOutputAtoms ();
}} else if (this.doProcessLines && (this.line.contains ("Atomic Populations (Mulliken)") || this.line.contains ("Hirshfield Charge (e)"))) {
this.readOutputCharges ();
} else if (this.doProcessLines && this.line.contains ("Born Effective Charges")) {
this.readOutputBornChargeTensors ();
} else if (this.line.contains ("Final energy ")) {
this.readEnergy (3, null);
} else if (this.line.contains ("Dispersion corrected final energy*")) {
this.readEnergy (5, null);
} else if (this.line.contains ("Total energy corrected")) {
this.readEnergy (8, null);
}return true;
}if (this.line.contains ("<-- E")) {
this.readPhononTrajectories ();
return true;
}if (this.line.indexOf ("Unit cell vectors") == 1) {
this.readPhononUnitCell ();
return true;
}if (this.line.indexOf ("Fractional Co-ordinates") >= 0) {
this.readPhononFractionalCoord ();
return true;
}if (this.line.indexOf ("q-pt") >= 0) {
this.readPhononFrequencies ();
return true;
}return true;
});
Clazz.defineMethod (c$, "readOutputUnitCell",
function () {
this.applySymmetryAndSetTrajectory ();
this.asc.newAtomSetClear (false);
this.setFractionalCoordinates (true);
this.abc = this.read3Vectors (false);
this.setLatticeVectors ();
});
Clazz.defineMethod (c$, "readOutputAtoms",
function () {
this.readLines (2);
while (this.rd ().indexOf ("xxx") < 0) {
var atom = new J.adapter.smarter.Atom ();
this.tokens = this.getTokens ();
atom.elementSymbol = this.tokens[1];
atom.atomName = this.tokens[1] + this.tokens[2];
this.asc.addAtomWithMappedName (atom);
this.setAtomCoordTokens (atom, this.tokens, 3);
}
});
Clazz.defineMethod (c$, "readEnergy",
function (pt, prefix) {
if (this.isTrajectory) this.applySymmetryAndSetTrajectory ();
this.tokens = this.getTokens ();
try {
var energy = Double.$valueOf (Double.parseDouble (this.tokens[pt]));
this.asc.setAtomSetName (prefix + "Energy = " + energy + " eV");
this.asc.setAtomSetEnergy ("" + energy, energy.floatValue ());
this.asc.setAtomSetAuxiliaryInfo ("Energy", energy);
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
this.appendLoadNote ("CASTEP Energy could not be read: " + this.line);
} else {
throw e;
}
}
}, "~N,~S");
Clazz.defineMethod (c$, "readPhononTrajectories",
function () {
if (!this.isTS) this.isTrajectory = (this.desiredVibrationNumber <= 0);
if (this.isTrajectory) this.asc.setTrajectory ();
this.doApplySymmetry = true;
while (this.line != null && this.line.contains ("<-- E")) {
var skip = (this.isTS && this.tsType != null && this.prevline.indexOf (this.tsType) < 0);
if (!skip) {
this.asc.newAtomSetClear (false);
if (this.isTS) this.readEnergy (0, JU.PT.getTokens (this.prevline + " -")[0] + " ");
this.discardLinesUntilContains ("<-- h");
this.setSpaceGroupName ("P1");
this.abc = this.read3Vectors (true);
this.setLatticeVectors ();
this.setFractionalCoordinates (false);
this.discardLinesUntilContains ("<-- R");
while (this.line != null && this.line.contains ("<-- R")) {
this.tokens = this.getTokens ();
this.setAtomCoordScaled (null, this.tokens, 2, 0.5291772).elementSymbol = this.tokens[0];
this.rd ();
}
this.applySymmetryAndSetTrajectory ();
}this.discardLinesUntilContains ("<-- E");
}
});
Clazz.overrideMethod (c$, "finalizeSubclassReader",
function () {
if (this.isPhonon || this.isOutput || this.isTS) {
this.isTrajectory = false;
} else {
this.doApplySymmetry = true;
this.setLatticeVectors ();
var nAtoms = this.asc.ac;
for (var i = 0; i < nAtoms; i++) this.setAtomCoord (this.asc.atoms[i]);
}this.finalizeReaderASCR ();
});
Clazz.defineMethod (c$, "setLatticeVectors",
function () {
if (this.abc[0] == null) {
this.setUnitCell (this.a, this.b, this.c, this.alpha, this.beta, this.gamma);
return;
}var lv = Clazz.newFloatArray (3, 0);
for (var i = 0; i < 3; i++) {
lv[0] = this.abc[i].x;
lv[1] = this.abc[i].y;
lv[2] = this.abc[i].z;
this.addPrimitiveLatticeVector (i, lv, 0);
}
});
Clazz.defineMethod (c$, "readLatticeAbc",
function () {
if (this.tokenizeCastepCell () == 0) return;
var factor = this.readLengthUnit (this.tokens[0]);
if (this.tokens.length >= 3) {
this.a = this.parseFloatStr (this.tokens[0]) * factor;
this.b = this.parseFloatStr (this.tokens[1]) * factor;
this.c = this.parseFloatStr (this.tokens[2]) * factor;
} else {
JU.Logger.warn ("error reading a,b,c in %BLOCK LATTICE_ABC in CASTEP .cell file");
return;
}if (this.tokenizeCastepCell () == 0) return;
if (this.tokens.length >= 3) {
this.alpha = this.parseFloatStr (this.tokens[0]);
this.beta = this.parseFloatStr (this.tokens[1]);
this.gamma = this.parseFloatStr (this.tokens[2]);
} else {
JU.Logger.warn ("error reading alpha,beta,gamma in %BLOCK LATTICE_ABC in CASTEP .cell file");
}});
Clazz.defineMethod (c$, "readLatticeCart",
function () {
if (this.tokenizeCastepCell () == 0) return;
var factor = this.readLengthUnit (this.tokens[0]);
var x;
var y;
var z;
for (var i = 0; i < 3; i++) {
if (this.tokens.length >= 3) {
x = this.parseFloatStr (this.tokens[0]) * factor;
y = this.parseFloatStr (this.tokens[1]) * factor;
z = this.parseFloatStr (this.tokens[2]) * factor;
this.abc[i] = JU.V3.new3 (x, y, z);
} else {
JU.Logger.warn ("error reading coordinates of lattice vector " + Integer.toString (i + 1) + " in %BLOCK LATTICE_CART in CASTEP .cell file");
return;
}if (this.tokenizeCastepCell () == 0) return;
}
this.a = this.abc[0].length ();
this.b = this.abc[1].length ();
this.c = this.abc[2].length ();
this.alpha = (this.abc[1].angle (this.abc[2]) * 57.29578);
this.beta = (this.abc[2].angle (this.abc[0]) * 57.29578);
this.gamma = (this.abc[0].angle (this.abc[1]) * 57.29578);
});
Clazz.defineMethod (c$, "readPositionsFrac",
function () {
if (this.tokenizeCastepCell () == 0) return;
this.readAtomData (1.0);
});
Clazz.defineMethod (c$, "readPositionsAbs",
function () {
if (this.tokenizeCastepCell () == 0) return;
var factor = this.readLengthUnit (this.tokens[0]);
this.readAtomData (factor);
});
Clazz.defineMethod (c$, "readLengthUnit",
function (units) {
var factor = 1.0;
for (var i = 0; i < J.adapter.readers.xtal.CastepReader.lengthUnitIds.length; i++) if (units.equalsIgnoreCase (J.adapter.readers.xtal.CastepReader.lengthUnitIds[i])) {
factor = J.adapter.readers.xtal.CastepReader.lengthUnitFactors[i];
this.tokenizeCastepCell ();
break;
}
return factor;
}, "~S");
Clazz.defineMethod (c$, "readAtomData",
function (factor) {
do {
if (this.tokens.length >= 4) {
var atom = this.asc.addNewAtom ();
var pt = this.tokens[0].indexOf (":");
if (pt >= 0) {
atom.elementSymbol = this.tokens[0].substring (0, pt);
atom.atomName = this.tokens[0];
} else {
atom.elementSymbol = this.tokens[0];
}atom.set (this.parseFloatStr (this.tokens[1]), this.parseFloatStr (this.tokens[2]), this.parseFloatStr (this.tokens[3]));
atom.scale (factor);
} else {
JU.Logger.warn ("cannot read line with CASTEP atom data: " + this.line);
}} while (this.tokenizeCastepCell () > 0 && !this.tokens[0].equalsIgnoreCase ("%ENDBLOCK"));
}, "~N");
Clazz.defineMethod (c$, "tokenizeCastepCell",
function () {
while (this.rd () != null) {
if ((this.line = this.line.trim ()).length == 0 || this.line.startsWith ("#") || this.line.startsWith ("!")) continue;
if (!this.isCell) {
if (this.line.startsWith ("%")) {
this.isCell = true;
break;
}if (this.line.startsWith ("LST")) {
this.isTS = true;
JU.Logger.info ("reading CASTEP .ts file");
return -1;
}if (this.line.startsWith ("BEGIN header")) {
this.isPhonon = true;
JU.Logger.info ("reading CASTEP .phonon file");
return -1;
}if (this.line.contains ("CASTEP")) {
this.isOutput = true;
JU.Logger.info ("reading CASTEP .castep file");
return -1;
}}break;
}
return (this.line == null ? 0 : (this.tokens = this.getTokens ()).length);
});
Clazz.defineMethod (c$, "readOutputBornChargeTensors",
function () {
if (this.rd ().indexOf ("--------") < 0) return;
var atoms = this.asc.atoms;
this.appendLoadNote ("Ellipsoids: Born Charge Tensors");
while (this.rd ().indexOf ('=') < 0) this.getTensor (atoms[this.readOutputAtomIndex ()], this.line.substring (12));
});
Clazz.defineMethod (c$, "readOutputAtomIndex",
function () {
this.tokens = this.getTokens ();
return this.asc.getAtomIndex (this.tokens[0] + this.tokens[1]);
});
Clazz.defineMethod (c$, "getTensor",
function (atom, line0) {
var data = Clazz.newFloatArray (9, 0);
var a = Clazz.newDoubleArray (3, 3, 0);
this.fillFloatArray (line0, 0, data);
JU.Logger.info ("tensor " + atom.atomName + "\t" + JU.Escape.eAF (data));
for (var p = 0, i = 0; i < 3; i++) for (var j = 0; j < 3; j++) a[i][j] = data[p++];
atom.addTensor (( new JU.Tensor ()).setFromAsymmetricTensor (a, "charge", atom.atomName + " " + line0), null, false);
if (!this.haveCharges) this.appendLoadNote ("Ellipsoids set \"charge\": Born Effective Charges");
this.haveCharges = true;
}, "J.adapter.smarter.Atom,~S");
Clazz.defineMethod (c$, "readOutputCharges",
function () {
if (this.line.toUpperCase ().indexOf (this.chargeType) < 0) return;
JU.Logger.info ("reading charges: " + this.line);
this.readLines (2);
var haveSpin = (this.line.indexOf ("Spin") >= 0);
this.rd ();
var atoms = this.asc.atoms;
var spins = (haveSpin ? Clazz.newFloatArray (atoms.length, 0) : null);
if (spins != null) for (var i = 0; i < spins.length; i++) spins[i] = 0;
while (this.rd () != null && this.line.indexOf ('=') < 0) {
var index = this.readOutputAtomIndex ();
var charge = this.parseFloatStr (this.tokens[haveSpin ? this.tokens.length - 2 : this.tokens.length - 1]);
atoms[index].partialCharge = charge;
if (haveSpin) spins[index] = this.parseFloatStr (this.tokens[this.tokens.length - 1]);
}
if (haveSpin) this.asc.setAtomProperties ("spin", spins, -1, false);
});
Clazz.defineMethod (c$, "readPhononUnitCell",
function () {
this.abc = this.read3Vectors (this.line.indexOf ("bohr") >= 0);
this.setSpaceGroupName ("P1");
this.setLatticeVectors ();
});
Clazz.defineMethod (c$, "readPhononFractionalCoord",
function () {
this.setFractionalCoordinates (true);
while (this.rd () != null && this.line.indexOf ("END") < 0) {
this.tokens = this.getTokens ();
this.addAtomXYZSymName (this.tokens, 1, this.tokens[4], null).bfactor = this.parseFloatStr (this.tokens[5]);
}
this.ac = this.asc.ac;
this.atomPts = new Array (this.ac);
var atoms = this.asc.atoms;
for (var i = 0; i < this.ac; i++) this.atomPts[i] = JU.P3.newP (atoms[i]);
});
Clazz.defineMethod (c$, "readPhononFrequencies",
function () {
this.tokens = this.getTokens ();
var v = new JU.V3 ();
var qvec = JU.V3.new3 (this.parseFloatStr (this.tokens[2]), this.parseFloatStr (this.tokens[3]), this.parseFloatStr (this.tokens[4]));
var fcoord = this.getFractionalCoord (qvec);
var qtoks = "{" + this.tokens[2] + " " + this.tokens[3] + " " + this.tokens[4] + "}";
if (fcoord == null) fcoord = qtoks;
else fcoord = "{" + fcoord + "}";
var isOK = this.isAllQ;
var isSecond = (this.tokens[1].equals (this.lastQPt));
this.qpt2 = (isSecond ? this.qpt2 + 1 : 1);
this.lastQPt = this.tokens[1];
if (!isOK && this.checkFilterKey ("Q=")) {
if (this.desiredQpt != null) {
v.sub2 (this.desiredQpt, qvec);
if (v.length () < 0.001) fcoord = this.desiredQ;
}isOK = (this.checkFilterKey ("Q=" + fcoord + "." + this.qpt2 + ";") || this.checkFilterKey ("Q=" + this.lastQPt + "." + this.qpt2 + ";") || !isSecond && this.checkFilterKey ("Q=" + fcoord + ";") || !isSecond && this.checkFilterKey ("Q=" + this.lastQPt + ";"));
if (!isOK) return;
}var isGammaPoint = (qvec.length () == 0);
var nx = 1;
var ny = 1;
var nz = 1;
var xSym = this.asc.getXSymmetry ();
if (this.ptSupercell != null && !isOK && !isSecond) {
xSym.setSupercellFromPoint (this.ptSupercell);
nx = this.ptSupercell.x;
ny = this.ptSupercell.y;
nz = this.ptSupercell.z;
var dx = (qvec.x == 0 ? 1 : qvec.x) * nx;
var dy = (qvec.y == 0 ? 1 : qvec.y) * ny;
var dz = (qvec.z == 0 ? 1 : qvec.z) * nz;
if (!J.adapter.readers.xtal.CastepReader.isInt (dx) || !J.adapter.readers.xtal.CastepReader.isInt (dy) || !J.adapter.readers.xtal.CastepReader.isInt (dz)) return;
isOK = true;
}if (this.ptSupercell == null || !this.havePhonons) this.appendLoadNote (this.line);
if (!isOK && isSecond) return;
if (!isOK && (this.ptSupercell == null) == !isGammaPoint) return;
if (this.havePhonons && !this.isAllQ) return;
this.havePhonons = true;
var qname = "q=" + this.lastQPt + " " + fcoord;
this.applySymmetryAndSetTrajectory ();
if (isGammaPoint) qvec = null;
var freqs = new JU.Lst ();
while (this.rd () != null && this.line.indexOf ("Phonon") < 0) {
this.tokens = this.getTokens ();
freqs.addLast (Float.$valueOf (this.parseFloatStr (this.tokens[1])));
}
this.rd ();
var frequencyCount = freqs.size ();
var data = Clazz.newFloatArray (8, 0);
var t = new JU.V3 ();
this.asc.setCollectionName (qname);
for (var i = 0; i < frequencyCount; i++) {
if (!this.doGetVibration (++this.vibrationNumber)) {
for (var j = 0; j < this.ac; j++) this.rd ();
continue;
}if (this.desiredVibrationNumber <= 0) {
if (!this.isTrajectory) {
this.cloneLastAtomSet (this.ac, this.atomPts);
this.applySymmetryAndSetTrajectory ();
}}this.symmetry = this.asc.getSymmetry ();
var iatom = this.asc.getLastAtomSetAtomIndex ();
var freq = freqs.get (i).floatValue ();
var atoms = this.asc.atoms;
var aCount = this.asc.ac;
for (var j = 0; j < this.ac; j++) {
this.fillFloatArray (null, 0, data);
for (var k = iatom++; k < aCount; k++) if (atoms[k].atomSite == j) {
t.sub2 (atoms[k], atoms[atoms[k].atomSite]);
xSym.rotateToSuperCell (t);
this.setPhononVector (data, atoms[k], t, qvec, v);
this.asc.addVibrationVectorWithSymmetry (k, v.x, v.y, v.z, true);
}
}
if (this.isTrajectory) this.asc.setTrajectory ();
this.asc.setAtomSetFrequency (null, null, "" + freq, null);
this.asc.setAtomSetName (JU.DF.formatDecimal (freq, 2) + " cm-1 " + qname);
}
});
Clazz.defineMethod (c$, "getFractionalCoord",
function (qvec) {
return (this.symmetry != null && J.adapter.readers.xtal.CastepReader.isInt (qvec.x * 12) && J.adapter.readers.xtal.CastepReader.isInt (qvec.y * 12) && J.adapter.readers.xtal.CastepReader.isInt (qvec.z * 12) ? this.symmetry.fcoord (qvec) : null);
}, "JU.V3");
c$.isInt = Clazz.defineMethod (c$, "isInt",
function (f) {
return (Math.abs (f - Math.round (f)) < 0.001);
}, "~N");
Clazz.defineMethod (c$, "setPhononVector",
function (data, atom, rTrans, qvec, v) {
if (qvec == null) {
v.set (data[2], data[4], data[6]);
} else {
var phase = qvec.dot (rTrans);
var cosph = Math.cos (6.283185307179586 * phase);
var sinph = Math.sin (6.283185307179586 * phase);
v.x = (cosph * data[2] - sinph * data[3]);
v.y = (cosph * data[4] - sinph * data[5]);
v.z = (cosph * data[6] - sinph * data[7]);
}v.scale (Math.sqrt (1 / atom.bfactor));
}, "~A,J.adapter.smarter.Atom,JU.V3,JU.V3,JU.V3");
Clazz.defineStatics (c$,
"RAD_TO_DEG", (57.29577951308232),
"lengthUnitIds", ["bohr", "m", "cm", "nm", "ang", "a0"],
"lengthUnitFactors", [0.5291772, 1E10, 1E8, 1E1, 1.0, 0.5291772],
"TWOPI", 6.283185307179586);
});
| m4rx9/rna-pdb-tools | rna_tools/tools/webserver-engine/app/static/app/jsmol/j2s/J/adapter/readers/xtal/CastepReader.js | JavaScript | mit | 19,032 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductStockistTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('fbf_food_product_stockist', function(Blueprint $table)
{
$table->integer('product_id');
$table->integer('stockist_id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('fbf_food_product_stockist');
}
}
| FbF/Laravel-Food | src/migrations/2013_12_02_114314_create_product_stockist_table.php | PHP | mit | 523 |
/**
* Created by wangwei01 on 2017/1/17.
*/
;(function () {
var type = zhx.getSearchName("type");
var list = [];
switch (type) {
case "storeMain":
list.push({key: "banner", bgColor: "#DE3A53"});
list.push({key: "textTitle", title: "新品上架"});
list.push({key: "goodsList", pattern: "small", showName: 0, type: "card"});
//list.push({key:"notice"})
break;
case "custom":
break;
}
//参数转换
var getConf = {
imgAd: function (plugin, typeId) {
var d = plugin.data;
var styleConf = {
type: typeId,
//showType:d.method
showType: "type-" + d.method,
imgSizeType: d.showSize == "small" ? "sm-list" : ""
};
var list = [];
$.each(d.imgList, function (idx) {
//http://www.ule.com\",\"showOrder\":1,\"title\":\"11111\",\"linkType\":\"1\",\"linkUrl\":\"1111\
list.push({
uuid: this.uuid || "",
imgUrl: this.src,
showOrder: idx + 1,
title: this.title,
linkType: this.type,
linkName:this.name,
linkUrl: this.link||"javascript:void(0)"
})
})
var dataConf = {
type: typeId,
data: JSON.stringify(list)
};
return {styleConf: styleConf, dataConf: dataConf};
},
imgNav: function (plugin, typeId) {
var d = plugin.data;
var list = [];
$.each(d.list, function (idx) {
//http://www.ule.com\",\"showOrder\":1,\"title\":\"11111\",\"linkType\":\"1\",\"linkUrl\":\"1111\
list.push({
uuid: this.uuid || "",
imgUrl: this.src,
showOrder: idx + 1,
title: this.title,
linkType: this.type,
linkName:this.name,
linkUrl: this.link
})
})
var dataConf = {
type: typeId,
data: JSON.stringify(list)
};
return {styleConf: null, dataConf: dataConf};
},
goods: function (plugin, typeId) {
var d = plugin.data;
var styleConfDto = {
type: typeId,
layoutStyle: plugin.def.listClass[d.pattern],
cardStyle: plugin.def.listStyle[d.type],
buyIconStyle: plugin.def.buyClass[d.buyStyle],
isShowPrice: d.showPrice ? 1 : 0,
isShowName: d.showName ? 1 : 0,
layoutValue: d.pattern,
cardValue: d.type,
buyIconValue: d.showBuy ? 1 : 0
};
var itemIds = [];
$.each(d.goodsList, function () {
itemIds.p(this.listingId);
})
var dataConfDto = {
type: typeId,
itemIds: itemIds.join(",")
}
return {styleConf: styleConfDto, dataConf: dataConfDto};
},
goodsList: function (plugin, typeId) {
var d = plugin.data, sd = plugin.data.searchData;
var styleConfDto = {
type: typeId,
layoutStyle: plugin.def.listClass[d.pattern],
cardStyle: plugin.def.listStyle[d.type],
buyIconStyle: plugin.def.buyClass[d.buyStyle],
isShowPrice: d.showPrice ? 1 : 0,
isShowName: d.showName ? 1 : 0,
layoutValue: d.pattern,
cardValue: d.type,
buyIconValue: d.showBuy ? 1 : 0
};
var dataConfDto = {
type: typeId,
brand: sd.brandId || "",
orderType: sd.orderType || "",
itemNumber: d.num,
uleCategroy: sd.categroyId || "",
storeCategroy: sd.storeCategroyId || "",
merchantId: ""
}
return {styleConf: styleConfDto, dataConf: dataConfDto};
},
banner: function (plugin, typeId) {
var d = plugin.data;
var styleConf = {
type: typeId,
bgColor: "background-color:" + d.bgColor,
bgImgUrl: d.bgImgSrc,
bannerLogo: d.logoSrc,
storeName: zhx.config.store.name
};
var dataConf = {
type: typeId,
data: {
uuid: d.uuid || "",
content: d.bgColor
}
};
return {styleConf: styleConf, dataConf: dataConf};
},
textNav: function (plugin, typeId) {
var d = plugin.data;
var list = [];
//datas\":[{\"title\":\"1\",\"showOrder\":1,\"linkType\":\"1\",\"linkUrl\":\"1\"}]}"
$.each(d.linkList, function (idx) {
list.p({
uuid: this.uuid || "",
title: this.title,
showOrder: idx + 1,
linkType: this.type,
linkName:this.name,
linkUrl: this.src
})
})
var dataConf = {
type: typeId,
data: JSON.stringify(list)
};
return {styleConf: null, dataConf: dataConf};
},
textTitle: function (plugin, typeId) {
var d = plugin.data;
var styleConf = {
type: typeId,
textAlign: "txt-" + d.tradition.txtAlign,
textAlignValue: d.tradition.txtAlign,
titleTemplateType: d.titleType == "tradition" ? 1 : 0,
bgColor: "background-color:"+ d.tradition.titleBg,
bgColorValue: d.tradition.titleBg
};
var dataConf = {
type: typeId,
data: {
title: d.title,
halfTitle: d.tradition.subtitle,
imgTxtLinkType: d.wx.linkType == "follow" ? 1 : 0,
haslink: d.tradition.hasLink,
author: d.wx.author,
date: d.wx.datetime,
linkTitle:d.wx.linkTitle,
textNavigationDataDto: {
uuid: d.uuid || "",
title: "",
showOrder: 1,
linkName:d.wx.link.name,
linkType: d.wx.link.type,
linkUrl: d.wx.link.src
}
}
};
if (styleConf.titleTemplateType) {
if (d.tradition.hasLink) {
dataConf.data.textNavigationDataDto = {
title: d.tradition.link.text,
showOrder: 1,
linkType: d.tradition.link.type,
linkName:d.tradition.link.name,
linkUrl: d.tradition.link.src
}
}
}
return {styleConf: styleConf, dataConf: dataConf};
},
blank: function (plugin, typeId) {
var d = plugin.data;
var styleConf = {
type: typeId,
height: d.height
};
return {styleConf: styleConf, dataConf: null};
},
editor: function (plugin, typeId) {
var d = plugin.data;
var styleConf = {
type: typeId,
backgroundColor: "background-color:" + d.bgColor,
backgroundColorValue:d.bgColor,
isFullScreen: d.isFull
};
var dataConf = {
type: typeId,
data: {
uuid: d.uuid || "",
content: d.html
}
};
return {styleConf: styleConf, dataConf: dataConf};
},
goodsSearch: function (plugin, typeId) {
var d = plugin.data;
var styleConf = {
type: typeId,
bgColor: "background-color:" + d.bgColor
};
return {styleConf: styleConf, dataConf: null};
},
hr: function (plugin, typeId) {
var d = plugin.data;
var styleConf = {
type: typeId,
//color:d.color,
colorCode: d.color,
isPadding: d.isBlank ? "is-blank" : "",
styleValue: d.type,
style: ["border:", d.color, d.type, "1px"].join(" ")
};
return {styleConf: styleConf, dataConf: null};
},
notice: function (plugin, typeId) {
var d = plugin.data;
var dataConf = {
type: typeId,
data: {
uuid: d.uuid || "",
content: d.text
}
};
return {styleConf: null, dataConf: dataConf};
},
enterStore: function (plugin, typeId) {
//后端需要url,单独加上
var styleConf = {
type: typeId,
url: zhx.config.store.mainPageUrl
};
return {styleConf: styleConf, dataConf: null};
}
};
var getSetting = {
imgAd: function (key, item) {
var dataConf = item.dataConfDto;
var styleConf = item.styleConfDto;
var list = [];
var tlist = dataConf.data || [];
$.each(tlist, function (idx, el) {
list.push({
uuid: el.uuid,
src: el.imgUrl,
title: el.title,
name:el.linkName,
link: el.linkUrl,
type: el.linkType
})
})
return {
method: styleConf.showType.replace("type-", ""),//"carousel",
showSize: styleConf.imgSizeType == "sm-list" ? "small" : "big",
imgList: list
}
},
imgNav: function (key, item) {
var dataConf = item.dataConfDto;
var list = [];
var tlist = dataConf.data || [];
$.each(tlist, function (idx, el) {
list.push({
uuid: el.uuid,
src: el.imgUrl,
title: el.title,
name:el.linkName,
link: el.linkUrl,
type: el.linkType
})
})
return {
list: list
};
},
goods: function (key, item) {
var dataConf = item.dataConfDto;
var styleConf = item.styleConfDto;
var d = {
itemIds: [],
pattern: styleConf.layoutValue,
type: styleConf.cardValue,
showBuy: zhx.int(styleConf.buyIconValue),
buyStyle: zhx.int(styleConf.buyIconStyle.replace("buy-","")),
showName: zhx.int(styleConf.isShowName),
showPrice: zhx.int(styleConf.isShowPrice)
};
if (dataConf.itemIds) {
d.itemIds = dataConf.itemIds.split(",");
}
return d;
},
goodsList: function (key, item) {
var dataConf = item.dataConfDto;
var styleConf = item.styleConfDto;
var d = {
itemIds: [],
pattern: styleConf.layoutValue,
type: styleConf.cardValue,
showBuy: styleConf.buyIconValue,
buyStyle: zhx.int(styleConf.buyIconStyle.replace("buy-","")),
showName: styleConf.isShowName,
showPrice: styleConf.isShowPrice
};
d.searchData = {
brandId: dataConf.brand,
orderType: dataConf.orderType,
categroyId: dataConf.uleCategroy,
storeCategroyId: dataConf.storeCategroy
};
d.initSearchData = dataConf;
return d;
},
banner: function (key, item) {
var styleConf = item.styleConfDto;
var color="";
if(styleConf.bgColor){
var idx = styleConf.bgColor.indexOf("#");
color = styleConf.bgColor.substr(idx,7);
}
return {
uuid:item.dataConf.data? item.dataConf.data.uuid:"",
bgColor: color,
bgImgSrc: styleConf.bgImgUrl,
logoSrc: styleConf.bannerLogo,
storeName: styleConf.storeName
}
},
textNav: function (key, item) {
var dataConf = item.dataConfDto;
var list = [];
var tlist = dataConf.data || [];
$.each(tlist, function (idx, el) {
list.push({
uuid: el.uuid,
name:el.name,
src: el.linkUrl,
title: el.title,
type: el.linkType
})
})
return {
linkList: list
};
},
textTitle: function (key, item) {
var dataConf = item.dataConfDto;
var styleConf = item.styleConfDto;
var d = {
title: dataConf.data.title, //标题
titleType: styleConf.titleTemplateType == 1 ? "tradition" : "wx", //类型 常规 或 仿微信
tradition: {
hasLink: dataConf.data.haslink, //是否有链接
link: {
name:"",
text: "",
type: "",
src: ""
},
titleBg: styleConf.bgColorValue,
txtAlign: styleConf.textAlignValue,//align 样式
subtitle: dataConf.data.halfTitle //副标题
},
wx: {
datetime: dataConf.data.date,
author: dataConf.data.author,
linkTitle: dataConf.data.linkTitle, //textNavigationDataDto
linkType: dataConf.data.imgTxtLinkType == 1 ? "follow" : "other",
link: {
name:"",
type: "",
src: ""
}
}
};
if (styleConf.titleTemplateType == 1) {
if (dataConf.data.haslink == 1) {
d.tradition.link = {
text: dataConf.data.textNavigationDataDto.title,
type: dataConf.data.textNavigationDataDto.linkType,
name: dataConf.data.textNavigationDataDto.linkName,
src: dataConf.data.textNavigationDataDto.linkUrl
}
}
} else {
if (dataConf.data.imgTxtLinkType == 0) {
d.wx.link = {
type: dataConf.data.textNavigationDataDto.linkType,
name: dataConf.data.textNavigationDataDto.linkName,
src: dataConf.data.textNavigationDataDto.linkUrl
}
}
}
d.uuid = dataConf.data.textNavigationDataDto.uuid;
return d;
},
blank: function (key, item) {
var styleConf = item.styleConfDto;
return {height: styleConf.height}
},
editor: function (key, item) {
var dataConf = item.dataConfDto;
var styleConf = item.styleConfDto;
return {
uuid: dataConf.data.uuid,
html: dataConf.data.content,
isFull: styleConf.isFullScreen,
bgColor: styleConf.backgroundColorValue
}
},
goodsSearch: function (key, item) {
var styleConf = item.styleConfDto;
var color="";
if(styleConf.bgColor){
var idx = styleConf.bgColor.indexOf("#");
color = styleConf.bgColor.substr(idx,7);
}
return {bgColor: color}
},
hr: function (key, item) {
var styleConf = item.styleConfDto;
var d = {
color: styleConf.colorCode, isBlank: !!styleConf.isPadding, type: styleConf.styleValue
}
return d;
},
notice: function (key, item) {
var dataConf = item.dataConfDto;
return {uuid: dataConf.data.uuid, text: dataConf.data.content}
},
enterStore: function (key, item) {
return {}
}
}
//zhx.init();
zhx.config.store = {
id: $("#storeId").val(), //店铺id
name: $("#storeName").val(), //店铺名称
templateId: $("#templateId").val(), //
merchantId: $("#merchantId").val(), //
pageId: $("#pageId").val(), //
storeLogo:$("#storeLogo").val(), //店铺logo
basePath:$("#basePath").val(), //接口主机地址
pcStoreId: $("#pcStoreId").val(), //pc 店铺id
mainPageUrl: $("#pageIndexUrl").val() //店铺主页url
};
//list.push({key:"goods",pattern: "small",type: "card"})
//和后端数据(moduleType)对应
var mType = {
"textTitle": 1,
"hr": 2,
"goods": 3,
"goodsList": 4,
"editor": 5,
"goodsSearch": 6,
"blank": 7,
"notice": 8,
"textNav": 9,
"imgNav": 10,
"imgAd": 11,
"enterStore": 12,
"banner": 13
}
function getKeyById(id) {
for (var k in mType) {
if (mType[k] == id) {
return k;
}
}
}
//初始化插件选择列表
// var customIdList = JSON.parse($("#mType").html() || null) || [];
// if (customIdList.length) {
// var keyList = [];
// $.each(customIdList, function () {
// keyList.push(getKeyById(this));
// })
// zhx.config.plugin = keyList;
// }
//编辑
var pageDtoStr = $("#pageDtoJson").text();
if ($.trim(pageDtoStr)) {
setEditInfo();
}
function setEditInfo() {
var dto = JSON.parse(pageDtoStr);
console.log("初始化信息:", dto);
if(dto){
if (dto.moduleList && dto.moduleList.length) {
$.each(dto.moduleList, function (idx, item) {
var key = getKeyById(item.moduleType);
var sett = getSetting[key](key, item);
$.extend(sett, {key: key, setInfo: item});
list.push(sett);
});
}
list.push({key: "pageTitle", title: dto.pageTitle, des: dto.pageDesc, bodyBg: dto.pageBgcolor||"#ffffff"});
}else{
list.push({key: "pageTitle", title: "店铺主页"});
}
}
//list.p(
// {
// key: "imgAd", method: "separate", showSize: "small", imgList: [{
// link: "585858",
// src: "http://static.beta.ule.com/mstore/user_0/store_0/images/20170308/a9a11cb22f71ee8c.jpg",
// title: "title",
// type: "7"
// }, {
// src: "http://static.beta.ule.com/mstore/user_0/store_0/images/20170313/21d3991e944adab8.jpg",
// title: "title",
// link: "88888888888888888",
// type: 5
// }
// ]
// })
//list.p(
// {
// key: "banner",
// bgColor: "#999999",
// bgImgSrc: "http://static.beta.ule.com/mstore/user_0/store_0/images/20170308/a9a11cb22f71ee8c.jpg",
// logoSrc: "http://static.beta.ule.com/mstore/user_0/store_0/images/20170313/21d3991e944adab8.jpg",
// storeName: "我的店铺"
// },
// {
// key: "goodsSearch", bgColor: "#999999"
// },
// {
// key: "notice", text: "三翻四复"
// },
// {
// key: "blank", height: 50
// }
//)
//初始化插件
console.log("初始化插件列表:", list);
zhx.init(list);
//zhx.init([{key:"pageTitle",title:"店铺主页"},{key:"editor",html:"<p>3333333333333333333</p>"}]);
// zhx.dialog.selectGoodsSingleton();
function getEditUUID(editItem) {
var uuid = "";
if (editItem) {
if (editItem.dataConf && editItem.dataConf.data && editItem.dataConf.data.uuid) {
uuid = editItem.dataConf.data.uuid;
}
}
return uuid;
}
function getData() {
var obj = {
"uuid": zhx.config.store.pageId,
"storeId": zhx.config.store.id,
"templateId": zhx.config.store.templateId,
"pageTitle": "页面标题",
"pageDesc": "页面描述",
"pageBgcolor": "",
//"pageUrl": "页面url",
"moduleList": []
};
$.each(zhx.pluginList, function (idx, item) {
var typeId = mType[item.data.key];
var data = {
uuid: "",
pageId: "",
storeId: obj.storeId,
moduleName: item.name,
moduleType: typeId,
showOrder: idx + 1
}
if (item.data.setInfo) {
data.uuid = item.data.setInfo.uuid;
data.pageId = item.data.setInfo.pageId;
}
var conf = getConf[item.data.key](item, typeId);
if (conf.styleConf != null) {
data["styleConf"] = JSON.stringify(conf.styleConf);
}
if (conf.dataConf != null) {
data["dataConf"] = JSON.stringify(conf.dataConf);
}
obj.moduleList.push(data);
});
$.each(zhx.holdPluginList, function (idx, item) {
if (item.data.key == "pageTitle") {
obj.pageTitle = item.data.title;
obj.pageDesc = item.data.des;
obj.pageBgcolor = item.data.bodyBg;
}
})
return obj;
}
//验证事件
var check = function () {
var isSubmit = true,flag = true, i, len, list = zhx.pluginList, item;
for (i = 0, len = list.length; i < len; i++) {
item = list[i];
if (item.check) {
flag = item.check();
if (!flag) {
zhx.activeView(item.view);
}
isSubmit = isSubmit&&flag;
}
}
return isSubmit;
//$.each(zhx.dataList,function (idx,el) {
// if(el.key=="imgNav"){
// //isSubmit
// if(el.list[0].type>0&&el.list[1].type>0&&el.list[2].type>0&&el.list[3].type>0){
//
// }else{
// isSubmit = false;
// zhx.activeView(zhx.pluginList[idx].view);
// }
// }
//})
//return isSubmit;
}
$(function () {
//发布
$(".btn-send").bind("click", function () {
var data = getData();
console.log("发布参数:", data);
var isSubmit = check();
if (isSubmit) {
zhx.data.put(zhx.config.store.basePath +"api/v1/page/publish", JSON.stringify(data)).success(function (res) {
if (res.status == 0) {
zhx.box.msg("发布成功!",function () {
location.href = zhx.config.store.basePath +"page/";
})
}else{
zhx.box.msg(res.message||"发布失败!")
}
}).error(function () {
zhx.box.msg("发生错误!")
});
}
})
//保存
$(".btn-save").bind("click", function () {
var data = getData();
console.log("保存参数:", data);
var isSubmit = check();
if (isSubmit) {
zhx.data.put( zhx.config.store.basePath + +"api/v1/page/save", JSON.stringify(data)).success(function (res) {
if (res.status == 0) {
zhx.box.msg("保存成功!",function () {
location.href = zhx.config.store.basePath +"page/";
})
}else{
zhx.box.msg(res.message||"保存失败!")
}
}).error(function () {
zhx.box.msg("发生错误!")
});
}
})
//预览
$(".btn-review").bind("click", function () {
var data = getData();
console.log("预览参数:", data);
var isSubmit = check();
if (isSubmit) {
zhx.data.put(zhx.config.store.basePath + "api/v1/page/save4PreView", JSON.stringify(data)).success(function (res) {
if (res.status == 0) {
window.open(zhx.config.store.basePath +"page/preView", "_blank");
}else{
zhx.box.msg(res.message||"预览失败!")
}
}).error(function () {
zhx.box.msg("发生错误!")
});
}
})
})
})(); | xyz252631m/web | h5zhx/src/index.js | JavaScript | mit | 18,905 |
/*!
* chain.js - blockchain management for decentraland
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* Copyright (c) 2016-2017, Manuel Araoz (MIT License).
* https://github.com/decentraland/decentraland-node
*/
'use strict';
var AsyncObject = require('../utils/async');
var Network = require('../protocol/network');
var Logger = require('../node/logger');
var ChainDB = require('./chaindb');
var constants = require('../protocol/constants');
var util = require('../utils/util');
var btcutils = require('../btc/utils');
var Locker = require('../utils/locker');
var LRU = require('../utils/lru');
var ChainEntry = require('./chainentry');
var CoinView = require('../coins/coinview');
var assert = require('assert');
var errors = require('../btc/errors');
var VerifyError = errors.VerifyError;
var VerifyResult = errors.VerifyResult;
var ContentDB = require('./contentdb');
var co = require('../utils/co');
const DX = [0, 1, 0, -1];
const DY = [1, 0, -1, 0];
/**
* Represents a blockchain.
* @exports Chain
* @constructor
* @param {Object} options
* @param {String?} options.name - Database name.
* @param {String?} options.location - Database file location.
* @param {String?} options.db - Database backend (`"leveldb"` by default).
* @param {Number?} options.orphanLimit
* @param {Number?} options.pendingLimit
* @param {Boolean?} options.spv
* @property {Boolean} loaded
* @property {ChainDB} db - Note that Chain `options` will be passed
* to the instantiated ChainDB.
* @property {Number} total
* @property {Number} orphanLimit
* @property {Locker} locker
* @property {Object} invalid
* @property {Number} bestHeight
* @property {ChainEntry?} tip
* @property {Number} height
* @property {DeploymentState} state
* @property {Object} orphan - Orphan map.
* @emits Chain#open
* @emits Chain#error
* @emits Chain#block
* @emits Chain#competitor
* @emits Chain#resolved
* @emits Chain#checkpoint
* @emits Chain#fork
* @emits Chain#reorganize
* @emits Chain#invalid
* @emits Chain#exists
* @emits Chain#purge
* @emits Chain#connect
* @emits Chain#reconnect
* @emits Chain#disconnect
*/
function Chain(options) {
if (!(this instanceof Chain))
return new Chain(options);
AsyncObject.call(this);
if (!options)
options = {};
this.options = options;
this.network = Network.get(options.network);
this.logger = options.logger || Logger.global;
this.content = new ContentDB(this);
this.db = new ChainDB(this);
this.total = 0;
this.orphanLimit = options.orphanLimit || (20 << 20);
this.locker = new Locker(true);
this.invalid = new LRU(100);
this.bestHeight = -1;
this.tip = null;
this.height = -1;
this.synced = false;
this.state = new DeploymentState();
this._time = util.hrtime();
this.orphan = {
map: {},
bmap: {},
count: 0,
size: 0
};
this._init();
}
util.inherits(Chain, AsyncObject);
/**
* Initialize the chain.
* @private
*/
Chain.prototype._init = function _init() {
var self = this;
this.on('competitor', function(block, entry) {
self.logger.warning('Heads up: Competing chain at height %d:'
+ ' tip-height=%d competitor-height=%d'
+ ' tip-hash=%s competitor-hash=%s'
+ ' tip-chainwork=%s competitor-chainwork=%s'
+ ' chainwork-diff=%s',
entry.height,
self.tip.height,
entry.height,
self.tip.rhash(),
entry.rhash(),
self.tip.chainwork.toString(),
entry.chainwork.toString(),
self.tip.chainwork.sub(entry.chainwork).toString());
});
this.on('resolved', function(block, entry) {
self.logger.debug('Orphan %s (%d) was resolved.',
block.rhash(), entry.height);
});
this.on('checkpoint', function(hash, height) {
self.logger.debug('Hit checkpoint block %s (%d).',
util.revHex(hash), height);
});
this.on('fork', function(hash, height, expected) {
self.logger.warning(
'Fork at height %d: expected=%s received=%s',
height,
util.revHex(expected),
util.revHex(hash)
);
});
this.on('reorganize', function(block, height, expected) {
self.logger.warning(
'Reorg at height %d: old=%s new=%s',
height,
util.revHex(expected),
block.rhash()
);
});
this.on('invalid', function(block, height) {
self.logger.warning('Invalid block at height %d: hash=%s',
height, block.rhash());
});
this.on('exists', function(block, height) {
self.logger.debug('Already have block %s (%d).', block.rhash(), height);
});
this.on('orphan', function(block, height) {
self.logger.debug('Handled orphan %s (%d).', block.rhash(), height);
});
this.on('purge', function(count, size) {
self.logger.debug('Warning: %d (%dmb) orphans cleared!',
count, util.mb(size));
});
this._fetchAllKnownTiles();
};
Chain.prototype._fetchAllKnownTiles = co(function* _fetchAllKnownTiles() {
yield this._open();
const { tiles } = yield this._bfs();
yield* tiles.map(tile => this.content.fetch(tile.x, tile.y, tile.content.toString('hex')));
});
/**
* Open the chain, wait for the database to load.
* @alias Chain#open
* @returns {Promise}
*/
Chain.prototype._open = co(function* open() {
var tip, state;
this.logger.info('Chain is loading.');
if (this.options.useCheckpoints)
this.logger.info('Checkpoints are enabled.');
if (this.options.coinCache)
this.logger.info('Coin cache is enabled.');
yield this.db.open();
tip = yield this.db.getTip();
assert(tip);
this.tip = tip;
this.height = tip.height;
this.logger.info('Chain Height: %d', tip.height);
if (tip.height > this.bestHeight)
this.bestHeight = tip.height;
this.logger.memory();
state = yield this.getDeploymentState();
this.setDeploymentState(state);
this.logger.memory();
this.emit('tip', tip);
this.maybeSync();
});
/**
* Close the chain, wait for the database to close.
* @alias Chain#close
* @returns {Promise}
*/
Chain.prototype._close = function close() {
return this.db.close();
};
/**
* Perform all necessary contextual verification on a block.
* @private
* @param {Block|MerkleBlock} block
* @param {ChainEntry} prev
* @returns {Promise} - Returns {@link ContextResult}.
*/
Chain.prototype.verifyContext = co(function* verifyContext(block, prev) {
var state, view;
// Initial non-contextual verification.
state = yield this.verify(block, prev);
// BIP30 - Verify there are no duplicate txids.
yield this.verifyDuplicates(block, prev, state);
// Verify scripts, spend and add coins.
view = yield this.verifyInputs(block, prev, state);
return new ContextResult(view, state);
});
/**
* Test whether a block is the genesis block.
* @param {Block} block
* @returns {Boolean}
*/
Chain.prototype.isGenesis = function isGenesis(block) {
return block.hash('hex') === this.network.genesis.hash;
};
/**
* Contextual verification for a block, including
* version deployments (IsSuperMajority), versionbits,
* coinbase height, finality checks.
* @private
* @param {Block|MerkleBlock} block
* @param {ChainEntry} entry
* @returns {Promise}
* [{@link VerifyError}, {@link VerifyFlags}].
*/
Chain.prototype.verify = co(function* verify(block, prev) {
var ret = new VerifyResult();
var now = this.network.now();
var i, err, height, ts, tx, medianTime;
var commit, ancestors, state;
// Non-contextual checks.
if (!block.verify(ret)) {
err = new VerifyError(block,
'invalid',
ret.reason,
ret.score);
// High hash is the only thing an
// adversary couldn't mutate in
// otherwise valid non-contextual
// checks.
if (ret.reason !== 'high-hash')
err.malleated = true;
throw err;
}
// Skip all blocks in spv mode.
if (this.options.spv)
return this.state;
// Skip any blocks below the
// last checkpoint.
if (!this.options.segwit) {
// We can't skip this with segwit
// enabled since the block may have
// been malleated: we don't know
// until we verify the witness
// merkle root.
if (prev.isHistorical())
return this.state;
}
ancestors = yield prev.getRetargetAncestors();
// Ensure the POW is what we expect.
if (block.bits !== this.getTarget(block, prev, ancestors)) {
throw new VerifyError(block,
'invalid',
'bad-diffbits',
100);
}
// Ensure the timestamp is correct.
medianTime = prev.getMedianTime(ancestors);
if (block.ts <= medianTime) {
throw new VerifyError(block,
'invalid',
'time-too-old',
0);
}
// Check timestamp against adj-time+2hours.
// If this fails we may be able to accept
// the block later.
if (block.ts > now + 2 * 60 * 60) {
err = new VerifyError(block,
'invalid',
'time-too-new',
0);
err.malleated = true;
throw err;
}
// Get the new deployment state.
state = yield this.getDeployments(block, prev);
// Get timestamp for tx.isFinal().
ts = state.hasMTP() ? medianTime : block.ts;
height = prev.height + 1;
// Transactions must be finalized with
// regards to nSequence and nLockTime.
for (i = 0; i < block.txs.length; i++) {
tx = block.txs[i];
if (!tx.isFinal(height, ts)) {
throw new VerifyError(block,
'invalid',
'bad-txns-nonfinal',
10);
}
}
// Make sure the height contained
// in the coinbase is correct.
if (state.hasBIP34()) {
if (block.getCoinbaseHeight() !== height) {
throw new VerifyError(block,
'invalid',
'bad-cb-height',
100);
}
}
// Check the commitment hash for segwit.
if (state.hasWitness()) {
commit = block.getCommitmentHash();
if (commit) {
// These are totally malleable. Someone
// may have even accidentally sent us
// the non-witness version of the block.
// We don't want to consider this block
// "invalid" if either of these checks
// fail.
if (!block.getWitnessNonce()) {
err = new VerifyError(block,
'invalid',
'bad-witness-merkle-size',
100);
err.malleated = true;
throw err;
}
if (!util.equal(commit, block.createCommitmentHash())) {
err = new VerifyError(block,
'invalid',
'bad-witness-merkle-match',
100);
err.malleated = true;
throw err;
}
}
}
// Blocks that do not commit to
// witness data cannot contain it.
if (!commit) {
if (block.hasWitness()) {
err = new VerifyError(block,
'invalid',
'unexpected-witness',
100);
err.malleated = true;
throw err;
}
}
// Check block weight (different from block size
// check in non-contextual verification).
if (block.getWeight() > constants.block.MAX_WEIGHT) {
throw new VerifyError(block,
'invalid',
'bad-blk-weight',
100);
}
return state;
});
/**
* Check all deployments on a chain, ranging from p2sh to segwit.
* @param {Block} block
* @param {ChainEntry} prev
* @returns {Promise}
* [{@link VerifyError}, {@link DeploymentState}].
*/
Chain.prototype.getDeployments = co(function* getDeployments(block, prev) {
var deployments = this.network.deployments;
var height = prev.height + 1;
var state = new DeploymentState();
var active;
// Only allow version 2 blocks (coinbase height)
// once the majority of blocks are using it.
if (block.version < 2 && height >= this.network.block.bip34height)
throw new VerifyError(block, 'obsolete', 'bad-version', 0);
// Only allow version 3 blocks (sig validation)
// once the majority of blocks are using it.
if (block.version < 3 && height >= this.network.block.bip66height)
throw new VerifyError(block, 'obsolete', 'bad-version', 0);
// Only allow version 4 blocks (checklocktimeverify)
// once the majority of blocks are using it.
if (block.version < 4 && height >= this.network.block.bip65height)
throw new VerifyError(block, 'obsolete', 'bad-version', 0);
// Only allow version 5 blocks (bip141 - segnet3)
// once the majority of blocks are using it.
if (this.options.witness && this.network.oldWitness) {
if (block.version < 5 && height >= this.network.block.bip141height)
throw new VerifyError(block, 'obsolete', 'bad-version', 0);
}
// For some reason bitcoind has p2sh in the
// mandatory flags by default, when in reality
// it wasn't activated until march 30th 2012.
// The first p2sh output and redeem script
// appeared on march 7th 2012, only it did
// not have a signature. See:
// 6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192
// 9c08a4d78931342b37fd5f72900fb9983087e6f46c4a097d8a1f52c74e28eaf6
if (block.ts >= constants.block.BIP16_TIME)
state.flags |= constants.flags.VERIFY_P2SH;
// Coinbase heights are now enforced (bip34).
if (height >= this.network.block.bip34height)
state.bip34 = true;
// Signature validation is now enforced (bip66).
if (height >= this.network.block.bip66height)
state.flags |= constants.flags.VERIFY_DERSIG;
// CHECKLOCKTIMEVERIFY is now usable (bip65)
if (height >= this.network.block.bip65height)
state.flags |= constants.flags.VERIFY_CHECKLOCKTIMEVERIFY;
// Segregrated witness is now usable (bip141 - segnet3)
if (this.options.witness && this.network.oldWitness) {
if (height >= this.network.block.bip141height)
state.flags |= constants.flags.VERIFY_WITNESS;
}
if (this.network.oldWitness)
return state;
// CHECKSEQUENCEVERIFY and median time
// past locktimes are now usable (bip9 & bip113).
active = yield this.isActive(prev, deployments.csv);
if (active) {
state.flags |= constants.flags.VERIFY_CHECKSEQUENCEVERIFY;
state.lockFlags |= constants.flags.VERIFY_SEQUENCE;
state.lockFlags |= constants.flags.MEDIAN_TIME_PAST;
}
// Segregrated witness is now usable (bip141 - segnet4)
active = yield this.isActive(prev, deployments.segwit);
if (active) {
if (this.options.witness)
state.flags |= constants.flags.VERIFY_WITNESS;
// BIP147
state.flags |= constants.flags.VERIFY_NULLDUMMY;
}
return state;
});
/**
* Set a new deployment state.
* @param {DeploymentState} state
*/
Chain.prototype.setDeploymentState = function setDeploymentState(state) {
if (!this.state.hasP2SH() && state.hasP2SH())
this.logger.warning('P2SH has been activated.');
if (!this.state.hasBIP34() && state.hasBIP34())
this.logger.warning('BIP34 has been activated.');
if (!this.state.hasBIP66() && state.hasBIP66())
this.logger.warning('BIP66 has been activated.');
if (!this.state.hasCLTV() && state.hasCLTV())
this.logger.warning('BIP65 has been activated.');
if (!this.state.hasWitness() && state.hasWitness())
this.logger.warning('Segwit has been activated.');
if (!this.state.hasCSV() && state.hasCSV())
this.logger.warning('CSV has been activated.');
this.state = state;
};
/**
* Determine whether to check block for duplicate txids in blockchain
* history (BIP30). If we're on a chain that has bip34 activated, we
* can skip this.
* @private
* @see https://github.com/bitcoin/bips/blob/master/bip-0030.mediawiki
* @param {Block|MerkleBlock} block
* @param {ChainEntry} prev
* @returns {Promise}
*/
Chain.prototype.verifyDuplicates = co(function* verifyDuplicates(block, prev, state) {
var height = prev.height + 1;
var i, tx, result;
if (this.options.spv)
return;
if (prev.isHistorical())
return;
// BIP34 made it impossible to
// create duplicate txids.
if (state.hasBIP34())
return;
// Check all transactions.
for (i = 0; i < block.txs.length; i++) {
tx = block.txs[i];
result = yield this.db.hasCoins(tx.hash());
if (result) {
// Blocks 91842 and 91880 created duplicate
// txids by using the same exact output script
// and extraNonce.
if (constants.bip30[height]) {
if (block.hash('hex') === constants.bip30[height])
continue;
}
throw new VerifyError(block, 'invalid', 'bad-txns-BIP30', 100);
}
}
});
Chain.prototype.getTile = co(function* getTile(x, y) {
return yield this.db.getTile(x,y);
});
Chain.prototype.setTile = co(function* setTile(x, y, base64content) {
var contentHash = yield this.content.putFile(x, y, base64content);
return contentHash;
});
Chain.prototype.getTileOutpoint = co(function* getTileOutpoint(x, y) {
return yield this.db.getTileOutpoint(x,y);
});
Chain.prototype.isAdjacent = co(function* isAdjacent(coinbase) {
var output = coinbase.outputs[0];
var x0 = output.x;
var y0 = output.y;
for (var i = 0; i < 4; i++) {
var x = x0 + DX[i];
var y = y0 + DY[i];
var tile = yield this.db.getTile(x, y);
if (tile) {
return true;
}
}
return false;
});
Chain.prototype.isEmpty = co(function* isEmpty(coinbase) {
var output = coinbase.outputs[0];
var tile = yield this.db.getTile(output.x, output.y);
return !tile;
});
/**
* Check block transactions for all things pertaining
* to inputs. This function is important because it is
* what actually fills the coins into the block. This
* function will check the block reward, the sigops,
* the tx values, and execute and verify the scripts (it
* will attempt to do this on the worker pool). If
* useCheckpoints is enabled, it will skip verification
* for historical data.
* @private
* @see TX#checkInputs
* @param {Block} block
* @param {ChainEntry} prev
* @param {DeploymentState} state
* @returns {Promise} - Returns {@link CoinView}.
*/
Chain.prototype.verifyInputs = co(function* verifyInputs(block, prev, state) {
var ret = new VerifyResult();
var view = new CoinView();
var height = prev.height + 1;
var historical = prev.isHistorical();
var sigops = 0;
var jobs = [];
var i, tx, valid;
if (this.options.spv)
return view;
// Make sure the miner is creating an adjacent tile
var coinbase = block.getCoinbase();
if (!this.isAdjacent(coinbase)) {
throw new VerifyError(block,
'invalid',
'bad-cb-position',
100);
}
// Make sure the miner is not overwriting existing tile
if (!this.isEmpty(coinbase)) {
throw new VerifyError(block,
'invalid',
'bad-cb-overwrite',
100);
}
// Check all transactions
for (i = 0; i < block.txs.length; i++) {
tx = block.txs[i];
// Ensure tx is not double spending an output.
if (i > 0) {
if (!(yield view.spendInputs(this.db, tx))) {
assert(!historical, 'BUG: Spent inputs in historical data!');
throw new VerifyError(block,
'invalid',
'bad-txns-inputs-missingorspent',
100);
}
}
// Skip everything if we're
// using checkpoints.
if (historical) {
view.addTX(tx, height);
continue;
}
// Verify sequence locks.
valid = yield this.verifyLocks(prev, tx, view, state.lockFlags);
if (!valid) {
throw new VerifyError(block,
'invalid',
'bad-txns-nonfinal',
100);
}
// Count sigops (legacy + scripthash? + witness?)
sigops += tx.getSigopsCost(view, state.flags);
if (sigops > constants.block.MAX_SIGOPS_COST) {
throw new VerifyError(block,
'invalid',
'bad-blk-sigops',
100);
}
// Contextual sanity checks.
if (i > 0) {
if (!tx.checkInputs(view, height, ret)) {
throw new VerifyError(block,
'invalid',
ret.reason,
ret.score);
}
// Push onto verification queue.
jobs.push(tx.verifyAsync(view, state.flags));
}
// Add new coins.
view.addTX(tx, height);
}
if (historical)
return view;
// Verify all txs in parallel.
valid = yield co.every(jobs);
if (!valid) {
throw new VerifyError(block,
'invalid',
'mandatory-script-verify-flag-failed',
100);
}
return view;
});
/**
* Get the cached height for a hash if present.
* @private
* @param {Hash} hash
* @returns {Number}
*/
Chain.prototype.checkHeight = function checkHeight(hash) {
var entry = this.db.getCache(hash);
if (!entry)
return -1;
return entry.height;
};
/**
* Find the block at which a fork ocurred.
* @private
* @param {ChainEntry} fork - The current chain.
* @param {ChainEntry} longer - The competing chain.
* @returns {Promise}
*/
Chain.prototype.findFork = co(function* findFork(fork, longer) {
while (fork.hash !== longer.hash) {
while (longer.height > fork.height) {
longer = yield longer.getPrevious();
if (!longer)
throw new Error('No previous entry for new tip.');
}
if (fork.hash === longer.hash)
return fork;
fork = yield fork.getPrevious();
if (!fork)
throw new Error('No previous entry for old tip.');
}
return fork;
});
/**
* Reorganize the blockchain (connect and disconnect inputs).
* Called when a competing chain with a higher chainwork
* is received.
* @private
* @param {ChainEntry} competitor - The competing chain's tip.
* @param {Block|MerkleBlock} block - The being being added.
* @returns {Promise}
*/
Chain.prototype.reorganize = co(function* reorganize(competitor, block) {
var tip = this.tip;
var fork = yield this.findFork(tip, competitor);
var disconnect = [];
var connect = [];
var i, entry;
assert(fork, 'No free space or data corruption.');
// Blocks to disconnect.
entry = tip;
while (entry.hash !== fork.hash) {
disconnect.push(entry);
entry = yield entry.getPrevious();
assert(entry);
}
// Blocks to connect.
entry = competitor;
while (entry.hash !== fork.hash) {
connect.push(entry);
entry = yield entry.getPrevious();
assert(entry);
}
// Disconnect blocks/txs.
for (i = 0; i < disconnect.length; i++) {
entry = disconnect[i];
yield this.disconnect(entry);
}
// Connect blocks/txs.
// We don't want to connect the new tip here.
// That will be done outside in setBestChain.
for (i = connect.length - 1; i >= 1; i--) {
entry = connect[i];
yield this.reconnect(entry);
}
this.emit('reorganize', block, tip.height, tip.hash);
});
/**
* Reorganize the blockchain for SPV. This
* will reset the chain to the fork block.
* @private
* @param {ChainEntry} competitor - The competing chain's tip.
* @param {Block|MerkleBlock} block - The being being added.
* @returns {Promise}
*/
Chain.prototype.reorganizeSPV = co(function* reorganizeSPV(competitor, block) {
var tip = this.tip;
var fork = yield this.findFork(tip, competitor);
var disconnect = [];
var entry = tip;
var i, headers, view;
assert(fork, 'No free space or data corruption.');
// Buffer disconnected blocks.
while (entry.hash !== fork.hash) {
disconnect.push(entry);
entry = yield entry.getPrevious();
assert(entry);
}
// Reset the main chain back
// to the fork block, causing
// us to redownload the blocks
// on the new main chain.
yield this._reset(fork.hash, true);
// Emit disconnection events now that
// the chain has successfully reset.
for (i = 0; i < disconnect.length; i++) {
entry = disconnect[i];
headers = entry.toHeaders();
view = new CoinView();
this.emit('disconnect', entry, headers, view);
}
this.emit('reorganize', block, tip.height, tip.hash);
});
/**
* Disconnect an entry from the chain (updates the tip).
* @param {ChainEntry} entry
* @returns {Promise}
*/
Chain.prototype.disconnect = co(function* disconnect(entry) {
var block = yield this.db.getBlock(entry.hash);
var prev, view;
if (!block) {
if (!this.options.spv)
throw new Error('Block not found.');
block = entry.toHeader();
}
prev = yield entry.getPrevious();
view = yield this.db.disconnect(entry, block);
assert(prev);
this.tip = prev;
this.height = prev.height;
this.bestHeight = prev.height;
this.emit('tip', prev);
this.emit('disconnect', entry, block, view);
});
/**
* Reconnect an entry to the chain (updates the tip).
* This will do contextual-verification on the block
* (necessary because we cannot validate the inputs
* in alternate chains when they come in).
* @param {ChainEntry} entry
* @returns {Promise}
*/
Chain.prototype.reconnect = co(function* reconnect(entry) {
var block = yield this.db.getBlock(entry.hash);
var prev, result;
if (!block) {
if (!this.options.spv)
throw new Error('Block not found.');
block = entry.toHeader();
}
prev = yield entry.getPrevious();
assert(prev);
try {
result = yield this.verifyContext(block, prev);
} catch (e) {
if (e.type === 'VerifyError') {
if (!e.malleated)
this.setInvalid(entry.hash);
this.emit('invalid', block, entry.height);
}
throw e;
}
yield this.db.reconnect(entry, block, result.view);
this.tip = entry;
this.height = entry.height;
this.bestHeight = entry.height;
this.setDeploymentState(result.state);
this.emit('tip', entry);
this.emit('reconnect', entry, block);
this.emit('connect', entry, block, result.view);
});
/**
* Set the best chain. This is called on every valid block
* that comes in. It may add and connect the block (main chain),
* save the block without connection (alternate chain), or
* reorganize the chain (a higher fork).
* @private
* @param {ChainEntry} entry
* @param {Block|MerkleBlock} block
* @param {ChainEntry} prev
* @returns {Promise}
*/
Chain.prototype.setBestChain = co(function* setBestChain(entry, block, prev) {
var result;
// A higher fork has arrived.
// Time to reorganize the chain.
if (entry.prevBlock !== this.tip.hash) {
this.logger.warning('WARNING: Reorganizing chain.');
// In spv-mode, we reset the
// chain and redownload the blocks.
if (this.options.spv)
return yield this.reorganizeSPV(entry, block);
yield this.reorganize(entry, block);
}
// Warn of unknown versionbits.
if (entry.hasUnknown()) {
this.logger.warning(
'Unknown version bits in block %d: %d.',
entry.height, entry.version);
}
// Otherwise, everything is in order.
// Do "contextual" verification on our block
// now that we're certain its previous
// block is in the chain.
try {
result = yield this.verifyContext(block, prev);
} catch (e) {
if (e.type === 'VerifyError') {
if (!e.malleated)
this.setInvalid(entry.hash);
this.emit('invalid', block, entry.height);
}
throw e;
}
// Save block and connect inputs.
yield this.db.save(entry, block, result.view);
// Expose the new state.
this.tip = entry;
this.height = entry.height;
this.setDeploymentState(result.state);
this.emit('tip', entry);
this.emit('block', block, entry);
this.emit('connect', entry, block, result.view);
});
/**
* Save block on an alternate chain.
* @private
* @param {ChainEntry} entry
* @param {Block|MerkleBlock} block
* @param {ChainEntry} prev
* @returns {Promise}
*/
Chain.prototype.saveAlternate = co(function* saveAlternate(entry, block, prev) {
try {
// Do as much verification
// as we can before saving.
yield this.verify(block, prev);
} catch (e) {
if (e.type === 'VerifyError') {
if (!e.malleated)
this.setInvalid(entry.hash);
this.emit('invalid', block, entry.height);
}
throw e;
}
// Warn of unknown versionbits.
if (entry.hasUnknown()) {
this.logger.warning(
'Unknown version bits in block %d: %d.',
entry.height, entry.version);
}
yield this.db.save(entry, block);
// Emit as a "competitor" block.
this.emit('competitor', block, entry);
});
/**
* Reset the chain to the desired block. This
* is useful for replaying the blockchain download
* for SPV.
* @param {Hash|Number} block
* @returns {Promise}
*/
Chain.prototype.reset = co(function* reset(block) {
var unlock = yield this.locker.lock();
try {
return yield this._reset(block, false);
} finally {
unlock();
}
});
/**
* Reset the chain to the desired block without a lock.
* @private
* @param {Hash|Number} block
* @returns {Promise}
*/
Chain.prototype._reset = co(function* reset(block, silent) {
var tip = yield this.db.reset(block);
var state;
// Reset state.
this.tip = tip;
this.height = tip.height;
this.synced = this.isFull(true);
state = yield this.getDeploymentState();
this.setDeploymentState(state);
this.emit('tip', tip);
if (!silent)
this.emit('reset', tip);
// Reset the orphan map completely. There may
// have been some orphans on a forked chain we
// no longer need.
this.purgeOrphans();
});
/**
* Reset the chain to a height or hash. Useful for replaying
* the blockchain download for SPV.
* @param {Hash|Number} block - hash/height
* @returns {Promise}
*/
Chain.prototype.replay = co(function* replay(block) {
var unlock = yield this.locker.lock();
try {
return yield this._replay(block);
} finally {
unlock();
}
});
/**
* Reset the chain without a lock.
* @private
* @param {Hash|Number} block - hash/height
* @returns {Promise}
*/
Chain.prototype._replay = co(function* replay(block) {
var entry = yield this.db.getEntry(block);
if (!entry)
throw new Error('Block not found.');
if (!(yield entry.isMainChain()))
throw new Error('Cannot reset on alternate chain.');
if (entry.isGenesis())
return yield this._reset(entry.hash, true);
yield this._reset(entry.prevBlock, true);
});
/**
* Scan the blockchain for transactions containing specified address hashes.
* @param {Hash} start - Block hash to start at.
* @param {Bloom} filter - Bloom filter containing tx and address hashes.
* @param {Function} iter - Iterator.
* @returns {Promise}
*/
Chain.prototype.scan = co(function* scan(start, filter, iter) {
var unlock = yield this.locker.lock();
try {
return yield this.db.scan(start, filter, iter);
} finally {
unlock();
}
});
/**
* Reset the chain to the desired timestamp (within 2
* hours). This is useful for replaying the blockchain
* download for SPV.
* @param {Number} ts - Timestamp.
* @returns {Promise}
*/
Chain.prototype.resetTime = co(function* resetTime(ts) {
var unlock = yield this.locker.lock();
try {
return yield this._resetTime(ts);
} finally {
unlock();
}
});
/**
* Reset the chain to the desired timestamp without a lock.
* @private
* @param {Number} ts - Timestamp.
* @returns {Promise}
*/
Chain.prototype._resetTime = co(function* resetTime(ts) {
var entry = yield this.byTime(ts);
if (!entry)
return;
yield this._reset(entry.height, false);
});
/**
* Wait for the chain to drain (finish processing
* all of the blocks in its queue).
* @returns {Promise}
*/
Chain.prototype.onDrain = function onDrain() {
return this.locker.wait();
};
/**
* Test whether the chain is in the process of adding blocks.
* @returns {Boolean}
*/
Chain.prototype.isBusy = function isBusy() {
return this.locker.isBusy();
};
/**
* Add a block to the chain, perform all necessary verification.
* @param {Block|MerkleBlock|MemBlock} block
* @returns {Promise}
*/
Chain.prototype.add = co(function* add(block) {
var hash = block.hash('hex');
var unlock = yield this.locker.lock(hash);
try {
return yield this._add(block);
} finally {
unlock();
}
});
/**
* Add a block to the chain without a lock.
* @private
* @param {Block|MerkleBlock|MemBlock} block
* @returns {Promise}
*/
Chain.prototype._add = co(function* add(block) {
var ret = new VerifyResult();
var initial = true;
var hash, height, entry, prev, result;
while (block) {
hash = block.hash('hex');
// Mark the start time.
this.mark();
// Special case for genesis block.
if (hash === this.network.genesis.hash)
break;
// Do we already have this block?
if (this.hasPending(hash)) {
this.emit('exists', block, block.getCoinbaseHeight());
throw new VerifyError(block, 'duplicate', 'duplicate', 0);
}
// If the block is already known to be
// an orphan, ignore it.
if (this.seenOrphan(hash)) {
this.emit('orphan', block, block.getCoinbaseHeight());
throw new VerifyError(block, 'duplicate', 'duplicate', 0);
}
// Do not revalidate known invalid blocks.
if (this.hasInvalid(hash, block)) {
this.emit('invalid', block, block.getCoinbaseHeight());
throw new VerifyError(block, 'duplicate', 'duplicate', 100);
}
// Validate the block we want to add.
// This is only necessary for new
// blocks coming in, not the resolving
// orphans.
if (!block.verify(ret)) {
this.emit('invalid', block, block.getCoinbaseHeight());
throw new VerifyError(block, 'invalid', ret.reason, ret.score);
}
// Do we already have this block?
if (yield this.db.hasEntry(hash)) {
this.emit('exists', block, block.getCoinbaseHeight());
throw new VerifyError(block, 'duplicate', 'duplicate', 0);
}
// Find the previous block height/index.
prev = yield this.db.getEntry(block.prevBlock);
// If previous block wasn't ever seen,
// add it current to orphans and break.
if (!prev) {
this.storeOrphan(block);
throw new VerifyError(block, 'invalid', 'bad-prevblk', 0);
}
height = prev.height + 1;
// Update best height seen.
if (height > this.bestHeight)
this.bestHeight = height;
// Verify a checkpoint if there is one.
if (!this.verifyCheckpoint(hash, height)) {
throw new VerifyError(block,
'checkpoint',
'checkpoint mismatch',
100);
}
// Explanation: we try to keep as much data
// off the javascript heap as possible. Blocks
// in the future may be 8mb or 20mb, who knows.
// In fullnode-mode we store the blocks in
// "compact" form (the headers plus the raw
// Buffer object) until they're ready to be
// fully validated here. They are deserialized,
// validated, and emitted. Hopefully the deserialized
// blocks get cleaned up by the GC quickly.
if (block.memory) {
try {
block = block.toBlock();
} catch (e) {
this.logger.error(e);
throw new VerifyError(block,
'malformed',
'error parsing message',
100);
}
}
// Create a new chain entry.
entry = ChainEntry.fromBlock(this, block, prev);
// The block is on a alternate chain if the
// chainwork is less than or equal to
// our tip's. Add the block but do _not_
// connect the inputs.
if (entry.chainwork.cmp(this.tip.chainwork) <= 0) {
// Save block to an alternate chain.
yield this.saveAlternate(entry, block, prev);
if (!initial)
this.emit('competitor resolved', block, entry);
} else {
// Attempt to add block to the chain index.
yield this.setBestChain(entry, block, prev);
if (!initial)
this.emit('resolved', block, entry);
}
// Keep track of stats.
this.finish(block, entry);
// Try to resolve orphan chain.
block = this.resolveOrphan(hash);
initial = false;
if (!result)
result = entry;
}
// Failsafe for large orphan chains. Do not
// allow more than 20mb stored in memory.
this.pruneOrphans();
// Check sync state.
this.maybeSync();
return result;
});
/**
* Test whether the chain has reached its slow height.
* @private
* @returns {Boolean}
*/
Chain.prototype.isSlow = function isSlow() {
if (this.options.spv)
return false;
if (this.total === 1 || this.total % 20 === 0)
return true;
return this.synced || this.height >= this.network.block.slowHeight;
};
/**
* Mark the start time for block processing.
* @private
*/
Chain.prototype.mark = function mark() {
this._time = util.hrtime();
};
/**
* Calculate the time difference from
* start time and log block.
* @private
* @param {Block} block
* @param {ChainEntry} entry
*/
Chain.prototype.finish = function finish(block, entry) {
var elapsed, time;
// Keep track of total blocks handled.
this.total += 1;
if (!this.isSlow())
return;
// Report memory for debugging.
util.gc();
this.logger.memory();
elapsed = util.hrtime(this._time);
time = elapsed[0] * 1000 + elapsed[1] / 1e6;
this.logger.info(
'Block %s (%d) added to chain (size=%d txs=%d time=%d).',
entry.rhash(),
entry.height,
block.getSize(),
block.txs.length,
time);
if (this.db.coinCache.capacity > 0) {
this.logger.debug('Coin Cache: size=%dmb, items=%d.',
util.mb(this.db.coinCache.size), this.db.coinCache.items);
}
};
/**
* Verify a block hash and height against the checkpoints.
* @private
* @param {Hash} hash
* @param {Number} height
* @returns {Boolean}
*/
Chain.prototype.verifyCheckpoint = function verifyCheckpoint(hash, height) {
var checkpoint;
if (!this.options.useCheckpoints)
return true;
checkpoint = this.network.checkpoints[height];
if (!checkpoint)
return true;
if (hash === checkpoint) {
this.emit('checkpoint', hash, height);
return true;
}
// Someone is either mining on top of
// an old block for no reason, or the
// consensus protocol is broken and
// there was a 20k+ block reorg.
this.logger.warning('Checkpoint mismatch!');
this.purgeOrphans();
this.emit('fork', hash, height, checkpoint);
return false;
};
/**
* Verify we do not already have an orphan.
* Throw if there is an orphan fork.
* @private
* @param {Block} block
* @returns {Boolean}
* @throws {VerifyError}
*/
Chain.prototype.seenOrphan = function seenOrphan(block) {
var orphan = this.orphan.map[block.prevBlock];
var hash;
if (!orphan)
return false;
hash = block.hash('hex');
// The orphan chain forked.
if (orphan.hash('hex') !== hash) {
this.emit('fork', hash,
block.getCoinbaseHeight(),
orphan.hash('hex'));
this.resolveOrphan(block.prevBlock);
this.storeOrphan(block);
throw new VerifyError(block, 'invalid', 'bad-prevblk', 0);
}
return true;
};
/**
* Store an orphan.
* @private
* @param {Block} block
*/
Chain.prototype.storeOrphan = function storeOrphan(block) {
var hash = block.hash('hex');
var height = block.getCoinbaseHeight();
this.orphan.count++;
this.orphan.size += block.getSize();
this.orphan.map[block.prevBlock] = block;
this.orphan.bmap[hash] = block;
// Update the best height based on the coinbase.
// We do this even for orphans (peers will send
// us their highest block during the initial
// getblocks sync, making it an orphan).
if (height > this.bestHeight)
this.bestHeight = height;
this.emit('orphan', block, height);
};
/**
* Resolve an orphan.
* @private
* @param {Hash} hash - Previous block hash.
* @returns {Block}
*/
Chain.prototype.resolveOrphan = function resolveOrphan(hash) {
var block = this.orphan.map[hash];
if (!block)
return;
delete this.orphan.bmap[block.hash('hex')];
delete this.orphan.map[hash];
this.orphan.count--;
this.orphan.size -= block.getSize();
return block;
};
/**
* Purge any waiting orphans.
*/
Chain.prototype.purgeOrphans = function purgeOrphans() {
var count = this.orphan.count;
var size = this.orphan.size;
if (count === 0)
return;
this.orphan.map = {};
this.orphan.bmap = {};
this.orphan.count = 0;
this.orphan.size = 0;
this.emit('purge', count, size);
};
/**
* Prune orphans, only keep the orphan with the highest
* coinbase height (likely to be the peer's tip).
*/
Chain.prototype.pruneOrphans = function pruneOrphans() {
var i, hashes, hash, orphan, height, best, last;
if (this.orphan.size <= this.orphanLimit)
return false;
hashes = Object.keys(this.orphan.map);
if (hashes.length === 0)
return false;
for (i = 0; i < hashes.length; i++) {
hash = hashes[i];
orphan = this.orphan.map[hash];
height = orphan.getCoinbaseHeight();
delete this.orphan.map[hash];
if (!best || height > best.getCoinbaseHeight())
best = orphan;
last = orphan;
}
// Save the best for last... or the
// last for best in this case.
if (best.getCoinbaseHeight() <= 0)
best = last;
hashes = Object.keys(this.orphan.bmap);
for (i = 0; i < hashes.length; i++) {
hash = hashes[i];
orphan = this.orphan.bmap[hash];
delete this.orphan.bmap[hash];
if (orphan !== best)
this.emit('unresolved', orphan);
}
this.emit('purge',
this.orphan.count - 1,
this.orphan.size - best.getSize());
this.orphan.map[best.prevBlock] = best;
this.orphan.bmap[best.hash('hex')] = best;
this.orphan.count = 1;
this.orphan.size = best.getSize();
return true;
};
/**
* Test whether an invalid block hash has been seen.
* @private
* @param {Hash} hash
* @param {Block} block
* @returns {Boolean}
*/
Chain.prototype.hasInvalid = function hasInvalid(hash, block) {
if (this.invalid.has(hash))
return true;
if (this.invalid.has(block.prevBlock)) {
this.setInvalid(hash);
return true;
}
return false;
};
/**
* Mark a block as invalid.
* @private
* @param {Hash} hash
*/
Chain.prototype.setInvalid = function setInvalid(hash) {
this.invalid.set(hash, true);
};
/**
* Forget an invalid block hash.
* @private
* @param {Hash} hash
*/
Chain.prototype.removeInvalid = function removeInvalid(hash) {
this.invalid.remove(hash);
};
/**
* Test the chain to see if it has a block, orphan, or pending block.
* @param {Hash} hash
* @returns {Promise} - Returns Boolean.
*/
Chain.prototype.has = co(function* has(hash) {
if (this.hasOrphan(hash))
return true;
if (this.locker.has(hash))
return true;
return yield this.hasEntry(hash);
});
/**
* Find a block entry by timestamp.
* @param {Number} ts - Timestamp.
* @returns {Promise} - Returns {@link ChainEntry}.
*/
Chain.prototype.byTime = co(function* byTime(ts) {
var start = 0;
var end = this.height;
var pos, delta, entry;
if (ts >= this.tip.ts)
return this.tip;
// Do a binary search for a block
// mined within an hour of the
// timestamp.
while (start < end) {
pos = (start + end) >>> 1;
entry = yield this.db.getEntry(pos);
if (!entry)
return;
delta = Math.abs(ts - entry.ts);
if (delta <= 60 * 60)
break;
if (ts < entry.ts)
end = pos - 1;
else
start = pos + 1;
}
return entry;
});
/**
* Test the chain to see if it contains a block.
* @param {Hash} hash
* @returns {Promise} - Returns Boolean.
*/
Chain.prototype.hasEntry = function hasEntry(hash) {
return this.db.hasEntry(hash);
};
/**
* Test the chain to see if it contains an orphan.
* @param {Hash} hash
* @returns {Promise} - Returns Boolean.
*/
Chain.prototype.hasOrphan = function hasOrphan(hash) {
return !!this.getOrphan(hash);
};
/**
* Test the chain to see if it contains a pending block in its queue.
* @param {Hash} hash
* @returns {Promise} - Returns Boolean.
*/
Chain.prototype.hasPending = function hasPending(hash) {
return this.locker.hasPending(hash);
};
/**
* Find the corresponding block entry by hash or height.
* @param {Hash|Number} hash/height
* @returns {Promise} - Returns {@link ChainEntry}.
*/
Chain.prototype.getEntry = function getEntry(hash) {
return this.db.getEntry(hash);
};
/**
* Get an orphan block.
* @param {Hash} hash
* @returns {Block|MerkleBlock|MemBlock}
*/
Chain.prototype.getOrphan = function getOrphan(hash) {
return this.orphan.bmap[hash] || null;
};
/**
* Get coin viewpoint.
* @param {TX} tx
* @returns {Promise} - Returns {@link CoinView}.
*/
Chain.prototype.getCoinView = co(function* getCoinView(tx) {
var unlock = yield this.locker.lock();
try {
return yield this.db.getCoinView(tx);
} finally {
unlock();
}
});
/**
* Test the chain to see if it is synced.
* @returns {Boolean}
*/
Chain.prototype.isFull = function isFull(force) {
return this.options.bootstrapNetwork || !this.isInitial(force);
};
/**
* Potentially emit a `sync` event.
* @private
*/
Chain.prototype.maybeSync = function maybeSync() {
if (!this.synced && this.isFull()) {
this.synced = true;
this.emit('full');
}
};
/**
* Test the chain to see if it is still in the initial
* syncing phase. Mimic's bitcoind's `IsInitialBlockDownload()`
* function.
* @see IsInitalBlockDownload()
* @returns {Boolean}
*/
Chain.prototype.isInitial = function isInitial(force) {
if (!force && this.synced)
return false;
if (this.height < this.network.checkpoints.lastHeight)
return true;
if (this.height < this.bestHeight - 24 * 6)
return true;
if (this.tip.ts < util.now() - this.network.block.maxTipAge)
return true;
return false;
};
/**
* Get the fill percentage.
* @returns {Number} percent - Ranges from 0.0 to 1.0.
*/
Chain.prototype.getProgress = function getProgress() {
var start = this.network.genesis.ts;
var current = this.tip.ts - start;
var end = util.now() - start - 40 * 60;
return Math.min(1, current / end);
};
/**
* Calculate chain locator (an array of hashes).
* @param {(Number|Hash)?} start - Height or hash to treat as the tip.
* The current tip will be used if not present. Note that this can be a
* non-existent hash, which is useful for headers-first locators.
* @returns {Promise} - Returns {@link Hash}[].
*/
Chain.prototype.getLocator = co(function* getLocator(start) {
var unlock = yield this.locker.lock();
try {
return yield this._getLocator(start);
} finally {
unlock();
}
});
/**
* Calculate chain locator without a lock.
* @private
* @param {(Number|Hash)?} start
* @returns {Promise}
*/
Chain.prototype._getLocator = co(function* getLocator(start) {
var hashes = [];
var step = 1;
var height, entry, main, hash;
if (start == null)
start = this.tip.hash;
entry = yield this.db.getEntry(start);
if (!entry) {
// We could simply return `start` here,
// but there is no required "spacing"
// for locator hashes. Pretend this hash
// is our tip. This is useful for
// getheaders.
if (typeof start === 'string')
hashes.push(start);
entry = this.tip;
}
height = entry.height;
main = yield entry.isMainChain();
hash = entry.hash;
while (hash) {
hashes.push(hash);
if (height === 0)
break;
height = Math.max(height - step, 0);
if (hashes.length > 10)
step *= 2;
if (height === 0) {
hash = this.network.genesis.hash;
continue;
}
// If we're on the main chain, we can
// do a fast lookup of the hash.
if (main) {
hash = yield this.db.getHash(height);
continue;
}
entry = yield entry.getAncestor(height);
if (!entry)
break;
hash = entry.hash;
}
return hashes;
});
/**
* Calculate the orphan root of the hash (if it is an orphan).
* Will also calculate "orphan soil" -- the block needed
* in * order to resolve the orphan root.
* @param {Hash} hash
* @returns {Hash}
*/
Chain.prototype.getOrphanRoot = function getOrphanRoot(hash) {
var root;
assert(hash);
while (this.orphan.bmap[hash]) {
root = hash;
hash = this.orphan.bmap[hash].prevBlock;
}
return root;
};
/**
* Calculate the next target based on the chain tip.
* @returns {Promise} - returns Number
* (target is in compact/mantissa form).
*/
Chain.prototype.getCurrentTarget = co(function* getCurrentTarget() {
return yield this.getTargetAsync(null, this.tip);
});
/**
* Calculate the target based on the passed-in chain entry.
* @param {ChainEntry} prev - Previous entry.
* @param {Block|MerkleBlock|null} - Current block.
* @returns {Promise} - returns Number
* (target is in compact/mantissa form).
*/
Chain.prototype.getTargetAsync = co(function* getTargetAsync(block, prev) {
var pow = this.network.pow;
var ancestors;
if ((prev.height + 1) % pow.retargetInterval !== 0) {
if (!pow.difficultyReset)
return this.getTarget(block, prev);
}
ancestors = yield prev.getAncestors(pow.retargetInterval);
return this.getTarget(block, prev, ancestors);
});
/**
* Calculate the target synchronously. _Must_
* have ancestors pre-allocated.
* @param {Block|MerkleBlock|null} - Current block.
* @param {ChainEntry} prev - Previous entry.
* @returns {Promise} - returns Number
* (target is in compact/mantissa form).
*/
Chain.prototype.getTarget = function getTarget(block, prev, ancestors) {
var pow = this.network.pow;
var ts, first, i;
// Genesis
if (!prev)
return pow.bits;
// Do not retarget
if ((prev.height + 1) % pow.retargetInterval !== 0) {
if (pow.difficultyReset) {
// Special behavior for testnet:
ts = block ? (block.ts || block) : this.network.now();
if (ts > prev.ts + pow.targetSpacing * 2)
return pow.bits;
i = 1;
while (ancestors[i]
&& prev.height % pow.retargetInterval !== 0
&& prev.bits === pow.bits) {
prev = ancestors[i++];
}
}
return prev.bits;
}
// Back 2 weeks
first = ancestors[pow.retargetInterval - 1];
assert(first);
return this.retarget(prev, first);
};
/**
* Retarget. This is called when the chain height
* hits a retarget diff interval.
* @param {ChainEntry} prev - Previous entry.
* @param {ChainEntry} first - Chain entry from 2 weeks prior.
* @returns {Number} target - Target in compact/mantissa form.
*/
Chain.prototype.retarget = function retarget(prev, first) {
var pow = this.network.pow;
var targetTimespan = pow.targetTimespan;
var actualTimespan, target;
if (pow.noRetargeting)
return prev.bits;
actualTimespan = prev.ts - first.ts;
target = btcutils.fromCompact(prev.bits);
if (actualTimespan < targetTimespan / 4 | 0)
actualTimespan = targetTimespan / 4 | 0;
if (actualTimespan > targetTimespan * 4)
actualTimespan = targetTimespan * 4;
target.imuln(actualTimespan);
target.idivn(targetTimespan);
if (target.cmp(pow.limit) > 0)
return pow.bits;
return btcutils.toCompact(target);
};
/**
* Find a locator. Analagous to bitcoind's `FindForkInGlobalIndex()`.
* @param {Hash[]} locator - Hashes.
* @returns {Promise} - Returns {@link Hash} (the
* hash of the latest known block).
*/
Chain.prototype.findLocator = co(function* findLocator(locator) {
var i, hash;
for (i = 0; i < locator.length; i++) {
hash = locator[i];
if (yield this.db.isMainChain(hash))
return hash;
}
return this.network.genesis.hash;
});
/**
* Check whether a versionbits deployment is active (BIP9: versionbits).
* @example
* yield chain.isActive(tip, deployments.segwit);
* @see https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki
* @param {ChainEntry} prev - Previous chain entry.
* @param {String} id - Deployment id.
* @returns {Promise} - Returns Number.
*/
Chain.prototype.isActive = co(function* isActive(prev, deployment) {
var state;
if (!this.options.witness) {
if (prev.isHistorical())
return false;
}
state = yield this.getState(prev, deployment);
return state === constants.thresholdStates.ACTIVE;
});
/**
* Get chain entry state for a deployment (BIP9: versionbits).
* @example
* yield chain.getState(tip, deployments.segwit);
* @see https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki
* @param {ChainEntry} prev - Previous chain entry.
* @param {String} id - Deployment id.
* @returns {Promise} - Returns Number.
*/
Chain.prototype.getState = co(function* getState(prev, deployment) {
var period = this.network.minerWindow;
var threshold = this.network.activationThreshold;
var thresholdStates = constants.thresholdStates;
var bit = deployment.bit;
var compute = [];
var i, entry, count, state, cached;
var block, time, height;
if (!prev)
return thresholdStates.DEFINED;
if (((prev.height + 1) % period) !== 0) {
height = prev.height - ((prev.height + 1) % period);
prev = yield prev.getAncestor(height);
if (prev) {
assert(prev.height === height);
assert(((prev.height + 1) % period) === 0);
}
}
entry = prev;
state = thresholdStates.DEFINED;
while (entry) {
cached = this.db.stateCache.get(bit, entry);
if (cached !== -1) {
state = cached;
break;
}
time = yield entry.getMedianTimeAsync();
if (time < deployment.startTime) {
state = thresholdStates.DEFINED;
this.db.stateCache.set(bit, entry, state);
break;
}
compute.push(entry);
height = entry.height - period;
entry = yield entry.getAncestor(height);
}
while (compute.length) {
entry = compute.pop();
switch (state) {
case thresholdStates.DEFINED:
time = yield entry.getMedianTimeAsync();
if (time >= deployment.timeout) {
state = thresholdStates.FAILED;
break;
}
if (time >= deployment.startTime) {
state = thresholdStates.STARTED;
break;
}
break;
case thresholdStates.STARTED:
time = yield entry.getMedianTimeAsync();
if (time >= deployment.timeout) {
state = thresholdStates.FAILED;
break;
}
block = entry;
count = 0;
for (i = 0; i < period; i++) {
if (block.hasBit(bit))
count++;
if (count >= threshold) {
state = thresholdStates.LOCKED_IN;
break;
}
block = yield block.getPrevious();
assert(block);
}
break;
case thresholdStates.LOCKED_IN:
state = thresholdStates.ACTIVE;
break;
case thresholdStates.FAILED:
case thresholdStates.ACTIVE:
break;
default:
assert(false, 'Bad state.');
break;
}
this.db.stateCache.set(bit, entry, state);
}
return state;
});
/**
* Compute the version for a new block (BIP9: versionbits).
* @see https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki
* @param {ChainEntry} prev - Previous chain entry (usually the tip).
* @returns {Promise} - Returns Number.
*/
Chain.prototype.computeBlockVersion = co(function* computeBlockVersion(prev) {
var version = 0;
var i, deployment, state;
for (i = 0; i < this.network.deploys.length; i++) {
deployment = this.network.deploys[i];
state = yield this.getState(prev, deployment);
if (state === constants.thresholdStates.LOCKED_IN
|| state === constants.thresholdStates.STARTED) {
version |= 1 << deployment.bit;
}
}
version |= constants.versionbits.TOP_BITS;
version >>>= 0;
return version;
});
/**
* Get the current deployment state of the chain. Called on load.
* @private
* @returns {Promise} - Returns {@link DeploymentState}.
*/
Chain.prototype.getDeploymentState = co(function* getDeploymentState() {
var prev = yield this.tip.getPrevious();
if (!prev) {
assert(this.tip.isGenesis());
return this.state;
}
return yield this.getDeployments(this.tip.toHeaders(), prev);
});
/**
* Check transaction finality, taking into account MEDIAN_TIME_PAST
* if it is present in the lock flags.
* @param {ChainEntry} prev - Previous chain entry.
* @param {TX} tx
* @param {LockFlags} flags
* @returns {Promise} - Returns Boolean.
*/
Chain.prototype.verifyFinal = co(function* verifyFinal(prev, tx, flags) {
var height = prev.height + 1;
var ts;
// We can skip MTP if the locktime is height.
if (tx.locktime < constants.LOCKTIME_THRESHOLD)
return tx.isFinal(height, -1);
if (flags & constants.flags.MEDIAN_TIME_PAST) {
ts = yield prev.getMedianTimeAsync();
return tx.isFinal(height, ts);
}
return tx.isFinal(height, this.network.now());
});
/**
* Get the necessary minimum time and height sequence locks for a transaction.
* @param {ChainEntry} prev
* @param {TX} tx
* @param {CoinView} view
* @param {LockFlags} flags
* @returns {Promise}
* [Error, Number(minTime), Number(minHeight)].
*/
Chain.prototype.getLocks = co(function* getLocks(prev, tx, view, flags) {
var mask = constants.sequence.MASK;
var granularity = constants.sequence.GRANULARITY;
var disableFlag = constants.sequence.DISABLE_FLAG;
var typeFlag = constants.sequence.TYPE_FLAG;
var hasFlag = flags & constants.flags.VERIFY_SEQUENCE;
var nextHeight = this.height + 1;
var minHeight = -1;
var minTime = -1;
var coinHeight, coinTime;
var i, input, entry;
if (tx.isCoinbase() || tx.version < 2 || !hasFlag)
return new LockTimes(minHeight, minTime);
for (i = 0; i < tx.inputs.length; i++) {
input = tx.inputs[i];
if (input.sequence & disableFlag)
continue;
coinHeight = view.getHeight(input);
if (coinHeight === -1)
coinHeight = nextHeight;
if ((input.sequence & typeFlag) === 0) {
coinHeight += (input.sequence & mask) - 1;
minHeight = Math.max(minHeight, coinHeight);
continue;
}
entry = yield prev.getAncestor(Math.max(coinHeight - 1, 0));
assert(entry, 'Database is corrupt.');
coinTime = yield entry.getMedianTimeAsync();
coinTime += ((input.sequence & mask) << granularity) - 1;
minTime = Math.max(minTime, coinTime);
}
return new LockTimes(minHeight, minTime);
});
/**
* Verify sequence locks.
* @param {ChainEntry} prev
* @param {TX} tx
* @param {CoinView} view
* @param {LockFlags} flags
* @returns {Promise} - Returns Boolean.
*/
Chain.prototype.verifyLocks = co(function* verifyLocks(prev, tx, view, flags) {
var locks = yield this.getLocks(prev, tx, view, flags);
var medianTime;
if (locks.height >= prev.height + 1)
return false;
if (locks.time === -1)
return true;
medianTime = yield prev.getMedianTimeAsync();
if (locks.time >= medianTime)
return false;
return true;
});
Chain.prototype._bfsFromLatest = co(function* _bfsFromLatest() {
const latest = yield this.db.getTip()
const block = yield this.db.getBlock(latest.hash)
const coinbase = block.txs[0]
const start = coinbase.outputs[0]
const queue = [];
let begin = 0;
const seen = {};
const isSeen = (x, y) => seen[x] && seen[x][y];
const markSeen = (x, y) => {
if (!seen[x]) {
seen[x] = {};
}
seen[x][y] = true;
};
const firstTile = yield this.db.getTile(start.x, start.y);
queue.push(start);
while (begin < queue.length) {
const current = queue[begin++];
const random = Math.ceil(Math.random() * 4);
for (let i = 0; i < 4; i++) {
const j = (i + random) % 4;
const x = current.x + DX[j];
const y = current.y + DY[j];
if (isSeen(x,y)) {
continue;
}
markSeen(x,y);
const tile = yield this.db.getTile(x,y);
if (!tile) {
return { x, y }
} else {
queue.push({ x, y });
}
}
}
});
Chain.prototype._bfs = co(function* getAllTiles() {
const queue = [];
let begin = 0;
const seen = {};
const isSeen = (x, y) => seen[x] && seen[x][y];
const markSeen = (x, y) => {
if (!seen[x]) {
seen[x] = {};
}
seen[x][y] = true;
};
const available = [];
const firstTile = yield this.db.getTile(0, 0);
queue.push({ x: 0, y: 0, content: firstTile.content });
while (begin < queue.length) {
const current = queue[begin++];
for (let i = 0; i < 4; i++) {
const x = current.x + DX[i];
const y = current.y + DY[i];
if (isSeen(x,y)) {
continue;
}
markSeen(x,y);
const tile = yield this.db.getTile(x,y);
if (!tile) {
available.push({x,y});
} else {
queue.push({ x, y, content: tile.content });
}
}
}
return { tiles: queue, available };
})
Chain.prototype.getAllTiles = co(function* getAllTiles() {
const { tiles } = yield this._bfs();
return tiles;
});
Chain.prototype.getBoundaryTile = co(function* getBoundaryTile() {
// TODO: better way to explore where to mine by using a map of boundary tiles
// on a database
return this._bfsFromLatest()
});
/**
* Represents the deployment state of the chain.
* @constructor
* @property {VerifyFlags} flags
* @property {LockFlags} lockFlags
* @property {Boolean} bip34
*/
function DeploymentState() {
if (!(this instanceof DeploymentState))
return new DeploymentState();
this.flags = constants.flags.MANDATORY_VERIFY_FLAGS;
this.flags &= ~constants.flags.VERIFY_P2SH;
this.lockFlags = constants.flags.MANDATORY_LOCKTIME_FLAGS;
this.bip34 = false;
}
/**
* Test whether p2sh is active.
* @returns {Boolean}
*/
DeploymentState.prototype.hasP2SH = function hasP2SH() {
return (this.flags & constants.flags.VERIFY_P2SH) !== 0;
};
/**
* Test whether bip34 (coinbase height) is active.
* @returns {Boolean}
*/
DeploymentState.prototype.hasBIP34 = function hasBIP34() {
return this.bip34;
};
/**
* Test whether bip66 (VERIFY_DERSIG) is active.
* @returns {Boolean}
*/
DeploymentState.prototype.hasBIP66 = function hasBIP66() {
return (this.flags & constants.flags.VERIFY_DERSIG) !== 0;
};
/**
* Test whether cltv is active.
* @returns {Boolean}
*/
DeploymentState.prototype.hasCLTV = function hasCLTV() {
return (this.flags & constants.flags.VERIFY_CHECKLOCKTIMEVERIFY) !== 0;
};
/**
* Test whether median time past locktime is active.
* @returns {Boolean}
*/
DeploymentState.prototype.hasMTP = function hasMTP() {
return (this.lockFlags & constants.flags.MEDIAN_TIME_PAST) !== 0;
};
/**
* Test whether csv is active.
* @returns {Boolean}
*/
DeploymentState.prototype.hasCSV = function hasCSV() {
return (this.flags & constants.flags.VERIFY_CHECKSEQUENCEVERIFY) !== 0;
};
/**
* Test whether segwit is active.
* @returns {Boolean}
*/
DeploymentState.prototype.hasWitness = function hasWitness() {
return (this.flags & constants.flags.VERIFY_WITNESS) !== 0;
};
/**
* LockTimes
* @constructor
*/
function LockTimes(height, time) {
this.height = height;
this.time = time;
}
/**
* ContextResult
* @constructor
*/
function ContextResult(view, state) {
this.view = view;
this.state = state;
}
/*
* Expose
*/
module.exports = Chain;
| decentraland/bronzeage-node | lib/blockchain/chain.js | JavaScript | mit | 62,343 |
/*
File generated by NetTiers templates [www.nettiers.com]
Important: Do not modify this file. Edit the file ContactType.cs instead.
*/
#region Using Directives
using System;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Security;
using System.Data;
using System.ServiceModel;
using Nettiers.AdventureWorks.Entities;
using Nettiers.AdventureWorks.Entities.Validation;
//using Entities = Nettiers.AdventureWorks.Entities;
using Nettiers.AdventureWorks.Data;
using Nettiers.AdventureWorks.Data.Bases;
using Microsoft.Practices.EnterpriseLibrary.Logging;
#endregion
namespace Nettiers.AdventureWorks.Contracts.Services
{
///<summary>
/// An interface representation of the 'ContactType' table.
///</summary>
/// <remarks>
/// IMPORTANT!!! You should not modify this partial interface, modify the IContactType.cs file instead.
/// All custom implementations should be done in the <see cref="IContactType"/> class.
/// </remarks>
[ServiceContract]
public partial interface IContactTypeServiceBase
{
#region Data Access Methods
#region GetByForeignKey Methods
#endregion GetByForeignKey Methods
#region GetByIndexes
/// <summary>
/// Gets a row from the DataSource based on its primary key.
/// </summary>
/// <param name="key">The unique identifier of the row to retrieve.</param>
/// <returns>Returns an instance of the Entity class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
ContactType Get(ContactTypeKey key);
/// <summary>
/// method that Gets rows in a <see cref="TList{ContactType}" /> from the datasource based on the primary key AK_ContactType_Name index.
/// </summary>
/// <param name="_name">Contact type description.</param>
/// <returns>Returns an instance of the <see cref="ContactType"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
ContactType GetByName(System.String _name);
/// <summary>
/// Method that Gets rows in a <see cref="TList{ContactType}" /> from the datasource based on the primary key AK_ContactType_Name index.
/// </summary>
/// <param name="_name">Contact type description.</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Page length of records you would like to retrieve</param>
/// <param name="totalCount">out parameter, number of total rows in given query.</param>
/// <returns>Returns an instance of the <see cref="ContactType"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
ContactType GetByName(System.String _name, int start, int pageLength, out int totalCount);
/// <summary>
/// method that Gets rows in a <see cref="TList{ContactType}" /> from the datasource based on the primary key PK_ContactType_ContactTypeID index.
/// </summary>
/// <param name="_contactTypeId">Primary key for ContactType records.</param>
/// <returns>Returns an instance of the <see cref="ContactType"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
ContactType GetByContactTypeId(System.Int32 _contactTypeId);
/// <summary>
/// Method that Gets rows in a <see cref="TList{ContactType}" /> from the datasource based on the primary key PK_ContactType_ContactTypeID index.
/// </summary>
/// <param name="_contactTypeId">Primary key for ContactType records.</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Page length of records you would like to retrieve</param>
/// <param name="totalCount">out parameter, number of total rows in given query.</param>
/// <returns>Returns an instance of the <see cref="ContactType"/> class.</returns>
[DataObjectMethod(DataObjectMethodType.Select)]
ContactType GetByContactTypeId(System.Int32 _contactTypeId, int start, int pageLength, out int totalCount);
#endregion GetByIndexes
#region GetAll
/// <summary>
/// Get a complete collection of <see cref="ContactType" /> entities.
/// </summary>
/// <returns></returns>
TList<ContactType> GetAll();
/// <summary>
/// Get a set portion of a complete list of <see cref="ContactType" /> entities
/// </summary>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="totalCount">out parameter, number of total rows in given query.</param>
/// <returns>a <see cref="TList{ContactType}"/> </returns>
TList<ContactType> GetAll(int start, int pageLength, out int totalCount);
#endregion GetAll
#region GetPaged
/// <summary>
/// Gets a page of <see cref="TList{ContactType}" /> rows from the DataSource.
/// </summary>
/// <param name="totalCount">Out Parameter, Number of rows in the DataSource.</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of <c>ContactType</c> objects.</returns>
TList<ContactType> GetPaged(out int totalCount);
/// <summary>
/// Gets a page of <see cref="TList{ContactType}" /> rows from the DataSource.
/// </summary>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="totalCount">Number of rows in the DataSource.</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of <c>ContactType</c> objects.</returns>
TList<ContactType> GetPaged(int start, int pageLength, out int totalCount);
/// <summary>
/// Gets a page of entity rows with a <see cref="TList{ContactType}" /> from the DataSource with a where clause and order by clause.
/// </summary>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC).</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="totalCount">Out Parameter, Number of rows in the DataSource.</param>
/// <remarks></remarks>
/// <returns>Returns a typed collection of <c>ContactType</c> objects.</returns>
TList<ContactType> GetPaged(string whereClause,string orderBy, int start, int pageLength, out int totalCount);
/// <summary>
/// Gets the number of rows in the DataSource that match the specified whereClause.
/// This method is only provided as a workaround for the ObjectDataSource's need to
/// execute another method to discover the total count instead of using another param, like our out param.
/// This method should be avoided if using the ObjectDataSource or another method.
/// </summary>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="totalCount">Number of rows in the DataSource.</param>
/// <returns>Returns the number of rows.</returns>
int GetTotalItems(string whereClause, out int totalCount);
#endregion GetPaged
#region Find
#region Parsed Find Methods
/// <summary>
/// Attempts to do a parameterized version of a simple whereclause.
/// Returns rows meeting the whereClause condition from the DataSource.
/// </summary>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <remarks>Does NOT Support Advanced Operations such as SubSelects. See GetPaged for that functionality.</remarks>
/// <returns>Returns a typed collection of Entity objects.</returns>
TList<ContactType> Find(string whereClause) ;
/// <summary>
/// Returns rows meeting the whereClause condition from the DataSource.
/// </summary>
/// <param name="whereClause">Specifies the condition for the rows returned by a query (Name='John Doe', Name='John Doe' AND Id='1', Name='John Doe' OR Id='1').</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="totalCount">out parameter to get total records for query</param>
/// <remarks>Does NOT Support Advanced Operations such as SubSelects. See GetPaged for that functionality.</remarks>
/// <returns>Returns a typed collection TList{ContactType} of <c>ContactType</c> objects.</returns>
TList<ContactType> Find(string whereClause, int start, int pageLength, out int totalCount);
#endregion Parsed Find Methods
#region Parameterized Find Methods
/// <summary>
/// Returns rows from the DataSource that meet the parameter conditions.
/// </summary>
/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
/// <returns>Returns a typed collection of <c>ContactType</c> objects.</returns>
TList<ContactType> Find(IFilterParameterCollection parameters);
/// <summary>
/// Returns rows from the DataSource that meet the parameter conditions.
/// </summary>
/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
/// <returns>Returns a typed collection of <c>ContactType</c> objects.</returns>
TList<ContactType> Find(IFilterParameterCollection parameters, string orderBy);
/// <summary>
/// Returns rows from the DataSource that meet the parameter conditions.
/// </summary>
/// <param name="parameters">A collection of <see cref="SqlFilterParameter"/> objects.</param>
/// <param name="orderBy">Specifies the sort criteria for the rows in the DataSource (Name ASC; BirthDay DESC, Name ASC);</param>
/// <param name="start">Row number at which to start reading.</param>
/// <param name="pageLength">Number of rows to return.</param>
/// <param name="count">out. The number of rows that match this query.</param>
/// <returns>Returns a typed collection of <c>ContactType</c> objects.</returns>
TList<ContactType> Find(IFilterParameterCollection parameters, string orderBy, int start, int pageLength, out int count);
#endregion Parameterized Find Methods
#endregion
#region Insert
#region Insert Entity
/// <summary>
/// public virtualmethod that Inserts a ContactType object into the datasource using a transaction.
/// </summary>
/// <param name="entity">ContactType object to Insert.</param>
/// <remarks>After Inserting into the datasource, the ContactType object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns bool that the operation is successful.</returns>
/// <example>
/// The following code shows the usage of the Insert Method with an already open transaction.
/// <code>
/// ContactType entity = new ContactType();
/// entity.StringProperty = "foo";
/// entity.IntProperty = 12;
/// entity.ChildObjectSource.StringProperty = "bar";
/// TransactionManager tm = null;
/// try
/// {
/// tm = ConnectionContext.CreateTransaction();
/// //Insert Child entity, Then Parent Entity
/// ChildObjectType.Insert(entity.ChildObjectSource);
/// ContactType.Insert(entity);
/// }
/// catch (Exception e)
/// {
/// if (tm != null && tm.IsOpen) tm.Rollback();
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// </code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Insert)]
bool Insert(ContactType entity);
#endregion Insert Entity
#region Insert Collection
/// <summary>
/// method that Inserts rows in <see cref="TList{ContactType}" /> to the datasource.
/// </summary>
/// <param name="entityCollection"><c>ContactType</c> objects in a <see cref="TList{ContactType}" /> object to Insert.</param>
/// <remarks>
/// This function will only Insert entity objects marked as dirty
/// and have an identity field equal to zero.
/// Upon Inserting the objects, each dirty object will have the public
/// method <c>Object.AcceptChanges()</c> called to make it clean.
/// After Inserting into the datasource, the <c>ContactType</c> objects will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
///</remarks>
/// <returns>Returns the number of successful Insert.</returns>
/// <example>
/// The following code shows the usage of the Insert Method with a collection of ContactType.
/// <code><![CDATA[
/// TList<ContactType> list = new TList<ContactType>();
/// ContactType entity = new ContactType();
/// entity.StringProperty = "foo";
/// ContactType entity2 = new ContactType();
/// entity.StringProperty = "bar";
/// list.Add(entity);
/// list.Add(entity2);
/// ContactTypeService.Insert(list);
/// }
/// catch (Exception e)
/// {
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// ]]></code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Insert)]
TList<ContactType> Insert(TList<ContactType> entityCollection);
#endregion Insert Collection
#endregion Insert
#region Update
#region Update Entity
/// <summary>
/// public virtualmethod that Updates a ContactType object into the datasource using a transaction.
/// </summary>
/// <param name="entity">ContactType object to Update.</param>
/// <remarks>After Updateing into the datasource, the ContactType object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns bool that the operation is successful.</returns>
/// <example>
/// The following code shows the usage of the Update Method with an already open transaction.
/// <code>
/// ContactType entity = ContactTypeService.GetByPrimaryKeyColumn(1234);
/// entity.StringProperty = "foo";
/// entity.IntProperty = 12;
/// entity.ChildObjectSource.StringProperty = "bar";
/// TransactionManager tm = null;
/// try
/// {
/// tm = ConnectionContext.CreateTransaction();
/// //Update Child entity, Then Parent Entity
/// ChildObjectType.Update(entity.ChildObjectSource);
/// ContactType.Update(entity);
/// }
/// catch (Exception e)
/// {
/// if (tm != null && tm.IsOpen) tm.Rollback();
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// </code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Update)]
bool Update(ContactType entity);
#endregion Update Entity
#region Update Collection
/// <summary>
/// method that Updates rows in <see cref="TList{ContactType}" /> to the datasource.
/// </summary>
/// <param name="entityCollection"><c>ContactType</c> objects in a <see cref="TList{ContactType}" /> object to Update.</param>
/// <remarks>
/// This function will only Update entity objects marked as dirty
/// and have an identity field equal to zero.
/// Upon Updateing the objects, each dirty object will have the public
/// method <c>Object.AcceptChanges()</c> called to make it clean.
/// After Updateing into the datasource, the <c>ContactType</c> objects will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
///</remarks>
/// <returns>Returns the number of successful Update.</returns>
/// <example>
/// The following code shows the usage of the Update Method with a collection of ContactType.
/// <code><![CDATA[
/// TList<ContactType> list = new TList<ContactType>();
/// ContactType entity = new ContactType();
/// entity.StringProperty = "foo";
/// ContactType entity2 = new ContactType();
/// entity.StringProperty = "bar";
/// list.Add(entity);
/// list.Add(entity2);
/// ContactTypeService.Update(list);
/// }
/// catch (Exception e)
/// {
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// ]]></code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Update)]
TList<ContactType> Update(TList<ContactType> entityCollection);
#endregion Update Collection
#endregion Update
#region Save
#region Save Entity
/// <summary>
/// public virtualmethod that Saves a ContactType object into the datasource using a transaction.
/// </summary>
/// <param name="entity">ContactType object to Save.</param>
/// <remarks>After Saveing into the datasource, the ContactType object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns bool that the operation is successful.</returns>
/// <example>
/// The following code shows the usage of the Save Method with an already open transaction.
/// <code>
/// ContactType entity = ContactTypeService.GetByPrimaryKeyColumn(1234);
/// entity.StringProperty = "foo";
/// entity.IntProperty = 12;
/// entity.ChildObjectSource.StringProperty = "bar";
/// TransactionManager tm = null;
/// try
/// {
/// tm = ConnectionContext.CreateTransaction();
/// //Save Child entity, Then Parent Entity
/// ChildObjectType.Save(entity.ChildObjectSource);
/// ContactType.Save(entity);
/// }
/// catch (Exception e)
/// {
/// if (tm != null && tm.IsOpen) tm.Rollback();
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// </code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Update)]
ContactType Save(ContactType entity);
#endregion Save Entity
#region Save Collection
/// <summary>
/// method that Saves rows in <see cref="TList{ContactType}" /> to the datasource.
/// </summary>
/// <param name="entityCollection"><c>ContactType</c> objects in a <see cref="TList{ContactType}" /> object to Save.</param>
/// <remarks>
/// This function will only Save entity objects marked as dirty
/// and have an identity field equal to zero.
/// Upon Saveing the objects, each dirty object will have the public
/// method <c>Object.AcceptChanges()</c> called to make it clean.
/// After Saveing into the datasource, the <c>ContactType</c> objects will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
///</remarks>
/// <returns>Returns the number of successful Save.</returns>
/// <example>
/// The following code shows the usage of the Save Method with a collection of ContactType.
/// <code><![CDATA[
/// TList<ContactType> list = new TList<ContactType>();
/// ContactType entity = new ContactType();
/// entity.StringProperty = "foo";
/// ContactType entity2 = new ContactType();
/// entity.StringProperty = "bar";
/// list.Add(entity);
/// list.Add(entity2);
/// ContactTypeService.Save(list);
/// }
/// catch (Exception e)
/// {
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// ]]></code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Update)]
TList<ContactType> Save(TList<ContactType> entityCollection);
#endregion Save Collection
#endregion Save
#region Delete
#region Delete Entity
/// <summary>
/// public virtualmethod that Deletes a ContactType object into the datasource using a transaction.
/// </summary>
/// <param name="entity">ContactType object to Delete.</param>
/// <remarks>After Deleteing into the datasource, the ContactType object will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
/// </remarks>
/// <returns>Returns bool that the operation is successful.</returns>
/// <example>
/// The following code shows the usage of the Delete Method with an already open transaction.
/// <code>
/// ContactType entity = ContactTypeService.GetByPrimaryKeyColumn(1234);
/// entity.StringProperty = "foo";
/// entity.IntProperty = 12;
/// entity.ChildObjectSource.StringProperty = "bar";
/// TransactionManager tm = null;
/// try
/// {
/// tm = ConnectionContext.CreateTransaction();
/// //Delete Child entity, Then Parent Entity
/// ChildObjectType.Delete(entity.ChildObjectSource);
/// ContactType.Delete(entity);
/// }
/// catch (Exception e)
/// {
/// if (tm != null && tm.IsOpen) tm.Rollback();
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// </code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Delete)]
bool Delete(ContactType entity);
#endregion Delete Entity
#region Delete Collection
/// <summary>
/// method that Deletes rows in <see cref="TList{ContactType}" /> to the datasource.
/// </summary>
/// <param name="entityCollection"><c>ContactType</c> objects in a <see cref="TList{ContactType}" /> object to Delete.</param>
/// <remarks>
/// This function will only Delete entity objects marked as dirty
/// and have an identity field equal to zero.
/// Upon Deleteing the objects, each dirty object will have the public
/// method <c>Object.AcceptChanges()</c> called to make it clean.
/// After Deleteing into the datasource, the <c>ContactType</c> objects will be updated
/// to refelect any changes made by the datasource. (ie: identity or computed columns)
///</remarks>
/// <returns>Returns the number of successful Delete.</returns>
/// <example>
/// The following code shows the usage of the Delete Method with a collection of ContactType.
/// <code><![CDATA[
/// TList<ContactType> list = new TList<ContactType>();
/// ContactType entity = new ContactType();
/// entity.StringProperty = "foo";
/// ContactType entity2 = new ContactType();
/// entity.StringProperty = "bar";
/// list.Add(entity);
/// list.Add(entity2);
/// ContactTypeService.Delete(list);
/// }
/// catch (Exception e)
/// {
/// if (DomainUtil.HandleException(e, name)) throw;
/// }
/// ]]></code>
/// </example>
[DataObjectMethod(DataObjectMethodType.Delete)]
TList<ContactType> Delete(TList<ContactType> entityCollection);
#endregion Delete Collection
#endregion Delete
#region Delete
/// <summary>
/// Deletes a row from the DataSource.
/// </summary>
/// <param name="key">The unique identifier of the row to delete.</param>
/// <returns>Returns true if operation suceeded.</returns>
bool Delete(ContactTypeKey key);
/// <summary>
/// Deletes a row from the DataSource based on the PK'S System.Int32 _contactTypeId
/// </summary>
/// <param name="_contactTypeId">ContactType pk id.</param>
/// <remarks>Deletes based on primary key(s).</remarks>
/// <returns>Returns true if operation suceeded.</returns>
[DataObjectMethod(DataObjectMethodType.Delete)]
bool Delete(System.Int32 _contactTypeId);
#endregion
#region GetBy m:m Aggregate Relationships
#endregion N2N Relationships
#region Custom Methods
#endregion Custom Methods
#endregion Data Access Methods
}//End Class
} // end namespace
| netTiers/netTiers | Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Contracts/Services/IContactTypeServiceBase.generated.cs | C# | mit | 24,769 |
/*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* 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.
*/
package com.iluwatar.pageobject;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.gargoylesoftware.htmlunit.WebClient;
import com.iluwatar.pageobject.pages.AlbumListPage;
import com.iluwatar.pageobject.pages.AlbumPage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test Album Page Operations
*/
public class AlbumPageTest {
private AlbumPage albumPage = new AlbumPage(new WebClient());
@BeforeEach
public void setUp() {
albumPage.navigateToPage();
}
@Test
public void testSaveAlbum() {
var albumPageAfterChanges = albumPage
.changeAlbumTitle("25")
.changeArtist("Adele Laurie Blue Adkins")
.changeAlbumYear(2015)
.changeAlbumRating("B")
.changeNumberOfSongs(20)
.saveChanges();
assertTrue(albumPageAfterChanges.isAt());
}
@Test
public void testCancelChanges() {
var albumListPage = albumPage.cancelChanges();
albumListPage.navigateToPage();
assertTrue(albumListPage.isAt());
}
}
| zik43/java-design-patterns | page-object/src/test/java/com/iluwatar/pageobject/AlbumPageTest.java | Java | mit | 2,185 |
<?php
declare(strict_types=1);
namespace AcMailer;
use Laminas\Mime\Part;
use Laminas\ServiceManager\Factory\InvokableFactory;
return [
'acmailer_options' => [
'emails' => [],
'mail_services' => [
'default' => [],
],
'attachment_parsers' => [
'factories' => [
Attachment\Parser\ArrayAttachmentParser::class => InvokableFactory::class,
Attachment\Parser\FilePathAttachmentParser::class => InvokableFactory::class,
Attachment\Parser\MimePartAttachmentParser::class => InvokableFactory::class,
Attachment\Parser\ResourceAttachmentParser::class => InvokableFactory::class,
],
'aliases' => [
'array' => Attachment\Parser\ArrayAttachmentParser::class,
'string' => Attachment\Parser\FilePathAttachmentParser::class,
Part::class => Attachment\Parser\MimePartAttachmentParser::class,
'resource' => Attachment\Parser\ResourceAttachmentParser::class,
],
],
],
'service_manager' => [
'factories' => [
Attachment\AttachmentParserManager::class => Attachment\AttachmentParserManagerFactory::class,
Model\EmailBuilder::class => Model\EmailBuilderFactory::class,
'acmailer.mailservice.default' => Service\Factory\MailServiceAbstractFactory::class,
View\MailViewRendererInterface::class => View\MailViewRendererFactory::class,
Service\MailServiceBuilder::class => Service\Factory\MailServiceBuilderFactory::class,
],
'abstract_factories' => [
Service\Factory\MailServiceAbstractFactory::class,
],
'aliases' => [
Service\MailServiceInterface::class => 'acmailer.mailservice.default',
Service\MailService::class => 'acmailer.mailservice.default',
'mailservice' => 'acmailer.mailservice.default',
'mailviewrenderer' => 'ViewRenderer',
],
],
];
| acelaya/ZF-AcMailer | config/module.config.php | PHP | mit | 2,048 |
require 'oysters'
require 'erb'
Oysters.with_configuration do
namespace :unified do
namespace :initd do
# This tasks install/uninstall initd scripts for:
# - KEWatcher from resque-sliders gem
# - Resque Scheduler
# - Unicorn
[:kewatcher, :resque_scheduler, :unicorn].each do |program|
namespace "#{program}" do
#Run this task as a sudo user!
desc "Install #{program}"
task :install, roles: :app do
tmp_config_path = "/tmp/#{program}_initd_script.sh"
# Remove old tmp config if present
sudo "rm -f #{tmp_config_path}", pty: true, shell: :bash
config = File.read(File.expand_path("../scripts/#{program}_initd_script.sh", __FILE__))
put config, tmp_config_path, shell: :bash
sudo "cp #{tmp_config_path} /etc/init.d/#{application}_#{program}", pty: true, shell: :bash
sudo "chmod +x /etc/init.d/#{application}_#{program}", pty: true, shell: :bash
sudo "chkconfig --add #{application}_#{program}", pty: true, shell: :bash
run "rm -f #{tmp_config_path}", shell: :bash
end
#Run this task as a sudo user!
desc "Remove #{program} init.d script"
task :uninstall, roles: :app do
sudo "chkconfig --del #{application}_#{program}", pty: true, shell: :bash
sudo "rm -f /etc/init.d/#{application}_#{program}", pty: true, shell: :bash
end
end
end
# This tasks install/uninstall sysconfig that contains configuration information for:
# - KEWatcher from resque-sliders gem
# - Resque Scheduler
# - Unicorn
namespace :sysconfig do
#Run this task as a sudo user!
desc 'Generate sysconfig used by init.d scripts and put it into /etc/sysconfig'
task :install, roles: :app do
tmp_config_path = "/tmp/deployed_application_sysconfig.sh"
# Remove old tmp config if present
sudo "rm -f #{tmp_config_path}", pty: true, shell: :bash
location = File.expand_path('../templates/app_sysconfig.sh.erb', __FILE__)
config = ERB.new(File.read(location))
put config.result(binding), tmp_config_path, shell: :bash
sudo "cp #{tmp_config_path} /etc/sysconfig/deployed_application", pty: true, shell: :bash
run "rm -f #{tmp_config_path}", shell: :bash
end
#Run this task as a sudo user!
desc 'Remove sysconfig'
task :uninstall, roles: :app do
sudo "rm -f /etc/sysconfig/deployed_application", pty: true, shell: :bash
end
end
#Run this task as a sudo user!
desc "Install all initd scripts(KEWatcher, Unicorn, Scheduler)"
task :install_all, roles: :app do
unified.initd.sysconfig.install
unified.initd.kewatcher.install
unified.initd.resque_scheduler.install
unified.initd.unicorn.install
end
#Run this task as a sudo user!
desc "Uninstall all initd scripts(KEWatcher, Unicorn, Scheduler)"
task :uninstall_all, roles: :app do
unified.initd.sysconfig.uninstall
unified.initd.kewatcher.uninstall
unified.initd.resque_scheduler.uninstall
unified.initd.unicorn.uninstall
end
end
end
end
| Ser1aL/oysters | lib/oysters/unified/initd.rb | Ruby | mit | 3,326 |
using System;
using BEPUphysics.BroadPhaseEntries;
using BEPUphysics.CollisionRuleManagement;
namespace BEPUphysics.BroadPhaseSystems
{
/// <summary>
/// A pair of overlapping BroadPhaseEntries.
/// </summary>
public struct BroadPhaseOverlap : IEquatable<BroadPhaseOverlap>
{
internal BroadPhaseEntry entryA;
/// <summary>
/// First entry in the pair.
/// </summary>
public BroadPhaseEntry EntryA
{
get { return entryA; }
}
internal BroadPhaseEntry entryB;
/// <summary>
/// Second entry in the pair.
/// </summary>
public BroadPhaseEntry EntryB
{
get { return entryB; }
}
internal CollisionRule collisionRule;
/// <summary>
/// Constructs an overlap.
/// </summary>
/// <param name="entryA">First entry in the pair.</param>
/// <param name="entryB">Second entry in the pair.</param>
public BroadPhaseOverlap(BroadPhaseEntry entryA, BroadPhaseEntry entryB)
{
this.entryA = entryA;
this.entryB = entryB;
collisionRule = CollisionRules.DefaultCollisionRule;
}
/// <summary>
/// Constructs an overlap.
/// </summary>
/// <param name="entryA">First entry in the pair.</param>
/// <param name="entryB">Second entry in the pair.</param>
/// <param name="collisionRule">Collision rule calculated for the pair.</param>
public BroadPhaseOverlap(BroadPhaseEntry entryA, BroadPhaseEntry entryB, CollisionRule collisionRule)
{
this.entryA = entryA;
this.entryB = entryB;
this.collisionRule = collisionRule;
}
/// <summary>
/// Gets the collision rule calculated for the pair.
/// </summary>
public CollisionRule CollisionRule
{
get { return collisionRule; }
}
/// <summary>
/// Gets the hash code of the object.
/// </summary>
/// <returns>Hash code of the object.</returns>
public override int GetHashCode()
{
//TODO: Use old prime-based system?
return (int)((entryA.hashCode + entryB.hashCode) * 0xd8163841);
}
#region IEquatable<BroadPhaseOverlap> Members
/// <summary>
/// Compares the overlaps for equality based on the involved entries.
/// </summary>
/// <param name="other">Overlap to compare.</param>
/// <returns>Whether or not the overlaps were equal.</returns>
public bool Equals(BroadPhaseOverlap other)
{
return (other.entryA == entryA && other.entryB == entryB) || (other.entryA == entryB && other.entryB == entryA);
}
#endregion
public override string ToString()
{
return "{" + entryA + ", " + entryB + "}";
}
}
}
| mayermatt/coms-437-trashdroids | Trashdroids/BEPUphysics/BroadPhaseSystems/BroadPhaseOverlap.cs | C# | mit | 2,977 |
# Rotational Cipher
Create an implementation of the rotational cipher, also sometimes called the Caesar cipher.
The Caesar cipher is a simple shift cipher that relies on
transposing all the letters in the alphabet using an integer key
between `0` and `26`. Using a key of `0` or `26` will always yield
the same output due to modular arithmetic. The letter is shifted
for as many values as the value of the key.
The general notation for rotational ciphers is `ROT + <key>`.
The most commonly used rotational cipher is `ROT13`.
A `ROT13` on the Latin alphabet would be as follows:
```text
Plain: abcdefghijklmnopqrstuvwxyz
Cipher: nopqrstuvwxyzabcdefghijklm
```
It is stronger than the Atbash cipher because it has 27 possible keys, and 25 usable keys.
Ciphertext is written out in the same formatting as the input including spaces and punctuation.
## Examples
- ROT5 `omg` gives `trl`
- ROT0 `c` gives `c`
- ROT26 `Cool` gives `Cool`
- ROT13 `The quick brown fox jumps over the lazy dog.` gives `Gur dhvpx oebja sbk whzcf bire gur ynml qbt.`
- ROT13 `Gur dhvpx oebja sbk whzcf bire gur ynml qbt.` gives `The quick brown fox jumps over the lazy dog.`
## Getting Started
For installation and learning resources, refer to the
[exercism help page](http://exercism.io/languages/haskell).
## Running the tests
To run the test suite, execute the following command:
```bash
stack test
```
#### If you get an error message like this...
```
No .cabal file found in directory
```
You are probably running an old stack version and need
to upgrade it.
#### Otherwise, if you get an error message like this...
```
No compiler found, expected minor version match with...
Try running "stack setup" to install the correct GHC...
```
Just do as it says and it will download and install
the correct compiler version:
```bash
stack setup
```
## Running *GHCi*
If you want to play with your solution in GHCi, just run the command:
```bash
stack ghci
```
## Feedback, Issues, Pull Requests
The [exercism/haskell](https://github.com/exercism/haskell) repository on
GitHub is the home for all of the Haskell exercises.
If you have feedback about an exercise, or want to help implementing a new
one, head over there and create an issue. We'll do our best to help you!
## Source
Wikipedia [https://en.wikipedia.org/wiki/Caesar_cipher](https://en.wikipedia.org/wiki/Caesar_cipher)
## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
| c19/Exercism-Haskell | rotational-cipher/README.md | Markdown | mit | 2,525 |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-3 10h-3v3c0 .55-.45 1-1 1s-1-.45-1-1v-3H8c-.55 0-1-.45-1-1s.45-1 1-1h3V8c0-.55.45-1 1-1s1 .45 1 1v3h3c.55 0 1 .45 1 1s-.45 1-1 1z" />
, 'AddBoxRounded');
| callemall/material-ui | packages/material-ui-icons/src/AddBoxRounded.js | JavaScript | mit | 359 |
package mockapi
//go:generate go get github.com/golang/mock/mockgen
//go:generate sh -c "mockgen -package=mockapi github.com/citwild/wfe/api AccountsServer > accounts.go"
| wide-field-ethnography/wfe | api/mockapi/gen.go | GO | mit | 172 |
//%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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include "UNIX_IPConnectivitySubnet.h"
#if defined(PEGASUS_OS_HPUX)
# include "UNIX_IPConnectivitySubnet_HPUX.hxx"
# include "UNIX_IPConnectivitySubnet_HPUX.hpp"
#elif defined(PEGASUS_OS_LINUX)
# include "UNIX_IPConnectivitySubnet_LINUX.hxx"
# include "UNIX_IPConnectivitySubnet_LINUX.hpp"
#elif defined(PEGASUS_OS_DARWIN)
# include "UNIX_IPConnectivitySubnet_DARWIN.hxx"
# include "UNIX_IPConnectivitySubnet_DARWIN.hpp"
#elif defined(PEGASUS_OS_AIX)
# include "UNIX_IPConnectivitySubnet_AIX.hxx"
# include "UNIX_IPConnectivitySubnet_AIX.hpp"
#elif defined(PEGASUS_OS_FREEBSD)
# include "UNIX_IPConnectivitySubnet_FREEBSD.hxx"
# include "UNIX_IPConnectivitySubnet_FREEBSD.hpp"
#elif defined(PEGASUS_OS_SOLARIS)
# include "UNIX_IPConnectivitySubnet_SOLARIS.hxx"
# include "UNIX_IPConnectivitySubnet_SOLARIS.hpp"
#elif defined(PEGASUS_OS_ZOS)
# include "UNIX_IPConnectivitySubnet_ZOS.hxx"
# include "UNIX_IPConnectivitySubnet_ZOS.hpp"
#elif defined(PEGASUS_OS_VMS)
# include "UNIX_IPConnectivitySubnet_VMS.hxx"
# include "UNIX_IPConnectivitySubnet_VMS.hpp"
#elif defined(PEGASUS_OS_TRU64)
# include "UNIX_IPConnectivitySubnet_TRU64.hxx"
# include "UNIX_IPConnectivitySubnet_TRU64.hpp"
#else
# include "UNIX_IPConnectivitySubnet_STUB.hxx"
# include "UNIX_IPConnectivitySubnet_STUB.hpp"
#endif
Boolean UNIX_IPConnectivitySubnet::validateKey(CIMKeyBinding &kb) const
{
/* Keys */
//InstanceID
CIMName name = kb.getName();
if (name.equal(PROPERTY_INSTANCE_ID)
)
return true;
return false;
}
void UNIX_IPConnectivitySubnet::setScope(CIMName scope)
{
currentScope = scope;
}
| brunolauze/openpegasus-providers-old | src/Providers/UNIXProviders/IPConnectivitySubnet/UNIX_IPConnectivitySubnet.cpp | C++ | mit | 3,277 |
#region Imports...
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Nettiers.AdventureWorks.Web.UI;
#endregion
public partial class ProductPhotoEdit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FormUtil.RedirectAfterInsertUpdate(FormView1, "ProductPhotoEdit.aspx?{0}", ProductPhotoDataSource);
FormUtil.RedirectAfterAddNew(FormView1, "ProductPhotoEdit.aspx");
FormUtil.RedirectAfterCancel(FormView1, "ProductPhoto.aspx");
FormUtil.SetDefaultMode(FormView1, "ProductPhotoId");
}
}
| netTiers/netTiers | Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Website/Admin/ProductPhotoEdit.aspx.cs | C# | mit | 779 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.storage.file.datalake.implementation.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.DateTimeRfc1123;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
/**
* Defines headers for Create operation.
*/
@Fluent
public final class PathCreateHeaders {
/*
* A UTC date/time value generated by the service that indicates the time
* at which the response was initiated.
*/
@JsonProperty(value = "Date")
private DateTimeRfc1123 dateProperty;
/*
* An HTTP entity tag associated with the file or directory.
*/
@JsonProperty(value = "ETag")
private String eTag;
/*
* The data and time the file or directory was last modified. Write
* operations on the file or directory update the last modified time.
*/
@JsonProperty(value = "Last-Modified")
private DateTimeRfc1123 lastModified;
/*
* A server-generated UUID recorded in the analytics logs for
* troubleshooting and correlation.
*/
@JsonProperty(value = "x-ms-request-id")
private String requestId;
/*
* The version of the REST protocol used to process the request.
*/
@JsonProperty(value = "x-ms-version")
private String version;
/*
* When renaming a directory, the number of paths that are renamed with
* each invocation is limited. If the number of paths to be renamed
* exceeds this limit, a continuation token is returned in this response
* header. When a continuation token is returned in the response, it must
* be specified in a subsequent invocation of the rename operation to
* continue renaming the directory.
*/
@JsonProperty(value = "x-ms-continuation")
private String continuation;
/*
* The size of the resource in bytes.
*/
@JsonProperty(value = "Content-Length")
private Long contentLength;
/*
* The errorCode property.
*/
@JsonProperty(value = "x-ms-error-code")
private String errorCode;
/**
* Get the dateProperty property: A UTC date/time value generated by the
* service that indicates the time at which the response was initiated.
*
* @return the dateProperty value.
*/
public OffsetDateTime getDateProperty() {
if (this.dateProperty == null) {
return null;
}
return this.dateProperty.getDateTime();
}
/**
* Set the dateProperty property: A UTC date/time value generated by the
* service that indicates the time at which the response was initiated.
*
* @param dateProperty the dateProperty value to set.
* @return the PathCreateHeaders object itself.
*/
public PathCreateHeaders setDateProperty(OffsetDateTime dateProperty) {
if (dateProperty == null) {
this.dateProperty = null;
} else {
this.dateProperty = new DateTimeRfc1123(dateProperty);
}
return this;
}
/**
* Get the eTag property: An HTTP entity tag associated with the file or
* directory.
*
* @return the eTag value.
*/
public String getETag() {
return this.eTag;
}
/**
* Set the eTag property: An HTTP entity tag associated with the file or
* directory.
*
* @param eTag the eTag value to set.
* @return the PathCreateHeaders object itself.
*/
public PathCreateHeaders setETag(String eTag) {
this.eTag = eTag;
return this;
}
/**
* Get the lastModified property: The data and time the file or directory
* was last modified. Write operations on the file or directory update the
* last modified time.
*
* @return the lastModified value.
*/
public OffsetDateTime getLastModified() {
if (this.lastModified == null) {
return null;
}
return this.lastModified.getDateTime();
}
/**
* Set the lastModified property: The data and time the file or directory
* was last modified. Write operations on the file or directory update the
* last modified time.
*
* @param lastModified the lastModified value to set.
* @return the PathCreateHeaders object itself.
*/
public PathCreateHeaders setLastModified(OffsetDateTime lastModified) {
if (lastModified == null) {
this.lastModified = null;
} else {
this.lastModified = new DateTimeRfc1123(lastModified);
}
return this;
}
/**
* Get the requestId property: A server-generated UUID recorded in the
* analytics logs for troubleshooting and correlation.
*
* @return the requestId value.
*/
public String getRequestId() {
return this.requestId;
}
/**
* Set the requestId property: A server-generated UUID recorded in the
* analytics logs for troubleshooting and correlation.
*
* @param requestId the requestId value to set.
* @return the PathCreateHeaders object itself.
*/
public PathCreateHeaders setRequestId(String requestId) {
this.requestId = requestId;
return this;
}
/**
* Get the version property: The version of the REST protocol used to
* process the request.
*
* @return the version value.
*/
public String getVersion() {
return this.version;
}
/**
* Set the version property: The version of the REST protocol used to
* process the request.
*
* @param version the version value to set.
* @return the PathCreateHeaders object itself.
*/
public PathCreateHeaders setVersion(String version) {
this.version = version;
return this;
}
/**
* Get the continuation property: When renaming a directory, the number of
* paths that are renamed with each invocation is limited. If the number
* of paths to be renamed exceeds this limit, a continuation token is
* returned in this response header. When a continuation token is returned
* in the response, it must be specified in a subsequent invocation of the
* rename operation to continue renaming the directory.
*
* @return the continuation value.
*/
public String getContinuation() {
return this.continuation;
}
/**
* Set the continuation property: When renaming a directory, the number of
* paths that are renamed with each invocation is limited. If the number
* of paths to be renamed exceeds this limit, a continuation token is
* returned in this response header. When a continuation token is returned
* in the response, it must be specified in a subsequent invocation of the
* rename operation to continue renaming the directory.
*
* @param continuation the continuation value to set.
* @return the PathCreateHeaders object itself.
*/
public PathCreateHeaders setContinuation(String continuation) {
this.continuation = continuation;
return this;
}
/**
* Get the contentLength property: The size of the resource in bytes.
*
* @return the contentLength value.
*/
public Long getContentLength() {
return this.contentLength;
}
/**
* Set the contentLength property: The size of the resource in bytes.
*
* @param contentLength the contentLength value to set.
* @return the PathCreateHeaders object itself.
*/
public PathCreateHeaders setContentLength(Long contentLength) {
this.contentLength = contentLength;
return this;
}
/**
* Get the errorCode property: The errorCode property.
*
* @return the errorCode value.
*/
public String getErrorCode() {
return this.errorCode;
}
/**
* Set the errorCode property: The errorCode property.
*
* @param errorCode the errorCode value to set.
* @return the PathCreateHeaders object itself.
*/
public PathCreateHeaders setErrorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
}
| navalev/azure-sdk-for-java | sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/implementation/models/PathCreateHeaders.java | Java | mit | 8,314 |
/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIiwic291cmNlcyI6WyJsb2dpbi5zY3NzIl0sInNvdXJjZXNDb250ZW50IjpbIiJdLCJmaWxlIjoibG9naW4uY3NzIiwic291cmNlUm9vdCI6Ii9zb3VyY2UvIn0= */
| ethan1341/heroku-league | css/login.css | CSS | mit | 227 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const common_1 = require("../common");
const ENDPT = 'achievementicons';
/**
* Achievement icons resource
*/
class AchievementIconsResource {
/**
* Construct the achievement icons resource
* @param context The context to make requests as
*/
constructor(context) {
this.context = context;
this.common = new common_1.Common(context, ENDPT);
}
/**
* Get a list of all preloaded achievement icons
* @param {object} userOpts option overrides for this request
* @returns {Promise<object[]>} A promise that resolves to an array of achievement icon identifiers
*/
getAllPreloaded(userOpts) {
return this.context.http.makeRequest({
method: 'GET',
url: `/v2/apps/${this.context.applicationId}/${ENDPT}/preloaded`
}, userOpts);
}
/**
* Get a list of all uploaded achievement icons
* @param userOpts option overrides for this request
* @returns A promise that resolves to an array of achievement icon identifiers
*/
getAll(userOpts) {
return this.context.http.makeRequest({
method: 'GET',
url: `/v2/apps/${this.context.applicationId}/${ENDPT}`
}, userOpts);
}
/**
* Delete previously uploaded achievement icon by filename.
* @param iconFileName icon file name (generated by BadgeUp when the icon was uploaded, not the original file name)
* @param userOpts option overrides for this request
* @returns A promise that resolves to the deleted achievement icon
*/
remove(iconFileName, userOpts) {
return this.common.remove(iconFileName, userOpts);
}
}
exports.AchievementIconsResource = AchievementIconsResource;
//# sourceMappingURL=index.js.map | BadgeUp/badgeup-browser-client | dist/src/achievementIcons/index.js | JavaScript | mit | 1,841 |
//: operators/Bool.java
package operators; /* Added by Eclipse.py */
// Relational and logical operators.
import java.util.*;
import static net.mindview.util.Print.*;
public class Bool {
public static void main(String[] args) {
Random rand = new Random(47);
int i = rand.nextInt(100);
int j = rand.nextInt(100);
print("i = " + i);
print("j = " + j);
print("i > j is " + (i > j));
print("i < j is " + (i < j));
print("i >= j is " + (i >= j));
print("i <= j is " + (i <= j));
print("i == j is " + (i == j));
print("i != j is " + (i != j));
// Treating an int as a boolean is not legal Java:
//! print("i && j is " + (i && j));
//! print("i || j is " + (i || j));
//! print("!i is " + !i);
print("(i < 10) && (j < 10) is "
+ ((i < 10) && (j < 10)) );
print("(i < 10) || (j < 10) is "
+ ((i < 10) || (j < 10)) );
}
} /* Output:
i = 58
j = 55
i > j is true
i < j is false
i >= j is true
i <= j is false
i == j is false
i != j is true
(i < 10) && (j < 10) is false
(i < 10) || (j < 10) is false
*///:~
| quchunguang/test | testjava/TIJ4-code/operators/Bool.java | Java | mit | 1,110 |
//: concurrency/MultiLock.java
package concurrency; /* Added by Eclipse.py */
// One thread can reacquire the same lock.
import static net.mindview.util.Print.*;
public class MultiLock {
public synchronized void f1(int count) {
if(count-- > 0) {
print("f1() calling f2() with count " + count);
f2(count);
}
}
public synchronized void f2(int count) {
if(count-- > 0) {
print("f2() calling f1() with count " + count);
f1(count);
}
}
public static void main(String[] args) throws Exception {
final MultiLock multiLock = new MultiLock();
new Thread() {
public void run() {
multiLock.f1(10);
}
}.start();
}
} /* Output:
f1() calling f2() with count 9
f2() calling f1() with count 8
f1() calling f2() with count 7
f2() calling f1() with count 6
f1() calling f2() with count 5
f2() calling f1() with count 4
f1() calling f2() with count 3
f2() calling f1() with count 2
f1() calling f2() with count 1
f2() calling f1() with count 0
*///:~
| quchunguang/test | testjava/TIJ4-code/concurrency/MultiLock.java | Java | mit | 1,054 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>StatisticsTableViewC Class Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset='utf-8'>
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Class/StatisticsTableViewC" class="dashAnchor"></a>
<a title="StatisticsTableViewC Class Reference"></a>
<header>
<div class="content-wrapper">
<p><a href="../index.html"> Docs</a> (1% documented)</p>
</div>
</header>
<div class="content-wrapper">
<p id="breadcrumbs">
<a href="../index.html"> Reference</a>
<img id="carat" src="../img/carat.png" />
StatisticsTableViewC Class Reference
</p>
</div>
<div class="content-wrapper">
<nav class="sidebar">
<ul class="nav-groups">
<li class="nav-group-name">
<a href="../Classes.html">Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Classes/AppDelegate.html">AppDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Classes/BFFetchedResultsController.html">BFFetchedResultsController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/BaseTableViewC.html">BaseTableViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/BlocMember.html">BlocMember</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CurrentBlocCellController.html">CurrentBlocCellController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CurrentBlocTableDataSource.html">CurrentBlocTableDataSource</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CurrentBlocTableViewC.html">CurrentBlocTableViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CurrentBlocTableViewCell.html">CurrentBlocTableViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DashboardController.html">DashboardController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DashboardViewC.html">DashboardViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DismissSideMenuView.html">DismissSideMenuView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/FriendCellController.html">FriendCellController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/FriendTableController.html">FriendTableController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/FriendTableViewC.html">FriendTableViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/FriendTableViewCell.html">FriendTableViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/GameKitManager.html">GameKitManager</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MainViewC.html">MainViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MapController.html">MapController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MapViewC.html">MapViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MultipeerManager.html">MultipeerManager</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Owner.html">Owner</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Run.html">Run</a>
</li>
<li class="nav-group-task">
<a href="../Classes/RunHistoryCellController.html">RunHistoryCellController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/RunHistoryTableController.html">RunHistoryTableController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/RunHistoryTableViewC.html">RunHistoryTableViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/RunHistoryTableViewCell.html">RunHistoryTableViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/RunPoint.html">RunPoint</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SettingsController.html">SettingsController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SettingsTableViewC.html">SettingsTableViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SettingsTableViewC/Loc.html">– Loc</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SideMenuTableController.html">SideMenuTableController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SideMenuTableDelegate.html">SideMenuTableDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SideMenuTableDelegate/Cell.html">– Cell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SideMenuTableViewC.html">SideMenuTableViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/StatisticsController.html">StatisticsController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/StatisticsTableViewC.html">StatisticsTableViewC</a>
</li>
<li class="nav-group-task">
<a href="../Classes/TopMenuViewC.html">TopMenuViewC</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Protocols/CurrentBlocCellControllerProtocol.html">CurrentBlocCellControllerProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/DashboardControllerProtocol.html">DashboardControllerProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/FriendCellControllerProtocol.html">FriendCellControllerProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/GameKitManagerDelegate.html">GameKitManagerDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/GameViewPresenterDelegate.html">GameViewPresenterDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/LoadRunDelegate.html">LoadRunDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/MapControllerProtocol.html">MapControllerProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/MapNotificationDelegate.html">MapNotificationDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/MultipeerManagerDelegate.html">MultipeerManagerDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/MultipeerViewHandlerProtocol.html">MultipeerViewHandlerProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/RequestMainDataDelegate.html">RequestMainDataDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/RunHistoryCellControllerProtocol.html">RunHistoryCellControllerProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ScoreReporterDelegate.html">ScoreReporterDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/SegueCoordinationDelegate.html">SegueCoordinationDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/SelectRowAndLoadRunProtocol.html">SelectRowAndLoadRunProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/SettingsControllerProtocol.html">SettingsControllerProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/SideMenuTableControllerProtocol.html">SideMenuTableControllerProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/StatisticsControllerProtocol.html">StatisticsControllerProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/TopMenuDelegate.html">TopMenuDelegate</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Structs.html">Structs</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Structs/BFFormatter.html">BFFormatter</a>
</li>
<li class="nav-group-task">
<a href="../Structs/BFUnitConverter.html">BFUnitConverter</a>
</li>
<li class="nav-group-task">
<a href="../Structs/BFUserDefaults.html">BFUserDefaults</a>
</li>
<li class="nav-group-task">
<a href="../Structs/DashboardModel.html">DashboardModel</a>
</li>
<li class="nav-group-task">
<a href="../Structs/HealthKitManager.html">HealthKitManager</a>
</li>
<li class="nav-group-task">
<a href="../Structs/MapRunModel.html">MapRunModel</a>
</li>
<li class="nav-group-task">
<a href="../Structs/MultipeerModel.html">MultipeerModel</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Path.html">Path</a>
</li>
<li class="nav-group-task">
<a href="../Structs/RandomNameGenerator.html">RandomNameGenerator</a>
</li>
<li class="nav-group-task">
<a href="../Structs/RunStatisticsModel.html">RunStatisticsModel</a>
</li>
<li class="nav-group-task">
<a href="../Structs/SegueIdentifier.html">SegueIdentifier</a>
</li>
<li class="nav-group-task">
<a href="../Structs/SettingsModel.html">SettingsModel</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section>
<section class="section">
<h1>StatisticsTableViewC</h1>
<p>Undocumented</p>
</section>
<section class="section task-group-section">
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:vC7BlocFit20StatisticsTableViewC14bestScoreLabelXwGSQCSo7UILabel_"></a>
<a name="//apple_ref/swift/Property/bestScoreLabel" class="dashAnchor"></a>
<a class="token" href="#/s:vC7BlocFit20StatisticsTableViewC14bestScoreLabelXwGSQCSo7UILabel_">bestScoreLabel</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vC7BlocFit20StatisticsTableViewC13bestRateLabelXwGSQCSo7UILabel_"></a>
<a name="//apple_ref/swift/Property/bestRateLabel" class="dashAnchor"></a>
<a class="token" href="#/s:vC7BlocFit20StatisticsTableViewC13bestRateLabelXwGSQCSo7UILabel_">bestRateLabel</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vC7BlocFit20StatisticsTableViewC17bestDistanceLabelXwGSQCSo7UILabel_"></a>
<a name="//apple_ref/swift/Property/bestDistanceLabel" class="dashAnchor"></a>
<a class="token" href="#/s:vC7BlocFit20StatisticsTableViewC17bestDistanceLabelXwGSQCSo7UILabel_">bestDistanceLabel</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vC7BlocFit20StatisticsTableViewC13bestTimeLabelXwGSQCSo7UILabel_"></a>
<a name="//apple_ref/swift/Property/bestTimeLabel" class="dashAnchor"></a>
<a class="token" href="#/s:vC7BlocFit20StatisticsTableViewC13bestTimeLabelXwGSQCSo7UILabel_">bestTimeLabel</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vC7BlocFit20StatisticsTableViewC17averageScoreLabelXwGSQCSo7UILabel_"></a>
<a name="//apple_ref/swift/Property/averageScoreLabel" class="dashAnchor"></a>
<a class="token" href="#/s:vC7BlocFit20StatisticsTableViewC17averageScoreLabelXwGSQCSo7UILabel_">averageScoreLabel</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vC7BlocFit20StatisticsTableViewC16averageRateLabelXwGSQCSo7UILabel_"></a>
<a name="//apple_ref/swift/Property/averageRateLabel" class="dashAnchor"></a>
<a class="token" href="#/s:vC7BlocFit20StatisticsTableViewC16averageRateLabelXwGSQCSo7UILabel_">averageRateLabel</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vC7BlocFit20StatisticsTableViewC20averageDistanceLabelXwGSQCSo7UILabel_"></a>
<a name="//apple_ref/swift/Property/averageDistanceLabel" class="dashAnchor"></a>
<a class="token" href="#/s:vC7BlocFit20StatisticsTableViewC20averageDistanceLabelXwGSQCSo7UILabel_">averageDistanceLabel</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vC7BlocFit20StatisticsTableViewC16averageTimeLabelXwGSQCSo7UILabel_"></a>
<a name="//apple_ref/swift/Property/averageTimeLabel" class="dashAnchor"></a>
<a class="token" href="#/s:vC7BlocFit20StatisticsTableViewC16averageTimeLabelXwGSQCSo7UILabel_">averageTimeLabel</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:vC7BlocFit20StatisticsTableViewC10controllerGSQPS_28StatisticsControllerProtocol__"></a>
<a name="//apple_ref/swift/Property/controller" class="dashAnchor"></a>
<a class="token" href="#/s:vC7BlocFit20StatisticsTableViewC10controllerGSQPS_28StatisticsControllerProtocol__">controller</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:FC7BlocFit20StatisticsTableViewC14viewWillAppearFSbT_"></a>
<a name="//apple_ref/swift/Method/viewWillAppear(_:)" class="dashAnchor"></a>
<a class="token" href="#/s:FC7BlocFit20StatisticsTableViewC14viewWillAppearFSbT_">viewWillAppear(_:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:FC7BlocFit20StatisticsTableViewC22viewWillLayoutSubviewsFT_T_"></a>
<a name="//apple_ref/swift/Method/viewWillLayoutSubviews()" class="dashAnchor"></a>
<a class="token" href="#/s:FC7BlocFit20StatisticsTableViewC22viewWillLayoutSubviewsFT_T_">viewWillLayoutSubviews()</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:FC7BlocFit20StatisticsTableViewC23didReceiveMemoryWarningFT_T_"></a>
<a name="//apple_ref/swift/Method/didReceiveMemoryWarning()" class="dashAnchor"></a>
<a class="token" href="#/s:FC7BlocFit20StatisticsTableViewC23didReceiveMemoryWarningFT_T_">didReceiveMemoryWarning()</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
</section>
</div>
</li>
</ul>
</div>
</section>
</section>
<section id="footer">
<p>© 2017 <a class="link" href="" target="_blank" rel="external"></a>. All rights reserved. (Last updated: 2017-01-17)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.7.3</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</article>
</div>
</body>
</div>
</html>
| ColinConduff/BlocFit | docs/docsets/.docset/Contents/Resources/Documents/Classes/StatisticsTableViewC.html | HTML | mit | 22,967 |
"use strict";
let XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
let xhr = new XMLHttpRequest();
// 8346870 - latest v1.0.1
// let url = "https://api.github.com/repos/ZencashOfficial/arizen/releases/8252416";
// 8252416 - v1.0.0
let url = "https://api.github.com/repos/ZencashOfficial/arizen/releases/8252416";
xhr.open("GET", url, true);
xhr.onload = function () {
let resp = JSON.parse(xhr.responseText);
if (xhr.readyState === 4 && (xhr.status === "200")) {
console.log(resp);
for (let i = 0; i < resp["assets"].length; i++) {
let obj = resp["assets"][i];
console.log("Downloaded: " + obj["download_count"] + ", " + obj["name"]);
}
} else {
console.error(resp);
}
};
xhr.send(null);
| woky/arizen | tools/get_statistics.js | JavaScript | mit | 774 |
# == Schema Information
#
# Table name: armors
#
# id :integer not null, primary key
# name :string
# type :string
# desc :string
# acBonus :integer
# maxDex :integer
# checkPenalty :integer
# spellFailure :integer
# speed :string
# weight :integer
# specialProperties :string
# created_at :datetime
# updated_at :datetime
#
require 'test_helper'
class ArmorTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| PDaily/RubyRPG | test/models/armor_test.rb | Ruby | mit | 589 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `Select3F64` type in crate `lapack`.">
<meta name="keywords" content="rust, rustlang, rust-lang, Select3F64">
<title>lapack::Select3F64 - Rust</title>
<link rel="stylesheet" type="text/css" href="../main.css">
</head>
<body class="rustdoc">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='index.html'>lapack</a></p><script>window.sidebarCurrent = {name: 'Select3F64', ty: 'type', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content type">
<h1 class='fqn'><span class='in-band'><a href='index.html'>lapack</a>::<wbr><a class='type' href=''>Select3F64</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a id='src-21' class='srclink' href='../src/lapack/lib.rs.html#40' title='goto source code'>[src]</a></span></h1>
<pre class='rust typedef'>type Select3F64 = <a class='enum' href='https://doc.rust-lang.org/nightly/core/option/enum.Option.html' title='core::option::Option'>Option</a>< extern "C" fn(<a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.pointer.html'>*const <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a></a>, <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.pointer.html'>*const <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a></a>, <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.pointer.html'>*const <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a></a>) -> <a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.i32.html'>i32</a>>;</pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../";
window.currentCrate = "lapack";
window.playgroundUrl = "";
</script>
<script src="../jquery.js"></script>
<script src="../main.js"></script>
<script async src="../search-index.js"></script>
</body>
</html> | ssgrn/Rust-Matrix-Computations | target/doc/lapack/type.Select3F64.html | HTML | mit | 4,569 |
package cucumber.eclipse.launching;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
public class CucumberFeaureLaunchUtils {
private CucumberFeaureLaunchUtils() {
// NO ENTRY NO INSTANCES
}
protected static IProject getProject() {
IWorkbenchPage page = JDIDebugUIPlugin.getActivePage();
if (page != null) {
IEditorPart part = page.getActiveEditor();
if (part != null) {
IFileEditorInput input = (IFileEditorInput) part.getEditorInput();
IFile file = input.getFile();
IProject activeProject = file.getProject();
return activeProject;
}
}
return null;
}
protected static String getFeaturePath() {
IWorkbenchPage page = JDIDebugUIPlugin.getActivePage();
if (page != null) {
IEditorPart part = page.getActiveEditor();
if (part != null) {
IFileEditorInput input = (IFileEditorInput) part.getEditorInput();
return input.getFile().getLocation().toString();
}
}
return null;
}
public static void updateFromConfig(ILaunchConfiguration config, String attrib, Text text) {
String s = "";
try {
s = config.getAttribute(attrib, "");
} catch (CoreException e) {
e.printStackTrace();
}
text.setText(s);
}
public static boolean updateFromConfig(ILaunchConfiguration config, String attrib) {
boolean b = false;
try {
b = config.getAttribute(attrib, b);
} catch (CoreException e) {
e.printStackTrace();
}
return b;
}
private TextSelection getTextSelection() {
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
ISelectionService service = window.getSelectionService();
if (service instanceof TextSelection) return (TextSelection) service.getSelection();
else return null;
}
}
| scandinave/cucumber-eclipse | cucumber.eclipse.editor/src/main/java/cucumber/eclipse/launching/CucumberFeaureLaunchUtils.java | Java | mit | 2,221 |
<html dir="LTR">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
<title>IErrorHandler Interface</title>
<xml>
</xml>
<link rel="stylesheet" type="text/css" href="MSDN.css" />
</head>
<body id="bodyID" class="dtBODY">
<div id="nsbanner">
<div id="bannerrow1">
<table class="bannerparthead" cellspacing="0">
<tr id="hdr">
<td class="runninghead">Apache log4net SDK Documentation - Microsoft .NET Framework 4.0</td>
<td class="product">
</td>
</tr>
</table>
</div>
<div id="TitleRow">
<h1 class="dtH1">IErrorHandler Interface</h1>
</div>
</div>
<div id="nstext">
<p> Appenders may delegate their error handling to an <b>IErrorHandler</b>. </p>
<p>For a list of all members of this type, see <a href="log4net.Core.IErrorHandlerMembers.html">IErrorHandler Members</a>.</p>
<p>
</p>
<div class="syntax">
<span class="lang">[Visual Basic]</span>
<br />Public Interface IErrorHandler</div>
<div class="syntax">
<span class="lang">[C#]</span>
<div>public interface IErrorHandler</div>
</div>
<h4 class="dtH4">Types that implement IErrorHandler</h4>
<div class="tablediv">
<table class="dtTABLE" cellspacing="0">
<tr valign="top">
<th width="50%">Type</th>
<th width="50%">Description</th>
</tr>
<tr valign="top">
<td width="50%">
<a href="log4net.Util.OnlyOnceErrorHandler.html">OnlyOnceErrorHandler</a>
</td>
<td width="50%"> Implements log4net's default error handling policy which consists of emitting a message for the first error in an appender and ignoring all subsequent errors. </td>
</tr>
</table>
</div>
<h4 class="dtH4">Remarks</h4>
<p> Error handling is a particularly tedious to get right because by definition errors are hard to predict and to reproduce. </p>
<h4 class="dtH4">Requirements</h4><p><b>Namespace: </b><a href="log4net.Core.html">log4net.Core</a></p><p><b>Assembly: </b>log4net (in log4net.dll)
</p><h4 class="dtH4">See Also</h4><p><a href="log4net.Core.IErrorHandlerMembers.html">IErrorHandler Members</a> | <a href="log4net.Core.html">log4net.Core Namespace</a></p><object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="IErrorHandler interface, about IErrorHandler interface"></param></object><hr /><div id="footer"><a href='http://logging.apache.org/log4net/'>Copyright 2004-2013 The Apache Software Foundation.</a><br></br>Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.</div></div>
</body>
</html> | YOTOV-LIMITED/pokerleaguemanager | lib/Log4net 1.2.13/doc/release/sdk/log4net.Core.IErrorHandler.html | HTML | mit | 2,994 |
file(REMOVE_RECURSE
"CMakeFiles/mapped_matrix_4.dir/mapped_matrix.cpp.o"
"mapped_matrix_4.pdb"
"mapped_matrix_4"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/mapped_matrix_4.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
| dybiszb/MeanCurvatureLibrary | code/external/eigen/build/test/CMakeFiles/mapped_matrix_4.dir/cmake_clean.cmake | CMake | mit | 283 |
import { Component, ViewChild } from '@angular/core';
import { jqxGridComponent } from '../../../../../jqwidgets-ts/angular_jqxgrid'
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myGrid') myGrid: jqxGridComponent;
source: any =
{
localdata: this.generateData(),
datatype: 'array'
}
dataAdapter: any = new jqx.dataAdapter(this.source);
columns: any[] =
[
{ text: 'First Name', datafield: 'firstname', width: 200 },
{ text: 'Last Name', datafield: 'lastname', width: 200 },
{ text: 'Title', datafield: 'title', width: 180 },
{ text: 'City', datafield: 'city', width: 100 },
{ text: 'Country', datafield: 'country' }
];
rowdetailstemplate: any =
{
rowdetails: '<div style="margin: 10px;"><ul style="margin-left: 30px;"><li class="title"></li><li>Notes</li></ul><div class="information"></div><div class="notes"></div></div>',
rowdetailsheight: 200
};
initrowdetails = (index: any, parentElement: any, gridElement: any, datarecord: any): void => {
let tabsdiv = parentElement.children[0];
let information = tabsdiv.children[1];
let notes = tabsdiv.children[2];
let title = tabsdiv.children[0].children[0];
if (tabsdiv != null) {
title.innerHTML = datarecord.firstname;
let container = document.createElement('div');
container.style.margin = '5px';
information.appendChild(container);
let photocolumn = document.createElement('div');
let leftcolumn = document.createElement('div');
let rightcolumn = document.createElement('div');
photocolumn.style.cssText = 'float: left; width: 15%';
leftcolumn.style.cssText = 'float: left; width: 45%';
rightcolumn.style.cssText = 'float: left; width: 40%';
container.appendChild(photocolumn);
container.appendChild(leftcolumn);
container.appendChild(rightcolumn);
let image = document.createElement('div');
image.style.marginTop = '10px';
let photo = document.createElement('div');
photo.style.margin = '10px';
photo.className = 'jqx-rc-all';
photo.innerHTML = '<b>Photo:</b>';
let img = document.createElement('img');
img.height = 60;
img.style.marginLeft = '10px';
img.src = '../images/' + datarecord.firstname.toLowerCase() + '.png';
image.appendChild(photo);
image.appendChild(img);
photocolumn.appendChild(image);
let firstname = '<div style="margin: 10px;"><b>First Name:</b> ' + datarecord.firstname + '</div>';
let lastname = '<div style="margin: 10px;"><b>Last Name:</b> ' + datarecord.lastname + '</div>';
title = '<div style="margin: 10px;"><b>Title:</b> ' + datarecord.title + '</div>';
let address = '<div style="margin: 10px;"><b>Address:</b> ' + datarecord.address + '</div>';
leftcolumn.insertAdjacentHTML('beforeend', firstname);
leftcolumn.insertAdjacentHTML('beforeend', lastname);
leftcolumn.insertAdjacentHTML('beforeend', title);
leftcolumn.insertAdjacentHTML('beforeend', address);
let postalcode = '<div style="margin: 10px;"><b>Postal Code:</b> ' + datarecord.postalcode + '</div>';
let city = '<div style="margin: 10px;"><b>City:</b> ' + datarecord.city + '</div>';
let phone = '<div style="margin: 10px;"><b>Phone:</b> ' + datarecord.homephone + '</div>';
let hiredate = '<div style="margin: 10px;"><b>Hire Date:</b> ' + datarecord.hiredate + '</div>';
rightcolumn.insertAdjacentHTML('beforeend', postalcode);
rightcolumn.insertAdjacentHTML('beforeend', city);
rightcolumn.insertAdjacentHTML('beforeend', phone);
rightcolumn.insertAdjacentHTML('beforeend', hiredate);
let notesContainer = document.createElement('div');
notesContainer.style.cssText = 'white-space: normal; margin: 5px;';
notesContainer.innerHTML = '<span>' + datarecord.notes + '</span>';
notes.appendChild(notesContainer);
tabsdiv.className = 'angularTabs';
jqwidgets.createInstance('.angularTabs', 'jqxTabs', { width: 820, height: 170 })
}
}
ready = (): void => {
this.myGrid.showrowdetails(0);
this.myGrid.showrowdetails(1);
}
generateData(): any[] {
let data = new Array();
let firstNames = ['Nancy', 'Andrew', 'Janet', 'Margaret', 'Steven', 'Michael', 'Robert', 'Laura', 'Anne'];
let lastNames = ['Davolio', 'Fuller', 'Leverling', 'Peacock', 'Buchanan', 'Suyama', 'King', 'Callahan', 'Dodsworth'];
let titles = ['Sales Representative', 'Vice President, Sales', 'Sales Representative', 'Sales Representative', 'Sales Manager', 'Sales Representative', 'Sales Representative', 'Inside Sales Coordinator', 'Sales Representative'];
let titleofcourtesy = ['Ms.', 'Dr.', 'Ms.', 'Mrs.', 'Mr.', 'Mr.', 'Mr.', 'Ms.', 'Ms.'];
let birthdate = ['08-Dec-48', '19-Feb-52', '30-Aug-63', '19-Sep-37', '04-Mar-55', '02-Jul-63', '29-May-60', '09-Jan-58', '27-Jan-66'];
let hiredate = ['01-May-92', '14-Aug-92', '01-Apr-92', '03-May-93', '17-Oct-93', '17-Oct-93', '02-Jan-94', '05-Mar-94', '15-Nov-94'];
let address = ['507 - 20th Ave. E. Apt. 2A', '908 W. Capital Way', '722 Moss Bay Blvd.', '4110 Old Redmond Rd.', '14 Garrett Hill', 'Coventry House', 'Miner Rd.', 'Edgeham Hollow', 'Winchester Way', '4726 - 11th Ave. N.E.', '7 Houndstooth Rd.'];
let city = ['Seattle', 'Tacoma', 'Kirkland', 'Redmond', 'London', 'London', 'London', 'Seattle', 'London'];
let postalcode = ['98122', '98401', '98033', '98052', 'SW1 8JR', 'EC2 7JR', 'RG1 9SP', '98105', 'WG2 7LT'];
let country = ['USA', 'USA', 'USA', 'USA', 'UK', 'UK', 'UK', 'USA', 'UK'];
let homephone = ['(206) 555-9857', '(206) 555-9482', '(206) 555-3412', '(206) 555-8122', '(71) 555-4848', '(71) 555-7773', '(71) 555-5598', '(206) 555-1189', '(71) 555-4444'];
let notes = ['Education includes a BA in psychology from Colorado State University in 1970. She also completed `The Art of the Cold Call.` Nancy is a member of Toastmasters International.',
'Andrew received his BTS commercial in 1974 and a Ph.D. in international marketing from the University of Dallas in 1981. He is fluent in French and Italian and reads German. He joined the company as a sales representative, was promoted to sales manager in January 1992 and to vice president of sales in March 1993. Andrew is a member of the Sales Management Roundtable, the Seattle Chamber of Commerce, and the Pacific Rim Importers Association.',
'Janet has a BS degree in chemistry from Boston College (1984). She has also completed a certificate program in food retailing management. Janet was hired as a sales associate in 1991 and promoted to sales representative in February 1992.',
'Margaret holds a BA in English literature from Concordia College (1958) and an MA from the American Institute of Culinary Arts (1966). She was assigned to the London office temporarily from July through November 1992.',
'Steven Buchanan graduated from St. Andrews University, Scotland, with a BSC degree in 1976. Upon joining the company as a sales representative in 1992, he spent 6 months in an orientation program at the Seattle office and then returned to his permanent post in London. He was promoted to sales manager in March 1993. Mr. Buchanan has completed the courses `Successful Telemarketing` and `International Sales Management.` He is fluent in French.',
'Michael is a graduate of Sussex University (MA, economics, 1983) and the University of California at Los Angeles (MBA, marketing, 1986). He has also taken the courses `Multi-Cultural Selling` and `Time Management for the Sales Professional.` He is fluent in Japanese and can read and write French, Portuguese, and Spanish.',
'Robert King served in the Peace Corps and traveled extensively before completing his degree in English at the University of Michigan in 1992, the year he joined the company. After completing a course entitled `Selling in Europe,` he was transferred to the London office in March 1993.',
'Laura received a BA in psychology from the University of Washington. She has also completed a course in business French. She reads and writes French.',
'Anne has a BA degree in English from St. Lawrence College. She is fluent in French and German.'];
let k = 0;
for (let i = 0; i < firstNames.length; i++) {
let datarecord = {};
datarecord['firstname'] = firstNames[k];
datarecord['lastname'] = lastNames[k];
datarecord['title'] = titles[k];
datarecord['titleofcourtesy'] = titleofcourtesy[k];
datarecord['birthdate'] = birthdate[k];
datarecord['hiredate'] = hiredate[k];
datarecord['address'] = address[k];
datarecord['city'] = city[k];
datarecord['postalcode'] = postalcode[k];
datarecord['country'] = country[k];
datarecord['homephone'] = homephone[k];
datarecord['notes'] = notes[k];
data[i] = datarecord;
k++;
}
return data;
}
} | juannelisalde/holter | assets/jqwidgets/demos/angular/app/grid/rowdetails/app.component.ts | TypeScript | mit | 9,653 |
package provider
////// SET UP API ACCESS:
//
// 1) In the Google Developer Console navigate to:
// Permissions > Service accounts
//
// 2) Create or use an existing Service Account
//
// 3) For your Service Account, create and save a key as "~/.gce/quilt.json"
//
// 4) In the Google Developer Console navigate to:
// Permissions > Permissions
//
// 5) If the Service Account is not already, assign it the "Editor" role.
// You select the account by email.
import (
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"time"
"github.com/NetSys/quilt/constants"
"github.com/NetSys/quilt/db"
"github.com/NetSys/quilt/stitch"
log "github.com/Sirupsen/logrus"
"github.com/satori/go.uuid"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
compute "google.golang.org/api/compute/v1"
)
const computeBaseURL string = "https://www.googleapis.com/compute/v1/projects"
const (
// These are the various types of Operations that the GCE API returns
local = iota
global
)
var supportedZones = []string{"us-central1-a", "us-east1-b", "europe-west1-b"}
var gAuthClient *http.Client // the oAuth client
var gceService *compute.Service // gce service
type gceCluster struct {
projID string // gce project ID
imgURL string // gce url to the VM image
baseURL string // gce project specific url prefix
ipv4Range string // ipv4 range of the internal network
intFW string // gce internal firewall name
extFW string // gce external firewall name
ns string // cluster namespace
id int // the id of the cluster, used externally
}
// Create a GCE cluster.
//
// Clusters are differentiated (namespace) by setting the description and
// filtering off of that.
//
// XXX: A lot of the fields are hardcoded.
func (clst *gceCluster) Connect(namespace string) error {
if err := gceInit(); err != nil {
log.WithError(err).Debug("failed to start up gce")
return err
}
clst.projID = "declarative-infrastructure"
clst.ns = namespace
clst.imgURL = fmt.Sprintf(
"%s/%s",
computeBaseURL,
"ubuntu-os-cloud/global/images/ubuntu-1510-wily-v20160310")
clst.baseURL = fmt.Sprintf("%s/%s", computeBaseURL, clst.projID)
clst.ipv4Range = "192.168.0.0/16"
clst.intFW = fmt.Sprintf("%s-internal", clst.ns)
clst.extFW = fmt.Sprintf("%s-external", clst.ns)
if err := clst.netInit(); err != nil {
log.WithError(err).Debug("failed to start up gce network")
return err
}
if err := clst.fwInit(); err != nil {
log.WithError(err).Debug("failed to start up gce firewalls")
return err
}
return nil
}
// Get a list of machines from the cluster
//
// XXX: This doesn't use the instance group listing functionality because
// listing that way doesn't get you information about the instances
func (clst *gceCluster) List() ([]Machine, error) {
var mList []Machine
for _, zone := range supportedZones {
list, err := gceService.Instances.List(clst.projID, zone).
Filter(fmt.Sprintf("description eq %s", clst.ns)).Do()
if err != nil {
return nil, err
}
for _, item := range list.Items {
// XXX: This make some iffy assumptions about NetworkInterfaces
machineSplitURL := strings.Split(item.MachineType, "/")
mtype := machineSplitURL[len(machineSplitURL)-1]
mList = append(mList, Machine{
ID: item.Name,
PublicIP: item.NetworkInterfaces[0].
AccessConfigs[0].NatIP,
PrivateIP: item.NetworkInterfaces[0].NetworkIP,
Size: mtype,
Region: zone,
Provider: db.Google,
})
}
}
return mList, nil
}
// Boots instances, it is a blocking call.
//
// XXX: currently ignores cloudConfig
// XXX: should probably have a better clean up routine if an error is encountered
func (clst *gceCluster) Boot(bootSet []Machine) error {
var names []string
for _, m := range bootSet {
name := "quilt-" + uuid.NewV4().String()
_, err := clst.instanceNew(name, m.Size, m.Region,
cloudConfigUbuntu(m.SSHKeys, "wily"))
if err != nil {
log.WithFields(log.Fields{
"error": err,
"id": m.ID,
}).Error("Failed to start instance.")
continue
}
names = append(names, name)
}
if err := clst.wait(names, true); err != nil {
return err
}
return nil
}
// Deletes the instances, it is a blocking call.
//
// If an error occurs while deleting, it will finish the ones that have
// successfully started before returning.
//
// XXX: should probably have a better clean up routine if an error is encountered
func (clst *gceCluster) Stop(machines []Machine) error {
var names []string
for _, m := range machines {
if _, err := clst.instanceDel(m.ID, m.Region); err != nil {
log.WithFields(log.Fields{
"error": err,
"id": m.ID,
}).Error("Failed to delete instance.")
continue
}
names = append(names, m.ID)
}
if err := clst.wait(names, false); err != nil {
return err
}
return nil
}
func (clst *gceCluster) ChooseSize(ram stitch.Range, cpu stitch.Range,
maxPrice float64) string {
return pickBestSize(constants.GoogleDescriptions, ram, cpu, maxPrice)
}
// Get() and operationWait() don't always present the same results, so
// Boot() and Stop() must have a special wait to stay in sync with Get().
func (clst *gceCluster) wait(names []string, live bool) error {
if len(names) == 0 {
return nil
}
after := time.After(3 * time.Minute)
tick := time.NewTicker(3 * time.Second)
defer tick.Stop()
for range tick.C {
select {
case <-after:
return errors.New("wait(): timeout")
default:
}
for len(names) > 0 {
name := names[0]
instances, err := clst.List()
if err != nil {
return err
}
exists := false
for _, ist := range instances {
if name == ist.ID {
exists = true
}
}
if live == exists {
names = append(names[:0], names[1:]...)
}
}
if len(names) == 0 {
return nil
}
}
return nil
}
// Blocking wait with a hardcoded timeout.
//
// Waits on operations, the type of which is indicated by 'domain'. All
// operations must be of the same 'domain'
//
// XXX: maybe not hardcode timeout, and retry interval
func (clst *gceCluster) operationWait(ops []*compute.Operation, domain int) error {
if len(ops) == 0 {
return nil
}
after := time.After(3 * time.Minute)
tick := time.NewTicker(3 * time.Second)
defer tick.Stop()
var op *compute.Operation
var err error
for {
select {
case <-after:
return fmt.Errorf("operationWait(): timeout")
case <-tick.C:
for len(ops) > 0 {
switch {
case domain == local:
op, err = gceService.ZoneOperations.
Get(clst.projID, ops[0].Zone,
ops[0].Name).Do()
case domain == global:
op, err = gceService.GlobalOperations.
Get(clst.projID, ops[0].Name).Do()
}
if err != nil {
return err
}
if op.Status != "DONE" {
break
}
ops = append(ops[:0], ops[1:]...)
}
if len(ops) == 0 {
return nil
}
}
}
}
// Get a GCE instance.
func (clst *gceCluster) instanceGet(name, zone string) (*compute.Instance, error) {
ist, err := gceService.Instances.
Get(clst.projID, zone, name).Do()
return ist, err
}
// Create new GCE instance.
//
// Does not check if the operation succeeds.
//
// XXX: all kinds of hardcoded junk in here
// XXX: currently only defines the bare minimum
func (clst *gceCluster) instanceNew(name string, size string, zone string,
cloudConfig string) (*compute.Operation, error) {
instance := &compute.Instance{
Name: name,
Description: clst.ns,
MachineType: fmt.Sprintf("%s/zones/%s/machineTypes/%s",
clst.baseURL,
zone,
size),
Disks: []*compute.AttachedDisk{
{
Boot: true,
AutoDelete: true,
InitializeParams: &compute.AttachedDiskInitializeParams{
SourceImage: clst.imgURL,
},
},
},
NetworkInterfaces: []*compute.NetworkInterface{
{
AccessConfigs: []*compute.AccessConfig{
{
Type: "ONE_TO_ONE_NAT",
Name: "External NAT",
},
},
Network: fmt.Sprintf("%s/global/networks/%s",
clst.baseURL,
clst.ns),
},
},
Metadata: &compute.Metadata{
Items: []*compute.MetadataItems{
{
Key: "startup-script",
Value: &cloudConfig,
},
},
},
}
op, err := gceService.Instances.
Insert(clst.projID, zone, instance).Do()
if err != nil {
return nil, err
}
return op, nil
}
// Delete a GCE instance.
//
// Does not check if the operation succeeds
func (clst *gceCluster) instanceDel(name, zone string) (*compute.Operation, error) {
op, err := gceService.Instances.Delete(clst.projID, zone, name).Do()
return op, err
}
func (clst *gceCluster) SetACLs(acls []string) error {
list, err := gceService.Firewalls.List(clst.projID).Do()
if err != nil {
return err
}
var fw *compute.Firewall
for _, val := range list.Items {
if val.Name == clst.extFW {
fw = val
break
}
}
sort.Strings(fw.SourceRanges)
sort.Strings(acls)
if fw == nil || reflect.DeepEqual(fw.SourceRanges, acls) {
return nil
}
op, err := clst.firewallPatch(clst.extFW, acls)
if err != nil {
return err
}
if err = clst.operationWait([]*compute.Operation{op}, global); err != nil {
return err
}
return nil
}
// Creates the network for the cluster.
func (clst *gceCluster) networkNew(name string) (*compute.Operation, error) {
network := &compute.Network{
Name: name,
IPv4Range: clst.ipv4Range,
}
op, err := gceService.Networks.Insert(clst.projID, network).Do()
return op, err
}
func (clst *gceCluster) networkExists(name string) (bool, error) {
list, err := gceService.Networks.List(clst.projID).Do()
if err != nil {
return false, err
}
for _, val := range list.Items {
if val.Name == name {
return true, nil
}
}
return false, nil
}
// This creates a firewall but does nothing else
//
// XXX: Assumes there is only one network
func (clst *gceCluster) insertFirewall(name, sourceRange string) (
*compute.Operation, error) {
firewall := &compute.Firewall{
Name: name,
Network: fmt.Sprintf("%s/global/networks/%s",
clst.baseURL,
clst.ns),
Allowed: []*compute.FirewallAllowed{
{
IPProtocol: "tcp",
Ports: []string{"0-65535"},
},
{
IPProtocol: "udp",
Ports: []string{"0-65535"},
},
{
IPProtocol: "icmp",
},
},
SourceRanges: []string{sourceRange},
}
op, err := gceService.Firewalls.Insert(clst.projID, firewall).Do()
return op, err
}
func (clst *gceCluster) firewallExists(name string) (bool, error) {
list, err := gceService.Firewalls.List(clst.projID).Do()
if err != nil {
return false, err
}
for _, val := range list.Items {
if val.Name == name {
return true, nil
}
}
return false, nil
}
// Updates the firewall using PATCH semantics.
//
// The IP addresses must be in CIDR notation.
// XXX: Assumes there is only one network
// XXX: Assumes the firewall only needs to adjust the IP addrs affected
func (clst *gceCluster) firewallPatch(name string,
ips []string) (*compute.Operation, error) {
firewall := &compute.Firewall{
Name: name,
Network: fmt.Sprintf("%s/global/networks/%s",
clst.baseURL,
clst.ns),
SourceRanges: ips,
}
op, err := gceService.Firewalls.Patch(clst.projID, name, firewall).Do()
return op, err
}
// Initialize GCE.
//
// Authenication and the client are things that are re-used across clusters.
//
// Idempotent, can call multiple times but will only initialize once.
//
// XXX: ^but should this be the case? maybe we can just have the user call it?
func gceInit() error {
if gAuthClient == nil {
log.Debug("GCE initializing...")
keyfile := filepath.Join(
os.Getenv("HOME"),
".gce",
"quilt.json")
err := os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", keyfile)
if err != nil {
return err
}
srv, err := newComputeService(context.Background())
if err != nil {
return err
}
gceService = srv
} else {
log.Debug("GCE already initialized! Skipping...")
}
log.Debug("GCE initialize success")
return nil
}
func newComputeService(ctx context.Context) (*compute.Service, error) {
client, err := google.DefaultClient(ctx, compute.ComputeScope)
if err != nil {
return nil, err
}
computeService, err := compute.New(client)
if err != nil {
return nil, err
}
return computeService, nil
}
// Initializes the network for the cluster
//
// XXX: Currently assumes that each cluster is entirely behind 1 network
func (clst *gceCluster) netInit() error {
exists, err := clst.networkExists(clst.ns)
if err != nil {
return err
}
if exists {
log.Debug("Network already exists")
return nil
}
log.Debug("Creating network")
op, err := clst.networkNew(clst.ns)
if err != nil {
return err
}
err = clst.operationWait([]*compute.Operation{op}, global)
if err != nil {
return err
}
return nil
}
// Initializes the firewall for the cluster
//
// XXX: Currently assumes that each cluster is entirely behind 1 network
func (clst *gceCluster) fwInit() error {
var ops []*compute.Operation
if exists, err := clst.firewallExists(clst.intFW); err != nil {
return err
} else if exists {
log.Debug("internal firewall already exists")
} else {
log.Debug("creating internal firewall")
op, err := clst.insertFirewall(clst.intFW, clst.ipv4Range)
if err != nil {
return err
}
ops = append(ops, op)
}
if exists, err := clst.firewallExists(clst.extFW); err != nil {
return err
} else if exists {
log.Debug("external firewall already exists")
} else {
log.Debug("creating external firewall")
op, err := clst.insertFirewall(clst.extFW, "127.0.0.1/32")
if err != nil {
return err
}
ops = append(ops, op)
}
if err := clst.operationWait(ops, global); err != nil {
return err
}
return nil
}
| akshayknarayan/quilt | cluster/provider/gce.go | GO | mit | 13,634 |
// flow-typed signature: 6caf4b7ee5de64bc907fc9dcfc714a1a
// flow-typed version: f0506e4101/reselect_v3.x.x/flow_>=v0.47.x
// flow-typed signature: 0199525b667f385f2e61dbeae3215f21
// flow-typed version: b43dff3e0e/reselect_v3.x.x/flow_>=v0.28.x
declare module "reselect" {
declare type Selector<-TState, TProps, TResult> = {
(state: TState, props: TProps, ...rest: any[]): TResult
};
declare type SelectorCreator = {
<TState, TProps, TResult, T1>(
selector1: Selector<TState, TProps, T1>,
resultFunc: (arg1: T1) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1>(
selectors: [Selector<TState, TProps, T1>],
resultFunc: (arg1: T1) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
resultFunc: (arg1: T1, arg2: T2) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2>(
selectors: [Selector<TState, TProps, T1>, Selector<TState, TProps, T2>],
resultFunc: (arg1: T1, arg2: T2) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
resultFunc: (arg1: T1, arg2: T2, arg3: T3) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>
],
resultFunc: (arg1: T1, arg2: T2, arg3: T3) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
resultFunc: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>
],
resultFunc: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
resultFunc: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>
],
resultFunc: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
selector8: Selector<TState, TProps, T8>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>,
Selector<TState, TProps, T8>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
selector8: Selector<TState, TProps, T8>,
selector9: Selector<TState, TProps, T9>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>,
Selector<TState, TProps, T8>,
Selector<TState, TProps, T9>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
selector8: Selector<TState, TProps, T8>,
selector9: Selector<TState, TProps, T9>,
selector10: Selector<TState, TProps, T10>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>,
Selector<TState, TProps, T8>,
Selector<TState, TProps, T9>,
Selector<TState, TProps, T10>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
selector8: Selector<TState, TProps, T8>,
selector9: Selector<TState, TProps, T9>,
selector10: Selector<TState, TProps, T10>,
selector11: Selector<TState, TProps, T11>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11
) => TResult
): Selector<TState, TProps, TResult>,
<TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>,
Selector<TState, TProps, T8>,
Selector<TState, TProps, T9>,
Selector<TState, TProps, T10>,
Selector<TState, TProps, T11>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12
>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
selector8: Selector<TState, TProps, T8>,
selector9: Selector<TState, TProps, T9>,
selector10: Selector<TState, TProps, T10>,
selector11: Selector<TState, TProps, T11>,
selector12: Selector<TState, TProps, T12>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12
>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>,
Selector<TState, TProps, T8>,
Selector<TState, TProps, T9>,
Selector<TState, TProps, T10>,
Selector<TState, TProps, T11>,
Selector<TState, TProps, T12>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12,
T13
>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
selector8: Selector<TState, TProps, T8>,
selector9: Selector<TState, TProps, T9>,
selector10: Selector<TState, TProps, T10>,
selector11: Selector<TState, TProps, T11>,
selector12: Selector<TState, TProps, T12>,
selector13: Selector<TState, TProps, T13>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12,
arg13: T13
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12,
T13
>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>,
Selector<TState, TProps, T8>,
Selector<TState, TProps, T9>,
Selector<TState, TProps, T10>,
Selector<TState, TProps, T11>,
Selector<TState, TProps, T12>,
Selector<TState, TProps, T13>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12,
arg13: T13
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12,
T13,
T14
>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
selector8: Selector<TState, TProps, T8>,
selector9: Selector<TState, TProps, T9>,
selector10: Selector<TState, TProps, T10>,
selector11: Selector<TState, TProps, T11>,
selector12: Selector<TState, TProps, T12>,
selector13: Selector<TState, TProps, T13>,
selector14: Selector<TState, TProps, T14>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12,
arg13: T13,
arg14: T14
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12,
T13,
T14
>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>,
Selector<TState, TProps, T8>,
Selector<TState, TProps, T9>,
Selector<TState, TProps, T10>,
Selector<TState, TProps, T11>,
Selector<TState, TProps, T12>,
Selector<TState, TProps, T13>,
Selector<TState, TProps, T14>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12,
arg13: T13,
arg14: T14
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12,
T13,
T14,
T15
>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
selector8: Selector<TState, TProps, T8>,
selector9: Selector<TState, TProps, T9>,
selector10: Selector<TState, TProps, T10>,
selector11: Selector<TState, TProps, T11>,
selector12: Selector<TState, TProps, T12>,
selector13: Selector<TState, TProps, T13>,
selector14: Selector<TState, TProps, T14>,
selector15: Selector<TState, TProps, T15>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12,
arg13: T13,
arg14: T14,
arg15: T15
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12,
T13,
T14,
T15
>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>,
Selector<TState, TProps, T8>,
Selector<TState, TProps, T9>,
Selector<TState, TProps, T10>,
Selector<TState, TProps, T11>,
Selector<TState, TProps, T12>,
Selector<TState, TProps, T13>,
Selector<TState, TProps, T14>,
Selector<TState, TProps, T15>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12,
arg13: T13,
arg14: T14,
arg15: T15
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12,
T13,
T14,
T15,
T16
>(
selector1: Selector<TState, TProps, T1>,
selector2: Selector<TState, TProps, T2>,
selector3: Selector<TState, TProps, T3>,
selector4: Selector<TState, TProps, T4>,
selector5: Selector<TState, TProps, T5>,
selector6: Selector<TState, TProps, T6>,
selector7: Selector<TState, TProps, T7>,
selector8: Selector<TState, TProps, T8>,
selector9: Selector<TState, TProps, T9>,
selector10: Selector<TState, TProps, T10>,
selector11: Selector<TState, TProps, T11>,
selector12: Selector<TState, TProps, T12>,
selector13: Selector<TState, TProps, T13>,
selector14: Selector<TState, TProps, T14>,
selector15: Selector<TState, TProps, T15>,
selector16: Selector<TState, TProps, T16>,
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12,
arg13: T13,
arg14: T14,
arg15: T15,
arg16: T16
) => TResult
): Selector<TState, TProps, TResult>,
<
TState,
TProps,
TResult,
T1,
T2,
T3,
T4,
T5,
T6,
T7,
T8,
T9,
T10,
T11,
T12,
T13,
T14,
T15,
T16
>(
selectors: [
Selector<TState, TProps, T1>,
Selector<TState, TProps, T2>,
Selector<TState, TProps, T3>,
Selector<TState, TProps, T4>,
Selector<TState, TProps, T5>,
Selector<TState, TProps, T6>,
Selector<TState, TProps, T7>,
Selector<TState, TProps, T8>,
Selector<TState, TProps, T9>,
Selector<TState, TProps, T10>,
Selector<TState, TProps, T11>,
Selector<TState, TProps, T12>,
Selector<TState, TProps, T13>,
Selector<TState, TProps, T14>,
Selector<TState, TProps, T15>,
Selector<TState, TProps, T16>
],
resultFunc: (
arg1: T1,
arg2: T2,
arg3: T3,
arg4: T4,
arg5: T5,
arg6: T6,
arg7: T7,
arg8: T8,
arg9: T9,
arg10: T10,
arg11: T11,
arg12: T12,
arg13: T13,
arg14: T14,
arg15: T15,
arg16: T16
) => TResult
): Selector<TState, TProps, TResult>
};
declare type Reselect = {
createSelector: SelectorCreator,
defaultMemoize: <TFunc: Function>(
func: TFunc,
equalityCheck?: (a: any, b: any) => boolean
) => TFunc,
createSelectorCreator: (
memoize: Function,
...memoizeOptions: any[]
) => SelectorCreator,
createStructuredSelector: <TState, TProps>(
inputSelectors: {
[k: string | number]: Selector<TState, TProps, any>
},
selectorCreator?: SelectorCreator
) => Selector<TState, TProps, any>
};
declare var exports: Reselect;
}
| splayd/react-redux-reference | flow-typed/npm/reselect_v3.x.x.js | JavaScript | mit | 23,515 |
import express from 'express';
import unpackByOutpoint from './unpackByOutpoint';
// Polyfills and `lbry-redux`
global.fetch = require('node-fetch');
global.window = global;
if (typeof global.fetch === 'object') {
global.fetch = global.fetch.default;
}
const { Lbry } = require('lbry-redux');
delete global.window;
export default async function startSandbox() {
const port = 5278;
const sandbox = express();
sandbox.get('/set/:outpoint', async (req, res) => {
const { outpoint } = req.params;
const resolvedPath = await unpackByOutpoint(Lbry, outpoint);
sandbox.use(`/sandbox/${outpoint}/`, express.static(resolvedPath));
res.send(`/sandbox/${outpoint}/`);
});
sandbox
.listen(port, 'localhost', () => console.log(`Sandbox listening on port ${port}.`))
.on('error', err => {
if (err.code === 'EADDRINUSE') {
console.log(
`Server already listening at localhost:${port}. This is probably another LBRY app running. If not, games in the app will not work.`
);
}
});
}
| lbryio/lbry-electron | electron/startSandbox.js | JavaScript | mit | 1,051 |
def zeus_running?
File.exist?(".zeus.sock")
end
ENV["RAILS_ENV"] ||= "test"
unless zeus_running?
require "simplecov"
SimpleCov.start("rails")
end
require "rails/all"
require "webmock/rspec"
require "database_cleaner"
require "spec_helper"
require File.expand_path("../../config/environment", __FILE__)
require "rspec/rails"
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
end
| enova/level_up_exercises | find_me_a_sandwich/spec/rails_helper.rb | Ruby | mit | 556 |
namespace Nancy.Testing.Tests
{
using System.Linq;
using CsQuery;
using CsQuery.Implementation;
using Nancy.Testing;
using Xunit;
public class QueryWrapperTests
{
[Fact]
public void Should_use_cq_find_when_indexer_invoked()
{
// Given
var document =
CQ.Create(@"<html><head></head><body><div id='testId' class='myClass'>Test</div></body></html>");
var queryResult =
document.Find("#testId").FirstOrDefault();
var wrapper =
new QueryWrapper(document);
// When
var result = (DomElement)wrapper["#testId"].FirstOrDefault();
// Then
Assert.NotNull(result);
Assert.Same(queryResult, result);
}
}
} | 151706061/Nancy | src/Nancy.Testing.Tests/QueryWrapperTests.cs | C# | mit | 850 |
from __future__ import division
class ExitNode:
"""
Class for the exit node on our network
"""
def __init__(self, max_simulation_time):
"""
Initialise a node.
"""
self.individuals = []
self.id_number = -1
self.next_event_date = max_simulation_time
self.node_capacity = "Inf"
def __repr__(self):
"""
Representation of a node::
"""
return 'Exit Node'
def accept(self, next_individual, current_time):
"""
Accepts a new customer to the queue
"""
self.individuals.append(next_individual)
def update_next_event_date(self):
"""
Finds the time of the next event at this node
"""
pass | geraintpalmer/ASQ | asq/exit_node.py | Python | mit | 759 |
//Copyright (C) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using System.Data.Linq;
using NorthwindMapping;
namespace WinFormsDataBinding {
public partial class EmployeeManagerGrids : Form {
private Northwind db;
public EmployeeManagerGrids() {
InitializeComponent();
db = new Northwind(Program.connString);
var employeeQuery = from employee in db.Employees
orderby employee.LastName
select employee;
//ToBindingList method converts query into a structure that supports IBindingList.
//The Table<T> is required to convert to a binding list so that the addition and
//deletion of entities are tracked correctly.
employeeBindingSource.DataSource = employeeQuery;
managerBindingSource.DataSource = employeeQuery.ToList();
}
private void employeeDataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
string s = e.Value as string;
//OfType is needed because the employeeBindingSource returns instances of type object.
Employee emp = (from employee in this.managerBindingSource.OfType<Employee>()
where employee.ToString()==s
select employee).FirstOrDefault();
e.Value = emp;
e.ParsingApplied = true;
}
private void btnSubmitChanges_Click(object sender, EventArgs e) {
//Causes the control container to validate and end editing.
this.Validate();
db.SubmitChanges();
}
}
} | SiddharthMishraPersonal/StudyMaterials | Linq/CSharpSamples/LinqSamples/WinFormsDataBinding/EmployeeManagerGrids.cs | C# | mit | 1,874 |
require "crash_log/auth_hmac"
| undecided/crashdown-auth-hmac | lib/crashlog-auth-hmac.rb | Ruby | mit | 30 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Entities;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Core.Services.Implement;
using Umbraco.Web.Actions;
namespace Umbraco.Web.Compose
{
public sealed class NotificationsComponent : IComponent
{
private readonly Notifier _notifier;
private readonly ActionCollection _actions;
private readonly IContentService _contentService;
public NotificationsComponent(Notifier notifier, ActionCollection actions, IContentService contentService)
{
_notifier = notifier;
_actions = actions;
_contentService = contentService;
}
public void Initialize()
{
//Send notifications for the send to publish action
ContentService.SentToPublish += (sender, args) => _notifier.Notify(_actions.GetAction<ActionToPublish>(), args.Entity);
//Send notifications for the published action
ContentService.Published += (sender, args) => _notifier.Notify(_actions.GetAction<ActionPublish>(), args.PublishedEntities.ToArray());
//Send notifications for the saved action
ContentService.Sorted += (sender, args) => ContentServiceSorted(_notifier, sender, args, _actions);
//Send notifications for the update and created actions
ContentService.Saved += (sender, args) => ContentServiceSaved(_notifier, sender, args, _actions);
//Send notifications for the unpublish action
ContentService.Unpublished += (sender, args) => _notifier.Notify(_actions.GetAction<ActionUnpublish>(), args.PublishedEntities.ToArray());
//Send notifications for the move/move to recycle bin and restore actions
ContentService.Moved += (sender, args) => ContentServiceMoved(_notifier, sender, args, _actions);
//Send notifications for the delete action when content is moved to the recycle bin
ContentService.Trashed += (sender, args) => _notifier.Notify(_actions.GetAction<ActionDelete>(), args.MoveInfoCollection.Select(m => m.Entity).ToArray());
//Send notifications for the copy action
ContentService.Copied += (sender, args) => _notifier.Notify(_actions.GetAction<ActionCopy>(), args.Original);
//Send notifications for the rollback action
ContentService.RolledBack += (sender, args) => _notifier.Notify(_actions.GetAction<ActionRollback>(), args.Entity);
//Send notifications for the public access changed action
PublicAccessService.Saved += (sender, args) => PublicAccessServiceSaved(_notifier, sender, args, _contentService, _actions);
UserService.UserGroupPermissionsAssigned += (sender, args) => UserServiceUserGroupPermissionsAssigned(_notifier, sender, args, _contentService, _actions);
}
public void Terminate()
{ }
private void ContentServiceSorted(Notifier notifier, IContentService sender, Core.Events.SaveEventArgs<IContent> args, ActionCollection actions)
{
var parentId = args.SavedEntities.Select(x => x.ParentId).Distinct().ToList();
if (parentId.Count != 1) return; // this shouldn't happen, for sorting all entities will have the same parent id
// in this case there's nothing to report since if the root is sorted we can't report on a fake entity.
// this is how it was in v7, we can't report on root changes because you can't subscribe to root changes.
if (parentId[0] <= 0) return;
var parent = sender.GetById(parentId[0]);
if (parent == null) return; // this shouldn't happen
notifier.Notify(actions.GetAction<ActionSort>(), new[] { parent });
}
private void ContentServiceSaved(Notifier notifier, IContentService sender, Core.Events.SaveEventArgs<IContent> args, ActionCollection actions)
{
var newEntities = new List<IContent>();
var updatedEntities = new List<IContent>();
//need to determine if this is updating or if it is new
foreach (var entity in args.SavedEntities)
{
var dirty = (IRememberBeingDirty)entity;
if (dirty.WasPropertyDirty("Id"))
{
//it's new
newEntities.Add(entity);
}
else
{
//it's updating
updatedEntities.Add(entity);
}
}
notifier.Notify(actions.GetAction<ActionNew>(), newEntities.ToArray());
notifier.Notify(actions.GetAction<ActionUpdate>(), updatedEntities.ToArray());
}
private void UserServiceUserGroupPermissionsAssigned(Notifier notifier, IUserService sender, Core.Events.SaveEventArgs<EntityPermission> args, IContentService contentService, ActionCollection actions)
{
var entities = contentService.GetByIds(args.SavedEntities.Select(e => e.EntityId)).ToArray();
if(entities.Any() == false)
{
return;
}
notifier.Notify(actions.GetAction<ActionRights>(), entities);
}
private void ContentServiceMoved(Notifier notifier, IContentService sender, Core.Events.MoveEventArgs<IContent> args, ActionCollection actions)
{
// notify about the move for all moved items
_notifier.Notify(_actions.GetAction<ActionMove>(), args.MoveInfoCollection.Select(m => m.Entity).ToArray());
// for any items being moved from the recycle bin (restored), explicitly notify about that too
var restoredEntities = args.MoveInfoCollection
.Where(m => m.OriginalPath.Contains(Constants.System.RecycleBinContentString))
.Select(m => m.Entity)
.ToArray();
if(restoredEntities.Any())
{
_notifier.Notify(_actions.GetAction<ActionRestore>(), restoredEntities);
}
}
private void PublicAccessServiceSaved(Notifier notifier, IPublicAccessService sender, Core.Events.SaveEventArgs<PublicAccessEntry> args, IContentService contentService, ActionCollection actions)
{
var entities = contentService.GetByIds(args.SavedEntities.Select(e => e.ProtectedNodeId)).ToArray();
if(entities.Any() == false)
{
return;
}
notifier.Notify(actions.GetAction<ActionProtect>(), entities);
}
/// <summary>
/// This class is used to send the notifications
/// </summary>
public sealed class Notifier
{
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
private readonly IRuntimeState _runtimeState;
private readonly INotificationService _notificationService;
private readonly IUserService _userService;
private readonly ILocalizedTextService _textService;
private readonly IGlobalSettings _globalSettings;
private readonly IContentSection _contentConfig;
private readonly ILogger _logger;
/// <summary>
/// Constructor
/// </summary>
/// <param name="umbracoContextAccessor"></param>
/// <param name="notificationService"></param>
/// <param name="userService"></param>
/// <param name="textService"></param>
/// <param name="globalSettings"></param>
/// <param name="contentConfig"></param>
/// <param name="logger"></param>
public Notifier(IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtimeState, INotificationService notificationService, IUserService userService, ILocalizedTextService textService, IGlobalSettings globalSettings, IContentSection contentConfig, ILogger logger)
{
_umbracoContextAccessor = umbracoContextAccessor;
_runtimeState = runtimeState;
_notificationService = notificationService;
_userService = userService;
_textService = textService;
_globalSettings = globalSettings;
_contentConfig = contentConfig;
_logger = logger;
}
public void Notify(IAction action, params IContent[] entities)
{
IUser user = null;
if (_umbracoContextAccessor.UmbracoContext != null)
{
user = _umbracoContextAccessor.UmbracoContext.Security.CurrentUser;
}
//if there is no current user, then use the admin
if (user == null)
{
_logger.Debug(typeof(Notifier), "There is no current Umbraco user logged in, the notifications will be sent from the administrator");
user = _userService.GetUserById(Constants.Security.SuperUserId);
if (user == null)
{
_logger.Warn(typeof(Notifier), "Notifications can not be sent, no admin user with id {SuperUserId} could be resolved", Constants.Security.SuperUserId);
return;
}
}
SendNotification(user, entities, action, _runtimeState.ApplicationUrl);
}
private void SendNotification(IUser sender, IEnumerable<IContent> entities, IAction action, Uri siteUri)
{
if (sender == null) throw new ArgumentNullException(nameof(sender));
if (siteUri == null)
{
_logger.Warn(typeof(Notifier), "Notifications can not be sent, no site url is set (might be during boot process?)");
return;
}
//group by the content type variation since the emails will be different
foreach(var contentVariantGroup in entities.GroupBy(x => x.ContentType.Variations))
{
_notificationService.SendNotifications(
sender,
contentVariantGroup,
action.Letter.ToString(CultureInfo.InvariantCulture),
_textService.Localize("actions", action.Alias),
siteUri,
((IUser user, NotificationEmailSubjectParams subject) x)
=> _textService.Localize(
"notifications/mailSubject",
x.user.GetUserCulture(_textService, _globalSettings),
new[] { x.subject.SiteUrl, x.subject.Action, x.subject.ItemName }),
((IUser user, NotificationEmailBodyParams body, bool isHtml) x)
=> _textService.Localize(
x.isHtml ? "notifications/mailBodyHtml" : "notifications/mailBody",
x.user.GetUserCulture(_textService, _globalSettings),
new[]
{
x.body.RecipientName,
x.body.Action,
x.body.ItemName,
x.body.EditedUser,
x.body.SiteUrl,
x.body.ItemId,
//format the summary depending on if it's variant or not
contentVariantGroup.Key == ContentVariation.Culture
? (x.isHtml ? _textService.Localize("notifications/mailBodyVariantHtmlSummary", new[]{ x.body.Summary }) : _textService.Localize("notifications/mailBodyVariantSummary", new []{ x.body.Summary }))
: x.body.Summary,
x.body.ItemUrl
}));
}
}
}
}
}
| dawoe/Umbraco-CMS | src/Umbraco.Web/Compose/NotificationsComponent.cs | C# | mit | 12,608 |
### EXESOFT PYIGNITION ###
# Copyright David Barker 2010
#
# Global constants module
# Which version is this?
PYIGNITION_VERSION = 1.0
# Drawtype constants
DRAWTYPE_POINT = 100
DRAWTYPE_CIRCLE = 101
DRAWTYPE_LINE = 102
DRAWTYPE_SCALELINE = 103
DRAWTYPE_BUBBLE = 104
DRAWTYPE_IMAGE = 105
# Interpolation type constants
INTERPOLATIONTYPE_LINEAR = 200
INTERPOLATIONTYPE_COSINE = 201
# Gravity constants
UNIVERSAL_CONSTANT_OF_MAKE_GRAVITY_LESS_STUPIDLY_SMALL = 1000.0 # Well, Newton got one to make it less stupidly large.
VORTEX_ACCELERATION = 0.01 # A tiny value added to the centripetal force exerted by vortex gravities to draw in particles
VORTEX_SWALLOWDIST = 20.0 # Particles closer than this will be swallowed up and regurgitated in the bit bucket
# Fraction of radius which can go inside an object
RADIUS_PERMITTIVITY = 0.3 | HelsinkiGroup5/Hackathon | display_manuel/constants.py | Python | mit | 865 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.Its.Domain.Serialization;
using Microsoft.Its.Recipes;
using log = Its.Log.Lite.Log;
namespace Microsoft.Its.Domain.Sql
{
/// <summary>
/// Represents a single atomic update to a read model database.
/// </summary>
public class ReadModelUpdate
{
/// <summary>
/// Configures <see cref="UnitOfWork{ReadModelUpdate}" /> to provide DbContext sharing and database transactions.
/// </summary>
public static void ConfigureUnitOfWork()
{
// creating a new unit of work starts a transaction
UnitOfWork<ReadModelUpdate>.Create = CreateUnitOfWork;
UnitOfWork<ReadModelUpdate>.Commit = CommitUnitOfWork;
UnitOfWork<ReadModelUpdate>.Reject = RejectUnitOfWork;
}
private static void CreateUnitOfWork(
UnitOfWork<ReadModelUpdate> unitOfWork,
Action<ReadModelUpdate> setSubject)
{
setSubject(new ReadModelUpdate());
}
private static void RejectUnitOfWork(UnitOfWork<ReadModelUpdate> unitOfWork)
{
var exception = unitOfWork.Exception;
if (exception != null)
{
unitOfWork.Subject.Projectors.ForEach(p => ReportFailure(
new Domain.EventHandlingError(
exception,
handler: p,
@event: unitOfWork.Resource<IEvent>()),
() => ProjectorExtensions.CreateDbContext(p)));
}
}
private static void CommitUnitOfWork(UnitOfWork<ReadModelUpdate> unitOfWork)
{
try
{
unitOfWork.Resource<DbContext>().SaveChanges();
}
catch (Exception exception)
{
unitOfWork.RejectDueTo(exception);
}
}
internal readonly HashSet<object> Projectors = new HashSet<object>();
internal static void ReportFailure(
Domain.EventHandlingError error,
Func<DbContext> createDbContext)
{
// add an EventHandlingError entry as well
EventHandlingError sqlError = CreateEventHandlingError((dynamic) error);
log.Write(() => new {error.Exception, sqlError.SerializedEvent});
using (var db = createDbContext())
{
var dbSet = db.Set<ReadModelInfo>();
var handler = error.Handler;
string readModelInfoName = null;
var exceptionJson = error.Exception.ToDiagnosticJson();
if (handler != null)
{
// update the affected ReadModelInfo
readModelInfoName = ReadModelInfo.NameForProjector(handler);
var readModelInfo = dbSet.SingleOrDefault(i => i.Name == readModelInfoName);
if (readModelInfo == null)
{
readModelInfo = new ReadModelInfo { Name = readModelInfoName };
dbSet.Add(readModelInfo);
}
readModelInfo.Error = exceptionJson;
readModelInfo.FailedOnEventId = sqlError.OriginalId;
}
sqlError.Error = exceptionJson;
sqlError.Handler = readModelInfoName;
db.Set<EventHandlingError>().Add(sqlError);
db.SaveChanges();
}
}
private static EventHandlingError CreateEventHandlingError(Domain.EventHandlingError e)
{
return new EventHandlingError
{
Actor = e.Event.Actor(),
AggregateId = e.Event.AggregateId,
SequenceNumber = e.Event.SequenceNumber,
SerializedEvent = e.Event.ToJson(),
StreamName = e.Event.EventStreamName(),
EventTypeName = e.Event.EventName(),
OriginalId = e.Event
.IfTypeIs<IHaveExtensibleMetada>()
.Then(ee => ee.Try(eee => eee.Metadata.AbsoluteSequenceNumber,
ignore: ex => true))
.Else(() => (long?) null)
};
}
private static EventHandlingError CreateEventHandlingError(IEvent e)
{
return new EventHandlingError
{
Actor = e.Actor(),
AggregateId = e.AggregateId,
SequenceNumber = e.SequenceNumber,
SerializedEvent = e.ToJson(),
StreamName = e.EventStreamName(),
EventTypeName = e.EventName(),
OriginalId = null
};
}
private static EventHandlingError CreateEventHandlingError(EventHandlingDeserializationError e)
{
return new EventHandlingError
{
Actor = e.Actor,
AggregateId = e.AggregateId,
SequenceNumber = e.SequenceNumber,
SerializedEvent = e.Body,
StreamName = e.StreamName,
EventTypeName = e.Type,
OriginalId = e.Try(ee => ee.Metadata.AbsoluteSequenceNumber, ignore: ex => true)
.Else(() => (long?) null)
};
}
private static EventHandlingError CreateEventHandlingError(StorableEvent e)
{
return new EventHandlingError
{
Actor = e.Actor,
AggregateId = e.AggregateId,
SequenceNumber = e.SequenceNumber,
SerializedEvent = e.Body,
StreamName = e.StreamName,
EventTypeName = e.Type,
OriginalId = e.Id
};
}
}
}
| commonsensesoftware/Its.Cqrs | Domain.Sql/ReadModelUpdate.cs | C# | mit | 6,181 |
//bubble sort
public class BubbleSort{
public static void main(String[] args){
int[] test = new int[]{7,5,2,4,3,9};
bubbleSort4(test);
for(int curr: test){
System.out.print(curr + " ");
}
}
//for every step, move largest element in the left unsorted left subarray to front of right sorted array
public static void bubbleSort(int[] arr){
if(arr==null || arr.length<=1){
return;
}
int len = arr.length;
for(int i=len-1; i>=0; i--){
//move largest element to the end of array
for(int j=1; j<=i; j++){
if(arr[j-1] > arr[j]){
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
//for every step, swap unordered pair until no swap is neede
public static void bubbleSort2(int[] arr){
if(arr==null || arr.length<=1){
return;
}
int len = arr.length;
boolean swap = true;
while(swap){
swap = false;
for(int i=1; i<len; i++){
if(arr[i-1] > arr[i]){
int temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
swap = true;
}
}
}
}
//combine first and second implementation
public static void bubbleSort3(int[] arr){
if(arr==null || arr.length<=1){
return;
}
int len = arr.length;
boolean swap = true;
while(swap){
swap = false;
for(int i=1; i<len; i++){
if(arr[i-1] > arr[i]){
int temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
swap = true;
}
}
len --;
}
}
//in one pass, more than one element can be placed into final positions
//position after last swap is sorted and no need to traverse again
public static void bubbleSort4(int[] arr){
if(arr==null || arr.length<=1){
return;
}
int len = arr.length;
while(len != 0){
int lastSwap = 0;
for(int i=1; i<len; i++){
if(arr[i-1] > arr[i]){
int temp = arr[i];
arr[i] = arr[i-1];
arr[i-1] = temp;
lastSwap = i;
}
}
len = lastSwap;
}
}
} | WenyingLiu/coding_problems | others/amazon/implementation/sorting/BubbleSort.java | Java | mit | 1,935 |
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=1e5;
int A[N];
void print_permutation(int n,int *A,int cur){
//generate permutation using number ranged from 1 to n inclusively;
if(n==cur){
for(int i=0;i<n;i++){
printf("%d ", A[i]);
}
printf("\n");
}
else {
for(int i=1;i<=n;i++){
int ok=1;
for(int j=0;j<cur;j++){
if(A[j]==i){ok=0;
break;
}
}
if(ok){
A[cur]=i;
print_permutation(n,A,cur+1);
}
}
}
}
void print_permutation_2(int *P,int n,int *A,int cur){
//generate permutation using number ranged from 1 to n inclusively;
if(n==cur){
for(int i=0;i<n;i++){
printf("%d ", A[i]);
}
printf("\n");
}
else {
for(int i=0;i<n;i++)if(i==0||P[i]!=P[i-1]){
int c1=0,c2=0;
for(int j=0;j<cur;j++)if(P[i]==A[j])c1++;
for(int j=0;j<n;j++)if(P[i]==P[j])c2++;
if(c1<c2){
A[cur]=P[i];
print_permutation_2(P,n,A,cur+1);
}
}
}
}
int main(){
int n=2;
int P[]={1,2};
sort(P,P+n);//lexigraphical order
print_permutation_2(P,n,A,0);
//print_permutation(n,A,0);
}
| xsthunder/a | modules/print_permutation.cc | C++ | mit | 1,061 |
---
layout: post
title: 大整数乘法和Strassen矩阵乘法
cateory: 摘录
tags: snippet
description:
---
本节中,研究两个不同寻常的算法,它们用于解决两个数的乘法和两个方阵的乘法。两个算法都以增加少量加法运算为代价,减少乘法运算的执行总次数 。为了达到这个目的,两者都使用了分治思想。
### 大整数乘法
当代的密码技术,需要对超过100位的十进制整数进行乘法运算。因为这样的整数过于长,现代计算机的一个“字”是装不下的,所以我们需要对它们作特别的处理。这就是研究高效的大整数乘法运算的现实需求。
经典的笔算算法对两个n位整数相乘,第一个数中的n个素质分别要被第二个数中的n个数字相乘,这样就一共要做n^2次位乘。现在我们用分治法设计一个乘法次数少于n^2的算法.
为了展示该算法的基本思想,我们研究一个两位整数相乘的案例,比如说,23和14.这两个数字可以这样表示:
> 23 = 2·10^1 + 3·10^0
> 14 = 1·10^1 + 4^10^0
现在把它们相乘:
> 23 = (2·10^1 + 3·10^0) * (1·10^1 + 4·10^0)
> = (2 * 1)10^2 + (3 * 1 + 2 * 4)10^1 + (3 * 4)10^0
方程产生出一个正确的结果322,和笔算算法一样,使用了四次位乘。
但是`2*1`和`3*4`无论如何都需要计算,我们可以利用它们的积,只做一次乘法计算出中间项的结果,来减少位乘的次数。
> 3 * 1 + 2 * 4 = (2+3) * (1+4) - (2 * 1) - (3 * 4)
总结一个规律,对于任何两位数a=a1a0和b=b1b0,它们的积c可以用这个公式来计算:
> c = a * b = c2 * 10^2 + c1 * 10^1 + c0
其中,
c2 = a1 * b1
c0 = a0 * b0
c1 = (a1+b1) * (a0+b0) - (c2+c0),即a数字和b数字和的积减去c2与c0的和。
现在我们应用这个窍门计算两个n位整数a和b的积,其中n是一个正的偶数。我们从中间把两个数字一分为二,毕竟,要利用分治技术。把a的前半部分记住a1, a的后半部分记住a0;对于b,则分别记住b1和b0.
在这种记法中,a=a1a0意味着`a=a1*10^(n/2) + a0`, b = b1b0意味着`b=b1*10^(n/2) + b0`.所以利用与计算两位数相同的方法,我们有:
> c = a * b = (a1 * 10^(n/2) + a0) * (b1 * 10^(n/2) + b0)
> = (a1 * b1)10^n + (a1 * b0 + a0 * b1)10^(n/2) + (a0 * b0)
> = c2 * 10^n + c1 * 10^(n/2) + c0
其中,
`c2 = a1*b1`是它们前半部分的积`c0 = a0*b0`,是它们后半部分的积,
`c1 = (a1+a0)*(b1+b0)-(c2+c1)`是a两部分和与b两部分和的积减去c2与c0的和。
因此,如果n是2的乘方,我们就得到了一个计算两个n位数积的递归算法。在这种完美的形式下,当n变成1时,递归就停止了。
该算法会做多少次位乘呢?
因为n位数的乘法需要对n/2位数做三次乘法运算,乘法次数M(n)的递推式将会是:
> 当n>1时,M(n) = 3M(n/2), M(1)=1
当b=2^k时,我们用反向替换法对它求解:
> M(2^k) = 3M(2^k-1) = 3[3M(2^(k-2))] = 3^2M(2^(k-2))
> = ...=3^iM(2^(k-i)=...=3^kM(2^(k-k))=3^k
因为k=log2 n,
> M(n) = 3^(log2 n) = n^(log2 3) ≈ n^1.585
> (最后一步,利用了对数的一个特性:a^logb c = c^logb a
对于不是很大的整数,该算法的运行时间很可能比经典算法长。报告说,实验显示,大于600位的整数开始,分治算法的性能超越了笔算算法的性能。如果我们使用类似Java,C++和Smalltalk这样的面向对象的语言,会发现这些语言专门为处理大整数提供了一些类。
### Strassen矩阵乘法
分治方法可以减少两个数乘法中的位乘次数,它在矩阵乘法中发挥的同样作用。V.Strassen在1969年发表了一个算法,该算法的成功依赖于这个实现:计算两个2阶方阵A和B的积C只需要进行7次乘法运算,而不是曼丽算法所需要的8次(n^3=2^3).为了做到这一点,我们使用了下面的公式。

其中,

因此,对两个2阶方阵相乘时,Strassen算法执行了7次乘法和18次加减法,而蛮力算法需要执行8次乘法和4次加减法。该算法的重要性体现在当矩阵的阶趋于无穷大时,该算法所表现出来的卓越的渐进效率。
假设n是2的乘方,A和B是两个n阶方阵(如果n不是2的乘方,矩阵可以用全0的行或列来填充)。我们把A,B和C分别划分为4个n/2阶的子矩阵:

我们像对待数字一样对待这些子矩阵,求得正确的积。例如,把数字替换成相应的子矩阵的话,C00用M2+M4-M5+M7来计算,其中M1,M4,M5和M7是由Strassen方程定义的。如果递归调用相同的方法来计算7个n/2阶矩阵的乘积,我们就得到了矩阵乘法的Strassen算法。
评估一下该算法的渐进效率。如果M(n)是Strassen算法在计算两个n阶方阵时执行的乘法次数,我们对它有下面的递推关系式:
> 当n > 1时,M(n) = 7M(n/2), M(1) = 1
因为n=2^k,

因为k=log2 n,

它比蛮力算法需要的n^3次乘法运算要来得小。
因为减少了的乘法运算次数是以额外的加法运算为代价的,我们必须检查一下Strassen算法执行的加法次数A(n).对两个n>1阶矩阵相乘时,该算法要对n/2阶的矩阵作7次乘法和18次加法;当n=1时,因为两个数字直接相乘,所以没有执行加法运算,从这一事实我们得出了下列递推关系式:

根据主定理,A(n)∈Θ(n^(log2 7)).换句话说,加法的增长次数和乘法的增长次数是相同的。所以Strassen算法属于集合Θ(n^(log2 7)),这个效率类型要比蛮力法的Θ(n^3)要来得好。
目前为止,这类算法中最快的是Coopersmith和Winograd发明的,它的时间效率达到了O(n^2.376).指数值的减小以算法越来越复杂为代价的。而且乘法常量的值很大,使它们没有实用的价值。然而从学术的观点看,我们得到的最优效率和理论上的最优效率之间还有鸿沟,但它们越来越接近。矩阵乘法在理论上的效率下界n^2次乘法。另一方面,矩阵乘法同其他一些重要问题在算法上是等价的,比如解线性方程组问题。
| hacpai/readme | _posts/snippet/2014-12-22-multiplication-of-large-integers-and-strassen's-matrix-multiplication.md | Markdown | mit | 7,367 |
<?php
namespace app\admin\controller;
use think\Loader;
/**
* 用户管理
* @author aierui github https://github.com/Aierui
* @version 1.0
*/
class User extends Admin
{
function _initialize()
{
parent::_initialize();
}
/**
* 列表
*/
public function index()
{
return view();
}
/**
* 异步获取列表数据
*
* @author chengbin
* @return mixed
*/
public function getList()
{
if(!request()->isAjax()) {
$this->error(lang('Request type error'), 4001);
}
$request = request()->param();
$data = model('User')->getList( $request );
return $data;
}
/**
* 添加
*/
public function add()
{
$roleData = model('role')->getKvData();
$this->assign('roleData', $roleData);
return $this->fetch('edit');
}
/**
* 编辑
* @param string $id 数据ID(主键)
*/
public function edit($id = 0)
{
if(intval($id) < 0){
return info(lang('Data ID exception'), 0);
}
if (intval($id == 1)) {
return info(lang('Edit without authorization'), 0);
}
$roleData = model('role')->getKvData();
$this->assign('roleData', $roleData);
$data = model('User')->get(['id'=>$id]);
$this->assign('data',$data);
return $this->fetch();
}
/**
* 保存数据
* @param array $data
*
* @author chengbin
*/
public function saveData()
{
$this->mustCheckRule( 'admin/user/edit' );
if(!request()->isAjax()) {
return info(lang('Request type error'));
}
$data = input('post.');
var_dump($data);die;
return model('User')->saveData( $data );
}
/**
* 删除
* @param string $id 数据ID(主键)
*/
public function delete($id = 0){
if(empty($id)){
return info(lang('Data ID exception'), 0);
}
if (intval($id == 1)) {
return info(lang('Delete without authorization'), 0);
}
return Loader::model('User')->deleteById($id);
}
} | Aierui/tp-admin | app/admin/controller/User.php | PHP | mit | 2,216 |
import json
import math
import random
import os
class KMeans(object):
# TO-DO: Richard
def __init__(self, dataset=None):
file_path = os.path.dirname(os.path.realpath(__file__))
if dataset is None:
self.mega_dataset = json.loads(open(file_path + '/dataset.json', 'r').read())
else:
self.mega_dataset = json.loads(dataset)
def _ED(self, point1, point2):
result = 0
for i in xrange(len(point1)):
result += pow(point2[i] - point1[i], 2)
return math.sqrt(result)
def _closest(self, datum, centroids):
closest_index = None
closest_distance = None
for i, point in enumerate(centroids):
dist = self._ED(datum, point)
if closest_index is None or dist < closest_distance:
closest_index = i
closest_distance = dist
return closest_index
def _avg(self, li):
return sum(li) / float(len(li))
def _get_centroid(self, data):
try:
datum_len = range(len(next(iter(data))))
result = [0 for x in datum_len]
for datum in data:
for i, value in enumerate(datum):
result[i] += value
for i in datum_len:
result[i] /= float(len(data))
return tuple(result)
except StopIteration:
return ([0, 0, 0])
def _kmeans(self, k, iterations=100):
clusters = [set() for _ in xrange(k)]
centroids = random.sample(self.dataset, k)
# init data to clusters
for datum in self.dataset:
i = random.choice(range(k))
clusters[i].add(datum)
for _ in xrange(iterations):
for datum in self.dataset:
# remove from clusters
for c in clusters:
try:
c.remove(datum)
except KeyError:
pass
# get closest centroid index
closest_index = self._closest(datum, centroids)
# add to the new cluster
clusters[closest_index].add(datum)
# update centroids
centroids = [self._get_centroid(c) for c in clusters]
return clusters, centroids
def calculate(self, attr, to_file=False):
self.dataset = []
for data in self.mega_dataset[attr]:
self.dataset.append(tuple(data))
self.dataset = set(self.dataset)
champ2stat = {}
for i in xrange(len(self.mega_dataset['champions'])):
champ2stat[tuple(self.mega_dataset[attr][i])] = self.mega_dataset['champions'][i]
clusters, centroids = self._kmeans(len(self.mega_dataset[attr][0]), 100)
champ2cluster = []
for i, c in enumerate(clusters):
new_c = []
champ2cluster.append(new_c)
new_c.append(tuple(centroids[i]))
for champ in c:
new_c.append(champ2stat[champ])
if to_file:
f = open('output/' + attr + '_output.json', 'w')
f.write(json.dumps(champ2cluster, indent=4))
f.close()
return champ2cluster
# Example:
| avathardev/matchine-learning | kmeans.py | Python | mit | 3,350 |
# run using:
#
# bundle exec rspec simplegesture_tests.rb
#
require 'rubygems'
require 'rspec'
require 'appium_lib'
#require 'net/http'
# Required for 3.x before Rspec
# RSpec.configure do |c|
# c.treat_symbols_as_metadata_keys_with_true_values = true
# end
APP_PATH = '../../build/Release-iphonesimulator/SimpleGestureRecognizers.app'
describe 'Gesture_Tests' do
def caps
{
caps: {
#appiumVersion: "1.3.7",
platformName: "iOS",
#platformVersion: "8.2",
deviceName: "iPhone 6",
app: APP_PATH
#name: "Basic iOS Native Test",
},
appium_lib: {
sauce_username: nil, # don't run on sauce
sauce_access_key: nil,
wait: 10,
}
}
end
before(:all) do
@driver = Appium::Driver.new(caps)
@driver.start_driver
Appium.promote_appium_methods RSpec::Core::ExampleGroup
end
after(:all) do
@driver.driver_quit
end
it 'Left Swipe' do
#Left Swipe
@driver.swipe(start_x: 300, end_x: 30, start_y: 50, end_y: 50, duration: 900).perform
lbl = find_element(:class_name, 'UIAStaticText')
expect(lbl.text).to eq 'Left Swipe'
end
it 'Right Swipe' do
#Left Swipe
@driver.swipe(start_x: 30, end_x: 300, start_y: 50, end_y: 50, duration: 900).perform
lbl = find_element(:class_name, 'UIAStaticText')
expect(lbl.text).to eq 'Left Swipe'
end
it 'Right Swipe' do
#Left Swipe
@driver.tap(start_x: 30, end_y: 50, duration: 900).perform
lbl = find_element(:class_name, 'UIAStaticText')
expect(lbl.text).to eq 'Left Swipe'
end
end
| mrudulp/iOSSrc | autotest/appiumTest/sampleApps/SimpleGestureRecognizers/tests/ruby/simplegesture_tests.rb | Ruby | mit | 1,706 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- modules.qdoc -->
<title>Qt 4.8: QtTest Module</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style/superfish.css" />
<link rel="stylesheet" type="text/css" href="style/narrow.css" />
<!--[if IE]>
<meta name="MSSmartTagsPreventParsing" content="true">
<meta http-equiv="imagetoolbar" content="no">
<![endif]-->
<!--[if lt IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie6.css">
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="style/style_ie7.css">
<![endif]-->
<!--[if IE 8]>
<link rel="stylesheet" type="text/css" href="style/style_ie8.css">
<![endif]-->
<script src="scripts/superfish.js" type="text/javascript"></script>
<script src="scripts/narrow.js" type="text/javascript"></script>
</head>
<body class="" onload="CheckEmptyAndLoadList();">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="narrowsearch"></div>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li>
<li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul>
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul>
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="supported-platforms.html">Supported Platforms</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul>
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search" id="sidebarsearch">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
<div id="resultdialog">
<a href="#" id="resultclose">Close</a>
<p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p>
<p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p>
<ul id="resultlist" class="all">
</ul>
</div>
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Breadcrumbs go here -->
<li><a href="modules.html">Modules</a></li>
<li>QtTest</li>
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content mainContent">
<div class="toc">
<h3><a name="toc">Contents</a></h3>
<ul>
<li class="level1"><a href="#namespaces">Namespaces</a></li>
<li class="level1"><a href="#classes">Classes</a></li>
<li class="level1"><a href="#details">Detailed Description</a></li>
</ul>
</div>
<h1 class="title">QtTest Module</h1>
<span class="subtitle"></span>
<!-- $$$QtTest-brief -->
<p>The QtTest module provides classes for unit testing Qt applications and libraries. <a href="#details">More...</a></p>
<!-- @@@QtTest -->
<a name="namespaces"></a>
<h2>Namespaces</h2>
<table class="annotated">
<tr class="odd topAlign"><td class="tblName"><p><a href="qtest.html">QTest</a></p></td><td class="tblDescr"><p>Contains all the functions and declarations that are related to the QTestLib tool</p></td></tr>
</table>
<a name="classes"></a>
<h2>Classes</h2>
<table class="annotated">
<tr class="odd topAlign"><td class="tblName"><p><a href="qsignalspy.html">QSignalSpy</a></p></td><td class="tblDescr"><p>Enables introspection of signal emission</p></td></tr>
<tr class="even topAlign"><td class="tblName"><p><a href="qtesteventlist.html">QTestEventList</a></p></td><td class="tblDescr"><p>List of GUI events</p></td></tr>
<tr class="odd topAlign"><td class="tblName"><p><a href="qtest-qtoucheventsequence.html">QTest::QTouchEventSequence</a></p></td><td class="tblDescr"><p>Used to simulate a sequence of touch events</p></td></tr>
</table>
<!-- $$$QtTest-description -->
<a name="details"></a>
<div class="descr">
<h2>Detailed Description</h2>
<a name="qttest"></a><p>Applications that use Qt's unit testing classes need to be configured to be built against the QtTest module. To include the definitions of the module's classes, use the following directive:</p>
<pre class="cpp"> <span class="preprocessor">#include <QtTest></span></pre>
<p>To link against the module, add this line to your <a href="qmake-manual.html#qmake">qmake</a> <tt>.pro</tt> file:</p>
<pre class="cpp"> CONFIG += qtestlib</pre>
<p>See the <a href="qtestlib-manual.html">QTestLib Manual</a> for a detailed introduction on how to use Qt's unit testing features with your applications.</p>
<p>The QtTest module is part of all <a href="editions.html">Qt editions</a>.</p>
</div>
<!-- @@@QtTest -->
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
subsidiaries. Documentation contributions included herein are the copyrights of
their respective owners.</p>
<br />
<p>
The documentation provided herein is licensed under the terms of the
<a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation
License version 1.3</a> as published by the Free Software Foundation.</p>
<p>
Documentation sources may be obtained from <a href="http://www.qt-project.org">
www.qt-project.org</a>.</p>
<br />
<p>
Digia, Qt and their respective logos are trademarks of Digia Plc
in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. <a title="Privacy Policy"
href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p>
</div>
<script src="scripts/functions.js" type="text/javascript"></script>
</body>
</html>
| stephaneAG/PengPod700 | QtEsrc/qt-everywhere-opensource-src-4.8.5/doc/html/qttest.html | HTML | mit | 11,246 |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = yogaNode => {
return yogaNode.getComputedWidth() - yogaNode.getComputedPadding() * 2;
};
exports.default = _default; | ykumawat/ykumawat.github.io | node_modules/ink/build/get-max-width.js | JavaScript | mit | 241 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.