text:
use std::cmp::Ordering;

/// Compares the non-digit parts of a version.
/// Special cases: ~ are before everything else, even ends ("a~" < "a")
/// Letters are before non-letters
fn version_non_digit_cmp(a: &str, b: &str) -> Ordering {
    let mut a_chars = a.chars();
    let mut b_chars = b.chars();
    loop {
        match (a_chars.next(), b_chars.next()) {
            (Some(c1), Some(c2)) if c1 == c2 => {}
            (None, None) => return Ordering::Equal,
            (_, Some('~')) => return Ordering::Greater,
            (Some('~'), _) => return Ordering::Less,
            (None, Some(_)) => return Ordering::Less,
            (Some(_), None) => return Ordering::Greater,
            (Some(c1), Some(c2)) if c1.is_ascii_alphabetic() && !c2.is_ascii_alphabetic() => {
                return Ordering::Less
            }
            (Some(c1), Some(c2)) if !c1.is_ascii_alphabetic() && c2.is_ascii_alphabetic() => {
                return Ordering::Greater
            }
            (Some(c1), Some(c2)) => return c1.cmp(&c2),
        }
    }
}

/// Remove file endings matching the regex (\.[A-Za-z~][A-Za-z0-9~]*)*$
fn remove_file_ending(a: &str) -> &str {
    let mut ending_start = None;
    let mut prev_was_dot = false;
    for (idx, char) in a.char_indices() {
        if char == '.' {
            if ending_start.is_none() || prev_was_dot {
                ending_start = Some(idx);
            }
            prev_was_dot = true;
        } else if prev_was_dot {
            prev_was_dot = false;
            if !char.is_ascii_alphabetic() && char != '~' {
                ending_start = None;
            }
        } else if !char.is_ascii_alphanumeric() && char != '~' {
            ending_start = None;
        }
    }
    if prev_was_dot {
        ending_start = None;
    }
    if let Some(ending_start) = ending_start {
        &a[..ending_start]
    } else {
        a
    }
}

