text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `each_child_of_item` fn in crate `rustc`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, each_child_of_item">

    <title>rustc::metadata::csearch::each_child_of_item - Rust</title>

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

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

rustc::<wbr>metadata::<wbr>csearch

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Function rustc::<wbr>metadata::<wbr>csearch::<wbr>each_child_of_item<wbr>Unstable
            [-] [+]
        [src]

pub fn each_child_of_item<F>(cstore: &CStore, def_id: DefId, callback: F) where F: FnMut(DefLike, Name, Visibility)

Iterates over each child of the given item.

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
.class public Lorg/apache/http/client/methods/HttpPost;
.super Lorg/apache/http/client/methods/HttpEntityEnclosingRequestBase;
.source "HttpPost.java"

# static fields
.field public static final METHOD_NAME:Ljava/lang/String; = "POST"

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 66
    invoke-direct {p0}, Lorg/apache/http/client/methods/HttpEntityEnclosingRequestBase;-><init>()V

    .line 67
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;)V
    .locals 1
    .param p1, "uri"    # Ljava/lang/String;

    .prologue
    .line 78
    invoke-direct {p0}, Lorg/apache/http/client/methods/HttpEntityEnclosingRequestBase;-><init>()V

    .line 81
    if-nez p1, :cond_0

    .line 82
    new-instance v0, Ljava/lang/IllegalArgumentException;

    invoke-direct {v0}, Ljava/lang/IllegalArgumentException;-><init>()V

    throw v0

    .line 84
    :cond_0
    invoke-static {p1}, Ljava/net/URI;->create(Ljava/lang/String;)Ljava/net/URI;

    move-result-object v0

    invoke-virtual {p0, v0}, Lorg/apache/http/client/methods/HttpPost;->setURI(Ljava/net/URI;)V

    .line 85
    return-void
.end method

.method public constructor <init>(Ljava/net/URI;)V
    .locals 0
    .param p1, "uri"    # Ljava/net/URI;

    .prologue
    .line 70
    invoke-direct {p0}, Lorg/apache/http/client/methods/HttpEntityEnclosingRequestBase;-><init>()V

    .line 71
    invoke-virtual {p0, p1}, Lorg/apache/http/client/methods/HttpPost;->setURI(Ljava/net/URI;)V

    .line 72
    return-void
.end method

# virtual methods
.method public getMethod()Ljava/lang/String;
    .locals 1

    .prologue
    .line 89
    const-string v0, "POST"

    return-object v0
.end method

redpajama_set_name: RedPajamaGithub


text:
<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description>to run pip_install_requirements, run the jenkins job named the same</description>
  <logRotator>
    <daysToKeep>14</daysToKeep>
    <numToKeep>-1</numToKeep>
    <artifactDaysToKeep>-1</artifactDaysToKeep>
    <artifactNumToKeep>-1</artifactNumToKeep>
  </logRotator>
  <keepDependencies>false</keepDependencies>
  <properties>
    <com.coravy.hudson.plugins.github.GithubProjectProperty>
      <projectUrl>http://github.com/canvasnetworks/canvas/</projectUrl>
    </com.coravy.hudson.plugins.github.GithubProjectProperty>
  </properties>
  <scm class="hudson.plugins.git.GitSCM">
    <configVersion>2</configVersion>
    <userRemoteConfigs>
      <hudson.plugins.git.UserRemoteConfig>
        <name>origin</name>
        <refspec>+refs/heads/*:refs/remotes/origin/*</refspec>
        <url>git@github.com:canvasnetworks/canvas.git</url>
      </hudson.plugins.git.UserRemoteConfig>
    </userRemoteConfigs>
    <branches>
      <hudson.plugins.git.BranchSpec>
        <name>master</name>
      </hudson.plugins.git.BranchSpec>
    </branches>
    <recursiveSubmodules>false</recursiveSubmodules>
    <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations>
    <authorOrCommitter>false</authorOrCommitter>
    <clean>false</clean>
    <wipeOutWorkspace>false</wipeOutWorkspace>
    <pruneBranches>false</pruneBranches>
    <remotePoll>false</remotePoll>
    <buildChooser class="hudson.plugins.git.util.DefaultBuildChooser"/>
    <gitTool>Default</gitTool>
    <submoduleCfg class="list"/>
    <relativeTargetDir></relativeTargetDir>
    <excludedRegions></excludedRegions>
    <excludedUsers></excludedUsers>
    <gitConfigName></gitConfigName>
    <gitConfigEmail></gitConfigEmail>
    <skipTag>false</skipTag>
    <scmName></scmName>
  </scm>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers class="vector">
    <hudson.triggers.TimerTrigger>
      <spec>30 * * * *</spec>
    </hudson.triggers.TimerTrigger>
  </triggers>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command>fab -P --fabfile=$WORKSPACE/deploy/jenkins/fabfile.py update_search_index:age=1</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers/>
  <buildWrappers/>
</project>


text:
//
//  JSBridgeManager.m
//  Pods
//
//  Created by ryan on 4/25/16.
//
//

#import "JSBridge.h"
#import "JSBridgeModule.h"

static NSMutableArray<Class> *JSModuleClasses;
NSArray<Class> *JSGetModuleClasses(void);
NSArray<Class> *JSGetModuleClasses(void)
{
    return JSModuleClasses;
}

/**
 * Register the given class as a bridge module. All modules must be registered
 * prior to the first bridge initialization.
 */
void JSRegisterModule(Class);
void JSRegisterModule(Class moduleClass)
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        JSModuleClasses = [NSMutableArray new];
    });

    if (![moduleClass conformsToProtocol:@protocol(JSBridgeModule)]) {
        NSLog(@"%@ does not conform to the JSBridgeModule protocol",
              moduleClass);
    }

    // Register module
    [JSModuleClasses addObject:moduleClass];
}

@interface JSBridge ()

@property (nonatomic, strong) NSMutableArray *modules;

@end

@implementation JSBridge

static JSBridge *JSCurrentBridgeInstance = nil;

+ (instancetype)currentBridge {
    return JSCurrentBridgeInstance;
}

+ (void)setCurrentBridge:(JSBridge *)bridge {
    JSCurrentBridgeInstance = bridge;
}

+ (instancetype)sharedBridge {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        JSCurrentBridgeInstance = [[JSBridge alloc] init];
    });
    return JSCurrentBridgeInstance;
}

- (instancetype)init {
    if (self = [super init]) {
        _modules = [NSMutableArray array];
    }
    return self;
}

- (void)addJSModule:(id<JSBridgeModule>)module {
    [_modules addObject:module];
    [self setBridgeForInstance:module];
}

- (void)removeJSModule:(id<JSBridgeModule>)module {
    [_modules removeObject:module];
}

- (id<JSBridgeModule>)moduleForName:(NSString *)moduleName {
    return [self moduleForClass:NSClassFromString(moduleName)];
}

- (id<JSBridgeModule>)moduleForClass:(Class)moduleClass {
    for(NSObject <JSBridgeModule>*module in self.modules) {
        if([module isMemberOfClass:moduleClass]) {
            return module;
        }
    }
    return nil;
}
//WKWebView 对象 --
- (void)attachToBridge:(id <WebViewJavascriptBridgeProtocol>)javascriptBridge {
    [_modules removeAllObjects];

    NSMutableSet *moduleClasses = [NSMutableSet new];
    [moduleClasses addObjectsFromArray:JSGetModuleClasses()];

    for (Class c in moduleClasses) {
        id <JSBridgeModule> module = [c new];
        [_modules addObject:module];
    }
    // sort
    [_modules sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        id <JSBridgeModule> module1 = obj1;
        id <JSBridgeModule> module2 = obj2;

        if([module1 priority] > [module2 priority]) {
            return NSOrderedAscending;
        } else if([module1 priority] == [module2 priority]) {
            return NSOrderedSame;
        } else {
            return NSOrderedDescending;
        }
    }];

    // load
    for(id <JSBridgeModule> module in _modules) {
        //TODO 更好的方式?
        [self setBridgeForInstance:module];
        [module attachToJSBridge:self];

        //将js api 注册到【self.webview】, oc api 注册到javaScriptBridge
        [self registerHandlersWithModule:module];
    }
}

- (void)setBridgeForInstance:(NSObject<JSBridgeModule> *)module
{
    if ([module respondsToSelector:@selector(bridge)] && module.bridge != self) {
        @try {
            [(id)module setValue:self forKey:@"bridge"];
        }
        @catch (NSException *exception) {
            NSLog(@"%@", exception);
        }
    }
}

- (void)registerHandlersWithModule:(id<JSBridgeModule>)module {
    if(self.webView) {
        if ([module respondsToSelector:@selector(moduleSourceFile)]) {
            NSString *moduleSourceFile = [module moduleSourceFile];
            if (moduleSourceFile) {
                NSString *source = [[NSString alloc] initWithContentsOfFile:moduleSourceFile encoding:NSUTF8StringEncoding error:NULL];
                if ([self.webView isKindOfClass:[WKWebView class]]) {
                    WKWebView *wkWebView = (WKWebView *)self.webView;
                    WKUserContentController *userContentController = wkWebView.configuration.userContentController;
                    WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
                    [userContentController addUserScript:script];
                } else {
                    [self.webView x_evaluateJavaScript:source];
                }
            }
        }

        NSDictionary *handlers = [module messageHandlers];
        for(NSString *key in handlers) {
            WVJBHandler handler = [handlers[key] copy];
            [self.javaScriptBridge registerHandler:key handler:handler];
        }

        UIWebView *webView  = (UIWebView *)self.webView;
        if ([webView isKindOfClass:[UIWebView class]]) {
            NSDictionary *JSContextHandlers = [module JSContextMessageHandlers];
            for(NSString *key in JSContextHandlers) {
                id handler = [JSContextHandlers[key] copy];
                [self.javascriptContext setObject:key forKeyedSubscript:handler];

            }

        }
    }
}

- (void)reset {
    self.viewController = nil;
    self.webView = nil;
    self.javaScriptBridge = nil;
    self.javascriptContext = nil;
}

//-(void)setJavascriptContext:(JSContext *)javascriptContext{
//    _javascriptContext=javascriptContext;
//}

@end


text:
package org.seasar.doma.internal.apt.entity;

import org.seasar.doma.jdbc.domain.AbstractDomainType;

/**
 * @author taedium
 *
 */
public class _Name extends AbstractDomainType<String, Name> {

    private _Name() {
        super(() -> new org.seasar.doma.wrapper.StringWrapper());
    }

    @Override
    public Name newDomain(String value) {
        return null;
    }

    @Override
    public String getBasicValue(Name domain) {
        return null;
    }

    @Override
    public Class<String> getBasicClass() {
        return null;
    }

    @Override
    public Class<Name> getDomainClass() {
        return null;
    }

    public static _Name getSingletonInternal() {
        return null;
    }

}


text:
namespace
{

bool ContainsMatrixNode(const TIntermSequence &sequence)
{
    for (size_t ii = 0; ii < sequence.size(); ++ii)
    {
        TIntermTyped *node = sequence[ii]->getAsTyped();
        if (node && node->isMatrix())
            return true;
    }
    return false;
}

bool ContainsVectorNode(const TIntermSequence &sequence)
{
    for (size_t ii = 0; ii < sequence.size(); ++ii)
    {
        TIntermTyped *node = sequence[ii]->getAsTyped();
        if (node && node->isVector())
            return true;
    }
    return false;
}

TIntermConstantUnion *ConstructIndexNode(int index)
{
    TConstantUnion *u = new TConstantUnion[1];
    u[0].setIConst(index);

    TType type(EbtInt, EbpUndefined, EvqConst, 1);
    TIntermConstantUnion *node = new TIntermConstantUnion(u, type);
    return node;
}

TIntermBinary *ConstructVectorIndexBinaryNode(TIntermSymbol *symbolNode, int index)
{
    TIntermBinary *binary = new TIntermBinary(EOpIndexDirect);
    binary->setLeft(symbolNode);
    TIntermConstantUnion *indexNode = ConstructIndexNode(index);
    binary->setRight(indexNode);
    return binary;
}

TIntermBinary *ConstructMatrixIndexBinaryNode(
    TIntermSymbol *symbolNode, int colIndex, int rowIndex)
{
    TIntermBinary *colVectorNode =
        ConstructVectorIndexBinaryNode(symbolNode, colIndex);

    TIntermBinary *binary = new TIntermBinary(EOpIndexDirect);
    binary->setLeft(colVectorNode);
    TIntermConstantUnion *rowIndexNode = ConstructIndexNode(rowIndex);
    binary->setRight(rowIndexNode);
    return binary;
}

}  // namespace anonymous

bool ScalarizeVecAndMatConstructorArgs::visitAggregate(Visit visit, TIntermAggregate *node)
{
    if (visit == PreVisit)
    {
        switch (node->getOp())
        {
          case EOpSequence:
            mSequenceStack.push_back(TIntermSequence());
            {
                for (TIntermSequence::const_iterator iter = node->getSequence()->begin();
                     iter != node->getSequence()->end(); ++iter)
                {
                    TIntermNode *child = *iter;
                    ASSERT(child != NULL);
                    child->traverse(this);
                    mSequenceStack.back().push_back(child);
                }
            }
            if (mSequenceStack.back().size() > node->getSequence()->size())
            {
                node->getSequence()->clear();
                *(node->getSequence()) = mSequenceStack.back();
            }
            mSequenceStack.pop_back();
            return false;
          case EOpConstructVec2:
          case EOpConstructVec3:
          case EOpConstructVec4:
          case EOpConstructBVec2:
          case EOpConstructBVec3:
          case EOpConstructBVec4:
          case EOpConstructIVec2:
          case EOpConstructIVec3:
          case EOpConstructIVec4:
            if (ContainsMatrixNode(*(node->getSequence())))
                scalarizeArgs(node, false, true);
            break;
          case EOpConstructMat2:
          case EOpConstructMat3:
          case EOpConstructMat4:
            if (ContainsVectorNode(*(node->getSequence())))
                scalarizeArgs(node, true, false);
            break;
          default:
            break;
        }
    }
    return true;
}

void ScalarizeVecAndMatConstructorArgs::scalarizeArgs(
    TIntermAggregate *aggregate, bool scalarizeVector, bool scalarizeMatrix)
{
    ASSERT(aggregate);
    int size = 0;
    switch (aggregate->getOp())
    {
      case EOpConstructVec2:
      case EOpConstructBVec2:
      case EOpConstructIVec2:
        size = 2;
        break;
      case EOpConstructVec3:
      case EOpConstructBVec3:
      case EOpConstructIVec3:
        size = 3;
        break;
      case EOpConstructVec4:
      case EOpConstructBVec4:
      case EOpConstructIVec4:
      case EOpConstructMat2:
        size = 4;
        break;
      case EOpConstructMat3:
        size = 9;
        break;
      case EOpConstructMat4:
        size = 16;
        break;
      default:
        break;
    }
    TIntermSequence *sequence = aggregate->getSequence();
    TIntermSequence original(*sequence);
    sequence->clear();
    for (size_t ii = 0; ii < original.size(); ++ii)
    {
        ASSERT(size > 0);
        TIntermTyped *node = original[ii]->getAsTyped();
        ASSERT(node);
        TString varName = createTempVariable(node);
        if (node->isScalar())
        {
            TIntermSymbol *symbolNode =
                new TIntermSymbol(-1, varName, node->getType());
            sequence->push_back(symbolNode);
            size--;
        }
        else if (node->isVector())
        {
            if (scalarizeVector)
            {
                int repeat = std::min(size, node->getNominalSize());
                size -= repeat;
                for (int index = 0; index < repeat; ++index)
                {
                    TIntermSymbol *symbolNode =
                        new TIntermSymbol(-1, varName, node->getType());
                    TIntermBinary *newNode = ConstructVectorIndexBinaryNode(
                        symbolNode, index);
                    sequence->push_back(newNode);
                }
            }
            else
            {
                TIntermSymbol *symbolNode =
                    new TIntermSymbol(-1, varName, node->getType());
                sequence->push_back(symbolNode);
                size -= node->getNominalSize();
            }
        }
        else
        {
            ASSERT(node->isMatrix());
            if (scalarizeMatrix)
            {
                int colIndex = 0, rowIndex = 0;
                int repeat = std::min(size, node->getCols() * node->getRows());
                size -= repeat;
                while (repeat > 0)
                {
                    TIntermSymbol *symbolNode =
                        new TIntermSymbol(-1, varName, node->getType());
                    TIntermBinary *newNode = ConstructMatrixIndexBinaryNode(
                        symbolNode, colIndex, rowIndex);
                    sequence->push_back(newNode);
                    rowIndex++;
                    if (rowIndex >= node->getRows())
                    {
                        rowIndex = 0;
                        colIndex++;
                    }
                    repeat--;
                }
            }
            else
            {
                TIntermSymbol *symbolNode =
                    new TIntermSymbol(-1, varName, node->getType());
                sequence->push_back(symbolNode);
                size -= node->getCols() * node->getRows();
            }
        }
    }
}

TString ScalarizeVecAndMatConstructorArgs::createTempVariable(TIntermTyped *original)
{
    TString tempVarName = "_webgl_tmp_";
    if (original->isScalar())
    {
        tempVarName += "scalar_";
    }
    else if (original->isVector())
    {
        tempVarName += "vec_";
    }
    else
    {
        ASSERT(original->isMatrix());
        tempVarName += "mat_";
    }
    tempVarName += Str(mTempVarCount).c_str();
    mTempVarCount++;

    ASSERT(original);
    TType type = original->getType();
    type.setQualifier(EvqTemporary);

    if (mShaderType == GL_FRAGMENT_SHADER &&
        type.getBasicType() == EbtFloat &&
        type.getPrecision() == EbpUndefined)
    {
        // We use the highest available precision for the temporary variable
        // to avoid computing the actual precision using the rules defined
        // in GLSL ES 1.0 Section 4.5.2.
        type.setPrecision(mFragmentPrecisionHigh ? EbpHigh : EbpMedium);
    }

    TIntermBinary *init = new TIntermBinary(EOpInitialize);
    TIntermSymbol *symbolNode = new TIntermSymbol(-1, tempVarName, type);
    init->setLeft(symbolNode);
    init->setRight(original);
    init->setType(type);

    TIntermAggregate *decl = new TIntermAggregate(EOpDeclaration);
    decl->getSequence()->push_back(init);

    ASSERT(mSequenceStack.size() > 0);
    TIntermSequence &sequence = mSequenceStack.back();
    sequence.push_back(decl);

    return tempVarName;
}


text:
using namespace std;

class ComputerService
{
public:
    ComputerService();

    void setComputerVector();

    void create(Computer computer);

    // Display functions
    vector<Computer> getComputers();
    vector<Computer> getComputersAlpha();
    vector<Computer> getComputersReversedAlpha();
    vector<Computer> getComputersYoung();
    vector<Computer> getComputersOld();
    vector<Computer> getComputersBuiltOrNot();
    vector<Computer> getComputersID();

    // search functions
    vector<Computer> searchComputerName(string name);
    vector<Computer> searchYearOfBuild(int buildYear);
    vector<Computer> searchType(const char type);
    vector<Computer> searchBuilt(char built);
    vector<Computer> searchRandomComputer();

    // Sends an ID and retrieves computers connected to the ID.
    vector<Computer> getScientistID(int SID);

    // Retrieves how many connections there are between scientists and computers.
    int getConnections();

    // Changes information in the database.
    void deleteComputer(int id);
    void editComputer(string name, int id, int buildYear,int built, string type); // sendir nýjar upplýsingar um computer database

private:
    vector<Computer> computers;
    ComputerDatabase data;
};

#endif // COMPURSERVICE_H


text:
date: 2020-11-24T11:33:11-04:00
description: "Overview of folders in the root of most Linux distributions"
tags: [ "linux" ]
title: "Linux File System"
---

# The Linux File System

## `/bin` - Binaries

The `/bin` folder contains the basic set of binaries available to every user. It contains the binaries for basic commands such as `ls`, `cat`, `chmod`, `mv`, and more.

## `/boot` - Bootloaders

The `/boot` folder contains the files necessary to load the operating system when the computer is turned on.

## `/dev` - Devices

The `/dev` folder contains files that represent devices. In Unix-like systems like Linux, disks and just about everything else are represented as files.