pub fn version_cmp(mut a: &str, mut b: &str) -> Ordering {
    let str_cmp = a.cmp(b);
    if str_cmp == Ordering::Equal {
        return str_cmp;
    }

    // Special cases:
    // 1. Empty strings
    match (a.is_empty(), b.is_empty()) {
        (true, false) => return Ordering::Less,
        (false, true) => return Ordering::Greater,
        (true, true) => unreachable!(),
        (false, false) => {}
    }
    // 2. Dots
    match (a == ".", b == ".") {
        (true, false) => return Ordering::Less,
        (false, true) => return Ordering::Greater,
        (true, true) => unreachable!(),
        (false, false) => {}
    }
    // 3. Two Dots
    match (a == "..", b == "..") {
        (true, false) => return Ordering::Less,
        (false, true) => return Ordering::Greater,
        (true, true) => unreachable!(),
        (false, false) => {}
    }
    // 4. Strings starting with a dot
    match (a.starts_with('.'), b.starts_with('.')) {
        (true, false) => return Ordering::Less,
        (false, true) => return Ordering::Greater,
        (true, true) => {
            // Strip the leading dot for later comparisons
            a = &a[1..];
            b = &b[1..];
        }
        _ => {}
    }

    // Try to strip file extensions
    let (mut a, mut b) = match (remove_file_ending(a), remove_file_ending(b)) {
        (a_stripped, b_stripped) if a_stripped == b_stripped => {
            // If both would be the same after stripping file extensions, don't strip them.
            (a, b)
        }
        stripped => stripped,
    };

    // 1. Compare leading non-numerical part
    // 2. Compare leading numerical part
    // 3. Repeat
    loop {
        let a_numerical_start = a.find(|c: char| c.is_ascii_digit()).unwrap_or(a.len());
        let b_numerical_start = b.find(|c: char| c.is_ascii_digit()).unwrap_or(b.len());

        let a_str = &a[..a_numerical_start];
        let b_str = &b[..b_numerical_start];

        match version_non_digit_cmp(a_str, b_str) {
            Ordering::Equal => {}
            ord => return ord,
        }

        a = &a[a_numerical_start..];
        b = &b[a_numerical_start..];

        let a_numerical_end = a.find(|c: char| !c.is_ascii_digit()).unwrap_or(a.len());
        let b_numerical_end = b.find(|c: char| !c.is_ascii_digit()).unwrap_or(b.len());

        let a_str = a[..a_numerical_end].trim_start_matches('0');
        let b_str = b[..b_numerical_end].trim_start_matches('0');

        match a_str.len().cmp(&b_str.len()) {
            Ordering::Equal => {}
            ord => return ord,
        }

        match a_str.cmp(b_str) {
            Ordering::Equal => {}
            ord => return ord,
        }

        a = &a[a_numerical_end..];
        b = &b[b_numerical_end..];

        if a.is_empty() && b.is_empty() {
            // Default to the lexical comparison.
            return str_cmp;
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::version_cmp::version_cmp;
    use std::cmp::Ordering;
    #[test]
    fn test_version_cmp() {
        // Identical strings
        assert_eq!(version_cmp("hello", "hello"), Ordering::Equal);

        assert_eq!(version_cmp("file12", "file12"), Ordering::Equal);

        assert_eq!(
            version_cmp("file12-suffix", "file12-suffix"),
            Ordering::Equal
        );

        assert_eq!(
            version_cmp("file12-suffix24", "file12-suffix24"),
            Ordering::Equal
        );

        // Shortened names
        assert_eq!(version_cmp("world", "wo"), Ordering::Greater,);

        assert_eq!(version_cmp("hello10wo", "hello10world"), Ordering::Less,);

        // Simple names
        assert_eq!(version_cmp("world", "hello"), Ordering::Greater,);

        assert_eq!(version_cmp("hello", "world"), Ordering::Less);

        assert_eq!(version_cmp("apple", "ant"), Ordering::Greater);

        assert_eq!(version_cmp("ant", "apple"), Ordering::Less);

        // Uppercase letters
        assert_eq!(
            version_cmp("Beef", "apple"),
            Ordering::Less,
            "Uppercase letters are sorted before all lowercase letters"
        );

        assert_eq!(version_cmp("Apple", "apple"), Ordering::Less);

        assert_eq!(version_cmp("apple", "aPple"), Ordering::Greater);

        // Numbers
        assert_eq!(
            version_cmp("100", "20"),
            Ordering::Greater,
            "Greater numbers are greater even if they start with a smaller digit",
        );

        assert_eq!(
            version_cmp("20", "20"),
            Ordering::Equal,
            "Equal numbers are equal"
        );

        assert_eq!(
            version_cmp("15", "200"),
            Ordering::Less,
            "Small numbers are smaller"
        );

        // Comparing numbers with other characters
        assert_eq!(
            version_cmp("1000", "apple"),
            Ordering::Less,
            "Numbers are sorted before other characters"
        );

        assert_eq!(
            // spell-checker:disable-next-line
            version_cmp("file1000", "fileapple"),
            Ordering::Less,
            "Numbers in the middle of the name are sorted before other characters"
        );

        // Leading zeroes
        assert_eq!(
            version_cmp("012", "12"),
            Ordering::Less,
            "A single leading zero can make a difference"
        );

        assert_eq!(
            version_cmp("000800", "0000800"),
            Ordering::Greater,
            "Leading number of zeroes is used even if both non-zero number of zeros"
        );

        // Numbers and other characters combined
        assert_eq!(version_cmp("ab10", "aa11"), Ordering::Greater);

        assert_eq!(
            version_cmp("aa10", "aa11"),
            Ordering::Less,
            "Numbers after other characters are handled correctly."
        );

        assert_eq!(
            version_cmp("aa2", "aa100"),
            Ordering::Less,
            "Numbers after alphabetical characters are handled correctly."
        );

        assert_eq!(
            version_cmp("aa10bb", "aa11aa"),
            Ordering::Less,
            "Number is used even if alphabetical characters after it differ."
        );

        assert_eq!(
            version_cmp("aa10aa0010", "aa11aa1"),
            Ordering::Less,
            "Second number is ignored if the first number differs."
        );

        assert_eq!(
            version_cmp("aa10aa0010", "aa10aa1"),
            Ordering::Greater,
            "Second number is used if the rest is equal."
        );

        assert_eq!(
            version_cmp("aa10aa0010", "aa00010aa1"),
            Ordering::Greater,
            "Second number is used if the rest is equal up to leading zeroes of the first number."
        );

        assert_eq!(
            version_cmp("aa10aa0022", "aa010aa022"),
            Ordering::Greater,
            "The leading zeroes of the first number has priority."
        );

        assert_eq!(
            version_cmp("aa10aa0022", "aa10aa022"),
            Ordering::Less,
            "The leading zeroes of other numbers than the first are used."
        );

        assert_eq!(
            version_cmp("file-1.4", "file-1.13"),
            Ordering::Less,
            "Periods are handled as normal text, not as a decimal point."
        );

        // Greater than u64::Max
        // u64 == 18446744073709551615 so this should be plenty:
        //        20000000000000000000000
        assert_eq!(
            version_cmp("aa2000000000000000000000bb", "aa002000000000000000000001bb"),
            Ordering::Less,
            "Numbers larger than u64::MAX are handled correctly without crashing"
        );

        assert_eq!(
            version_cmp("aa2000000000000000000000bb", "aa002000000000000000000000bb"),
            Ordering::Greater,
            "Leading zeroes for numbers larger than u64::MAX are \
            handled correctly without crashing"
        );

        assert_eq!(
            version_cmp("  a", "a"),
            Ordering::Greater,
            "Whitespace is after letters because letters are before non-letters"
        );

        assert_eq!(
            version_cmp("a~", "ab"),
            Ordering::Less,
            "A tilde is before other letters"
        );

        assert_eq!(
            version_cmp("a~", "a"),
            Ordering::Less,
            "A tilde is before the line end"
        );
        assert_eq!(
            version_cmp("~", ""),
            Ordering::Greater,
            "A tilde is after the empty string"
        );
        assert_eq!(
            version_cmp(".f", ".1"),
            Ordering::Greater,
            "if both start with a dot it is ignored for the comparison"
        );

        // The following tests are incompatible with GNU as of 2021/06.
        // I think that's because of a bug in GNU, reported as https://lists.gnu.org/archive/html/bug-coreutils/2021-06/msg00045.html
        assert_eq!(
            version_cmp("a..a", "a.+"),
            Ordering::Less,
            ".a is stripped before the comparison"
        );
        assert_eq!(
            version_cmp("a.", "a+"),
            Ordering::Greater,
            ". is not stripped before the comparison"
        );
        assert_eq!(
            version_cmp("a\0a", "a"),
            Ordering::Greater,
            "NULL bytes are handled comparison"
        );
    }
}


text:
package networkjavaproject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TCPServer {
    public static void main(String []args){
        System.out.print("/* * * * * * * * * * * * * * * * * * * * * * * * * * */\n"
                + "\t\t T C P   S E R V E R\n"
                + "/* * * * * * * * * * * * * * * * * * * * * * * * * * */\n");

        //declare a TCP socket object and initialize it to null
        ServerSocket serverSocket = null;

        //create the port number
        int port = 1234;

        try {
            //create the TCP socket server
            serverSocket = new ServerSocket(port);
            System.out.println("TCP server created on port = "+port);

        } catch (IOException ex) {
            //will be executed when the server cannot be created
            System.out.println("Error: The server with port="+port+" cannot be created");
        }

        //starts an endless loop
        while(true){
            Socket clientSocket = null;

            try {
                //start listening to incoming client request (blocking function)
                System.out.println("[TCP Server] waiting for the incoming request ...");
                clientSocket = serverSocket.accept();

            } catch (IOException e) {
                System.out.println("Error: cannot accept client request. Exit program");
                return;
            }

            try {
                processClientRequest(clientSocket);

            } catch (IOException e) {
                //log exception and go on to next request.
            }
        }

    }

    public static void processClientRequest(Socket clientSocket) throws IOException {
        System.out.println("[TCP Server] processing the incoming request");
        try {
            PrintStream printStream = new PrintStream(clientSocket.getOutputStream());
            InputStreamReader inputStream = new InputStreamReader(clientSocket.getInputStream());

            //read the received message
            BufferedReader bufferedReader = new BufferedReader(inputStream);
            String message = null;
            message = bufferedReader.readLine();

            System.out.println("message received from client: \n\t"+message);

            //prepare the String.
            //WARNING: add \n to make sure that the message is considered as one line
            String messageSend = "Hello World From TCP Server!\n";
            printStream.println(messageSend);
            printStream.close();

        }catch (Exception e){
            System.out.print("[TCP Server] The server cannot send the message");
        }
    }

    public static void processClientRequestHTML(Socket clientSocket) throws IOException {
        InputStream  input  = clientSocket.getInputStream();
        OutputStream output = clientSocket.getOutputStream();
        long time = System.currentTimeMillis();

        output.write(("HTTP/1.1 200 OK\n\n" +
                "Singlethreaded Server: " +
                time +
                "
Testing 1 2 3
").getBytes());
        output.close();
        input.close();

        System.out.println("Request processed: " + time);
    }

}

redpajama_set_name: RedPajamaGithub


text:
function printfg(hFig, name, output, resize, prop)
%PRINTFG Print figure to a file using specified format
%
%   Prints the figure with the handle hfig to a file at the specified size
%   using a supported format. If a style is provided, then this function will
%   try to apply the corresponding properties to every axis, line, label,
%   title and legend object found under figure hfig.
%
%   PRINTFG(hfig, 'filename', output)
%   PRINTFG(hfig, 'filename', output, [width, height])
%   PRINTFG(hfig, 'filename', output, [width, height], prop)
%
%   Arguments:
%       hFig    : Figure handle to print
%       name    : Output filename without extension
%       output  : Cell array of output formats
%       width   : Printing width (points by default)
%       height  : Printing height (points by default)
%       prop    : Struct array of figure properties to be overloaded
%
%   Examples:
%       printfg(hf1, 'figure1', 'png', [350 275]);
%       printfg(hf1, 'figure1', {'eps', 'png'}, [350 275]);
%       printfg(hf2, 'figure2', {'eps', 'png'}, [350 275], prop);
%
%   License:
%       MIT License (http://opensource.org/licenses/MIT)
%       Copyright (c) 2015 José L. Corrales <https://github.com/jlcorra>
%

%% Arguments
if nargin <= 2
    error('Requires handle to figure, filename and extension.');
end
if length(hFig) > 1 || ~isgraphics(hFig)
    error('Figure handle must be a single valid graphic object.');
end
if ~exist('resize', 'var')
    resize = [];
elseif ~isempty(resize) && length(resize) ~= 2
    error(['Print size must be a 2-element vector containing ',...
        'width and height.']);
end
if ~exist('prop', 'var')
    prop = struct();
end

% Make sure output is a cell array of strings
output = cellstr(output);

%% Recover figure handles
% Axis handles
% Filter legend & colorbar handles on MATLAB R2014a and earlier
if verLessThan('matlab','8.4.0')
    hAx = findobj(hFig, 'Type', 'Axes', '-not', 'Tag', 'legend',...
        '-not', 'Tag', 'colorbar');
else
    hAx = findobj(hFig, 'Type', 'Axes');
end

% Line handles
hLine = findobj(hAx, 'Type', 'Line');

% Legend handles
% On MATLAB R2014b and higher, legends have their own graphic object type
if verLessThan('matlab','8.4.0')
    hLeg = findobj(hFig, 'Type', 'Axes', 'Tag', 'legend');
else
    hLeg = findobj(hFig, 'Type', 'Legend');
end

%% Size properties
% Paper size and position properties need to be specified in order [!]
% i.e. units must be applied before corresponding numerical values
if isempty(resize)
    set(hFig, 'PaperPositionMode', 'auto');
    % Ensure paper size adjusts to figure size (no whitespace)
    paperp = get(hFig, 'PaperPosition');
    resize = [paperp(3), paperp(4)];
else
    defs.Figure.PaperUnits = 'points';
end

defs.Figure.PaperSize = [resize(1), resize(2)];
defs.Figure.PaperPositionMode = 'manual';
defs.Figure.PaperPosition = [0, 0, resize(1), resize(2)];

%% Figure properties
if isfield(prop, 'Figure')
    % Find fields that were defined or overriden by the user
    fn = fieldnames(prop.Figure);
    % Merge into defs.Figure to ensure fields follow correct order
    % PaperUnits, PaperSize, PaperPositionMode, PaperPosition, ...
    for k = 1:length(fn)
        defs.Figure.(fn{k}) = prop.Figure.(fn{k});
    end
end
set(hFig, defs.Figure);

%% Plot lines & markers
if isfield(prop, 'Line')
    set(hLine, prop.Line);
end

%% Axis lines, ticks & tick labels
% [!] Axis font is also applied to legends and labels, depending on MATLAB
% version
if isfield(prop, 'Axes')
    set(hAx, prop.Axes);
end

%% Labels
if isfield(prop, 'XLabel')
    for n = 1:length(hAx)
        set(get(hAx(n), 'XLabel'), prop.XLabel);
    end
end
if isfield(prop, 'YLabel')
    for n = 1:length(hAx)
        set(get(hAx(n), 'YLabel'), prop.YLabel);
    end
end
if isfield(prop, 'ZLabel')
    for n = 1:length(hAx)
        set(get(hAx(n), 'ZLabel'), prop.ZLabel);
    end
end

%% Title
if isfield(prop, 'Title')
    for n = 1:length(hAx)
        set(get(hAx(n), 'Title'), prop.Title);
    end
end

%% Legend
if isfield(prop, 'Legend')
    set(hLeg, prop.Legend);
end

%% Remove additional whitespace margins
% Undocumented property, might cause some issues with the LaTeX interpreter
LooseInset = get(hAx, {'LooseInset'});
set(hAx, {'LooseInset'}, get(hAx, {'TightInset'}));

%% Print figure to file
for i = 1:length(output)
    switch output{i}
        case 'pdf'
            print(hFig, name, '-dpdf', '-painters');
        case {'eps','epsc','eps2','epsc2'}
            % Workaround R2014b issues with PostScript printing margins
            if verLessThan('matlab','8.4.0')
                print(hFig, name, ['-d',output{i}], '-painters');
            else
                print(hFig, name, ['-d',output{i}],...
                    '-loose', '-painters');
            end
        case {'png','tiff','tiffn','bmpmono','bmp','bmp16m','bmp256'}
            % Use 300dpi resolution for bitmap output types
            print(hFig, name, ['-d',output{i}], '-r300');
        otherwise
            % Fallback to saveas() on other output types
            saveas(hFig, name, output{i});
    end
end

%% Restore whitespace margins
set(hAx, {'LooseInset'}, LooseInset);


text:
# AMP Access and Analytics

## Access analytics triggers

Access service issues events for major states in the access flow. These events can be reported through the analytics configuration by using triggers.

See [amp-analytics.md](../amp-analytics/amp-analytics.md) for details on *amp-analytics* configuration.

### Authorization received trigger (`"on": "access-authorization-received"`)

The `access-authorization-received` event is issued when the Authorization endpoint has succeeded. Use these configurations to fire a request for this event.

```javascript
"triggers": {
  "accessAuthorizationReceived": {
    "on": "access-authorization-received",
    "request": "event"
  }
}
```

### Authorization received trigger (`"on": "access-authorization-failed"`)

The `access-authorization-failed` event is issued when the Authorization endpoint has failed. Use these configurations to fire a request for this event.

```javascript
"triggers": {
  "accessAuthorizationFailed": {
    "on": "access-authorization-failed",
    "request": "event"
  }
}
```

### Access view registered trigger (`"on": "access-viewed"`)

The `access-viewed` event is issued when the access system considers the page viewed and right before pingback is sent. Use these configurations to fire a request for this event.

```javascript
"triggers": {
  "accessViewed": {
    "on": "access-viewed",
    "request": "event"
  }
}
```

### Pingback sent trigger (`"on": "access-pingback-sent"`)

The `access-pingback-sent` event is issued when the Pingback endpoint has succeeded. Use these configurations to fire a request for this event.

```javascript
"triggers": {
  "accessPingbackSent": {
    "on": "access-pingback-sent",
    "request": "event"
  }
}
```

### Pingback failed trigger (`"on": "access-pingback-failed"`)

The `access-pingback-failed` event is issued when the Pingback endpoint has failed. Use these configurations to fire a request for this event.

```javascript
"triggers": {
  "accessPingbackFailed": {
    "on": "access-pingback-failed",
    "request": "event"
  }
}
```

### Login started trigger (`"on": "access-login[-type]-started"`)

The `access-login[-type]-started` event is issued right before the Login dialog has been opened. Use these configurations to fire a request for this event.

When only one Login URL is configured, the event is `access-login-started`. When multiple Login URLs are configured, the event is `access-login-type-started`, e.g. "access-login-signup-started". See [Login Page Spec](./amp-access-spec.md#login-page) for more info.

```javascript
"triggers": {
  "accessLoginStarted": {
    "on": "access-login-started",
    "request": "event"
  }
}
```

### Login success trigger (`"on": "access-login[-type]-success"`)

The `access-login[-type]-success` event is issued when Login dialog has succeeded. Use these configurations to fire a request for this event.

When only one Login URL is configured, the event is `access-login-success`. When multiple Login URLs are configured, the event is `access-login-type-success`, e.g. "access-login-signup-success". See [Login Page Spec](./amp-access-spec.md#login-page) for more info.

```javascript
"triggers": {
  "accessLoginSuccess": {
    "on": "access-login-success",
    "request": "event"
  }
}
```

### Login rejected trigger (`"on": "access-login[-type]-rejected"`)

The `access-login[-type]-rejected` event is issued when Login dialog has been rejected by the user. Use these configurations to fire a request for this event.

When only one Login URL is configured, the event is `access-login-rejected`. When multiple Login URLs are configured, the event is `access-login-type-rejected`, e.g. "access-login-signup-rejected". See [Login Page Spec](./amp-access-spec.md#login-page) for more info.

```javascript
"triggers": {
  "accessLoginRejected": {
    "on": "access-login-rejected",
    "request": "event"
  }
}
```

### Login failed trigger (`"on": "access-login[-type]-failed"`)

The `access-login[-type]-failed` event is issued when Login dialog has failed due to an unknown reason. Use these configurations to fire a request for this event.

When only one Login URL is configured, the event is `access-login[-type]-failed`. When multiple Login URLs are configured, the event is `access-login-type-failed`, e.g. "access-login-signup-failed". See [Login Page Spec](./amp-access-spec.md#login-page) for more info.

```javascript
"triggers": {
  "accessLoginFailed": {
    "on": "access-login-failed",
    "request": "event"
  }
}
```

## Access analytics variables

Access contributes the following URL substitutions to the [amp-var-substitutions.md](/spec/amp-var-substitutions.md).

### ACCESS_READER_ID

The `ACCESS_READER_ID` variable is substituted with the Reader ID used for access operations. This is a sensitive ID and care should be taken in sharing it. Please ensure that any data you pass to a third party complies with its terms of service.

### AUTHDATA(field)

The `AUTHDATA(field)` variable is substituted with the value of the field in the authorization response. The nested fields are allowed, such as `AUTHDATA(nested.field)`.

This variable will wait until authorization is complete before being available.

Data contained in `AUTHDATA` may be sensitive and care should be taken in sharing it. Please ensure that any data you pass to a third party complies with its terms of service.


text:
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="style.css">

        Select a File to Upload

        <input type="file" ng-model-instant id="fileToUpload" name="filename" multiple onchange="angular.element(this).scope().setFiles(this)" />

{{dropText}}

            {{file.webkitRelativePath || file.name}}
            ( 1024*1024">
                {{file.size / 1024 / 1024 | number:2}} MB
                {{file.size / 1024 | number:2}} kB
            )

        <input type="button" ng-click="uploadFile()" value="Upload" />

{{progress}}%


text:
    {{ Form::label('title', 'Title') }}
    {{ Form::text('title', null, ['class' => 'form-control']) }}
    {{ $errors->first('title', ':message')}}

    {{ Form::label('description', 'Description') }}
    {{ Form::textarea('description', null, ['class' => 'form-control']) }}
    {{ $errors->first('description', ':message')}}

<button type="submit" class="btn btn-success">
     {{ isset($buttonText) ? $buttonText : "Create Category" }}
</button>
<button type="reset" class="btn">Reset</button>


text:
import datetime
import operator
import storymarket
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.generic import GenericForeignKey
from . import converters
from . import managers

STORYMARKET_TYPES = ("audio", "data", "photo", "text", "video")
STORYMARKET_TYPE_CHOICES = [(t, t) for t in STORYMARKET_TYPES]

def _ct(model):
    """Shortcut for getting a content type for a model."""
    return ContentType.objects.get_for_model(model)

class SyncedObject(models.Model):
    """
    Tracks an object that's been synced to Storymarket.
    """
    # The Django object that's been synced.
    content_type = models.ForeignKey(ContentType, related_name='storymarket_synced_objects')
    object_pk    = models.TextField()
    object       = GenericForeignKey('content_type', 'object_pk')

    # The Storymarket content object that's been synced to.
    storymarket_type = models.CharField(max_length=50, choices=STORYMARKET_TYPE_CHOICES)
    storymarket_id   = models.PositiveIntegerField()

    # For ease of local reference, the related org/category/etc.
    tags     = models.CharField(max_length=500)
    org      = models.PositiveIntegerField()
    category = models.PositiveIntegerField()
    pricing  = models.PositiveIntegerField(blank=True, null=True)
    rights   = models.PositiveIntegerField(blank=True, null=True)

    # When we last did a sync.
    last_updated = models.DateTimeField(default=datetime.datetime.now)

    objects = managers.SyncedObjectManager()

    def __unicode__(self):
        return "%s synced as %s ID=%s" % (self.object, self.storymarket_type, self.storymarket_id)

class AutoSyncedModel(models.Model):
    """
    A model that should be auto-synced to Storymarket, perhaps upon
    matching some associated sync rules.
    """
    content_type = models.ForeignKey(ContentType,
                                     related_name='storymarket_autosynced_models',
                                     limit_choices_to=models.Q(
                                        id__in=lambda: [_ct(m).id for m in converters.registered_models()]
                                     ))
    enabled = models.BooleanField(default=False)

    def __unicode__(self):
        return "Autosync for %s%s" % (self.content_type, "" if self.enabled else " (disabled)")

    def should_sync(self, instance):
        """
        Returns True if the given instance should be synced.
        """
        if not self.enabled or _ct(instance) != self.content_type:
            return False

        for rule in self.rules.all():
            rule_opinion = rule.should_sync(instance)
            if rule_opinion is False:
                return False

        return True

AUTO_SYNC_INCLUDE_CHOICES = (
    (True,  'include'),
    (False, 'exclude'),
)

# The stored values here are the function names in the `operator` module or
# names of string methods. They're prefixed by ! to negate the results. The
# human-readable names are stolen from iTunes' "smart playlists" -- I don't
# have money for HCI research, but Apple (hopefully) already did it for me.
AUTO_SYNC_OP_CHOICES = (
    ('eq',          'is'),
    ('ne',          'is not'),
    ('lt',          'is less than'),
    ('lte',         'is less than or equal to'),
    ('gt',          'is greater than'),
    ('gte',         'is greater than or equal to'),
    ('contains',    'contains'),
    ('!contains',   'does not contain'),
    ('startswith',  'starts with'),
    ('!startswith', 'does not start with'),
    ('endswith',    'ends with'),
    ('!endswith',   'does not end with')
)

class AutoSyncRule(models.Model):
    """
    An individual rule conditionally syncing models.

    This generates rules of the form::

        <include/exclude> instances where <field> <op> <value>

    e.g.::

        include instances where name contains 'joe'
        exclude instances where photographer_id == 14

    etc.

    Right now this only "ands" together all the rules -- there's not
    special nested rule logic. For more complicated uses, you'll need to
    listen to the model's save signal and do the sync manually.
    """
    sync_model = models.ForeignKey(AutoSyncedModel, related_name='rules')

    # Whether to include (True) or exclude (False) models matching this rule.
    include = models.BooleanField("Include?", default=True, choices=AUTO_SYNC_INCLUDE_CHOICES)

    # The field name
    # TODO: would be nice to support object traversal via dots.
    field = models.CharField("Where this field...", max_length=500)

    # The operator (contains, lessthan, etc.)
    op = models.CharField("is/is not/...", max_length=50, choices=AUTO_SYNC_OP_CHOICES)

    # The value to compare against.
    value = models.CharField("this value", max_length=250)

    def __unicode__(self):
        return "%s.%s %s '%s'" % (self.sync_model.content_type, self.field, self.op, self.value)

    def should_sync(self, instance):
        """
        Does this rule think we should sync the given instance?

        Returns ``True`` for a "yes", ``False`` for a "no", and ``None`` if
        this rule has no opinion or something went wrong.
        """
        # Try to get the value named by self.field.
        try:
            field_val = getattr(instance, self.field)
        except AttributeError:
            return None

        # Try to look up the operator function, first as a member
        # of the operator library, and then as a str method
        op_func_name = self.op.lstrip('!')
        try:
            op_func = getattr(operator, op_func_name)
        except AttributeError:
            try:
                op_func = getattr(str, op_func_name)
            except AttributeError:
                return None

        # If the op was a negative one, negate the op.
        if self.op.startswith('!'):
            op_func = lambda lhs, rhs: not op_func(lhs, rhs)

        # Try to check for a match.
        try:
            match = op_func(field_val, self.value)
        except (ValueError, TypeError):
            return None

        # Negate the match if self.include is False (and thus this is an
        # exclude rule).
        return match if self.include else not match


text:
package grpctabletconn

import (
	"net"
	"testing"
	"time"

	"google.golang.org/grpc"

	"github.com/youtube/vitess/go/vt/tabletserver/grpcqueryservice"
	"github.com/youtube/vitess/go/vt/tabletserver/tabletconntest"
	"github.com/youtube/vitess/go/vt/topo"
	"golang.org/x/net/context"
)

// This test makes sure the go rpc service works
func TestGoRPCTabletConn(t *testing.T) {
	// fake service
	service := tabletconntest.CreateFakeServer(t)

	// listen on a random port
	listener, err := net.Listen("tcp", ":0")
	if err != nil {
		t.Fatalf("Cannot listen: %v", err)
	}
	host := listener.Addr().(*net.TCPAddr).IP.String()
	port := listener.Addr().(*net.TCPAddr).Port

	// Create a gRPC server and listen on the port
	server := grpc.NewServer()
	grpcqueryservice.RegisterForTest(server, service)
	go server.Serve(listener)

	// Create a gRPC client connecting to the server
	ctx := context.Background()
	client, err := DialTablet(ctx, topo.EndPoint{
		Host: host,
		NamedPortMap: map[string]int{
			"grpc": port,
		},
	}, tabletconntest.TestKeyspace, tabletconntest.TestShard, 30*time.Second)
	if err != nil {
		t.Fatalf("dial failed: %v", err)
	}

	// run the test suite
	tabletconntest.TestSuite(t, client, service)

	// and clean up
	client.Close()
}


text:
<!doctype html>

  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="h7BaHlqi6VjlciSt0RF-KHgIXZcGfx3L3gyQ9qfx_ek" />

  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>

<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=0.4.5.2" rel="stylesheet" type="text/css" />

  <meta name="keywords" content="C," />

  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=0.4.5.2" />

<meta name="description" content="这个问题其实比较常见了,但是经常会出错,就是C中函数的参数是值传递的,即使对于指针,也是值传递。很多高级语言在这一点是相通的。 今天看到这个问题是在 c-fqa.com 上的一个问题,看下面的代码: void f(int *ip) &#123;	static int dummy = 5;	// static make dummy accessiable for whole file	ip = &a">
<meta name="keywords" content="C">
<meta property="og:type" content="article">
<meta property="og:title" content="C中使用指针作为参数的一些问题">
<meta property="og:url" content="http://blog.wuxu92.com/using-pointer-as-parameter/index.html">
<meta property="og:site_name" content="Wu Xu">
<meta property="og:description" content="这个问题其实比较常见了,但是经常会出错,就是C中函数的参数是值传递的,即使对于指针,也是值传递。很多高级语言在这一点是相通的。 今天看到这个问题是在 c-fqa.com 上的一个问题,看下面的代码: void f(int *ip) &#123;	static int dummy = 5;	// static make dummy accessiable for whole file	ip = &a">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-14T11:19:13.385Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="C中使用指针作为参数的一些问题">
<meta name="twitter:description" content="这个问题其实比较常见了,但是经常会出错,就是C中函数的参数是值传递的,即使对于指针,也是值传递。很多高级语言在这一点是相通的。 今天看到这个问题是在 c-fqa.com 上的一个问题,看下面的代码: void f(int *ip) &#123;	static int dummy = 5;	// static make dummy accessiable for whole file	ip = &a">

  <title> C中使用指针作为参数的一些问题 | Wu Xu </title>

      Wu Xu

关注C、Go、C++、JavaScript和Rust

  <button>

  </button>

            首页

            分类

            标签

            归档

            关于

                C中使用指针作为参数的一些问题

            发表于
            <time itemprop="dateCreated" datetime="2015-12-08T12:34:50+08:00" content="2015-12-08">
              2015-12-08
            </time>

                |   分类于

                    Programming

这个问题其实比较常见了,但是经常会出错,就是C中函数的参数是值传递的,即使对于指针,也是值传递。很多高级语言在这一点是相通的。

今天看到这个问题是在 c-fqa.com 上的一个问题,看下面的代码:

void f(int *ip) {
	static int dummy = 5;	// static make dummy accessiable for whole file
	ip = &dummy;
}

int *ip;
f(ip);

这时候ip指向哪里呢?实际上ip可能指向任何地址。因为ip没有初始化,传递给f函数调用的参数只是指针值的拷贝,对拷贝的修改并不会改变 ip 本身的内容。要达到本来的目的,需要传入 ip的地址,也就是指针的指针作为参数:

void f(int **ipp) {
	static int dummy = 5;	// if no static here, then ip can be anywhere, *ip can be any value
	*ip = &dummy;
}

int  *ip;
f(&ip);

另一种方法是把结果的指针作为函数的返回值,这是更常用的方式:

int *f() {
	static int dummy = 5;
	return &dummy;
}
int *ip = f();

另一个例子是,定制一个 malloc 的自己的版本:

void mymalloc(void *retp, size_t size) {
	retp = malloc(size);
	if (retp == NULL) {
		fprintf(stderr, "out of memory\n");
		exit(EXIT_FAILURE);
	}
}

看起来没有什么问题,但是在调用这个函数时并不能正常工作,因为被调用函数接受的指针是调用者传入的指针的拷贝。

C always uses pass by value. You can simulate pass by reference yourself, by defining functions which accept pointers and then using the & operator when calling, and the compiler will essentially simulate it for you when you pass an array to a function

这些内容在Java和Go中也是通用的,指针作为参数实际上也是值传递的哦。

参考:

http://c-faq.com/ptrs/passptrinit.html

http://c-faq.com/ptrs/passbyref.html

            #C

                 malloc的强制类型转换

                预处理器

            文章目录

            站点概览

wuxu

Wu Xu的个人博客

              178
              日志

              25
              分类

              148
              标签

                     GitHub

                     Twitter

                     Weibo

                     Douban

                     Zhihu

此文章未包含目录

  ©  2014 -
  2020

  wuxu

  由 Hexo 强力驱动

  主题 -

    NexT


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Periferico_model extends MY_Model {

    /**
     * Nombre de la tabla gestionada por éste modelo
     * @var string
     */
    public $_table = 'periferico';

    /**
     * Reglas de validación utilizadas
     * por la libreria MY_Model
     * para la inserción de datos en la tabla.
     * @var array
     */
    public $validate = array(
        array('field' => 'nombre', 'label' => 'Nombre', 'rules' => 'trim|required|max_length[20]'),
        array('field' => 'tipo_periferico_id', 'label' => 'Tipo', 'rules' => 'trim|required|max_length[20]'),
        array('field' => 'marca_id', 'label' => 'Marca', 'rules' => 'trim|required|max_length[20]'),
        array('field' => 'modelo_id', 'label' => 'Marca', 'rules' => 'trim|required|max_length[20]'),
        array('field' => 'serial', 'label' => 'Serial', 'rules' => 'trim|required|unique[periferico.serial]'),
        array('field' => 'estado_id', 'label' => 'Estado', 'rules' => 'trim|required'),
        array('field' => 'usuario_id', 'label' => 'Asignado', 'rules' => 'trim|required'),
    );

    /**
     * Reglas de validación utilizadas
     * por la libreria MY_Model
     * para la actualización de datos en la tabla.
     * @var array
     */
    public $validate_update = array(
        array('field' => 'nombre', 'label' => 'Nombre', 'rules' => 'trim|required|max_length[20]'),
        array('field' => 'tipo_periferico_id', 'label' => 'Tipo', 'rules' => 'trim|required|max_length[20]'),
        array('field' => 'marca_id', 'label' => 'Marca', 'rules' => 'trim|required|max_length[20]'),
        array('field' => 'modelo_id', 'label' => 'Marca', 'rules' => 'trim|required|max_length[20]'),
        array('field' => 'serial', 'label' => 'Serial', 'rules' => 'trim|required|unique[periferico.serial]'),
        array('field' => 'estado_id', 'label' => 'Estado', 'rules' => 'trim|required'),
        array('field' => 'usuario_id', 'label' => 'Asignado', 'rules' => 'trim|required'),
    );

    /**
     * Este método consulta todos los usuarios
     * y su relación con la tabla usuario_rol
     * @return array Todos los grados
     *  select C.*, TC.descripcion, MA.descripcion, PRO.descripcion, SO.descripcion, US.nombre, US.apellido, E.descripcion
     *  from computadoras C inner join tcomputadora TC on C.tcomputadora_id=TC.id
     *  inner join marca MA on C.marca_id=MA.id
     *  inner join Procesador PRO on C.Procesador_id=PRO.id
     *  inner join sistema_operativo SO on C.sistema_operativo_id=SO.id
     *  inner join usuario US on C.usuario_id=US.id
     *  inner join estado E on C.estado_id=E.id;
     */
    public function getAll() {
        return $this->db
                        ->select('P.*, MA.descripcion MAdescripcion, TP.descripcion TPdescripcion,'
                                . 'MO.descripcion MOdescripcion, '
                                . 'US.nombre USNombre, US.apellido, E.descripcion Edescripcion')
                        ->from($this->_table . ' P')
                        ->join('tperiferico TP', 'P.tipo_periferico_id=TP.id')
                        ->join('marca MA', 'P.marca_id=MA.id')
                        ->join('modelo MO', 'P.modelo_id=MO.id')
                        ->join('estado E', 'P.estado_id=E.id')
                        ->join('usuario US', 'P.usuario_id=US.id')
                        ->get()
                        ->result();
    }

    /**
     * Retorna el registro del usuario solicitado,
     * @param Int $id id del usuario
     * @return String Array
     */
    public function getDato($id) {
        return $this->db
                        ->select('P.*, MA.descripcion MAdescripcion, TP.descripcion,'
                                . 'MO.descripcion MOdescripcion, '
                                . 'US.nombre USNombre, US.apellido, E.descripcion Edescripcion')
                        ->from($this->_table . ' P')
                        ->join('tperiferico TP', 'P.tipo_periferico_id=TP.id AND P.id= ' . $id)
                        ->join('marca MA', 'P.marca_id=MA.id AND P.id= ' . $id)
                        ->join('modelo MO', 'P.modelo_id=MO.id AND P.id= ' . $id)
                        ->join('estado E', 'P.estado_id=E.id AND P.id= ' . $id)
                        ->join('usuario US', 'P.usuario_id=US.id AND P.id= ' . $id)
                        ->get()
                        ->row();
    }

    /*
     * SELECT U.*, UR.rol_id, UD.departamento_id
     * FROM ((usuario U INNER JOIN usuario_rol UR ON  UR.usuario_id = U.id )
     *  INNER JOIN usuario_departamento UD ON UD.usuario_id = U.id)
     */

    /**
     * Se crea el usuario en la tabla usuario,
     * y su respectiva relación en las tablas:
     *  - usuario_rol
     * @return Boolean
     */
    public function crear() {
        $data = array(
            'nombre' => $this->input->post('nombre'),
            'tipo_periferico_id' => $this->input->post('tipo_periferico_id'),
            'marca_id' => $this->input->post('marca_id'),
            'modelo_id' => $this->input->post('modelo_id'),
            'usuario_id' => $this->input->post('usuario_id'),
            'serial' => $this->input->post('serial'),
            'estado_id' => $this->input->post('estado_id'),
        );
        $this->db->insert('periferico', beforeInsert($data));
        $computadoras_id = $this->db->insert_id();

        /*
         * Se crea el rol para la persona
         */
        /*$this->db->insert('direccion_ip', beforeInsert(array('computadoras_id' => $computadoras_id, 'direccion_ip' => $this->input->post('direccion_ip'), 'observaciones' => $this->input->post('observaciones'))));*/

        return TRUE;
    }

    /**
     * Método para actualizar el registro del
     * usuario y reasignar.
     * @param Int $id
     * @return Boolean
     */
    public function actualizar($id) {
          $data = array(
            'nombre' => $this->input->post('nombre'),
            'tipo_periferico_id' => $this->input->post('tipo_periferico_id'),
            'marca_id' => $this->input->post('marca_id'),
            'modelo_id' => $this->input->post('modelo_id'),
            'usuario_id' => $this->input->post('usuario_id'),
            'serial' => $this->input->post('serial'),
            'estado_id' => $this->input->post('estado_id'),
        );
        $this->db->where('id', $id)->update('periferico', beforeUpdate($data));
        /*$this->db->where('computadoras_id', $id)->update('direccion_ip', beforeUpdate(array('computadoras_id' => $id, 'direccion_ip' => $this->input->post('direccion_ip'), 'observaciones' => $this->input->post('observaciones'))));*/

        return TRUE;
    }

}


text:
all: rshell

rshell:
	mkdir bin
	g++ -Wall -Werror -ansi -pedantic ./src/main.cpp -o bin/rshell

clean:
	rm -rf ./bin


text:
import("core.project.project")
import("core.tool.compiler")

-- get unix path
function _get_unix_path(filepath)
    return (path.translate(filepath):gsub('\\', '/'))
end

-- add values from target options
function _add_values_from_targetopts(values, target, name)
	for _, opt in ipairs(target:orderopts()) do
		table.join2(values, table.wrap(opt:get(name)))
	end
end

-- add values from target packages
function _add_values_from_targetpkgs(values, target, name)
    for _, pkg in ipairs(target:orderpkgs()) do
        -- uses them instead of the builtin configs if exists extra package config
        -- e.g. `add_packages("xxx", {links = "xxx"})`
        local configinfo = target:pkgconfig(pkg:name())
        if configinfo and configinfo[name] then
            table.join2(values, configinfo[name])
        else
            -- uses the builtin package configs
            table.join2(values, pkg:get(name))
        end
    end
end

-- add project info
function _add_project(cmakelists)
    cmakelists:print("# project")
    cmakelists:print("cmake_minimum_required(VERSION 3.13.0)")
    local project_name = project.name()
    if project_name then
        local project_info = ""
        local project_version = project.version()
        if project_version then
            project_info = project_info .. " VERSION " .. project_version
        end
        cmakelists:print("project(%s%s LANGUAGES C CXX ASM)", project_name, project_info)
    end
    cmakelists:print("")
end

-- add target: phony
function _add_target_phony(cmakelists, target)
    cmakelists:printf("add_custom_target(%s", target:name())
    local deps = target:get("deps")
    if deps then
        cmakelists:write(" DEPENDS")
        for _, dep in ipairs(deps) do
            cmakelists:write(" " .. dep)
        end
    end
    cmakelists:print(")")
    cmakelists:print("")
end

-- add target: binary
function _add_target_binary(cmakelists, target)
    cmakelists:print("add_executable(%s \"\")", target:name())
    cmakelists:print("set_target_properties(%s PROPERTIES OUTPUT_NAME \"%s\")", target:name(), target:basename())
    cmakelists:print("set_target_properties(%s PROPERTIES RUNTIME_OUTPUT_DIRECTORY \"%s\")", target:name(), _get_unix_path(target:targetdir()))
end

-- add target: static
function _add_target_static(cmakelists, target)
    cmakelists:print("add_library(%s STATIC \"\")", target:name())
    cmakelists:print("set_target_properties(%s PROPERTIES OUTPUT_NAME \"%s\")", target:name(), target:basename())
    cmakelists:print("set_target_properties(%s PROPERTIES ARCHIVE_OUTPUT_DIRECTORY \"%s\")", target:name(), _get_unix_path(target:targetdir()))
end

-- add target: shared
function _add_target_shared(cmakelists, target)
    cmakelists:print("add_library(%s SHARED \"\")", target:name())
    cmakelists:print("set_target_properties(%s PROPERTIES OUTPUT_NAME \"%s\")", target:name(), target:basename())
    cmakelists:print("set_target_properties(%s PROPERTIES LIBRARY_OUTPUT_DIRECTORY \"%s\")", target:name(), _get_unix_path(target:targetdir()))
end

-- add target dependencies
function _add_target_dependencies(cmakelists, target)
    local deps = target:get("deps")
    if deps then
        cmakelists:printf("add_dependencies(%s", target:name())
        for _, dep in ipairs(deps) do
            cmakelists:write(" " .. dep)
        end
        cmakelists:print(")")
    end
end

-- add target sources
function _add_target_sources(cmakelists, target)
    cmakelists:print("target_sources(%s PRIVATE", target:name())
    for _, sourcefile in ipairs(target:sourcefiles()) do
        cmakelists:print("    " .. _get_unix_path(sourcefile))
    end
    cmakelists:print(")")
end

-- add target include directories
function _add_target_include_directories(cmakelists, target)
    local includedirs = table.wrap(target:get("includedirs"))
    _add_values_from_targetopts(includedirs, target, "includedirs")
    _add_values_from_targetpkgs(includedirs, target, "includedirs")
    if #includedirs > 0 then
        cmakelists:print("target_include_directories(%s PRIVATE", target:name())
        for _, includedir in ipairs(includedirs) do
            cmakelists:print("    " .. _get_unix_path(includedir))
        end
        cmakelists:print(")")
    end

    -- TODO deprecated
    local headerdirs = target:get("headerdirs")
    if headerdirs then
        cmakelists:print("target_include_directories(%s PUBLIC", target:name())
        for _, headerdir in ipairs(headerdirs) do
            cmakelists:print("    " .. _get_unix_path(headerdir))
        end
        cmakelists:print(")")
    end
    local includedirs_interface = target:get("includedirs", {interface = true})
    if includedirs_interface then
        cmakelists:print("target_include_directories(%s INTERFACE", target:name())
        for _, headerdir in ipairs(includedirs_interface) do
            cmakelists:print("    " .. _get_unix_path(headerdir))
        end
        cmakelists:print(")")
    end
    -- export config header directory (deprecated)
    local configheader = target:configheader()
    if configheader then
        cmakelists:print("target_include_directories(%s PUBLIC %s)", target:name(), _get_unix_path(path.directory(configheader)))
    end
end

-- add target compile definitions
function _add_target_compile_definitions(cmakelists, target)
    local defines = table.wrap(target:get("defines"))
    _add_values_from_targetopts(defines, target, "defines")
    _add_values_from_targetpkgs(defines, target, "defines")
    if #defines > 0 then
        cmakelists:print("target_compile_definitions(%s PRIVATE", target:name())
        for _, define in ipairs(defines) do
            cmakelists:print("    " .. define)
        end
        cmakelists:print(")")
    end
end

-- add target compile options
function _add_target_compile_options(cmakelists, target)
    local cflags   = target:get("cflags")
    local cxflags  = target:get("cxflags")
    local cxxflags = target:get("cxxflags")
    local cuflags  = target:get("cuflags")
    if cflags or cxflags or cxxflags or cuflags then
        cmakelists:print("target_compile_options(%s PRIVATE", target:name())
        for _, flag in ipairs(cflags) do
            if compiler.has_flags("c", flag, {target = target}) then
                cmakelists:print("    $<$<COMPILE_LANGUAGE:C>:" .. flag .. ">")
            end
        end
        for _, flag in ipairs(cxflags) do
            if compiler.has_flags("c", flag, {target = target}) then
                cmakelists:print("    $<$<COMPILE_LANGUAGE:C>:" .. flag .. ">")
            end
            if compiler.has_flags("cxx", flag, {target = target}) then
                cmakelists:print("    $<$<COMPILE_LANGUAGE:CXX>:" .. flag .. ">")
            end
        end
        for _, flag in ipairs(cxxflags) do
            if compiler.has_flags("cxx", flag, {target = target}) then
                cmakelists:print("    $<$<COMPILE_LANGUAGE:CXX>:" .. flag .. ">")
            end
        end
        for _, flag in ipairs(cuflags) do
            cmakelists:print("    $<$<COMPILE_LANGUAGE:CUDA>:" .. flag .. ">")
        end
        cmakelists:print(")")
    end
end

-- add target language standards
function _add_target_language_standards(cmakelists, target)
    local cstds =
    {
        c89         = "90"
    ,   gnu89       = "90" -- TODO add cflags -std=gnu90 if supported
    ,   c99         = "99"
    ,   gnu99       = "99" -- TODO
    ,   c11         = "11"
    ,   gnu11       = "11" -- TODO
    }
    local cxxstds =
    {
        cxx98       = "98"
    ,   gnuxx98     = "98" -- TODO
    ,   cxx11       = "11"
    ,   gnuxx11     = "11"
    ,   cxx14       = "14"
    ,   gnuxx14     = "14"
    ,   cxx17       = "17"
    ,   gnuxx17     = "17"
    ,   cxx1z       = "17"
    ,   gnuxx1z     = "17"
    ,   cxx2a       = "20"
    ,   gnuxx2a     = "20"
    }
    for _, lang in ipairs(target:get("languages")) do
        local cstd = cstds[lang]
        if cstd then
            cmakelists:print("set_property(TARGET %s PROPERTY C_STANDARD %s)", target:name(), cstd)
            if cstd == "99" or cstd == "11" then
                cmakelists:print("if(MSVC)")
                cmakelists:print("    target_compile_options(%s PRIVATE $<$<COMPILE_LANGUAGE:C>:-TP>)", target:name())
                cmakelists:print("endif()")
            end
        end
        local cxxstd = cxxstds[lang]
        if cxxstd then
            cmakelists:print("set_property(TARGET %s PROPERTY CXX_STANDARD %s)", target:name(), cxxstd)
        end
    end
end

-- add target warnings
function _add_target_warnings(cmakelists, target)
    local flags_gcc =
    {
        none  = "-w"
    ,   less  = "-Wall"
    ,   more  = "-Wall"
    ,   all   = "-Wall"
    ,   error = "-Werror"
    }
    local flags_msvc =
    {
        none  = "-W0"
    ,   less  = "-W1"
    ,   more  = "-W3"
    ,   all   = "-W3" -- = "-Wall" will enable too more warnings
    ,   error = "-WX"
    }
    local warnings = target:get("warnings")
    if warnings then
        cmakelists:print("if(MSVC)")
        for _, warn in ipairs(warnings) do
            cmakelists:print("    target_compile_options(%s PRIVATE %s)", target:name(), flags_msvc[warn])
        end
        cmakelists:print("else()")
        for _, warn in ipairs(warnings) do
            cmakelists:print("    target_compile_options(%s PRIVATE %s)", target:name(), flags_gcc[warn])
        end
        cmakelists:print("endif()")
    end
end

-- add target optimization
function _add_target_optimization(cmakelists, target)
    local flags_gcc =
    {
        none       = "-O0"
    ,   fast       = "-O1"
    ,   faster     = "-O2"
    ,   fastest    = "-O3"
    ,   smallest   = "-Os"
    ,   aggressive = "-Ofast"
    }
    local flags_msvc =
    {
        none        = "$<$<CONFIG:Debug>:-Od>"
    ,   faster      = "$<$<CONFIG:Release>:-O2>"
    ,   fastest     = "$<$<CONFIG:Release>:-Ox -fp:fast>"
    ,   smallest    = "$<$<CONFIG:Release>:-O1>"
    ,   aggressive  = "$<$<CONFIG:Release>:-Ox -fp:fast>"
    }
    local optimization = target:get("optimize")
    if optimization then
        cmakelists:print("if(MSVC)")
        cmakelists:print("    target_compile_options(%s PRIVATE %s)", target:name(), flags_msvc[optimization])
        cmakelists:print("else()")
        cmakelists:print("    target_compile_options(%s PRIVATE %s)", target:name(), flags_gcc[optimization])
        cmakelists:print("endif()")
    end
end

-- add target link libraries
function _add_target_link_libraries(cmakelists, target)

    -- add links
    local links = table.wrap(target:get("links"))

    -- add links from target options
    _add_values_from_targetopts(links, target, "links")

    -- add links from target packages
    _add_values_from_targetpkgs(links, target, "links")

    -- add links from target deps
    local targetkind = target:targetkind()
    if targetkind == "binary" or targetkind == "shared" then
        for _, dep in ipairs(target:orderdeps()) do
            local depkind = dep:targetkind()
            if depkind == "static" or depkind == "shared" then
                table.insert(links, dep:name())
            end
        end
    end
    table.join2(links, target:get("syslinks"))
    if #links > 0 then
        cmakelists:print("target_link_libraries(%s PRIVATE", target:name())
        for _, link in ipairs(links) do
            cmakelists:print("    " .. link)
        end
        cmakelists:print(")")
    end
end

-- add target link directories
function _add_target_link_directories(cmakelists, target)
    local linkdirs = table.wrap(target:get("linkdirs"))
    _add_values_from_targetopts(linkdirs, target, "linkdirs")
    _add_values_from_targetpkgs(linkdirs, target, "linkdirs")
    if #linkdirs > 0 then
        cmakelists:print("target_link_directories(%s PRIVATE", target:name())
        for _, linkdir in ipairs(linkdirs) do
            cmakelists:print("    " .. _get_unix_path(linkdir))
        end
        cmakelists:print(")")
    end
end

-- add target link options
function _add_target_link_options(cmakelists, target)
    local shflags = target:get("shflags")
    local ldflags = target:get("ldflags")
    if ldflags or shflags then
        cmakelists:print("target_link_options(%s PRIVATE", target:name())
        for _, flag in ipairs(ldflags) do
            if target:linker():has_flags(flag) then
                cmakelists:print("    " .. flag)
            end
        end
        for _, flag in ipairs(shflags) do
            if target:linker():has_flags(flag) then
                cmakelists:print("    " .. flag)
            end
        end
        cmakelists:print(")")
    end
end

-- TODO export target headers (deprecated)
function _export_target_headers(target)
    local srcheaders, dstheaders = target:headers()
    if srcheaders and dstheaders then
        local i = 1
        for _, srcheader in ipairs(srcheaders) do
            local dstheader = dstheaders[i]
            if dstheader then
                os.cp(srcheader, dstheader)
            end
            i = i + 1
        end
    end
end

-- add target
function _add_target(cmakelists, target)

    -- add comment
    cmakelists:print("# target")

    -- is phony target?
    local targetkind = target:targetkind()
    if target:isphony() then
        return _add_target_phony(cmakelists, target)
    elseif targetkind == "binary" then
        _add_target_binary(cmakelists, target)
    elseif targetkind == "static" then
        _add_target_static(cmakelists, target)
    elseif targetkind == "shared" then
        _add_target_shared(cmakelists, target)
    else
        raise("unknown target kind %s", target:targetkind())
    end

    -- TODO export target headers (deprecated)
    _export_target_headers(target)

    -- add target dependencies
    _add_target_dependencies(cmakelists, target)

    -- add target include directories
    _add_target_include_directories(cmakelists, target)

    -- add target compile definitions
    _add_target_compile_definitions(cmakelists, target)

    -- add target language standards
    _add_target_language_standards(cmakelists, target)

    -- add target compile options
    _add_target_compile_options(cmakelists, target)

    -- add target warnings
    _add_target_warnings(cmakelists, target)

    -- add target optimization
    _add_target_optimization(cmakelists, target)

    -- add target link libraries
    _add_target_link_libraries(cmakelists, target)

    -- add target link directories
    _add_target_link_directories(cmakelists, target)

    -- add target link options
    _add_target_link_options(cmakelists, target)

    -- add target sources
    _add_target_sources(cmakelists, target)

    -- end
    cmakelists:print("")
end

-- generate cmakelists
function _generate_cmakelists(cmakelists)

    -- add project info
    _add_project(cmakelists)

    -- add targets
    for _, target in pairs(project.targets()) do
        _add_target(cmakelists, target)
    end
end

-- make
function make(outputdir)

    -- enter project directory
    local oldir = os.cd(os.projectdir())

    -- open the cmakelists
    local cmakelists = io.open(path.join(outputdir, "CMakeLists.txt"), "w")

    -- generate cmakelists
    _generate_cmakelists(cmakelists)

    -- close the cmakelists
    cmakelists:close()

    -- leave project directory
    os.cd(oldir)
end


text:
Bijector which computes Y = g(X) = exp(X).

Example Use:

```python
# Create the Y=g(X)=exp(X) transform which works only on Tensors with 1
# batch ndim and 2 event ndims (i.e., vector of matrices).
exp = Exp(batch_ndims=1, event_ndims=2)
x = [[[1., 2],
       [3, 4]],
      [[5, 6],
       [7, 8]]]
exp(x) == exp.forward(x)
log(x) == exp.inverse(x)
```

Note: the exp(.) is applied element-wise but the Jacobian is a reduction
over the event space.
- - -

#### `tf.contrib.distributions.bijector.Exp.__init__(event_ndims=0, validate_args=False, name='Exp')` {#Exp.__init__}

- - -

#### `tf.contrib.distributions.bijector.Exp.dtype` {#Exp.dtype}

dtype of `Tensor`s transformable by this distribution.

- - -

#### `tf.contrib.distributions.bijector.Exp.forward(x, name='forward', **condition_kwargs)` {#Exp.forward}

Returns the forward `Bijector` evaluation, i.e., X = g(Y).

##### Args:

*  <b>`x`</b>: `Tensor`. The input to the "forward" evaluation.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

  `Tensor`.

##### Raises:

*  <b>`TypeError`</b>: if `self.dtype` is specified and `x.dtype` is not
    `self.dtype`.
*  <b>`NotImplementedError`</b>: if `_forward` is not implemented.

- - -

#### `tf.contrib.distributions.bijector.Exp.inverse(y, name='inverse', **condition_kwargs)` {#Exp.inverse}

Returns the inverse `Bijector` evaluation, i.e., X = g^{-1}(Y).

##### Args:

*  <b>`y`</b>: `Tensor`. The input to the "inverse" evaluation.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

  `Tensor`.

##### Raises:

*  <b>`TypeError`</b>: if `self.dtype` is specified and `y.dtype` is not
    `self.dtype`.
*  <b>`NotImplementedError`</b>: if neither `_inverse` nor
    `_inverse_and_inverse_log_det_jacobian` are implemented.

- - -

#### `tf.contrib.distributions.bijector.Exp.inverse_and_inverse_log_det_jacobian(y, name='inverse_and_inverse_log_det_jacobian', **condition_kwargs)` {#Exp.inverse_and_inverse_log_det_jacobian}

Returns both the inverse evaluation and inverse_log_det_jacobian.

Enables possibly more efficient calculation when both inverse and
corresponding Jacobian are needed.

See `inverse()`, `inverse_log_det_jacobian()` for more details.

##### Args:

*  <b>`y`</b>: `Tensor`. The input to the "inverse" Jacobian evaluation.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

  `Tensor`.

##### Raises:

*  <b>`TypeError`</b>: if `self.dtype` is specified and `y.dtype` is not
    `self.dtype`.
*  <b>`NotImplementedError`</b>: if neither `_inverse_and_inverse_log_det_jacobian`
    nor {`_inverse`, `_inverse_log_det_jacobian`} are implemented.

- - -

#### `tf.contrib.distributions.bijector.Exp.inverse_log_det_jacobian(y, name='inverse_log_det_jacobian', **condition_kwargs)` {#Exp.inverse_log_det_jacobian}

Returns the (log o det o Jacobian o inverse)(y).

Mathematically, returns: `log(det(dX/dY))(Y)`. (Recall that: `X=g^{-1}(Y)`.)

Note that `forward_log_det_jacobian` is the negative of this function.

##### Args:

*  <b>`y`</b>: `Tensor`. The input to the "inverse" Jacobian evaluation.
*  <b>`name`</b>: The name to give this op.
*  <b>`**condition_kwargs`</b>: Named arguments forwarded to subclass implementation.

##### Returns:

  `Tensor`.

##### Raises:

*  <b>`TypeError`</b>: if `self.dtype` is specified and `y.dtype` is not
    `self.dtype`.
*  <b>`NotImplementedError`</b>: if neither `_inverse_log_det_jacobian` nor
    `_inverse_and_inverse_log_det_jacobian` are implemented.

- - -

#### `tf.contrib.distributions.bijector.Exp.is_constant_jacobian` {#Exp.is_constant_jacobian}

Returns true iff the Jacobian is not a function of x.

Note: Jacobian is either constant for both forward and inverse or neither.

##### Returns:

  `Boolean`.

- - -

#### `tf.contrib.distributions.bijector.Exp.name` {#Exp.name}

Returns the string name of this `Bijector`.

- - -

#### `tf.contrib.distributions.bijector.Exp.parameters` {#Exp.parameters}

Returns this `Bijector`'s parameters as a name/value dictionary.

- - -

#### `tf.contrib.distributions.bijector.Exp.shaper` {#Exp.shaper}

Returns shape object used to manage shape constraints.

- - -

#### `tf.contrib.distributions.bijector.Exp.validate_args` {#Exp.validate_args}

Returns True if Tensor arguments will be validated.


text:
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/Basic/Range.h"
#include "swift/ABI/TypeIdentity.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Runtime/Portability.h"
#include "swift/Strings.h"
#include "Private.h"

#include <vector>

#if SWIFT_OBJC_INTEROP
#include <objc/runtime.h>
#endif

using namespace swift;

Demangle::NodePointer
swift::_buildDemanglingForContext(const ContextDescriptor *context,
                                  llvm::ArrayRef<NodePointer> demangledGenerics,
                                  Demangle::Demangler &Dem) {
  unsigned usedDemangledGenerics = 0;
  NodePointer node = nullptr;

  // Walk up the context tree.
  std::vector<const ContextDescriptor *> descriptorPath;
  {
    const ContextDescriptor *parent = context;
    while (parent) {
      descriptorPath.push_back(parent);
      parent = parent->Parent;
    }
  }

  auto getGenericArgsTypeListForContext =
    [&](const ContextDescriptor *context) -> NodePointer {
      if (demangledGenerics.empty())
        return nullptr;

      auto generics = context->getGenericContext();
      if (!generics)
        return nullptr;

      auto numParams = generics->getGenericContextHeader().NumParams;
      if (numParams <= usedDemangledGenerics)
        return nullptr;

      auto genericArgsList = Dem.createNode(Node::Kind::TypeList);
      for (unsigned e = generics->getGenericContextHeader().NumParams;
           usedDemangledGenerics < e;
           ++usedDemangledGenerics) {
        genericArgsList->addChild(demangledGenerics[usedDemangledGenerics],
                                  Dem);
      }
      return genericArgsList;
    };

  for (auto component : reversed(descriptorPath)) {
    switch (auto kind = component->getKind()) {
    case ContextDescriptorKind::Module: {
      assert(node == nullptr && "module should be top level");
      auto name = llvm::cast<ModuleContextDescriptor>(component)->Name.get();
      node = Dem.createNode(Node::Kind::Module, name);
      break;
    }

    case ContextDescriptorKind::Extension: {
      auto extension = llvm::cast<ExtensionContextDescriptor>(component);
      // Demangle the extension self type.
      auto selfType = Dem.demangleType(extension->getMangledExtendedContext());
      if (selfType->getKind() == Node::Kind::Type)
        selfType = selfType->getChild(0);

      // Substitute in the generic arguments.
      auto genericArgsList = getGenericArgsTypeListForContext(component);

      if (selfType->getKind() == Node::Kind::BoundGenericEnum
          || selfType->getKind() == Node::Kind::BoundGenericStructure
          || selfType->getKind() == Node::Kind::BoundGenericClass
          || selfType->getKind() == Node::Kind::BoundGenericOtherNominalType) {
        if (genericArgsList) {
          auto substSelfType = Dem.createNode(selfType->getKind());
          substSelfType->addChild(selfType->getChild(0), Dem);
          substSelfType->addChild(genericArgsList, Dem);
          selfType = substSelfType;
        } else {
          // TODO: Use the unsubstituted type if we can't handle the
          // substitutions yet.
          selfType = selfType->getChild(0)->getChild(0);
        }
      }

      auto extNode = Dem.createNode(Node::Kind::Extension);
      extNode->addChild(node, Dem);
      extNode->addChild(selfType, Dem);

      // TODO: Turn the generic signature into a demangling as the third
      // generic argument.

      node = extNode;
      break;
    }

    case ContextDescriptorKind::Protocol: {
      auto protocol = llvm::cast<ProtocolDescriptor>(component);
      auto name = protocol->Name.get();

      auto protocolNode = Dem.createNode(Node::Kind::Protocol);
      protocolNode->addChild(node, Dem);
      auto nameNode = Dem.createNode(Node::Kind::Identifier, name);
      protocolNode->addChild(nameNode, Dem);

      node = protocolNode;
      break;
    }

    default:
      // Form a type context demangling for type contexts.
      if (auto type = llvm::dyn_cast<TypeContextDescriptor>(component)) {
        auto identity = ParsedTypeIdentity::parse(type);

        Node::Kind nodeKind;
        Node::Kind genericNodeKind;
        switch (kind) {
        case ContextDescriptorKind::Class:
          nodeKind = Node::Kind::Class;
          genericNodeKind = Node::Kind::BoundGenericClass;
          break;
        case ContextDescriptorKind::Struct:
          nodeKind = Node::Kind::Structure;
          genericNodeKind = Node::Kind::BoundGenericStructure;
          break;
        case ContextDescriptorKind::Enum:
          nodeKind = Node::Kind::Enum;
          genericNodeKind = Node::Kind::BoundGenericEnum;
          break;
        default:
          // We don't know about this kind of type. Use an "other type" mangling
          // for it.
          nodeKind = Node::Kind::OtherNominalType;
          genericNodeKind = Node::Kind::BoundGenericOtherNominalType;
          break;
        }

        // Override the node kind if this is a Clang-imported type so we give it
        // a stable mangling.
        if (identity.isCTypedef()) {
          nodeKind = Node::Kind::TypeAlias;
        } else if (nodeKind != Node::Kind::Structure &&
                   _isCImportedTagType(type, identity)) {
          nodeKind = Node::Kind::Structure;
        }

        auto typeNode = Dem.createNode(nodeKind);
        typeNode->addChild(node, Dem);
        auto nameNode = Dem.createNode(Node::Kind::Identifier,
                                       identity.getABIName());
        if (identity.isAnyRelatedEntity()) {
          auto relatedName = Dem.createNode(Node::Kind::RelatedEntityDeclName,
                                            identity.getRelatedEntityName());
          relatedName->addChild(nameNode, Dem);
          nameNode = relatedName;
        }
        typeNode->addChild(nameNode, Dem);
        node = typeNode;

        // Apply generic arguments if the context is generic.
        if (auto genericArgsList = getGenericArgsTypeListForContext(component)){
          auto unspecializedType = Dem.createNode(Node::Kind::Type);
          unspecializedType->addChild(node, Dem);

          auto genericNode = Dem.createNode(genericNodeKind);
          genericNode->addChild(unspecializedType, Dem);
          genericNode->addChild(genericArgsList, Dem);
          node = genericNode;
        }

        break;
      }

      // This runtime doesn't understand this context, or it's a context with
      // no richer runtime information available about it (such as an anonymous
      // context). Use an unstable mangling to represent the context by its
      // pointer identity.
      char addressBuf[sizeof(void*) * 2 + 1 + 1];
      snprintf(addressBuf, sizeof(addressBuf), "$%" PRIxPTR, (uintptr_t)component);

      auto anonNode = Dem.createNode(Node::Kind::AnonymousContext);
      CharVector addressStr;
      addressStr.append(addressBuf, Dem);
      auto name = Dem.createNode(Node::Kind::Identifier, addressStr);
      anonNode->addChild(name, Dem);
      anonNode->addChild(node, Dem);

      // Collect generic arguments if the context is generic.
      auto genericArgsList = getGenericArgsTypeListForContext(component);
      if (!genericArgsList)
        genericArgsList = Dem.createNode(Node::Kind::TypeList);
      anonNode->addChild(genericArgsList, Dem);

      node = anonNode;

      break;
    }
  }

  // Wrap the final result in a top-level Type node.
  auto top = Dem.createNode(Node::Kind::Type);
  top->addChild(node, Dem);
  return top;
}

// FIXME: This stuff should be merged with the existing logic in
// include/swift/Reflection/TypeRefBuilder.h as part of the rewrite
// to change stdlib reflection over to using remote mirrors.

Demangle::NodePointer
swift::_swift_buildDemanglingForMetadata(const Metadata *type,
                                         Demangle::Demangler &Dem);

static Demangle::NodePointer
_buildDemanglerForBuiltinType(const Metadata *type, Demangle::Demangler &Dem) {
#define BUILTIN_TYPE(Symbol, Name) \
  if (type == &METADATA_SYM(Symbol).base) \
    return Dem.createNode(Node::Kind::BuiltinTypeName, Name);
#include "swift/Runtime/BuiltinTypes.def"
  return nullptr;
}

/// Build a demangled type tree for a nominal type.
static Demangle::NodePointer
_buildDemanglingForNominalType(const Metadata *type, Demangle::Demangler &Dem) {
  using namespace Demangle;

  // Get the context descriptor from the type metadata.
  const TypeContextDescriptor *description;

  switch (type->getKind()) {
  case MetadataKind::Class: {
    auto classType = static_cast<const ClassMetadata *>(type);
#if SWIFT_OBJC_INTEROP
    // Peek through artificial subclasses.
    while (classType->isTypeMetadata() && classType->isArtificialSubclass())
      classType = classType->Superclass;
#endif
    description = classType->getDescription();
    break;
  }
  case MetadataKind::Enum:
  case MetadataKind::Optional: {
    auto enumType = static_cast<const EnumMetadata *>(type);
    description = enumType->Description;
    break;
  }
  case MetadataKind::Struct: {
    auto structType = static_cast<const StructMetadata *>(type);
    description = structType->Description;
    break;
  }
  case MetadataKind::ForeignClass: {
    auto foreignType = static_cast<const ForeignClassMetadata *>(type);
    description = foreignType->Description;
    break;
  }
  default:
    return nullptr;
  }

  // Gather the complete set of generic arguments that must be written to
  // form this type.
  std::vector<const Metadata *> allGenericArgs;
  gatherWrittenGenericArgs(type, description, allGenericArgs);

  // Demangle the generic arguments.
  std::vector<NodePointer> demangledGenerics;
  for (auto genericArg : allGenericArgs) {
    // When there is no generic argument, put in a placeholder.
    if (!genericArg) {
      auto placeholder = Dem.createNode(Node::Kind::Tuple);
      auto emptyList = Dem.createNode(Node::Kind::TypeList);
      placeholder->addChild(emptyList, Dem);
      auto type = Dem.createNode(Node::Kind::Type);
      type->addChild(placeholder, Dem);
      demangledGenerics.push_back(type);
      continue;
    }

    // Demangle this argument.
    auto genericArgDemangling =
      _swift_buildDemanglingForMetadata(genericArg, Dem);
    if (!genericArgDemangling)
      return nullptr;
    demangledGenerics.push_back(genericArgDemangling);
  }

  return _buildDemanglingForContext(description, demangledGenerics, Dem);
}

// Build a demangled type tree for a type.
//
// FIXME: This should use MetadataReader.h.
Demangle::NodePointer
swift::_swift_buildDemanglingForMetadata(const Metadata *type,
                                         Demangle::Demangler &Dem) {
  using namespace Demangle;

  switch (type->getKind()) {
  case MetadataKind::Class:
  case MetadataKind::Enum:
  case MetadataKind::Optional:
  case MetadataKind::Struct:
  case MetadataKind::ForeignClass:
    return _buildDemanglingForNominalType(type, Dem);
  case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
    auto objcWrapper = static_cast<const ObjCClassWrapperMetadata *>(type);
    const char *className = class_getName(objcWrapper->getObjCClassObject());

    auto module = Dem.createNode(Node::Kind::Module, MANGLING_MODULE_OBJC);
    auto node = Dem.createNode(Node::Kind::Class);
    node->addChild(module, Dem);
    node->addChild(Dem.createNode(Node::Kind::Identifier,
                                       llvm::StringRef(className)), Dem);

    return node;
#else
    assert(false && "no ObjC interop");
    return nullptr;
#endif
  }
  case MetadataKind::Existential: {
    auto exis = static_cast<const ExistentialTypeMetadata *>(type);
    auto protocols = exis->getProtocols();

    auto type_list = Dem.createNode(Node::Kind::TypeList);
    auto proto_list = Dem.createNode(Node::Kind::ProtocolList);
    proto_list->addChild(type_list, Dem);

    // The protocol descriptors should be pre-sorted since the compiler will
    // only ever make a swift_getExistentialTypeMetadata invocation using
    // its canonical ordering of protocols.

    for (auto protocol : protocols) {
#if SWIFT_OBJC_INTEROP
      if (protocol.isObjC()) {
        // The protocol name is mangled as a type symbol, with the _Tt prefix.
        StringRef ProtoName(protocol.getName());
        NodePointer protocolNode = Dem.demangleSymbol(ProtoName);

        // ObjC protocol names aren't mangled.
        if (!protocolNode) {
          auto module = Dem.createNode(Node::Kind::Module,
                                            MANGLING_MODULE_OBJC);
          auto node = Dem.createNode(Node::Kind::Protocol);
          node->addChild(module, Dem);
          node->addChild(Dem.createNode(Node::Kind::Identifier, ProtoName),
                         Dem);
          auto typeNode = Dem.createNode(Node::Kind::Type);
          typeNode->addChild(node, Dem);
          type_list->addChild(typeNode, Dem);
          continue;
        }

        // Dig out the protocol node.
        // Global -> (Protocol|TypeMangling)
        protocolNode = protocolNode->getChild(0);
        if (protocolNode->getKind() == Node::Kind::TypeMangling) {
          protocolNode = protocolNode->getChild(0); // TypeMangling -> Type
          protocolNode = protocolNode->getChild(0); // Type -> ProtocolList
          protocolNode = protocolNode->getChild(0); // ProtocolList -> TypeList
          protocolNode = protocolNode->getChild(0); // TypeList -> Type

          assert(protocolNode->getKind() == Node::Kind::Type);
          assert(protocolNode->getChild(0)->getKind() == Node::Kind::Protocol);
        } else {
          assert(protocolNode->getKind() == Node::Kind::Protocol);
        }

        type_list->addChild(protocolNode, Dem);
        continue;
      }
#endif

      auto protocolNode =
          _buildDemanglingForContext(protocol.getSwiftProtocol(), { }, Dem);
      if (!protocolNode)
        return nullptr;

      type_list->addChild(protocolNode, Dem);
    }

    if (auto superclass = exis->getSuperclassConstraint()) {
      // If there is a superclass constraint, we mangle it specially.
      auto result = Dem.createNode(Node::Kind::ProtocolListWithClass);
      auto superclassNode = _swift_buildDemanglingForMetadata(superclass, Dem);

      result->addChild(proto_list, Dem);
      result->addChild(superclassNode, Dem);
      return result;
    }

    if (exis->isClassBounded()) {
      // Check if the class constraint is implied by any of our
      // protocols.
      bool requiresClassImplicit = false;

      for (auto protocol : protocols) {
        if (protocol.getClassConstraint() == ProtocolClassConstraint::Class)
          requiresClassImplicit = true;
      }

      // If it was implied, we don't do anything special.
      if (requiresClassImplicit)
        return proto_list;

      // If the existential type has an explicit AnyObject constraint,
      // we must mangle it as such.
      auto result = Dem.createNode(Node::Kind::ProtocolListWithAnyObject);
      result->addChild(proto_list, Dem);
      return result;
    }

    // Just a simple composition of protocols.
    return proto_list;
  }
  case MetadataKind::ExistentialMetatype: {
    auto metatype = static_cast<const ExistentialMetatypeMetadata *>(type);
    auto instance = _swift_buildDemanglingForMetadata(metatype->InstanceType,
                                                      Dem);
    auto node = Dem.createNode(Node::Kind::ExistentialMetatype);
    node->addChild(instance, Dem);
    return node;
  }
  case MetadataKind::Function: {
    auto func = static_cast<const FunctionTypeMetadata *>(type);

    Node::Kind kind;
    switch (func->getConvention()) {
    case FunctionMetadataConvention::Swift:
      if (!func->isEscaping())
        kind = Node::Kind::NoEscapeFunctionType;
      else
        kind = Node::Kind::FunctionType;
      break;
    case FunctionMetadataConvention::Block:
      kind = Node::Kind::ObjCBlock;
      break;
    case FunctionMetadataConvention::CFunctionPointer:
      kind = Node::Kind::CFunctionPointer;
      break;
    case FunctionMetadataConvention::Thin:
      kind = Node::Kind::ThinFunctionType;
      break;
    }

    std::vector<std::pair<NodePointer, bool>> inputs;
    for (unsigned i = 0, e = func->getNumParameters(); i < e; ++i) {
      auto param = func->getParameter(i);
      auto flags = func->getParameterFlags(i);
      auto input = _swift_buildDemanglingForMetadata(param, Dem);

      auto wrapInput = [&](Node::Kind kind) {
        auto parent = Dem.createNode(kind);
        parent->addChild(input, Dem);
        input = parent;
      };
      switch (flags.getValueOwnership()) {
      case ValueOwnership::Default:
        /* nothing */
        break;
      case ValueOwnership::InOut:
        wrapInput(Node::Kind::InOut);
        break;
      case ValueOwnership::Shared:
        wrapInput(Node::Kind::Shared);
        break;
      case ValueOwnership::Owned:
        wrapInput(Node::Kind::Owned);
        break;
      }

      inputs.push_back({input, flags.isVariadic()});
    }

    NodePointer totalInput = nullptr;
    switch (inputs.size()) {
    case 1: {
      auto &singleParam = inputs.front();
      if (!singleParam.second) {
        totalInput = singleParam.first;
        break;
      }

      // If single parameter has a variadic marker it
      // requires a tuple wrapper.
      LLVM_FALLTHROUGH;
    }

    // This covers both none and multiple parameters.
    default:
      auto tuple = Dem.createNode(Node::Kind::Tuple);
      for (auto &input : inputs) {
        NodePointer eltType;
        bool isVariadic;
        std::tie(eltType, isVariadic) = input;

        // Tuple element := variadic-marker label? type
        auto tupleElt = Dem.createNode(Node::Kind::TupleElement);

        if (isVariadic)
          tupleElt->addChild(Dem.createNode(Node::Kind::VariadicMarker), Dem);

        if (eltType->getKind() == Node::Kind::Type) {
          tupleElt->addChild(eltType, Dem);
        } else {
          auto type = Dem.createNode(Node::Kind::Type);
          type->addChild(eltType, Dem);
          tupleElt->addChild(type, Dem);
        }

        tuple->addChild(tupleElt, Dem);
      }
      totalInput = tuple;
      break;
    }

    NodePointer parameters = Dem.createNode(Node::Kind::ArgumentTuple);
    NodePointer paramType = Dem.createNode(Node::Kind::Type);

    paramType->addChild(totalInput, Dem);
    parameters->addChild(paramType, Dem);

    NodePointer resultTy = _swift_buildDemanglingForMetadata(func->ResultType,
                                                             Dem);
    NodePointer result = Dem.createNode(Node::Kind::ReturnType);
    result->addChild(resultTy, Dem);

    auto funcNode = Dem.createNode(kind);
    if (func->throws())
      funcNode->addChild(Dem.createNode(Node::Kind::ThrowsAnnotation), Dem);
    funcNode->addChild(parameters, Dem);
    funcNode->addChild(result, Dem);
    return funcNode;
  }
  case MetadataKind::Metatype: {
    auto metatype = static_cast<const MetatypeMetadata *>(type);
    auto instance = _swift_buildDemanglingForMetadata(metatype->InstanceType,
                                                      Dem);
    auto typeNode = Dem.createNode(Node::Kind::Type);
    typeNode->addChild(instance, Dem);
    auto node = Dem.createNode(Node::Kind::Metatype);
    node->addChild(typeNode, Dem);
    return node;
  }
  case MetadataKind::Tuple: {
    auto tuple = static_cast<const TupleTypeMetadata *>(type);
    const char *labels = tuple->Labels;
    auto tupleNode = Dem.createNode(Node::Kind::Tuple);
    for (unsigned i = 0, e = tuple->NumElements; i < e; ++i) {
      auto elt = Dem.createNode(Node::Kind::TupleElement);

      // Add a label child if applicable:
      if (labels) {
        // Look for the next space in the labels string.
        if (const char *space = strchr(labels, ' ')) {
          // If there is one, and the label isn't empty, add a label child.
          if (labels != space) {
            auto eltName =
              Dem.createNode(Node::Kind::TupleElementName,
                                  llvm::StringRef(labels, space - labels));
            elt->addChild(eltName, Dem);
          }

          // Skip past the space.
          labels = space + 1;
        }
      }

      // Add the element type child.
      auto eltType =
        _swift_buildDemanglingForMetadata(tuple->getElement(i).Type, Dem);

      if (eltType->getKind() == Node::Kind::Type) {
        elt->addChild(eltType, Dem);
      } else {
        auto type = Dem.createNode(Node::Kind::Type);
        type->addChild(eltType, Dem);
        elt->addChild(type, Dem);
      }

      // Add the completed element to the tuple.
      tupleNode->addChild(elt, Dem);
    }
    return tupleNode;
  }
  case MetadataKind::HeapLocalVariable:
  case MetadataKind::HeapGenericLocalVariable:
  case MetadataKind::ErrorObject:
    break;
  case MetadataKind::Opaque:
  default: {
    if (auto builtinType = _buildDemanglerForBuiltinType(type, Dem))
      return builtinType;

    // FIXME: Some opaque types do have manglings, but we don't have enough info
    // to figure them out.
    break;
  }
  }
  // Not a type.
  return nullptr;
}

// NB: This function is not used directly in the Swift codebase, but is
// exported for Xcode support and is used by the sanitizers. Please coordinate
// before changing.
char *swift_demangle(const char *mangledName,
                     size_t mangledNameLength,
                     char *outputBuffer,
                     size_t *outputBufferSize,
                     uint32_t flags) {
  if (flags != 0) {
    swift::fatalError(0, "Only 'flags' value of '0' is currently supported.");
  }
  if (outputBuffer != nullptr && outputBufferSize == nullptr) {
    swift::fatalError(0, "'outputBuffer' is passed but the size is 'nullptr'.");
  }

  // Check if we are dealing with Swift mangled name, otherwise, don't try
  // to demangle and send indication to the user.
  if (!Demangle::isSwiftSymbol(mangledName))
    return nullptr; // Not a mangled name

  // Demangle the name.
  auto options = Demangle::DemangleOptions();
  options.DisplayDebuggerGeneratedModule = false;
  auto result =
      Demangle::demangleSymbolAsString(mangledName,
                                       mangledNameLength,
                                       options);

  // If the output buffer is not provided, malloc memory ourselves.
  if (outputBuffer == nullptr || *outputBufferSize == 0) {
    return strdup(result.c_str());
  }

  // Indicate a failure if the result does not fit and will be truncated
  // and set the required outputBufferSize.
  if (*outputBufferSize < result.length() + 1) {
    *outputBufferSize = result.length() + 1;
  }

  // Copy into the provided buffer.
  _swift_strlcpy(outputBuffer, result.c_str(), *outputBufferSize);
  return outputBuffer;
}


text:
declare interface DeviceMethodParams {
    name: string;
    payload?: any;
    responseTimeoutInSeconds?: number;
    connectTimeoutInSeconds?: number; // default is 0
}

export = DeviceMethodParams;


text:
layout: page
title: Arroyo Group Trade Fair
date: 2016-05-24
author: Robert Powers
tags: weekly links, java
status: published
summary: Nulla facilisi. Mauris a ex.
banner: images/banner/wedding.jpg
booking:
  startDate: 01/26/2019
  endDate: 01/29/2019
  ctyhocn: NYCEMHX
  groupCode: AGTF
published: true
---
Nulla et est a tortor faucibus vulputate ut eu dolor. Maecenas vulputate odio ut enim hendrerit scelerisque. Morbi dui lorem, euismod eget tristique a, sagittis id leo. Donec a bibendum lorem, gravida maximus est. Curabitur aliquet ipsum suscipit, rutrum diam sed, ullamcorper elit. Vivamus eu velit eget sem congue maximus. Donec in orci ante. Aenean at ipsum in nulla posuere condimentum non non urna. Mauris non metus eget ante imperdiet iaculis ut eget lectus. Sed suscipit rutrum justo. Etiam facilisis congue consectetur. Praesent eleifend odio quis quam condimentum, ac euismod nibh placerat. Praesent semper hendrerit ligula id iaculis. Praesent at ornare sem. Praesent lacinia malesuada aliquam.

* Praesent ac risus pulvinar, pretium tellus pulvinar, tincidunt est
* Donec quis sem imperdiet, faucibus odio eget, pellentesque ipsum
* In molestie ante a est faucibus suscipit
* Etiam porttitor purus sit amet cursus tempus.

Duis venenatis volutpat ante, vitae molestie dui tristique et. Aliquam erat volutpat. Vestibulum tempor, metus sed pretium tincidunt, nisi felis vulputate felis, a eleifend urna orci viverra velit. In porttitor nisi at aliquet vestibulum. Integer enim nisl, vehicula id aliquet posuere, semper eu urna. Donec ac turpis gravida, venenatis urna non, euismod augue. Ut viverra mollis libero id aliquam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Phasellus ullamcorper mauris et nulla convallis, non sodales enim ultricies. Pellentesque malesuada augue id erat sollicitudin facilisis. Praesent sit amet porttitor sem. Nam commodo rhoncus lectus elementum consequat. Integer eu libero vitae leo rhoncus rhoncus. Aliquam erat volutpat.


text:
/* global chai */

'use strict';

import Selector from '../src/Selector';

const expect = chai.expect;

describe( 'Selector', () => {
	it( 'is a class', () => {
		expect( Selector ).to.be.a( 'function' );
	} );

	it( 'creates properties based on parameters passed to the constructor', () => {
		const selector = new Selector( 'bem', 'css' );

		expect( selector.BEM ).to.equal( 'bem' );
		expect( selector.CSS ).to.equal( 'css' );
	} );

	it( 'creates immutable instances', () => {
		const selector = new Selector( 'bem', 'css' );

		expect( selector ).to.be.frozen;
	} );
} );


text:
package de.mickare.xserver.net;

import java.io.IOException;
import java.util.Collection;
import java.util.Queue;

public interface Connection {

  public enum Status {
    disconnected(true), connecting(false), connected(false), error(true);

    private final boolean finished;

    private Status(boolean finished) {
      this.finished = finished;
    }

    public boolean isFinished() {
      return finished;
    }
  }

  public abstract void ping(Ping ping) throws InterruptedException, IOException;

  public abstract boolean isSocketOpen();

  public abstract void disconnect();

  public abstract void errorDisconnect();

  public abstract String getHost();

  public abstract int getPort();

  public abstract boolean send(Packet packet);

  public abstract boolean sendAll(Collection<Packet> packets);

  public abstract Status getStatus();

  public abstract XServer getXserver();

  public abstract Queue<Packet> getPendingPackets();

  public abstract boolean isLoggedIn();

  public abstract boolean isLoggingIn();

  public abstract String toString();

  public abstract long getSendingRecordSecondPackageCount();

  public abstract long getSendinglastSecondPackageCount();

  public abstract long getReceivingRecordSecondPackageCount();

  public abstract long getReceivinglastSecondPackageCount();

}