For example: `sda` is a disk. Originally `sd` stood for `SCSI device` but became a catch-all for any [block storage](https://en.wikipedia.org/wiki/Block_(data_storage)) device. The letter that follows `sd`, `a` in this case, represents the order in which the device was found.

## `/etc` - Etcetera (and so on)

The `/etc` folder contains system-wide (as opposed to user-specific) configuration files.

## `/home` - Home Folders

The `/home` directory contains home directories for users other than `root`.

## `/media` - Media

The `/media` folder is where removable disks (e.g. CDs, thumb drives) are automatically mounted.

## `/mnt` - Mount

The `/media` folder is where removable disks (e.g. CDs, thumb drives) are manually mounted, very similar to the `/media` folder.

## `/opt` - Optional

The `/opt` folder is intended to hold manually installed 3rd-party software.

## `/proc` - Processes

The `/proc` folder contains pseudo files that contain information about processes and resources. All running processes have a folder under `/proc`.

## `/root` - Root (user) Home

The `/root` folder is the `root` user's home directory

## `/run` - Run (temporary) Files

The `/run` directory contains temporary files, all of which actually reside in memory. The contents of this directory are deleted upon reboot (because memory is cleared).

## `/sbin` - System (or Super User) Binaries

The `/sbin` folder contains binaries used for system administration tasks including disk and network management. It contains the binaries for commands such as `chkconfig`, `ifcondfig`, and `fsck`.

## `/srv` - Service (or Server) Data

The `/srv` folder stores service/server data to be accessed by external users, for example via a web server.

## `/sys` - System Temporary Files

The `/sys` folder contains temporary files used by the system, all of which are stored in memory (very similar to the `/run` folder). The contents of this directory are deleted upon reboot (because memory is cleared).

## `/tmp` - Temporary Files

The `/tmp` folder contains temporary files. Unlike the `/run` folder, files stored in `/tmp` are less restricted and may be accessed by other users. Generally speaking, developers should prever to use `/run` over `/tmp` for security.

## `/usr` - Users

The `/usr` folder contains "non essential" apps and files used by users (as opposed to the system).

## `/var` - Variable

The `/var` folder contains files that are expected to grow over time (e.g. logs and caches).


text:
<!--

    DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.

    Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.

    Oracle licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.jvnet.jax-ws-commons.test</groupId>
        <artifactId>parent</artifactId>
        <version>2.3.1-SNAPSHOT</version>
    </parent>

    <artifactId>mojo.it.jaxwscommons98</artifactId>

    <name>JAX_WS_COMMONS-98</name>
    <description>wsimport - NPE When WSDL File Cannot be found</description>

    <build>
        <plugins>
            <plugin>
                <groupId>org.jvnet.jax-ws-commons</groupId>
                <artifactId>jaxws-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>generate-wscoor-types</id>
                        <goals>
                            <goal>wsimport</goal>
                        </goals>
                        <configuration>
                            <wsdlDirectory>${basedir}/src/main/wsdls</wsdlDirectory>
                            <wsdlFiles>
                                <wsdlFile>wstx-wscoor-1.1-wsdl-200702.wsdl</wsdlFile>
                            </wsdlFiles>
                            <packageName>weblogic.wsee.wstx.wsc.v11.types</packageName>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>

#include "ruby.h"

#include <unistd.h>

static VALUE mReadline;

#define TOLOWER(c) (isupper(c) ? tolower(c) : c)

#define COMPLETION_PROC "completion_proc"
#define COMPLETION_CASE_FOLD "completion_case_fold"
static ID completion_proc, completion_case_fold;

static char **readline_attempted_completion_function(const char *text,
                                                     int start, int end);

static VALUE readline_unlocked(void* prompt) {
  return (VALUE)readline((char*)prompt);
}

static VALUE
readline_readline(VALUE self, VALUE tmp, VALUE add_hist)
{
    VALUE result;
    char *prompt = NULL;
    char *buff;

    rb_secure(4);
    SafeStringValue(tmp);
    prompt = RSTRING_PTR(tmp);

    if(!isatty(0) && errno == EBADF) rb_raise(rb_eIOError, "stdin closed");

    buff = (char*)rb_thread_blocking_region(readline_unlocked, prompt, 0, 0);

    if(RTEST(add_hist) && buff) {
      add_history(buff);
    }

    if(buff) {
      result = rb_tainted_str_new2(buff);
      free(buff);
    } else {
      result = Qnil;
    }

    return result;
}

static VALUE
readline_s_set_completion_proc(self, proc)
    VALUE self;
    VALUE proc;
{
    rb_secure(4);
    if (!rb_respond_to(proc, rb_intern("call")))
        rb_raise(rb_eArgError, "argument must respond to `call'");
    return rb_ivar_set(mReadline, completion_proc, proc);
}

static VALUE
readline_s_get_completion_proc(self)
    VALUE self;
{
    rb_secure(4);
    return rb_attr_get(mReadline, completion_proc);
}

static VALUE
readline_s_set_completion_case_fold(self, val)
    VALUE self;
    VALUE val;
{
    rb_secure(4);
    return rb_ivar_set(mReadline, completion_case_fold, val);
}

static VALUE
readline_s_get_completion_case_fold(self)
    VALUE self;
{
    rb_secure(4);
    return rb_attr_get(mReadline, completion_case_fold);
}

struct complete_args {
  const char* text;
  int start;
  int end;
};

static void*
readline_complete_locked(struct complete_args* args) {
    const char *text = args->text;
    int start = args->start;
    int end = args->end;

    VALUE proc, ary, temp;
    char **result;
    int case_fold;
    int i, matches;

    proc = rb_attr_get(mReadline, completion_proc);
    if (NIL_P(proc))
        return NULL;
#ifdef HAVE_RL_ATTEMPTED_COMPLETION_OVER
    rl_attempted_completion_over = 1;
#endif
    case_fold = RTEST(rb_attr_get(mReadline, completion_case_fold));
    ary = rb_funcall(proc, rb_intern("call"), 1, rb_tainted_str_new2(text));
    ary = rb_Array(ary);

    matches = rb_ary_size(ary);
    if (matches == 0) return NULL;
    result = ALLOC_N(char *, matches + 2);
    for (i = 0; i < matches; i++) {
      temp = rb_obj_as_string(rb_ary_entry(ary, i));
      result[i + 1] = ALLOC_N(char, RSTRING_LEN(temp) + 1);
      strcpy(result[i + 1], RSTRING_PTR(temp));
    }
    result[matches + 1] = NULL;

    if (matches == 1) {
        result[0] = strdup(result[1]);
    }
    else {
        register int i = 1;
        int low = 100000;

        while (i < matches) {
            register int c1, c2, si;

            if (case_fold) {
                for (si = 0;
                     (c1 = TOLOWER(result[i][si])) &&
                         (c2 = TOLOWER(result[i + 1][si]));
                     si++)
                    if (c1 != c2) break;
            } else {
                for (si = 0;
                     (c1 = result[i][si]) &&
                         (c2 = result[i + 1][si]);
                     si++)
                    if (c1 != c2) break;
            }

            if (low > si) low = si;
            i++;
        }
        result[0] = ALLOC_N(char, low + 1);
        strncpy(result[0], result[1], low);
        result[0][low] = '\0';
    }

    return (void*)result;
}

static char **
readline_attempted_completion_function(text, start, end)
    const char *text;
    int start;
    int end;
{
  struct complete_args args = {text, start, end};
  void* ret = rb_thread_call_with_gvl((rb_thread_call_func)readline_complete_locked, &args);
  return (char**)ret;
}

static VALUE
readline_s_set_completion_append_character(self, str)
    VALUE self, str;
{
    rb_secure(4);
    if (NIL_P(str)) {
        rl_completion_append_character = '\0';
    }
    else {
        SafeStringValue(str);
        if (RSTRING_LEN(str) == 0) {
            rl_completion_append_character = '\0';
        } else {
            rl_completion_append_character = RSTRING_PTR(str)[0];
        }
    }
    return self;
}

static VALUE
readline_s_get_completion_append_character(self)
    VALUE self;
{
    rb_secure(4);
    if (rl_completion_append_character == '\0')
        return Qnil;

    return rb_str_new((char*)&rl_completion_append_character, 1);
}

static VALUE
readline_s_set_basic_word_break_characters(self, str)
    VALUE self, str;
{
    static char *basic_word_break_characters = NULL;

    rb_secure(4);
    SafeStringValue(str);
    if (basic_word_break_characters == NULL) {
        basic_word_break_characters =
        ALLOC_N(char, RSTRING_LEN(str) + 1);
    }
    else {
        REALLOC_N(basic_word_break_characters, char, RSTRING_LEN(str) + 1);
    }
    strncpy(basic_word_break_characters,
	    RSTRING_PTR(str), RSTRING_LEN(str));
    basic_word_break_characters[RSTRING_LEN(str)] = '\0';
    rl_basic_word_break_characters = basic_word_break_characters;
    return self;
}

static VALUE
readline_s_get_basic_word_break_characters(self, str)
    VALUE self, str;
{
    rb_secure(4);
    if (rl_basic_word_break_characters == NULL)
        return Qnil;
    return rb_tainted_str_new2(rl_basic_word_break_characters);
}

static VALUE
readline_s_set_completer_word_break_characters(self, str)
    VALUE self, str;
{
    static char *completer_word_break_characters = NULL;

    rb_secure(4);
    SafeStringValue(str);
    if (completer_word_break_characters == NULL) {
        completer_word_break_characters =
	      ALLOC_N(char, RSTRING_LEN(str) + 1);
    }
    else {
        REALLOC_N(completer_word_break_characters, char, RSTRING_LEN(str) + 1);
    }
    strncpy(completer_word_break_characters,
	    RSTRING_PTR(str), RSTRING_LEN(str));
    completer_word_break_characters[RSTRING_LEN(str)] = '\0';
    rl_completer_word_break_characters = completer_word_break_characters;
    return self;
}

static VALUE
readline_s_get_completer_word_break_characters(self, str)
    VALUE self, str;
{
    rb_secure(4);
    if (rl_completer_word_break_characters == NULL)
        return Qnil;
    return rb_tainted_str_new2(rl_completer_word_break_characters);
}

static VALUE
readline_s_set_completer_quote_characters(self, str)
    VALUE self, str;
{
    static char *completer_quote_characters = NULL;

    rb_secure(4);
    SafeStringValue(str);
    if (completer_quote_characters == NULL) {
        completer_quote_characters =
	      ALLOC_N(char, RSTRING_LEN(str) + 1);
    }
    else {
        REALLOC_N(completer_quote_characters, char, RSTRING_LEN(str) + 1);
    }
    strncpy(completer_quote_characters,
	    RSTRING_PTR(str), RSTRING_LEN(str));
    completer_quote_characters[RSTRING_LEN(str)] = '\0';
    rl_completer_quote_characters = completer_quote_characters;

    return self;
}

static VALUE
readline_s_get_completer_quote_characters(self, str)
    VALUE self, str;
{
    rb_secure(4);
    if (rl_completer_quote_characters == NULL)
        return Qnil;
    return rb_tainted_str_new2(rl_completer_quote_characters);
}

static VALUE
hist_to_s(self)
    VALUE self;
{
    return rb_str_new2("HISTORY");
}

static VALUE
hist_get(self, index)
    VALUE self;
    VALUE index;
{
    HIST_ENTRY *entry;
    int i;

    rb_secure(4);
    i = NUM2INT(index);
    if (i < 0) {
        i += history_length;
    }
    entry = history_get(history_base + i);
    if (entry == NULL) {
        rb_raise(rb_eIndexError, "invalid index");
    }
    return rb_tainted_str_new2(entry->line);
}

static VALUE
hist_set(self, index, str)
    VALUE self;
    VALUE index;
    VALUE str;
{
    HIST_ENTRY *entry;
    int i;

    rb_secure(4);
    i = NUM2INT(index);
    SafeStringValue(str);
    if (i < 0) {
        i += history_length;
    }
    entry = replace_history_entry(i, RSTRING_PTR(str), NULL);
    if (entry == NULL) {
      rb_raise(rb_eIndexError, "invalid index");
    }
    return str;
}

static VALUE
hist_push(self, str)
    VALUE self;
    VALUE str;
{
    rb_secure(4);
    SafeStringValue(str);
    add_history(RSTRING_PTR(str));
    return self;
}

static VALUE
hist_push_method(argc, argv, self)
    int argc;
    VALUE *argv;
    VALUE self;
{
    VALUE str;

    rb_secure(4);
    while (argc--) {
        str = *argv++;
        SafeStringValue(str);
        add_history(RSTRING_PTR(str));
    }
    return self;
}

static VALUE
rb_remove_history(index)
    int index;
{
    HIST_ENTRY *entry;
    VALUE val;

    rb_secure(4);
    entry = remove_history(index);
    if (entry) {
        val = rb_tainted_str_new2(entry->line);
        free((char*)entry->line);
        free(entry);
        return val;
    }
    return Qnil;
}

static VALUE
hist_pop(self)
    VALUE self;
{
    rb_secure(4);
    if (history_length > 0) {
        return rb_remove_history(history_length - 1);
    } else {
        return Qnil;
    }
}

static VALUE
hist_shift(self)
    VALUE self;
{
    rb_secure(4);
    if (history_length > 0) {
        return rb_remove_history(0);
    } else {
        return Qnil;
    }
}

static VALUE
hist_each(self)
    VALUE self;
{
    HIST_ENTRY *entry;
    int i;

    rb_secure(4);
    for (i = 0; i < history_length; i++) {
        entry = history_get(history_base + i);
        if (entry == NULL)
            break;
        rb_yield(rb_tainted_str_new2(entry->line));
    }
    return self;
}

static VALUE
hist_length(self)
    VALUE self;
{
    rb_secure(4);
    return INT2NUM(history_length);
}

static VALUE
hist_empty_p(self)
    VALUE self;
{
    rb_secure(4);
    return history_length == 0 ? Qtrue : Qfalse;
}

static VALUE
hist_delete_at(self, index)
    VALUE self;
    VALUE index;
{
    int i;

    rb_secure(4);
    i = NUM2INT(index);
    if (i < 0)
        i += history_length;
    if (i < 0 || i > history_length - 1) {
        rb_raise(rb_eIndexError, "invalid index");
    }
    return rb_remove_history(i);
}

void
Init_readline()
{
    VALUE history;

    /* Allow conditional parsing of the ~/.inputrc file. */
    rl_readline_name = "Ruby";

    using_history();

    completion_proc = rb_intern(COMPLETION_PROC);
    completion_case_fold = rb_intern(COMPLETION_CASE_FOLD);

    mReadline = rb_define_module("Readline");
    rb_define_singleton_method(mReadline, "perform_readline",
                              readline_readline, 2);
    rb_define_singleton_method(mReadline, "completion_proc=",
                               readline_s_set_completion_proc, 1);
    rb_define_singleton_method(mReadline, "completion_proc",
                               readline_s_get_completion_proc, 0);
    rb_define_singleton_method(mReadline, "completion_case_fold=",
                               readline_s_set_completion_case_fold, 1);
    rb_define_singleton_method(mReadline, "completion_case_fold",
                               readline_s_get_completion_case_fold, 0);
    rb_define_singleton_method(mReadline, "completion_append_character=",
                               readline_s_set_completion_append_character, 1);
    rb_define_singleton_method(mReadline, "completion_append_character",
                               readline_s_get_completion_append_character, 0);
    rb_define_singleton_method(mReadline, "basic_word_break_characters=",
                               readline_s_set_basic_word_break_characters, 1);
    rb_define_singleton_method(mReadline, "basic_word_break_characters",
                               readline_s_get_basic_word_break_characters, 0);
    rb_define_singleton_method(mReadline, "completer_word_break_characters=",
                               readline_s_set_completer_word_break_characters, 1);
    rb_define_singleton_method(mReadline, "completer_word_break_characters",
                               readline_s_get_completer_word_break_characters, 0);
    rb_define_singleton_method(mReadline, "completer_quote_characters=",
                               readline_s_set_completer_quote_characters, 1);
    rb_define_singleton_method(mReadline, "completer_quote_characters",
                               readline_s_get_completer_quote_characters, 0);

    history = rb_obj_alloc(rb_cObject);
    rb_define_singleton_method(history,"to_s", hist_to_s, 0);
    rb_define_singleton_method(history,"[]", hist_get, 1);
    rb_define_singleton_method(history,"[]=", hist_set, 2);
    rb_define_singleton_method(history,"<<", hist_push, 1);
    rb_define_singleton_method(history,"push", hist_push_method, -1);
    rb_define_singleton_method(history,"pop", hist_pop, 0);
    rb_define_singleton_method(history,"shift", hist_shift, 0);
    rb_define_singleton_method(history,"each", hist_each, 0);
    rb_define_singleton_method(history,"length", hist_length, 0);
    rb_define_singleton_method(history,"size", hist_length, 0);
    rb_define_singleton_method(history,"empty?", hist_empty_p, 0);
    rb_define_singleton_method(history,"delete_at", hist_delete_at, 1);
    rb_define_const(mReadline, "HISTORY", history);

    rb_define_const(mReadline, "VERSION", rb_str_new2(rl_library_version));

    rl_attempted_completion_function = readline_attempted_completion_function;
}


text:
using System;
using System.Diagnostics.Contracts;
using IBApi.Connection;
using IBApi.Messages.Server;

namespace IBApi
{
    internal class IdsDispenser : IIdsDispenser
    {
        private readonly IDisposable subscription;
        private int nextRequestId;
        private int nextOrderId;

        public IdsDispenser(IConnection connection)
        {
            Contract.Requires(connection != null);
            this.subscription = connection.Subscribe((NextValidIdMessage message) => this.OnNextValidId(message));
        }

        private void OnNextValidId(NextValidIdMessage message)
        {
            this.nextOrderId = message.ValidId;
        }

        public int NextOrderId()
        {
            return this.nextOrderId++;
        }

        public int NextRequestId()
        {
            return this.nextRequestId++;
        }

        public void Dispose()
        {
            this.subscription.Dispose();
        }
    }
}


text:
module Main where

import Data.Maybe

import Math.Symbolic.Wheeler.Basic
import Math.Symbolic.Wheeler.Canonicalize
import Math.Symbolic.Wheeler.Commutativity
import Math.Symbolic.Wheeler.Expr
import Math.Symbolic.Wheeler.MetricTensor
import Math.Symbolic.Wheeler.Numeric
import Math.Symbolic.Wheeler.Symbol
import Math.Symbolic.Wheeler.IO
import Math.Symbolic.Wheeler.Tensor
import Math.Symbolic.Wheeler.TensorBasics
import Math.Symbolic.Wheeler.TensorUtilities

a = Symbol $ simpleSymbol "a"
b = Symbol $ simpleSymbol "b"
c = Symbol $ simpleSymbol "c"
e = Symbol $ simpleSymbol "e"

l = Symbol $ ncSymbol "l" "foo"
m = Symbol $ ncSymbol "m" "foo"
n = Symbol $ ncSymbol "n" "foo"

x = Symbol $ ncSymbol "x" "pauli"
y = Symbol $ ncSymbol "y" "pauli"
z = Symbol $ ncSymbol "z" "pauli"

(s, unnamedMetric) = mkManifold "s" 4 minkowski

mu    = mkIndex  s "mu"
nu    = mkIndex_ s "nu" "\\nu"
rho   = mkIndex s "delta"
sigma = mkIndex s "sigma"

g = (fromJust unnamedMetric) "g" "g"

g'   = g mu (-nu) * g (-sigma) rho * d (-rho) sigma
g''  = g mu (-nu) * g (-rho) sigma * d (-mu) sigma
g''' = g mu (-nu) * g (-mu) sigma  * d (-mu) rho

d = mkKroneckerDelta s "delta"

foo :: Expr -> Expr
foo (Const (I n)) = if n == 1 then Const 0 else Const 2
foo _ = Const 3

fct :: Expr -> Expr
fct (Const (I 1)) = Const 1
fct i@(Const (I n)) = if n > 1 then i * fct (i - 1) else Const 1

hermite :: Integer -> Expr -> Expr
hermite n x =
    let
        herm 0 _ = 1 :: Expr
        herm 1 x = 2 * x
        herm n x = 2 * x * herm (n - 1) x - 2 * (n - 1) * herm (n - 2) x
    in
        expand $ herm (fromInteger n) x

main = do
    print $ hermite 10 (y+x)


text:
package com.sap.hcp.cf.log4j2.converter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.impl.Log4jLogEvent.Builder;
import org.apache.logging.log4j.core.pattern.LogEventPatternConverter;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.message.SimpleMessage;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.fasterxml.jackson.jr.ob.JSON;
import com.fasterxml.jackson.jr.ob.JSONObjectException;
import com.sap.hcp.cf.logging.common.customfields.CustomField;

public abstract class AbstractConverterTest {
    protected static final String PREFIX = "prefix";
    protected static final String EMPTY = "";
    protected static final String SOME_KEY = "some_key";
    protected static final String SOME_VALUE = "some value";
    protected static final String STRANGE_SEQ = "}{:\",\"";
    protected static final String SOME_OTHER_KEY = "some_other_key";
    protected static final String SOME_OTHER_VALUE = "some other value";
    protected static final String TEST_MSG_NO_ARGS = "This is a test ";
    protected static final Object[] NO_ARGS = new Object[0];

    @Before
    public void start() {
        Logger logger = LoggerFactory.getLogger(AbstractConverterTest.class);
        logger.debug("starting");
    }

    protected String format(LogEventPatternConverter converter, LogEvent event) {
        StringBuilder sb = new StringBuilder();
        converter.format(event, sb);
        return sb.toString();
    }

    protected LogEvent makeEvent(String msg, Object[] args) {
        return makeEvent(msg, null, args);
    }

    protected LogEvent makeEvent(String msg, Throwable t, Object[] args) {
        Message message;
        if (args == null || args.length == 0) {
            message = new SimpleMessage(msg);
        } else {
            message = new ParameterizedMessage(msg, args);
        }
        LogEvent event = new Builder().setLevel(Level.INFO).setMessage(message).setThrown(t).build();
        return event;
    }

    protected Object arrayElem(String serialized, int i) throws JSONObjectException, IOException {
        return arrayFrom(serialized)[i];
    }

    protected Object[] arrayFrom(String serialized) throws JSONObjectException, IOException {
        return JSON.std.arrayFrom(serialized);
    }

    protected Map<String, Object> makeMap(CustomField[] custFields) {
        Map<String, Object> map = new HashMap<String, Object>();
        for (CustomField cf: custFields) {
            map.put(cf.getKey(), cf.getValue());
        }
        return map;
    }

    protected Map<String, Object> makeMap(String[] keys) {
        Map<String, Object> map = new HashMap<String, Object>();
        for (String key: keys) {
            map.put(key, MDC.get(key));
        }
        return map;
    }

    protected Map<String, Object> mapFrom(String serialized) throws JSONObjectException, IOException {
        return mapFrom(serialized, true);
    }

    protected Map<String, Object> mapFrom(String serialized, boolean wrap) throws JSONObjectException, IOException {
        if (wrap) {
            return JSON.std.mapFrom("{" + serialized + "}");
        }
        return JSON.std.mapFrom(serialized);
    }

    protected Map<String, Object> mdcMap() {
        return mdcMap(null);
    }

    protected Map<String, Object> mdcMap(String[] exclusions) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<String> exclusionList;
        if (exclusions == null) {
            exclusionList = Arrays.asList(new String[0]);
        } else {
            exclusionList = Arrays.asList(exclusions);
        }
        for (Entry<String, String> t: MDC.getCopyOfContextMap().entrySet()) {
            if (!exclusionList.contains(t.getKey())) {
                result.put(t.getKey(), t.getValue());
            }
        }
        return result;
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Pap. 166: 88 (1993)

#### Original name
Meliolina leptospermi S. Hughes, 1993

### Remarks
null


text:
files = Dir["*.codesnippet"]

#Get the text from a xml element "<string>text</string>"
def get_text(str)
    return str.strip.sub("<string>", "").sub("</string>", "").strip
end

#Get new file name from the snippets content using prefix and title
def get_file_name(file)
    content = File.read(file)
    lines = content.split("\n")
    prefix = ""
    title = ""
    for i in 1...lines.length
        if lines[i].include?("IDECodeSnippetCompletionPrefix")
            prefix = get_text(lines[i+1])
        end

        if lines[i].include?("IDECodeSnippetTitle")
            title =  get_text(lines[i+1])
            title.downcase!
            title.gsub!(", ", "_")
            title.gsub!(" ", "_");
            title.gsub!(",", "_")
        end
    end
    return "#{prefix}-#{title}.codesnippet";
end

files.each do |file|
    new_name = get_file_name(file)
    puts "Rename #{file} to #{new_name}"
    File.rename(file, new_name)
end


text:
using System;
namespace BusinessEngine.Models
{
    public class DetailsBonReceptionFournisseur : Entity
    {
        virtual public int Id { get; set; }
        virtual public DateTime DateCreation { get; set; }
        virtual public Produit Produit { get; set; }
        virtual public BonReceptionFournisseur BonReceptionFournisseur { get; set; }
        virtual public decimal Quantite { get; set; }
        virtual public decimal PrixUnitaire { get; set; }
        virtual public decimal Tva { get; set; }
        virtual public int TypeColisage { get; set; }

    }
}


text:
package dev.kkorolyov.pancake.core.component.movement;

import dev.kkorolyov.pancake.platform.entity.Component;
import dev.kkorolyov.pancake.platform.math.Vector3;
import dev.kkorolyov.pancake.platform.math.Vectors;

/**
 * Maximum velocity of a moving entity.
 */
public final class VelocityCap implements Component {
	private final Vector3 value;

	/**
	 * Constructs a new velocity cap.
	 * @param value vector defining maximum speed
	 */
	public VelocityCap(Vector3 value) {
		this.value = Vectors.create(verify(value.getX()), verify(value.getY()), verify(value.getZ()));
	}
	private static double verify(double value) {
		if (value < 0) throw new IllegalArgumentException("cap must be >= 0; was " + value);
		return value;
	}

	/**
	 * Caps the speed along each component of {@code velocity}.
	 */
	public void cap(Vector3 velocity) {
		velocity.setX(cap(round(velocity.getX()), value.getX()));
		velocity.setY(cap(round(velocity.getY()), value.getY()));
		velocity.setZ(cap(round(velocity.getZ()), value.getZ()));
	}
	private static double cap(double velocity, double maxSpeed) {
		return velocity < 0 ? Math.max(velocity, -maxSpeed) : Math.min(velocity, maxSpeed);
	}
	private static double round(double value) {
		return Double.compare(0, value) == 0 ? 0 : value;
	}
}


text:
import createDb from '../db'
import { echoValue } from './test-util'

test('reset', async () => {
  const onFetch = jest.fn(echoValue)
  const s = createDb({ users: { onFetch } })

  // fetch 'a'
  await s.findAsync('users', ['a'])
  expect(s.users._byIdAts.a).toBeTruthy()

  s.reset('users')
  // preload invalidated
  expect(s.getById('users')).toEqual({})
  expect(s.users._byIdAts.a).toBeFalsy()

  // fetch 'b'
  await s.findAsync('users', ['b']).then(arr => arr[0])

  s.reset('users')
  // preload invalidated
  expect(s.getById('users')).toEqual({})
  expect(s.users._byIdAts).toEqual({})

  // will re-fetch 'b'
  onFetch.mockClear()
  expect(onFetch).toHaveBeenCalledTimes(0)
  s.find('users', ['b', 'c'])
  await s.getPending('users')
  expect(onFetch).toHaveBeenCalledTimes(1)

  // invalidate 'b'
  expect(s.users._byIdAts.b).toBeTruthy()
  s.invalidate('users', ['b'])
  // preload invalidated
  expect(s.getById('users')).toEqual({ c: 'C' })
  expect(s.users._byIdAts.b).toBeFalsy()

  // re-fetch 'b' after invalidate
  s.get('users', 'b')
  expect(onFetch).toHaveBeenCalledTimes(2)
})


text:
using Robust.Shared.Map;
using Robust.Shared.Serialization;

namespace Content.Shared.Weapons.Melee.Events;

/// <summary>
/// Raised when a light attack is made.
/// </summary>
[Serializable, NetSerializable]
public sealed class LightAttackEvent : AttackEvent
{
    public readonly EntityUid? Target;
    public readonly EntityUid Weapon;

    public LightAttackEvent(EntityUid? target, EntityUid weapon, EntityCoordinates coordinates) : base(coordinates)
    {
        Target = target;
        Weapon = weapon;
    }
}


text:
"use strict";
var minimist = require('minimist');
var cli_1 = require('../utils/cli');
var config_1 = require('../utils/config');
var dependencies_1 = require('../lib/dependencies');
var args = minimist(process.argv.slice(2), {
    boolean: ['verbose', 'help', 'production'],
    alias: {
        verbose: ['v'],
        production: ['p'],
        help: ['h']
    }
});
if (args.help) {
    console.log("\n" + config_1.PROJECT_NAME + " ls [--ambient] [--production]\n\nAliases: la, ll, list\n");
    process.exit(0);
}
var cwd = process.cwd();
var verbose = args.verbose;
var dev = !args.production;
cli_1.loader(dependencies_1.resolveTypeDependencies({ cwd: cwd, ambient: true, dev: dev }), { verbose: verbose })
    .then(function (tree) {
    console.log(cli_1.archifyDependencyTree(tree));
});
//# sourceMappingURL=typings-list.js.map


text:
<?php

use kartik\helpers\Html;
//use yii\widgets\ActiveForm;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use kartik\builder\FormGrid;

/* @var $this yii\web\View */
/* @var $model app\models\ElaporanKomposisiPenyertaan */
/* @var $form yii\widgets\ActiveForm */
?>

* lapangan mandatori

    <?php $form = ActiveForm::begin(['type'=>ActiveForm::TYPE_VERTICAL]); ?>
    <?php
        echo FormGrid::widget([
    'model' => $model,
    'form' => $form,
    'autoGenerateColumns' => true,
    'rows' => [
        [
            'columns'=>12,
            'autoGenerateColumns'=>false, // override columns setting
            'attributes' => [
                'kumpulan_penyertaan' => ['type'=>Form::INPUT_DROPDOWN_LIST,'items'=>[''=>'-- Pilih Kumpulan Penyertaan --'],'columnOptions'=>['colspan'=>3]],
                'jenis_komposisi' => ['type'=>Form::INPUT_DROPDOWN_LIST,'items'=>[''=>'-- Pilih Komposisi --'],'columnOptions'=>['colspan'=>3]],
                'bilangan' => ['type'=>Form::INPUT_TEXT,'columnOptions'=>['colspan'=>3],'options'=>['maxlength'=>20]],
            ],
        ],

    ]
]);
    ?>

        <?= Html::submitButton($model->isNewRecord ? 'Hantar' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
package se.litsec.eidas.opensaml.ext;

/**
 * An enumeration of the {@code <eidas:SPType>} element.
 *
 * @author Martin Lindström (martin.lindstrom@litsec.se)
 */
public enum SPTypeEnumeration {

  /** The "public" SP type. */
  PUBLIC("public"),

  /** The "private" SP type. */
  PRIVATE("private");

  /** The SP type. */
  private String type;

  /**
   * Returns the type value.
   *
   * @return the value
   */
  public String getValue() {
    return this.type;
  }

  /**
   * Given the string representation of a SPType, the method returns its {@code SPTypeEnumeration} representation.
   *
   * @param value
   *          the value to parse
   * @return the corresponding SPTypeEnumeration
   * @throws IllegalArgumentException
   *           if the supplied value is not a valid SPType
   */
  public static SPTypeEnumeration parseValue(final String value) {
    for (SPTypeEnumeration e : SPTypeEnumeration.values()) {
      if (e.getValue().equalsIgnoreCase(value)) {
        return e;
      }
    }
    throw new IllegalArgumentException("Not a valid SPType - " + value);
  }

  /** {@inheritDoc} */
  @Override
  public String toString() {
    return this.type;
  }

  /**
   * Constructor.
   *
   * @param type
   *          the SP type
   */
  private SPTypeEnumeration(final String type) {
    this.type = type;
  }

}


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Custofixo;

/**
 * CustofixoSearch represents the model behind the search form about `app\models\Custofixo`.
 */
class CustofixoSearch extends Custofixo
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['idconta', 'tipocustofixo_idtipocustofixo'], 'integer'],
            [['consumo'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Custofixo::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
              'pagination' => [
                'pageSize' => 10,
            ],
               'sort'=> ['defaultOrder' => ['idconta'=>SORT_DESC]],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'idconta' => $this->idconta,
            'consumo' => $this->consumo,
            'tipocustofixo_idtipocustofixo' => $this->tipocustofixo_idtipocustofixo,
        ]);

        return $dataProvider;
    }

    /**
     * @param $idTipoFixoCusto
     * @return mixed
     */
    public function searchConsumoCustoFixoporTipoMensal($idTipoFixoCusto)
    {

        //Guarda o mês anterior
        $mes = (date('m')-1);

        //Guarda o último dia do mês
        $lastDayOfMonth = date('t', strtotime(date('Y') . '-' . $mes . '-' . date('d')));

        //Busca os custos fixo no período mensal(Do primeiro até o último dia do mês atual)
        $query = Custofixo::find()
            ->joinWith('idcontaAPagar')
            ->joinWith('idcontaAPagar.conta')
            ->where(['tipocustofixo_idtipocustofixo'=>$idTipoFixoCusto])
                ->andWhere(['between','dataVencimento',
                    date('Y').'-'.$mes.'-'.'01',  date('Y').'-'.$mes.'-'.$lastDayOfMonth]);

        //Guarda o valor médio de um tipo de custo fixo no período mensal(Do primeiro até o último dia do mês atual)
        $mediaConsumo = $query->average('valor');

        return $mediaConsumo;

    }
}


text:
import os
from os import listdir
from os.path import isfile, join
import pprint
import subprocess
import shutil
import zipfile
import xml.etree.ElementTree as ET
from sets import Set
import tarfile
import io

def load_rtwsrc():
    rtwsrc = open('/etc/rtwsrc')
    lines = rtwsrc.readlines()
    rtwsrc.close()
    for ln in lines:
        (key, _, value) = ln.partition('=')
        os.environ[key] = value

def is_class_in_jar(jar_file, class_to_find):
    '''prints out .class files from jar_file'''
    zf = zipfile.ZipFile(TMP_TRANSPORT_LIB_DIR + '/' + jar_file, 'r')
    try:
        lst = zf.infolist()
        for zi in lst:
            fn = zi.filename
            if fn.endswith('.class'):
                package_name = fn.replace(r'/','.').replace(r'.class','')
                #print 'comparing:', package_name, 'to:',class_to_find
                if package_name == class_to_find:
                    return True
    finally:
        zf.close()
    return False

def process_transports():
    print 'Loading',TRANSPORT_CONFIG_FILEPATH
    tree = ET.parse(TRANSPORT_CONFIG_FILEPATH)
    root = tree.getroot()

    transports = Set([])
    for entry in root.findall('.//transport-services'):
        transport = entry.attrib['{http://www.w3.org/2001/XMLSchema-instance}type'][5:]

        if transport not in transports:
            transports.add(transport)

    print 'Processing transports:',transports
    for tsprt in transports:
        print '\nLoading the resources for transport:', tsprt
        onlyfiles = [ f for f in listdir(TMP_TRANSPORT_LIB_DIR) if isfile(join(TMP_TRANSPORT_LIB_DIR,f)) ]
        for jar in onlyfiles:
            if jar.endswith(".jar"):
                if is_class_in_jar(jar, tsprt) == True:
                    print 'Found jar with desired transport: ', jar, tsprt
                    print TMP_TRANSPORT_LIB_DIR + '/' + jar,  ' -> ', TRANSPORT_LIB_DIR + '/' + jar
                    shutil.copyfile(TMP_TRANSPORT_LIB_DIR + '/' + jar, TRANSPORT_LIB_DIR + '/' + jar)

                    # Extract the prestart script if appliable
                    jar_zip_file = zipfile.ZipFile(TMP_TRANSPORT_LIB_DIR + '/' + jar, 'r')
                    try:
                        if "env/pre_start" in [member.filename for member in jar_zip_file.infolist()]:
                            jar_zip_file.extract('env/pre_start', '', '/usr/local/rtws/transport/bin')
                    finally:
                            jar_zip_file.close()

                    expected_jar_zip = jar.replace(r'.jar','-plugin-deps.zip')
                    if os.path.isfile(TMP_TRANSPORT_LIB_DIR + '/' + expected_jar_zip):
                        zf = zipfile.ZipFile(TMP_TRANSPORT_LIB_DIR + '/' + expected_jar_zip, 'r')
                        try:
                            zf.extractall(TRANSPORT_LIB_DIR)
                        finally:
                            zf.close()
                    else:
                        print 'WARNING: Cannot locate plugin zip with this expected name: ', expected_jar_zip

def extract_hadoop_native_libs():
    command = ['tar', '-C', TRANSPORT_LIB_DIR, '-xzvf', TMP_TRANSPORT_LIB_DIR + '/hadoop-cdh4.3.0-native.tar.gz']
    proc = subprocess.Popen(command, stdout = subprocess.PIPE)
    for line in proc.stdout:
       print line

    proc.communicate()

def run():
    print 'loading /etc/rtwsrc...'
    load_rtwsrc()

    print 'Extracting Hadoop Native libs'
    extract_hadoop_native_libs()

    print 'Processing resources for the configured transports ....'
    process_transports()

# Main
if __name__ == '__main__':
    TMP_TRANSPORT_GPL_LIB_DIR = '/usr/local/rtws/boot/lib'
    TMP_TRANSPORT_LIB_DIR = '/tmp/transport/lib'
    TMP_TRANSPORT_SCRIPTS_DIR = '/tmp/transport/scripts'
    TMP_DEPS_DIR = '/tmp/transport/lib/plugin-dependencies'
    TRANSPORT_LIB_DIR = '/usr/local/rtws/transport/lib'
    TRANSPORT_CONFIG_FILEPATH = '/usr/local/rtws/transport/conf/transports.default.xml'
    run()


text:
package com.mylikes.likes.etchasketch;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.Log;

import java.util.HashMap;
import java.util.List;

/**
 * Created by nick on 11/29/14.
 */
public class TextDrawing extends MoveableDrawing {
    public static final String[] FONTS = {"Overlock-Regular.ttf", "AmaticSC-Bold.ttf", "Bangers.ttf", "ClickerScript-Regular.ttf", "ClickerScript-Regular.ttf"};
    public static final String TAG = "TextDrawing";
    private static HashMap<String, Typeface> fontCache;
    static  {
        fontCache = new HashMap<String, Typeface>(6);
    }
    private String text, font = "Overlock-Regular.ttf";
    private float fontSize = 60.0f;
    private final Paint paint = new Paint();

    public TextDrawing(Context context, String text, int x, int y) {
        super(context, x, y);
        this.text = text;
        fontSize = context.getResources().getDimensionPixelSize(R.dimen.default_font_size);
        paint.setColor(color);
        paint.setTextSize(fontSize);
        paint.setTypeface(getFont());
        measure(text);
        Log.d(TAG, "x=" + x + " y=" + y + " w=" + width + " h=" + height);
    }

    private void measure(String text) {
        Rect bounds = new Rect();
        paint.setTextSize(fontSize);
        paint.getTextBounds(text, 0, text.length(), bounds);
        width = bounds.width();
        height = bounds.height();
    }

    public static int measureWidth(String text, float fontSize, Context context) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setTextSize(fontSize);
        paint.setTypeface(getTypeface("Overlock-Regular.ttf", context));
        Rect bounds = new Rect();
        paint.getTextBounds(text, 0, text.length(), bounds);
        return bounds.width();
    }

    public void setText(String text) {
        this.text = text;
        measure(text);
    }
    public String getText() {
        return text;
    }

    public void setFont(String font) {
        this.font = font;
    }

    private Typeface getFont() {
        return getTypeface(font, context);
    }

    public static Typeface getTypeface(String fontName, Context context) {
        if (fontCache.containsKey(fontName)) {
            return fontCache.get(fontName);
        }
        Typeface face = Typeface.createFromAsset(context.getAssets(), "fonts/" + fontName);
        fontCache.put(fontName, face);
        return face;
    }

    @Override
    public void setColor(int color) {
        super.setColor(color);
        paint.setColor(color);
    }

    @Override
    public void resizeCorner(String corner, int x, int y) {
        float oldWidth = width;
        Log.d(TAG, "corner: " + corner + " x=" + x + " y=" + y + " width=" + width);
        if (corner.endsWith("r")) {
            width = Math.max(10, width + x);
        } else {
            if (width - x < 10) return;
            width -= x;
            this.x += x;
        }
        paint.setTextSize(10);
        fontSize *= (width / oldWidth);
        int newWidth = width;
        Log.d(TAG, "New width: " + width + " font: " + fontSize);
        paint.setTextSize(fontSize);
        if (corner.startsWith("t")) {
            int oldHeight = height;
            measure(text);
            this.y += oldHeight - height;
        } else {
            measure(text);
        }
        width = newWidth;
    }

    public void resizeBy(float amount) {
        float oldWidth = width;
        paint.setTextSize(10);
        fontSize *= amount;
        paint.setTextSize(fontSize);
        int oldHeight = height;
        measure(text);
        this.y += (oldHeight - height) / 2;
        this.x += (oldWidth - width) / 2;
    }

    public void renderInto(Canvas canvas, boolean showBorders) {
        float finalX = x, finalY = y;
        canvas.save();
        canvas.translate(finalX, finalY);
        if (rotation != 0) {
            canvas.rotate((float)Math.toDegrees(rotation), width / 2, height / 2);
        }

        canvas.drawText(text, - threshold / 2, height - threshold / 2, paint);
        if (showBorders) renderBorders(canvas);
        canvas.restore();
    }

    @Override
    public void renderBorders(Canvas canvas) {
        super.renderBorders(canvas);
        float left = x - threshold, right = x + width + threshold;
        float top = y - threshold, bottom = y + height + threshold;
        //canvas.drawBitmap(editIcon, left - editIcon.getWidth() / 2, top - editIcon.getHeight() / 2, fillColor);
    }
}


text:
	  <title>DeepChart</title>
    <link rel="stylesheet" type="text/css" href="./style.css">
    <link rel="stylesheet" type="text/css" href="./about_style.css">
    <link rel="shortcut icon" type="image/png" href="./favicon.png"/>

DeepChart

HOME

CHART

ABOUT

Easy way to visualize your neural models

This project is born to make neural network and deep learning models easier to visualize.

The visual models this site creates are not meant to completely describe a neural model, but they are easy to explain those complicated algorithm to everyone.

Add your image to your code project to make it more understandable.

How to get your chart

It'easy to generate your own model, just paste your code into the box on the chart page and click generate.

There are only few rules to follow:

 Each new layer declaration must be done on a new line.

 It doesn't matter if you write only the class or the complete declaration.

 You must specify numerically the input shapes and the output.

 If you add a # at the beginning of the line that line will be ignored.

Remeber that not all the layers have been implemented yet!

This project is 100% OpenSource

This project is hosted on github, if you want to contribute
        at the code, help us to implement new wrappers (so far only the keras wrapper has been implemented) come on the page and work on the code.

Contact us also if you notice any bugs, and if you got time(and coffee) help us to fix it.


text:
var olapManager = (function(){

    return {
        // array of all user data received
        userData: [],

        // get all olap data for a given user
        getData: function(jsonParams){
            var req = new XMLHttpRequest();
            req.onreadystatechange=function(){
                // TODO uncomment the req.status == 200 snippet
                if (req.readyState==4 && req.status == 200){
                    olapManager.displayData(JSON.parse(req.responseText));
                    //olapManager.graphUserData(user
                } else if (req.readyState==4 && req.status != 200){
                    swal("Could not get OLAP data");
                }
            };
            // send post request to /main/remove_user_from_group
            // json object passed {"groupMember": groupMember, "groupName":groupName}
            req.open("POST","/main/get_olap_data/", true);
            req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            req.send(jsonParams);
        },

        displayData: function(table){
            // find the column names
            columnLabels = Object.keys(table[0]);
            tableElement = document.createElement("table");
            // place the table in the document
            tableContainer = document.getElementById("table-container");

            // delete any existing table before appending the new one
            while (tableContainer.hasChildNodes()){
                tableContainer.removeChild(tableContainer.lastChild);
            }
            tableContainer.appendChild(tableElement);
            table.className = "table";
            tableHeaderRow = document.createElement("tr");
            tableElement.appendChild(tableHeaderRow);
            for (var i = 0; i < columnLabels.length; i++){
                columbLabel = document.createElement("th");
                columbLabel.innerHTML = columnLabels[i];
                tableHeaderRow.appendChild(columbLabel);
            }

            // create the rows
            for (var j = 0; j < table.length; j++){
                row = table[j];
                tableRow = document.createElement("tr");
                tableElement.appendChild(tableRow);
                for (var attribute in row) {
                    if (row.hasOwnProperty(attribute)){
                        tableAttribute = document.createElement("td");
                        tableAttribute.innerHTML = row[attribute];
                        tableRow.appendChild(tableAttribute);
                    }
                }
            }
        }
    };
})();

window.onload = function() {
    // set up the user selection box
    $("#search-term").hide();
    $("#btn-group").hide();
    userSelectBox = document.getElementById("get-data-button");
    userSelectBox.addEventListener("click", function() {
        var byUser = document.getElementById("user");
        var byUser = byUser.options[byUser.selectedIndex].dataset.byuser;
        var byDate = document.getElementById("time-period");
        var byDate = byDate.options[byDate.selectedIndex].dataset.bydate;
        var bySubject = document.getElementById("subject");
        var bySubject = bySubject.options[bySubject.selectedIndex].dataset.bysubject;
        var startDate = document.getElementById("start-date").value;
        if (startDate == ""){
            startDate = "False";
        }
        var endDate = document.getElementById("end-date").value;
        if (endDate == ""){
            endDate = "False";
        }
        olapManager.getData(JSON.stringify({byUser: byUser, byDate: byDate,
                                bySubject: bySubject, startDate: startDate, endDate: endDate}));
    });
};


text:
#ifndef _EGLUGLUTIL_HPP
#define _EGLUGLUTIL_HPP
/*!
 * \file
 * \brief EGL utilities for interfacing with GL APIs.
 *//*--------------------------------------------------------------------*/

#include "egluDefs.hpp"
#include "eglwDefs.hpp"

#include "gluRenderConfig.hpp"
#include "glwDefs.hpp"

namespace eglw
{
class Library;
}

namespace eglu
{

glw::GLenum			getImageGLTarget		(eglw::EGLenum source);
eglw::EGLint		apiRenderableType		(glu::ApiType apiType);
eglw::EGLContext	createGLContext			(const eglw::Library& egl, eglw::EGLDisplay display, eglw::EGLConfig config, const glu::ContextType& contextType);
eglw::EGLConfig		chooseConfig			(const eglw::Library& egl, eglw::EGLDisplay display, const glu::RenderConfig& config);

}

#endif // _EGLUGLUTIL_HPP


text:
    /// vtbl in G++ seem to be alligned by 16 bytes
    #define XTL_IRRELEVANT_VTBL_BITS 4
#endif

//------------------------------------------------------------------------------

#define XTL_FUNCTION __func__

//------------------------------------------------------------------------------

#define XTL_COUNTER __COUNTER__

//------------------------------------------------------------------------------

#if __has_builtin(__builtin_assume)
#define XTL_ASSUME(expr) __builtin_assume(expr)
#endif
#if __has_builtin(__builtin_unreachable)
#define XTL_UNREACHABLE  __builtin_unreachable()
#endif

#if !XTL_TRACE_LIKELINESS
    /// Macros to use compiler's branch hinting.
    /// \note These macros are only to be used in Case macro expansion, not in
    ///       user's code since they explicitly expect a pointer argument
    /// \note We use ... (__VA_ARGS__ parameters) to allow expressions
    ///       containing comma as argument. Essentially this is a one arg macro
#if __has_builtin(__builtin_expect)
    #define   XTL_LIKELY(...) (__builtin_expect((long int)(__VA_ARGS__), 1))
    #define XTL_UNLIKELY(...) (__builtin_expect((long int)(__VA_ARGS__), 0))
#endif
#endif

#if __has_attribute(noinline)
/// A macro that is supposed to be put before the function definition whose inlining should be disabled
#define XTL_DO_NOT_INLINE_BEGIN __attribute__ ((noinline))
/// A macro that is supposed to be put after  the function definition whose inlining should be disabled
#define XTL_DO_NOT_INLINE_END
#endif
#if __has_attribute(always_inline)
/// A macro that is supposed to be put before the function definition whose body must be inlined
#define XTL_FORCE_INLINE_BEGIN __attribute__ ((always_inline)) static inline
/// A macro that is supposed to be put after  the function definition whose body must be inlined
#define XTL_FORCE_INLINE_END
#endif
#if __has_attribute(unused)
/// An attribute used in GCC code to silence warning about potentially unused typedef target_type, which we
/// generate to fall back on from Case clauses. The typedef is required in some cases, do not remove.
#define XTL_UNUSED_TYPEDEF __attribute__((unused))
#endif

//------------------------------------------------------------------------------

/// Helper macro to use the sandard _Pragma operator
#define XTL_PRAGMA(x) _Pragma(#x)
#if XTL_MESSAGE_ENABLED
    /// Helper macro to output a message during compilation. GCC prepends file and line info to it anyways
    #define XTL_MESSAGE(str) XTL_PRAGMA(message str)
#endif

    /// Macro to save the settings for diagnostics before the library will modify some
    #define XTL_WARNING_PUSH XTL_PRAGMA(GCC diagnostic push)
    /// Macro to restore the settings for diagnostics after the library has modified some
    #define XTL_WARNING_POP  XTL_PRAGMA(GCC diagnostic pop)
#if __has_warning("-Wall")
    /// Macro that disables all warnings
  //#define XTL_WARNING_IGNORE_ALL                  XTL_PRAGMA(GCC diagnostic ignored "-Wall")
#endif
    /// Macro that disables warning on constant conditional expression, which we have a lot from code generated by macros
    #define XTL_WARNING_IGNORE_CONSTANT_CONDITIONAL
#if __has_warning("-Wstrict-aliasing")
    /// Macro that disables warning on manipulating pointers with reinterpret_cast
    #define XTL_WARNING_IGNORE_STRICT_ALIASING      XTL_PRAGMA(GCC diagnostic ignored "-Wstrict-aliasing") // warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
#endif

//------------------------------------------------------------------------------

// to avoid deprecation macro
#define register

//------------------------------------------------------------------------------


text:
/******************************************************************************
 *
 * Module Name: oswindir - Windows directory access interfaces
 *
 *****************************************************************************/

/******************************************************************************
 *
 * 1. Copyright Notice
 *
 * Some or all of this work - Copyright (c) 1999 - 2011, Intel Corp.
 * All rights reserved.
 *
 * 2. License
 *
 * 2.1. This is your license from Intel Corp. under its intellectual property
 * rights.  You may have additional license terms from the party that provided
 * you this software, covering your right to use that party's intellectual
 * property rights.
 *
 * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
 * copy of the source code appearing in this file ("Covered Code") an
 * irrevocable, perpetual, worldwide license under Intel's copyrights in the
 * base code distributed originally by Intel ("Original Intel Code") to copy,
 * make derivatives, distribute, use and display any portion of the Covered
 * Code in any form, with the right to sublicense such rights; and
 *
 * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
 * license (with the right to sublicense), under only those claims of Intel
 * patents that are infringed by the Original Intel Code, to make, use, sell,
 * offer to sell, and import the Covered Code and derivative works thereof
 * solely to the minimum extent necessary to exercise the above copyright
 * license, and in no event shall the patent license extend to any additions
 * to or modifications of the Original Intel Code.  No other license or right
 * is granted directly or by implication, estoppel or otherwise;
 *
 * The above copyright and patent license is granted only if the following
 * conditions are met:
 *
 * 3. Conditions
 *
 * 3.1. Redistribution of Source with Rights to Further Distribute Source.
 * Redistribution of source code of any substantial portion of the Covered
 * Code or modification with rights to further distribute source must include
 * the above Copyright Notice, the above License, this list of Conditions,
 * and the following Disclaimer and Export Compliance provision.  In addition,
 * Licensee must cause all Covered Code to which Licensee contributes to
 * contain a file documenting the changes Licensee made to create that Covered
 * Code and the date of any change.  Licensee must include in that file the
 * documentation of any changes made by any predecessor Licensee.  Licensee
 * must include a prominent statement that the modification is derived,
 * directly or indirectly, from Original Intel Code.
 *
 * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
 * Redistribution of source code of any substantial portion of the Covered
 * Code or modification without rights to further distribute source must
 * include the following Disclaimer and Export Compliance provision in the
 * documentation and/or other materials provided with distribution.  In
 * addition, Licensee may not authorize further sublicense of source of any
 * portion of the Covered Code, and must include terms to the effect that the
 * license from Licensee to its licensee is limited to the intellectual
 * property embodied in the software Licensee provides to its licensee, and
 * not to intellectual property embodied in modifications its licensee may
 * make.
 *
 * 3.3. Redistribution of Executable. Redistribution in executable form of any
 * substantial portion of the Covered Code or modification must reproduce the
 * above Copyright Notice, and the following Disclaimer and Export Compliance
 * provision in the documentation and/or other materials provided with the
 * distribution.
 *
 * 3.4. Intel retains all right, title, and interest in and to the Original
 * Intel Code.
 *
 * 3.5. Neither the name Intel nor any other trademark owned or controlled by
 * Intel shall be used in advertising or otherwise to promote the sale, use or
 * other dealings in products derived from or relating to the Covered Code
 * without prior written authorization from Intel.
 *
 * 4. Disclaimer and Export Compliance
 *
 * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
 * HERE.  ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
 * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT,  ASSISTANCE,
 * INSTALLATION, TRAINING OR OTHER SERVICES.  INTEL WILL NOT PROVIDE ANY
 * UPDATES, ENHANCEMENTS OR EXTENSIONS.  INTEL SPECIFICALLY DISCLAIMS ANY
 * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE.
 *
 * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
 * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
 * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
 * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
 * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
 * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.  THESE LIMITATIONS
 * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
 * LIMITED REMEDY.
 *
 * 4.3. Licensee shall not export, either directly or indirectly, any of this
 * software or system incorporating such software without first obtaining any
 * required license or other approval from the U. S. Department of Commerce or
 * any other agency or department of the United States Government.  In the
 * event Licensee exports any such software from the United States or
 * re-exports any such software from a foreign destination, Licensee shall
 * ensure that the distribution and export/re-export of the software is in
 * compliance with all laws, regulations, orders, or other restrictions of the
 * U.S. Export Administration Regulations. Licensee agrees that neither it nor
 * any of its subsidiaries will export/re-export any technical data, process,
 * software, or service, directly or indirectly, to any country for which the
 * United States government or any agency thereof requires an export license,
 * other governmental approval, or letter of assurance, without first obtaining
 * such license, approval or letter.
 *
 *****************************************************************************/

#include <acpi.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>

typedef struct ExternalFindInfo
{
    struct _finddata_t          DosInfo;
    char                        *FullWildcardSpec;
    long                        FindHandle;
    char                        State;
    char                        RequestedFileType;

} EXTERNAL_FIND_INFO;

/*******************************************************************************
 *
 * FUNCTION:    AcpiOsOpenDirectory
 *
 * PARAMETERS:  DirPathname         - Full pathname to the directory
 *              WildcardSpec        - string of the form "*.c", etc.
 *              RequestedFileType   - Either a directory or normal file
 *
 * RETURN:      A directory "handle" to be used in subsequent search operations.
 *              NULL returned on failure.
 *
 * DESCRIPTION: Open a directory in preparation for a wildcard search
 *
 ******************************************************************************/

void *
AcpiOsOpenDirectory (
    char                    *DirPathname,
    char                    *WildcardSpec,
    char                    RequestedFileType)
{
    long                    FindHandle;
    char                    *FullWildcardSpec;
    EXTERNAL_FIND_INFO      *SearchInfo;

    /* No directory path means "use current directory" - use a dot */

    if (!DirPathname || strlen (DirPathname) == 0)
    {
        DirPathname = ".";
    }

    /* Allocate the info struct that will be returned to the caller */

    SearchInfo = calloc (sizeof (EXTERNAL_FIND_INFO), 1);
    if (!SearchInfo)
    {
        return (NULL);
    }

    /* Allocate space for the full wildcard path */

    FullWildcardSpec = calloc (strlen (DirPathname) + strlen (WildcardSpec) + 2, 1);
    if (!FullWildcardSpec)
    {
        printf ("Could not allocate buffer for wildcard pathname\n");
        return (NULL);
    }

    /* Create the full wildcard path */

    strcpy (FullWildcardSpec, DirPathname);
    strcat (FullWildcardSpec, "/");
    strcat (FullWildcardSpec, WildcardSpec);

    /* Initialize the find functions, get first match */

    FindHandle = _findfirst (FullWildcardSpec, &SearchInfo->DosInfo);
    if (FindHandle == -1)
    {
        /* Failure means that no match was found */

        free (FullWildcardSpec);
        free (SearchInfo);
        return (NULL);
    }

    /* Save the info in the return structure */

    SearchInfo->RequestedFileType = RequestedFileType;
    SearchInfo->FullWildcardSpec = FullWildcardSpec;
    SearchInfo->FindHandle = FindHandle;
    SearchInfo->State = 0;
    return (SearchInfo);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiOsGetNextFilename
 *
 * PARAMETERS:  DirHandle           - Created via AcpiOsOpenDirectory
 *
 * RETURN:      Next filename matched. NULL if no more matches.
 *
 * DESCRIPTION: Get the next file in the directory that matches the wildcard
 *              specification.
 *
 ******************************************************************************/

char *
AcpiOsGetNextFilename (
    void                    *DirHandle)
{
    EXTERNAL_FIND_INFO      *SearchInfo = DirHandle;
    int                     Status;
    char                    FileTypeNotMatched = 1;

    /*
     * Loop while we have matched files but not found any files of
     * the requested type.
     */
    while (FileTypeNotMatched)
    {
        /* On the first call, we already have the first match */

        if (SearchInfo->State == 0)
        {
            /* No longer the first match */

            SearchInfo->State = 1;
        }
        else
        {
            /* Get the next match */

            Status = _findnext (SearchInfo->FindHandle, &SearchInfo->DosInfo);
            if (Status != 0)
            {
                return (NULL);
            }
        }

        /*
         * Found a match, now check to make sure that the file type
         * matches the requested file type (directory or normal file)
         *
         * NOTE: use of the attrib field saves us from doing a very
         * expensive stat() on the file!
         */
        switch (SearchInfo->RequestedFileType)
        {
        case REQUEST_FILE_ONLY:

            /* Anything other than A_SUBDIR is OK */

            if (!(SearchInfo->DosInfo.attrib & _A_SUBDIR))
            {
                FileTypeNotMatched = 0;
            }
            break;

        case REQUEST_DIR_ONLY:

            /* Must have A_SUBDIR bit set */

            if (SearchInfo->DosInfo.attrib & _A_SUBDIR)
            {
                FileTypeNotMatched = 0;
            }
            break;

        default:
            return (NULL);
        }
    }

    return (SearchInfo->DosInfo.name);
}

/*******************************************************************************
 *
 * FUNCTION:    AcpiOsCloseDirectory
 *
 * PARAMETERS:  DirHandle           - Created via AcpiOsOpenDirectory
 *
 * RETURN:      None
 *
 * DESCRIPTION: Close the open directory and cleanup.
 *
 ******************************************************************************/

void
AcpiOsCloseDirectory (
    void                    *DirHandle)
{
    EXTERNAL_FIND_INFO      *SearchInfo = DirHandle;

    /* Close the directory and free allocations */

    _findclose (SearchInfo->FindHandle);
    free (SearchInfo->FullWildcardSpec);
    free (DirHandle);
}


text:
from draftlog.logdraft import LogDraft
from draftlog import ansi
import draftlog
import time
import sys
import threading

# Imports the correct module according to
# Python version.
if sys.version_info[0] <= 2:
    import Queue as queue
else:
    import queue

"""
A background process to coordinate all the intervals
with their correct times rather than having clashing
multiple threads.
"""
class DaemonDrafter(threading.Thread):
    def __init__(self):
        super(DaemonDrafter, self).__init__()

        self.lcs = sys.stdout
        self.intervals = []
        self.counter = -1
        self.time_interval = 0
        self.end = False

    """
    What actually adds the interval.
    "Loader" specifies if the interval should
    affect when the draft actually exits.
    line, or to add a new line afterwards.
    """
    def add_interval(self, logdraft, func, seconds, loader=False):
        if loader != None:
            loader = not loader

        self.intervals.append({
            "function":  func,
            "logdraft":  logdraft,
            "time"    :  seconds,
            "backup"  :  "",
            "status"  :  loader,
        })
        self.sort_intervals()

    # Generates correct timing for intervals
    def sort_intervals(self):
        smallest = lambda x: x["time"]
        sort = sorted(self.intervals, key=smallest)
        self.smallest_interval = min(sort, key=smallest)
        self.time_interval = self.smallest_interval["time"]
        for interval in self.intervals:
            interval["increment_on"] = int(round(interval["time"] / self.time_interval))
            interval["backup"] = "" # This is an important thing to change/remember

    # Parses interval output according to its statuses
    def parse_interval_output(self, interval):
        try:
            if self.counter % interval["increment_on"] == 0:
                output = interval["function"]()
                interval["backup"] = output
            else:
                output = interval["backup"]
        except draftlog.Exception:
            output = interval["backup"]
            interval["status"] = False

        return str(output)

    # What actually updates the LogDraft lines.
    def run_intervals(self):
        for interval in self.intervals:
            text = self.parse_interval_output(interval)
            interval["logdraft"].update(text)

    # Checks if all intervals are done.
    def check_done(self):
        return all(x["status"] in (False, None) for x in self.intervals)

    # The actual running loop for updating intervals.
    def run(self):
        lines = 0
        while self.check_done() == False and self.end == False:
            self.counter += 1
            self.run_intervals()
            time.sleep(self.time_interval)
        self.lcs.write(ansi.clearline)
        sys.exit()

    def stop(self):
        self.end = True

"""
Pretty much just a wrapper for "DaemonDrafter".
It's what the user actually interacts with and what
"draftlog.inject()" returns.
"""
class Drafter:
    def __init__(self):
        self.daemon_drafter = DaemonDrafter()
        self.lcs = self.daemon_drafter.lcs

    # Returns a "LogDraft" object on the correct line
    def log(self, text="\n"):
        if text != "\n": text = text + "\n"
        logdraft = LogDraft(self.daemon_drafter, text=text)
        return logdraft

    def start(self):
        self.daemon_drafter.start()

    def stop(self):
        self.daemon_drafter.stop()


text:
ENV['THOR_COLUMNS'] = '160'

require 'simplecov'
SimpleCov.start do
  add_filter '/spec/'
end

require 'bundler/setup'
require 'bundle_outdated_formatter'

require 'stringio'
class StringIO
  def ioctl(*)
    0
  end
end

RSpec.configure do |config|
  # Enable flags like --only-failures and --next-failure
  config.example_status_persistence_file_path = '.rspec_status'

  # Disable RSpec exposing methods globally on `Module` and `main`
  config.disable_monkey_patching!

  config.expect_with :rspec do |c|
    c.syntax = :expect
  end

  original_stdout = $stdout
  original_stderr = $stderr
  config.before(:suite) do
    $stdout = File.open(File::NULL, 'w')
    $stderr = File.open(File::NULL, 'w')
  end
  config.after(:suite) do
    $stdout = original_stdout
    $stderr = original_stderr
  end
end