text:
Express 3 handlebars template engine with multiple layouts, blocks and cached partials.

Open source project from [Barc](http://barc.com), instant real-time forum on any website.

**0.7 BREAKING CHANGES**: The logic for layout resolution for layoutsDir,
layout and declarative layouts in previous versions stepped on each other.
Read Layouts section below on how layouts are resolved.

## Usage

To use with express 3.

    var hbs = require('express-hbs');

    // Use `.hbs` for extensions and find partials in `views/partials`.
    app.engine('hbs', hbs.express3({
      partialsDir: __dirname + '/views/partials'
    }));
    app.set('view engine', 'hbs');
    app.set('views', __dirname + '/views');

Options for `#express3`

    hbs.express3({
      partialsDir: "{String/Array} [Required] Path to partials templates, one or several directories",

      // OPTIONAL settings
      blockHelperName: "{String} Override 'block' helper name.",
      contentHelperName: "{String} Override 'contentFor' helper name.",
      defaultLayout: "{String} Absolute path to default layout template",
      extname: "{String} Extension for templates, defaults to `.hbs`",
      handlebars: "{Module} Use external handlebars instead of express-hbs dependency",
      i18n: "{Object} i18n object",
      layoutsDir: "{String} Path to layout templates",
      templateOptions: "{Object} options to pass to template()",
      beautify: "{Boolean} whether to pretty print HTML, see github.com/einars/js-beautify .jsbeautifyrc
    });

Partials may use any extension, which is better for syntax highlighting.

## Syntax

To mark where layout should insert page

    {{{body}}}

To declare a block placeholder in layout

    {{{block "pageScripts"}}}

To define block content in a page

    {{#contentFor "pageScripts"}}
      CONTENT HERE
    {{/contentFor}}

## Layouts

There are three ways to use a layout, listed in precedence order

1.  Declarative within a page. Use handlebars comment

        {{!< LAYOUT}}

    Layout file resolution:

        If path starts with '.'
            LAYOUT is relative to template
        Else If `layoutsDir` is set
            LAYOUT is relative to `layoutsDir`
        Else
            LAYOUT from path.resolve(dirname(template), LAYOUT)

2.  As an option to render

        res.render('veggies', {
          title: 'My favorite veggies',
          veggies: veggies,
          layout: 'layout/veggie'
        });

    This option also allows for layout suppression (both the default layout and when specified declaratively in a page) by passing in a falsey Javascript value as the value of the `layout` property:

        res.render('veggies', {
          title: 'My favorite veggies',
          veggies: veggies,
          layout: null // render without using a layout template
        });

    Layout file resolution:

        If path starts with '.'
            layout is relative to template
        Else If `layoutsDir` is set
            layout is relative to `layoutsDir`
        Else
            layout from path.resolve(viewsDir, layout)

3.  Lastly, use `defaultLayout` if specified in hbs configuration options.

Layouts can be nested: just include a declarative layout tag within any layout
template to have its content included in the declared "parent" layout.  Be
aware that too much nesting can impact performances, and stay away from
infinite loops!

## Helpers

Synchronous helpers

    hbs.registerHelper('link', function(text, options) {
      var attrs = [];
      for(var prop in options.hash) {
        attrs.push(prop + '="' + options.hash[prop] + '"');
      }
      return new hbs.SafeString(
        "<a " + attrs.join(" ") + ">" + text + "</a>"
      );
    });

    # in markup
    {{{link 'barc.com' href='http://barc.com'}}}

Asynchronous helpers

    hbs.registerAsyncHelper('readFile', function(filename, cb) {
      fs.readFile(path.join(viewsDir, filename), 'utf8', function(err, content) {
        cb(new hbs.SafeString(content));
      });
    });

    # in markup
    {{{readFile 'tos.txt'}}}

## i18n support

Express-hbs supports [i18n](https://github.com/mashpie/i18n-node)

    var i18n = require('i18n');

    // minimal config
    i18n.configure({
        locales: ['en', 'fr'],
        cookie: 'locale',
        directory: __dirname + "/locales"
    });

    app.engine('hbs', hbs.express3({
        // ... options from above
        i18n: i18n,  // registers __ and __n helpers
    }));
    app.set('view engine', 'hbs');
    app.set('views', viewsDir);

    // cookies are needed
    app.use(express.cookieParser());

    // init i18n module
    app.use(i18n.init);

## Engine Instances

Create isolated engine instances with their own cache system and handlebars engine.

    var hbs = require('express-hbs');
    var instance1 = hbs.create();
    var instance2 = hbs.create();

## Example

in File `app.js`
```
// http://expressjs.com/api.html#app.locals
app.locals({
    'PROD_MODE': 'production' === app.get('env')
});

```

File `views/layout/default.hbs`

```
<html>
  <head>
    <title>{{title}}</title>
    <link type="text/css" rel="stylesheet" href="/css/style.css"/>
    {{{block "pageStyles"}}}
  </head>
  <body>
    {{{body}}}

    {{> scripts}}

    {{#if PROD_MODE}}
    {{{block 'googleAnalyticsScripts'}}}
    {{/if}}

  </body>
</html>
```

File `views/index.hbs`

```
{{!< default}}

{{#contentFor 'pageStyles'}}
<style>
  .clicker {
    color: blue;
  };
</style>
{{/contentFor}}

<h1>{{title}}</h1>
<p class="clicker">Click me!</p>
```

To run example project

    npm install -d
    node example/app.js

## Testing

The test suite requires the `grunt-cli` package:

    npm install -g grunt-cli
    npm install -d

Once everything's installed, just run:

    npm test

## Credits

Inspiration and code from [donpark/hbs](https://github.com/donpark/hbs)

Big thanks to all [CONTRIBUTORS](https://github.com/barc/express-hbs/contributors)

## License

The MIT License (MIT)

Copyright (c) 2012-2014 Barc, Inc.

See file LICENSE for copying permissions.


text:
using System;
using System.Collections.Generic;
using System.IO;

using FlacBox;

namespace FlacTranscode
{
    class Program
    {
        private static void PrintUsage()
        {
            Console.WriteLine("FlacTranscode.exe <mode> <input-file> <output-file>");
            Console.WriteLine("Modes:");
            Console.WriteLine("    -wave2flac");
            Console.WriteLine("    -wave2ogg");
            Console.WriteLine("    -flac2wave");
            Console.WriteLine("    -flac2wave16");
            Console.WriteLine("    -ogg2wave");
        }

        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                PrintUsage(); return;
            }

            string mode = args[0].ToLowerInvariant();
            string inputFile = args[1];
            string outputFile = args[2];

            Stream inputStream = null;
            Stream outputStream = null;
            try
            {
                switch (mode)
                {
                    case "-wave2flac":
                        inputStream = File.OpenRead(inputFile);
                        outputStream = new WaveOverFlacStream(
                            File.Create(outputFile), WaveOverFlacStreamMode.Encode);
                        break;
                    case "-wave2ogg":
                        inputStream = File.OpenRead(inputFile);
                        outputStream = new FlacOverOggStream(
                            new WaveOverFlacStream(File.Create(outputFile), WaveOverFlacStreamMode.Encode),
                            FlacOverOggStreamMode.Encode);
                        break;
                    case "-flac2wave":
                        inputStream = new WaveOverFlacStream(
                            File.OpenRead(inputFile), WaveOverFlacStreamMode.Decode);
                        outputStream = File.Create(outputFile);
                        break;
                    case "-flac2wave16":
                        inputStream = new Wave16OverFlacStream(File.OpenRead(inputFile));
                        outputStream = File.Create(outputFile);
                        break;
                    case "-ogg2wave":
                        inputStream = new FlacOverOggStream(
                            new WaveOverFlacStream(File.OpenRead(inputFile), WaveOverFlacStreamMode.Decode),
                            FlacOverOggStreamMode.Decode);
                        outputStream = File.Create(outputFile);
                        break;
                    default:
                        throw new ApplicationException("Unknown transcode option: " + mode);
                }

                Console.WriteLine("Copying data from '{0}' to '{1}'.",
                    inputFile, outputFile);

                CopyStreams(inputStream, outputStream);

                Console.WriteLine();
                Console.WriteLine("Done.");
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
            finally
            {
                if (inputStream != null) inputStream.Close();
                if (outputStream != null) outputStream.Close();
            }
        }

        private static void CopyStreams(Stream s, Stream t)
        {
            byte[] buffer = new byte[0x1000];
            int read = s.Read(buffer, 0, buffer.Length);
            while (read > 0)
            {
                t.Write(buffer, 0, read);
                read = s.Read(buffer, 0, buffer.Length);
                Console.Write('.');
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "cinder/Cinder.h"

#if !defined(CINDER_ANDROID)
#   error UNSUPPORTED PLATFORM
#endif

// ---

#include "chronotext/system/FileHelperBase.h"
#include "chronotext/system/SystemInfo.h"
#include "chronotext/InputSource.h"

#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>

namespace chr
{
    namespace file
    {
        class Helper : public HelperBase
        {
        public:
            static void setup(const system::InitInfo &initInfo);
            static void shutdown();

            static AAssetManager* getAssetManager();

            static ci::fs::path getInternalDataPath();
            static ci::fs::path getExternalDataPath();
            static ci::fs::path getApkPath();

            static AAsset* openAsset(const InputSource &inputSource, int mode = AASSET_MODE_UNKNOWN);
        };
    }
}


text:
package org.workcraft.utils;

import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.w3c.dom.Document;
import org.workcraft.dom.visual.VisualGroup;
import org.workcraft.dom.visual.VisualModel;
import org.workcraft.exceptions.SerialisationException;
import org.workcraft.gui.tools.Decorator;

import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class BatikUtils {

    private static final double SCALE_FACTOR = 50.0;

    public static void transcode(VisualModel model, OutputStream out)
            throws SerialisationException {

        generateSvgGraphics(model, out);
    }

    public static void transcode(VisualModel model, OutputStream out, Transcoder transcoder)
            throws SerialisationException {

        ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
        generateSvgGraphics(model, bufOut);
        ByteArrayInputStream bufIn = new ByteArrayInputStream(bufOut.toByteArray());
        TranscoderInput transcoderInput = new TranscoderInput(bufIn);
        TranscoderOutput transcoderOutput = new TranscoderOutput(out);
        try {
            transcoder.transcode(transcoderInput, transcoderOutput);
        } catch (TranscoderException e) {
            throw new SerialisationException(e);
        }
    }

    private static void generateSvgGraphics(VisualModel model, OutputStream out) throws SerialisationException {
        try {
            Document doc = XmlUtils.createDocument();
            SVGGraphics2D g2d = new SVGGraphics2D(doc);
            g2d.setUnsupportedAttributes(null);
            g2d.scale(SCALE_FACTOR, SCALE_FACTOR);
            VisualGroup visualGroup = (VisualGroup) model.getRoot();
            Rectangle2D bounds = visualGroup.getBoundingBoxInLocalSpace();
            g2d.translate(-bounds.getMinX(), -bounds.getMinY());
            int canvasWidth = (int) (bounds.getWidth() * SCALE_FACTOR);
            int canvasHeight = (int) (bounds.getHeight() * SCALE_FACTOR);
            g2d.setSVGCanvasSize(new Dimension(canvasWidth, canvasHeight));
            model.draw(g2d, Decorator.Empty.INSTANCE);
            g2d.stream(new OutputStreamWriter(out, StandardCharsets.UTF_8));
            out.flush();
        } catch (IOException e) {
            throw new SerialisationException(e);
        }
    }

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:screenOrientation="portrait"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainScreenActivity" >

    <ImageView
        android:id="@+id/alertBackground"
        android:layout_width="450dp"
        android:layout_height="75dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:contentDescription="@string/generic_desc"
        android:scaleType="fitXY"
        android:src="@drawable/applabelsdark" />

    <TextView
        android:id="@+id/alertLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/alertBackground"
        android:layout_centerHorizontal="true"
        android:textColor="#FFFFFF" />

    <Button
        android:id="@+id/schedules"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/alertBackground"
        android:layout_alignRight="@+id/alertBackground"
        android:layout_below="@+id/alertBackground"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="27dp"
        android:background="@drawable/applabels"
        android:onClick="openSchedule"
        android:layout_centerInParent="true"
        android:text="Schedules" />

    <Button
        android:id="@+id/agendaButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/schedules"
        android:layout_alignRight="@+id/schedules"
        android:layout_below="@+id/schedules"
        android:layout_marginTop="22dp"
        android:background="@drawable/applabels"
        android:onClick="openAgenda"
        android:layout_centerInParent="true"
        android:text="Agenda" />

    <Button
        android:id="@+id/callButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/agendaButton"
        android:layout_alignRight="@+id/agendaButton"
        android:layout_below="@+id/agendaButton"
        android:layout_marginTop="26dp"
        android:background="@drawable/applabels"
        android:onClick="callPandr"
        android:layout_centerInParent="true"
        android:text="Call Rec Center" />

    <TextView
        android:id="@+id/alertDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/alertLabel"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:maxHeight="350px"
        android:maxLines="5"
        android:maxWidth="550px"
        android:scrollHorizontally="false"
        android:scrollbars="vertical"
        android:text="No Alerts!"
        android:textColor="#FFFFFF" />

</RelativeLayout><!-- From: file:/Users/nikhilparanjape/Parks-and-Recreation/app/src/main/res/layout/activity_main.xml -->


text:
#include "stdafx.h"
#include "DriveItem.h"
#include <stdio.h>

using namespace Fusion::GoogleDrive;

CDriveItem::CDriveItem()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::CDriveItem()");

  _fileInfo = NULL;
}

CDriveItem::CDriveItem(Fusion::GoogleDrive::FileInfo* fileInfo)
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::CDriveItem(Fusion::GoogleDrive::FileInfo* fileInfo)");

  _fileInfo = NULL;

  FileInfo(fileInfo);
}

CDriveItem::~CDriveItem()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::~CDriveItem()");

  FileInfo(NULL);
}

Fusion::GoogleDrive::FileInfo* CDriveItem::FileInfo()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::FileInfo()");

  return _fileInfo;
}

void CDriveItem::FileInfo(Fusion::GoogleDrive::FileInfo* value)
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::FileInfo(Fusion::GoogleDrive::FileInfo* value)");

  FileInfo::Release(&_fileInfo);

  _fileInfo = value;

  if (_fileInfo != NULL)
  {
    _fileInfo->AddRef();
  }
}

std::vector<FileInfo*>* CDriveItem::Files()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::Files()");

  return &_fileInfo->Files;
}

std::wstring CDriveItem::Id()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::Id()");

  return _fileInfo->Id;
}

bool CDriveItem::IsFolder()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::IsFolder()");

  return _fileInfo->IsFolder();
}

bool CDriveItem::IsFile()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::IsFile()");

  return _fileInfo->IsFile();
}

bool CDriveItem::IsGoogleDoc()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::IsGoogleDoc()");

  return _fileInfo->IsGoogleDoc();
}

bool CDriveItem::IsRoot()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::IsRoot()");

  return _fileInfo->IsRoot();
}

DriveItemType::eType CDriveItem::Type()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::Type()");

  if (IsRoot())
  {
    return DriveItemType::Root;
  }
  else if (IsFolder())
  {
    return DriveItemType::Folder;
  }
  else if (IsFile())
  {
    return DriveItemType::File;
  }
  else
  {
    return DriveItemType::None;
  }
}

bool CDriveItem::HasChildren()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::HasChildren()");

  bool hasChildren = false;

  if (_fileInfo->IsFolder())
  {
    hasChildren = _fileInfo->HasFoldersOrFiles();
  }
  else
  {
    hasChildren = false;
  }

  return hasChildren;
}

bool CDriveItem::HasSubFolder()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::HasSubFolder()");

  bool hasSubFolder = false;

  if (_fileInfo->IsFolder())
  {
    hasSubFolder = _fileInfo->HasFolders();
  }
  else
  {
    hasSubFolder = false;
  }

  return hasSubFolder;
}

std::wstring CDriveItem::ItemName()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::ItemName()");

  return _fileInfo->Title;
}

std::wstring CDriveItem::ItemPathDisplay()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::ItemPathDisplay()");

  std::wstring path = _fileInfo->FilePath();

  return path;
}

std::wstring CDriveItem::ItemFolderPathDisplay(const std::wstring& rootPath, bool includeSelf)
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::ItemFolderPathDisplay(std::wstring& rootPath, bool includeSelf)");

  if (Type() == DriveItemType::None)
    return L"";

  if (IsRoot() || !includeSelf)
    return rootPath;

  std::wstring path = PathInfo::CombinePath(rootPath, _fileInfo->Title);

  return path;
}

std::wstring CDriveItem::ItemUrl()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::ItemUrl()");

  if (IsFolder())
    return L"";

  std::wstring path = _fileInfo->FilePath();

  path = PathInfo::GetFileUrl(path);

  return path;
}

std::wstring CDriveItem::ItemType()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::ItemType()");

  if (IsFolder())
  {
    return L"Folder";
  }
  else if (IsGoogleDoc())
  {
    return _fileInfo->MimeType;
  }
  else if (IsFile())
  {
    return _fileInfo->FileExtension;
  }
  else
  {
    return L"";
  }
}

std::wstring CDriveItem::ItemTypeText()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::ItemTypeText()");

  if (IsFolder())
  {
    return _fileInfo->Association.FileType;
  }
  else if (IsGoogleDoc())
  {
    return _fileInfo->Association.FileType;
  }
  else if (IsFile())
  {
    return _fileInfo->Association.FileType;
  }
  else
  {
    return L"";
  }
}

std::wstring CDriveItem::ParsingPath()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::ParsingPath()");

  std::wstring path = ItemPathDisplay();

  return path;
}

std::wstring CDriveItem::FileExtension()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::FileExtension()");

  if (IsFolder())
  {
    return L"";
  }
  else
  {
    return _fileInfo->FileExtension;
  }
}

ULONG CDriveItem::FileAttributes()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::FileAttributes()");

  ULONG value = FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED;

  if (IsFolder())
  {
    value |= FILE_ATTRIBUTE_DIRECTORY;
  }

  if (!_fileInfo->Editable)
  {
    value |= FILE_ATTRIBUTE_READONLY;
  }

  return value;
}

std::wstring CDriveItem::DateModified()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::DateModified()");

  if (_fileInfo->ModifiedDate.length() > 0)
  {
    return _fileInfo->ModifiedDate;
  }
  else
  {
    return this->DateCreated();
  }
}

std::wstring CDriveItem::Size()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::Size()");

  if (!IsFile())
    return L"";

  if (IsFolder() || IsGoogleDoc())
    return L"";

  return std::to_wstring(_fileInfo->FileSize);
}

std::wstring CDriveItem::DateCreated()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::DateCreated()");

  return _fileInfo->CreatedDate;
}

std::wstring CDriveItem::DateAccessed()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::DateAccessed()");

  if (_fileInfo->LastViewedByMeDate.length() > 0)
  {
    return _fileInfo->LastViewedByMeDate;
  }
  else
  {
    return this->DateModified();
  }
}

std::wstring CDriveItem::Status()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::Status()");

  if (_fileInfo->Trashed)
  {
    return L"Trashed";
  }
  else if (_fileInfo->Shared)
  {
    return L"Shared";
  }
  else
  {
    return L"";
  }
}

BOOL CDriveItem::IsSendToTarget()
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::IsSendToTarget()");

  if (IsFolder())
  {
    return false;
  }
  else if (IsFile())
  {
    return true;
  }
  else
  {
    return false;
  }
}

BOOL CDriveItem::TryWIN32FindData(WIN32_FIND_DATA& findData)
{
  Log::WriteOutput(LogType::Debug, L"CDriveItem::WIN32FindData()");

  BOOL r = false;

  ZeroMemory(&findData, sizeof(WIN32_FIND_DATA));

  findData.dwFileAttributes = FileAttributes();
  findData.nFileSizeHigh = FileInfo()->FileSize >> 32;
  findData.nFileSizeLow = FileInfo()->FileSize & 0xFFFFFFFF;
  r = FileInfo::TryConvertDateStringToFILETIME(DateCreated(), findData.ftCreationTime);

  if (r)
  {
    r = FileInfo::TryConvertDateStringToFILETIME(DateAccessed(), findData.ftLastAccessTime);
  }

  if (r)
  {
    r = FileInfo::TryConvertDateStringToFILETIME(DateModified(), findData.ftLastWriteTime);
  }

  if (r)
  {
    std::wstring itemName = ItemName();
    r = wcsncpy_s(&findData.cFileName[0], MAX_PATH, itemName.c_str(),  _TRUNCATE) == ERROR_SUCCESS;
  }

  return r;
}

HRESULT CDriveItem::PreceivedType(__out std::wstring& preceivedString)
{
  try
  {
    HRESULT hr = S_OK;

    if (this->IsFile())
    {
      PERCEIVED perceivedType;
      PERCEIVEDFLAG perceivedTypeFlag;
      CComHeapPtr<WCHAR> perceivedTypeString;

      hr = AssocGetPerceivedType(this->FileExtension().c_str(), &perceivedType, &perceivedTypeFlag, &perceivedTypeString);

      if (SUCCEEDED(hr))
      {
        preceivedString.assign(perceivedTypeString);
      }
    }
    else
    {
      preceivedString.assign(L"Folder");
    }

    return hr;
  }
  catch (...)
  {
    Log::WriteOutput(LogType::Error, L"CDriveItem::PreceivedType");

    return E_FAIL;
  }
}


text:
using Aurum.SQL.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Xml.Linq;
using DbTypeLookup = System.Collections.Generic.Dictionary<Aurum.SQL.Data.SqlType, System.Type>;

namespace Aurum.SQL
{
    public class SqlTypeMap
    {
        //Reference: https://msdn.microsoft.com/en-us/library/system.data.SqlType(v=vs.110).aspx

        static readonly DbTypeLookup _SqlTypeLookup;

        static SqlTypeMap()
        {
            _SqlTypeLookup = BuildDbTypeLookup();
        }

        static DbTypeLookup BuildDbTypeLookup()
        {
            return new Dictionary<SqlType, Type>
            {
                {SqlType.BigInt,          typeof(long) },
                {SqlType.Binary,          typeof(byte[]) },
                {SqlType.Bit,             typeof(bool) },
                {SqlType.NVarChar,        typeof(string) },
                {SqlType.VarChar,         typeof(string) },
                {SqlType.Char,            typeof(string) },
                {SqlType.Date,            typeof(DateTime) },
                {SqlType.DateTime,        typeof(DateTime) },
                {SqlType.DateTime2,       typeof(DateTime) },
                {SqlType.DateTimeOffset,  typeof(TimeSpan) }, //TODO: Validate this decision
                {SqlType.Decimal,         typeof(decimal) },
                {SqlType.Float,           typeof(float) },
                {SqlType.Image,           typeof(byte[]) },
                {SqlType.Int,             typeof(int) },
                {SqlType.Money,           typeof(decimal) },
                {SqlType.NChar,           typeof(string) },
                {SqlType.NText,           typeof(string) },
                {SqlType.Real,            typeof(Single) },
                {SqlType.SmallDateTime,   typeof(DateTime) },
                {SqlType.SmallInt,        typeof(Int16) },
                {SqlType.SmallMoney,      typeof(Decimal) },
                //{SqlType.Structured,      null },
                {SqlType.Text,            typeof(string) },
                {SqlType.Time,            typeof(DateTime) },
                {SqlType.Timestamp,       typeof(byte[]) },
                {SqlType.TinyInt,         typeof(byte) },
                {SqlType.Udt,             null },
                {SqlType.UniqueIdentifier,typeof(Guid) },
                {SqlType.VarBinary,       typeof(byte[]) },
                {SqlType.Sql_Variant,         typeof(object) },
                {SqlType.Xml,             typeof(XElement) }
            };
        }

        public static SqlType Get(Type type) => _SqlTypeLookup.Where(l => l.Value == type).Select(l => l.Key).FirstOrDefault();
    }
}


text:
Esoterion Universe
==================

A deep and colourful generative 3D AV project.

Main features:
- Infinite 3D space
- Infinite number of planet-like dynamic objects
- Single screen for interface and output

What you need
-------------

- The most recent version of openFrameworks, download here: https://github.com/openframeworks/openFrameworks/archive/master.zip
- Max 7, download trial here: https://cycling74.com/products/max/
- FTM library for Max 7, download here: http://ftm.ircam.fr/index.php/Download

Installation
------------

- Unzip openFrameworks to a convenient place in your system
- Clone this repository to `apps/myApps/EsoterionUniverse/` inside openFrameworks folder
- Download sound source from http://wirelesscowboy.org/esoterionuniverse/balayage444.wav and place in `EsoterionUniverse/bin/max/` folder
- Install Max 7
- Install FTM library: if needed add it manually to `Max 7/Packages` folder inside your user's `Documents` folder

Running
-------

- Open `max/MainPatch.maxpat` in Max 7, when loaded click Audio On/Off (beware of a glitch first time)
- Open and run XCode project `esoterionUniverse.xcodeproj`
- Add an object with `a` key and try changing the parameters
- If there`s no sound, first turn volume up, then click Audio On/Off twice in Max patch
- Show instructions with `h` key
- Play around and have fun

Known issue
-----------

Due to either a compabitility issue between poly~ and gbr.ola objects, or cpu consumption issues between video/osc/synthesis on the same computer, the granular synthesis is affected by glitches. A new version should see these problems solved hopefully.

Disclaimer
----------

This software is provided here on an "as is" basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that it is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the software is with you.

Credits
---------------------

[Coralie Diatkine](http://coraliediatkine.eu)

[Matthias Moos](http://matthiasmoos.tumblr.com)

[Will Gallia](http://willgallia.com)

[Borut Kumperscak](http://wirelesscowboy.org)


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TipOfTheDay.Domain.Concrete;
using System.Web.Mvc;

namespace TipOfTheDay.UnitTests
{
    [TestClass]
    public class HomeControllerTest
    {
        [TestMethod]
        public void TestGetTodaysTip()
        {
            // Arrange
            FakeTipRepository repo = new FakeTipRepository();
            var target = new TipOfTheDay.WebUI.Controllers.HomeController(repo);

            // Act
            target.Index();

            // Assert
            Assert.AreEqual(repo.CurrentTip.Title, "Tip 1");
        }
    }
}


text:
            <button class="uk-button uk-button-primary uk-form-file">
                {{ 'Upload' | trans }}
                <input type="file" name="files[]" multiple="multiple">
            </button>

            <button class="uk-button" v-on="click: createFolder()">{{ 'Add Folder' | trans }}</button>

            <button class="uk-button pk-button-danger" v-show="selected.length" v-on="click: remove">{{ 'Delete' | trans }}</button>
            <button class="uk-button" v-show="selected.length === 1" v-on="click: rename">{{ 'Rename' | trans }}</button>

            <input type="text" placeholder="{{ 'Search' | trans }}" v-model="search" lazy>

                <button class="uk-button uk-icon-bars" v-class="'uk-active': view == 'table'"     v-on="click: view = 'table'"></button>
                <button class="uk-button uk-icon-th"   v-class="'uk-active': view == 'thumbnail'" v-on="click: view = 'thumbnail'"></button>

            {{ title }}
            {{ title }}

{{ upload.progress }}%

         {{ 'Drop files here.' | trans }}


text:
<lccdd>

<!-----------------------------------------------------------------------------------------------
     AHCal Barrel implementation of the layout from 70th SiD Optimization Meeting presentation
     from Ross Gordon McCoy (ross.mccoy@mavs.uta.edu) - June 30, 2016
     Updated by Ross on Nov 20, 2016
------------------------------------------------------------------------------------------------->

<readouts>
    <readout name="HCalBarrelHits">
      <segmentation type="CartesianGridXY" grid_size_x="3.0*cm" grid_size_y="3.0*cm" />
      <!-- <segmentation type="RegularNgonCartesianGridXY" gridSizeX="1.0*cm" gridSizeY="1.0*cm" /> -->
      <!-- <id>system:6,barrel:3,module:4,layer:6,slice:5,x:32:-16,y:-16</id> -->
      <id>system:5,side:2,layer:9,module:8,sensor:8,x:32:-16,y:-16</id>

    </readout>
</readouts>

<detectors>
 <detector id="7" name="HCalBarrel" type="GenericCalBarrel_o1_v01" readout="HCalBarrelHits" vis="HCalBarrelVis" calorimeterType="HAD_BARREL" gap="0.*cm" material="Steel235">
  <comment>Hadron Calorimeter Barrel</comment>
  <type_flags type=" DetType_CALORIMETER + DetType_HADRONIC + DetType_BARREL"/>
  <dimensions numsides="HCalBarrel_symmetry" rmin="HCalBarrel_rmin" z="2*HCalBarrel_half_length"/>

  <envelope vis="HCalBarrelVis">
    <shape type="PolyhedraRegular" numsides="HCalBarrel_symmetry"  rmin="HCalBarrel_rmin - env_safety" rmax="HCalBarrel_rmax + 10*env_safety" dz="2*HCalBarrel_half_length + 2*env_safety" material="Air"/>
    <rotation x="0*deg" y="0*deg" z="90*deg-180*deg/HCalBarrel_symmetry"/>
  </envelope>

  <staves />
  <layer repeat="40">
        <slice material = "Steel235"   thickness = "19.0*mm" />    <!-- Absorber -->
	<slice material = "Air"        thickness =  "2.0*mm" />
	<slice material = "Steel235"   thickness =  "0.5*mm" />    <!-- Top plate -->
	<slice material = "Kapton"    thickness = "0.115*mm" />    <!-- Polyimide foil -->
	<slice material = "Copper"    thickness = "0.068*mm" />
	<slice material = "PCB"       thickness =   "1.0*mm" />    <!-- PCB made of FR4 -->
	<slice material = "Polystyrole" thickness = "0.1*mm" />    <!-- Reflector foil -->
	<slice material = "Polystyrene" thickness = "3.0*mm" sensitive="yes" limits="cal_limits" />
	<slice material = "Polystyrole" thickness = "0.1*mm" />    <!-- Reflector foil -->
	<slice material = "Steel235"    thickness = "0.5*mm" />    <!-- Bottom plate -->
	<slice material = "Air"       thickness = "0.617*mm" />    <!-- Clearance gap between active layer and next absorber -->
  </layer>
  <!--layer repeat="1"-->
	<!--slice material = "Steel235"   thickness = "19.0*mm" /--><!-- Terminator plate -->
  <!--/layer-->
 </detector>
</detectors>

</lccdd>


text:
@interface FLTestGroupFinder ()
@property (readwrite, strong, nonatomic) NSDictionary* testGroups;
@end

@implementation FLTestGroupFinder

@synthesize testGroups = _testGroups;

- (id) init {
	self = [super init];
	if(self) {
		_testFinders = [[NSMutableArray alloc] init];
	}
	return self;
}

+ (id) testGroupFinder {
    return FLAutorelease([[[self class] alloc] init]);
}

#if FL_MRC
- (void)dealloc {
    [_testFinders release];
    [super dealloc];
}
#endif

- (NSArray*) removeUnitTestBaseClasses:(NSArray*) factoryList {

    FLAssertNotNil(factoryList);

    NSMutableArray* newList = [NSMutableArray array];

    for(NSUInteger i = 0; i < factoryList.count; i++) {
        id<FLTestFactory> factory = [factoryList objectAtIndex:i];
        Class outerClass = [factory testableClass];

        BOOL foundSubclass = NO;

        for(NSUInteger j = 0; j < factoryList.count; j++) {

            if( i == j ) {
                continue;
            }

            Class innerClass = [[factoryList objectAtIndex:j] testableClass];

            if( [innerClass isSubclassOfClass:outerClass] ) {
                foundSubclass = YES;
                break;
            }

        }

        if(!foundSubclass) {
            [newList addObject:factory];
        }
    }

    return newList;
}

- (void) addTestFinder:(id) finder {
    [_testFinders addObject:finder];
}

- (NSArray*) addUnitTestsForTestMethods:(NSDictionary*) testMethods {

// TODO: create test objects for methods.

    return nil;
}

- (NSDictionary*) sortClassesIntoGroups:(NSArray*) allTestFactories
                       discoveredGroups:(NSDictionary*) discoveredGroups {

    FLAssertNotNil(allTestFactories);
    FLAssertNotNil(discoveredGroups);

    NSMutableDictionary* groups = [NSMutableDictionary dictionary];

    for(id<FLTestFactory> factory in allTestFactories) {

        Class testGroupClass = nil;

        NSString* testGroupName = [[factory testableClass] testGroupName];
        if(testGroupName) {
            testGroupClass = [discoveredGroups objectForKey:testGroupName];
        }

        // default test group
        if(!testGroupClass) {
            testGroupClass = [FLTestGroup class];
        }

        FLTestFactoryList* factoryList = [groups objectForKey:[testGroupClass testGroupName]];
        if(!factoryList) {
            factoryList = [FLTestFactoryList testFactoryList:testGroupClass];
            [groups setObject:factoryList forKey:[testGroupClass testGroupName]];
        }

        [factoryList addObject:factory];
    }

    for(FLTestFactoryList* group in [groups allValues]) {
        [group organizeTests];
    }

    return groups;

}

- (NSDictionary*) findTestGroups {

    NSMutableArray* unitTestFactories = [NSMutableArray array];
    NSMutableDictionary* testMethods = [NSMutableDictionary dictionary];
    NSMutableDictionary* testGroups = [NSMutableDictionary dictionary];

    FLRuntimeVisitEveryClass(
        ^(FLRuntimeInfo classInfo, BOOL* stop) {
            for(id finder in _testFinders) {

                // find test subclasses
                if([finder respondsToSelector:@selector(findPossibleUnitTestClass:)]) {
                    id<FLTestFactory> factory = [finder findPossibleUnitTestClass:classInfo];
                    if(factory) {
                        [unitTestFactories addObject:factory];
                    }
                }

                // find test groups
                if([finder respondsToSelector:@selector(findPossibleTestGroup:)]) {
                    Class testGroup = [finder findPossibleTestGroup:classInfo];
                    if(testGroup) {
                        [testGroups setObject:testGroup forKey:[testGroup testGroupName]];
                    }
                }
            }

            FLRuntimeVisitEachSelectorInClass(classInfo.class,
                ^(FLRuntimeInfo methodInfo, BOOL* stopInner) {
                    for(id finder in _testFinders) {
                        if([finder respondsToSelector:@selector(findPossibleTestMethod:)]) {
                            FLTestMethod* testMethod = [finder findPossibleTestMethod:methodInfo];

                            if(testMethod) {
                                NSMutableArray* methods = [testMethods objectForKey:testMethod.className];
                                if(!methods) {
                                    methods = [NSMutableArray array];
                                    [testMethods setObject:methods forKey:testMethod.className];
                                }
                                [methods addObject:testMethod];
                            }
                        }
                    }
                }
            );

        }
    );

    NSArray* testMethodObjectFactories = [self addUnitTestsForTestMethods:testMethods];
    if(testMethodObjectFactories) {
        [unitTestFactories addObjectsFromArray:testMethodObjectFactories];
    }

    NSArray* finalizedFactoryList = [self removeUnitTestBaseClasses:unitTestFactories];

    return [self sortClassesIntoGroups:finalizedFactoryList discoveredGroups:testGroups];
}

@end


text:
<?php

require 'base.php';

class Phpbb extends base {

public $set_file="config.php";
public $redir=false;

function info($path_host) {

    $url = str_replace("installation/integ", "", str_replace('\\', '/', dirname(__FILE__)));

    $this->info['jsloc'] = 'overall_header.html in styles/your_default_template/template/';
    $this->info['phpcode'] = '

if(!function_exists("freichatx_get_hash")){
function freichatx_get_hash(){

global $user;
$ses = $user->session_id;

       if(is_file("' . $url . 'hardcode.php")){

               require "' . $url . 'hardcode.php";

               $temp_id =  $ses . $uid;

               return md5($temp_id);

       }
       else
       {
               echo "";
       }

       return 0;
}
}

';
    $this->info['jscode'] = '';
    $this->info['csscode'] = '<link rel="stylesheet" href="' . $path_host . 'client/jquery/freichat_themes/freichatcss.php" type="text/css">
';

    $this->info['addn_info'] = "After adding the below code , you need to enable PHP in templates.
You
can do that by going to the ACP in General tab -> Security setting -> Allow PHP in templates
Set it to yes.

Dont forget to purge the cache in phpBB after changing this setting

";

    return $this->info;
}

function get_config() {

$params = array("dbhost", "dbuser", "dbpasswd", "dbname", "table_prefix");
        $i = 0;
        $path = $_SESSION['config_path'];

        if (!is_readable($path)) {
            return false;
        }

        $contents = file_get_contents($path, true);

        foreach ($params as $param) {

            $pattern1 = "/\b" . $param . "\b.*;/";
            $pattern2 = "/'.*'/";

            preg_match($pattern1, $contents, $match);
            preg_match($pattern2, $match[0], $mat);
            $final[$i] = str_replace("'", "", $mat[0]);
            $i++;
        }

        return $final;
    }

}
//Except for Elgg users: Add it in footer.php in views/default/page_elements/


text:
namespace DineroPortableClientSDK.Ledgers
{
    /// <summary>
    /// Represents a collection of CreateLedgerItemResult.
    /// </summary>
    public class CreateLedgerItemResultCollection : DineroParsableCollection<CreateLedgerItemResult>
    {
    }
}


text:
package com.soklet.web.server;

import static java.lang.String.format;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet;
import static java.util.Objects.requireNonNull;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;

/**
 * @author Mark Allen
 * @since 1.0.0
 */
public class FilterConfiguration {
  private static final Set<DispatcherType> DEFAULT_DISPATCHER_TYPES = unmodifiableSet(EnumSet
    .of(DispatcherType.REQUEST));

  private final Class<? extends Filter> filterClass;
  private final String urlPattern;
  private final Set<DispatcherType> dispatcherTypes;
  private final Map<String, String> initParameters;

  public FilterConfiguration(Class<? extends Filter> filterClass, String urlPattern) {
    this.filterClass = requireNonNull(filterClass);
    this.urlPattern = requireNonNull(urlPattern);
    this.initParameters = emptyMap();
    this.dispatcherTypes = DEFAULT_DISPATCHER_TYPES;
  }

  public FilterConfiguration(Class<? extends Filter> filterClass, String urlPattern, Map<String, String> initParameters) {
    this.filterClass = requireNonNull(filterClass);
    this.urlPattern = requireNonNull(urlPattern);
    this.initParameters = unmodifiableMap(new HashMap<>(requireNonNull(initParameters)));
    this.dispatcherTypes = DEFAULT_DISPATCHER_TYPES;
  }

  public FilterConfiguration(Class<? extends Filter> filterClass, String urlPattern,
      Set<DispatcherType> dispatcherTypes, Map<String, String> initParameters) {
    this.filterClass = requireNonNull(filterClass);
    this.urlPattern = requireNonNull(urlPattern);
    this.dispatcherTypes = unmodifiableSet(EnumSet.copyOf(dispatcherTypes));
    this.initParameters = unmodifiableMap(new HashMap<>(requireNonNull(initParameters)));
  }

  @Override
  public String toString() {
    return format("%s{filterClass=%s, urlPattern=%s, dispatcherTypes=%s, initParameters=%s}", getClass()
      .getSimpleName(), filterClass().getName(), urlPattern(), dispatcherTypes(), initParameters());
  }

  @Override
  public boolean equals(Object object) {
    if (this == object)
      return true;

    if (!(object instanceof FilterConfiguration))
      return false;

    FilterConfiguration filterConfiguration = (FilterConfiguration) object;

    return Objects.equals(filterClass(), filterConfiguration.filterClass())
        && Objects.equals(urlPattern(), filterConfiguration.urlPattern())
        && Objects.equals(dispatcherTypes(), filterConfiguration.dispatcherTypes())
        && Objects.equals(initParameters(), filterConfiguration.initParameters());
  }

  @Override
  public int hashCode() {
    return Objects.hash(filterClass(), urlPattern(), dispatcherTypes(), initParameters());
  }

  public Class<? extends Filter> filterClass() {
    return filterClass;
  }

  public String urlPattern() {
    return urlPattern;
  }

  public Map<String, String> initParameters() {
    return initParameters;
  }

  public Set<DispatcherType> dispatcherTypes() {
    return dispatcherTypes;
  }
}


text:
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/spinlock.h>
#include <linux/usb_bam.h>

#include "usb_gadget_xport.h"
#include "u_ether.h"
#include "u_rmnet.h"
#include "gadget_chips.h"

#define RMNET_NOTIFY_INTERVAL	5
#define RMNET_MAX_NOTIFY_SIZE	sizeof(struct usb_cdc_notification)

#define ACM_CTRL_DTR	(1 << 0)

/* TODO: use separate structures for data and
 * control paths
 */
struct f_rmnet {
	struct gether			gether_port;
	struct grmnet			port;
	int				ifc_id;
	u8				port_num;
	atomic_t			online;
	atomic_t			ctrl_online;
	struct usb_composite_dev	*cdev;

	spinlock_t			lock;

	/* usb eps*/
	struct usb_ep			*notify;
	struct usb_request		*notify_req;

	/* control info */
	struct list_head		cpkt_resp_q;
	unsigned long			notify_count;
	unsigned long			cpkts_len;
	const struct usb_endpoint_descriptor *in_ep_desc_backup;
	const struct usb_endpoint_descriptor *out_ep_desc_backup;
};

static unsigned int nr_rmnet_ports;
static unsigned int no_ctrl_smd_ports;
static unsigned int no_ctrl_qti_ports;
static unsigned int no_ctrl_hsic_ports;
static unsigned int no_ctrl_hsuart_ports;
static unsigned int no_data_bam_ports;
static unsigned int no_data_bam2bam_ports;
static unsigned int no_data_hsic_ports;
static unsigned int no_data_hsuart_ports;
static struct rmnet_ports {
	enum transport_type		data_xport;
	enum transport_type		ctrl_xport;
	unsigned			data_xport_num;
	unsigned			ctrl_xport_num;
	unsigned			port_num;
	struct f_rmnet			*port;
} rmnet_ports[NR_RMNET_PORTS];

static struct usb_interface_descriptor rmnet_interface_desc = {
	.bLength =		USB_DT_INTERFACE_SIZE,
	.bDescriptorType =	USB_DT_INTERFACE,
	.bNumEndpoints =	3,
	.bInterfaceClass =	USB_CLASS_VENDOR_SPEC,
	.bInterfaceSubClass =	USB_CLASS_VENDOR_SPEC,
	.bInterfaceProtocol =	USB_CLASS_VENDOR_SPEC,
	/* .iInterface = DYNAMIC */
};

/* Full speed support */
static struct usb_endpoint_descriptor rmnet_fs_notify_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_INT,
	.wMaxPacketSize =	__constant_cpu_to_le16(RMNET_MAX_NOTIFY_SIZE),
	.bInterval =		1 << RMNET_NOTIFY_INTERVAL,
};

static struct usb_endpoint_descriptor rmnet_fs_in_desc  = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize   = __constant_cpu_to_le16(64),
};

static struct usb_endpoint_descriptor rmnet_fs_out_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_OUT,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize   = __constant_cpu_to_le16(64),
};

static struct usb_descriptor_header *rmnet_fs_function[] = {
	(struct usb_descriptor_header *) &rmnet_interface_desc,
	(struct usb_descriptor_header *) &rmnet_fs_notify_desc,
	(struct usb_descriptor_header *) &rmnet_fs_in_desc,
	(struct usb_descriptor_header *) &rmnet_fs_out_desc,
	NULL,
};

/* High speed support */
static struct usb_endpoint_descriptor rmnet_hs_notify_desc  = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_INT,
	.wMaxPacketSize =	__constant_cpu_to_le16(RMNET_MAX_NOTIFY_SIZE),
	.bInterval =		RMNET_NOTIFY_INTERVAL + 4,
};

static struct usb_endpoint_descriptor rmnet_hs_in_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	__constant_cpu_to_le16(512),
};

static struct usb_endpoint_descriptor rmnet_hs_out_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_OUT,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	__constant_cpu_to_le16(512),
};

static struct usb_descriptor_header *rmnet_hs_function[] = {
	(struct usb_descriptor_header *) &rmnet_interface_desc,
	(struct usb_descriptor_header *) &rmnet_hs_notify_desc,
	(struct usb_descriptor_header *) &rmnet_hs_in_desc,
	(struct usb_descriptor_header *) &rmnet_hs_out_desc,
	NULL,
};

/* Super speed support */
static struct usb_endpoint_descriptor rmnet_ss_notify_desc  = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_INT,
	.wMaxPacketSize =	__constant_cpu_to_le16(RMNET_MAX_NOTIFY_SIZE),
	.bInterval =		RMNET_NOTIFY_INTERVAL + 4,
};

static struct usb_ss_ep_comp_descriptor rmnet_ss_notify_comp_desc = {
	.bLength =		sizeof rmnet_ss_notify_comp_desc,
	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,

	/* the following 3 values can be tweaked if necessary */
	/* .bMaxBurst =		0, */
	/* .bmAttributes =	0, */
	.wBytesPerInterval =	cpu_to_le16(RMNET_MAX_NOTIFY_SIZE),
};

static struct usb_endpoint_descriptor rmnet_ss_in_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_IN,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	__constant_cpu_to_le16(1024),
};

static struct usb_ss_ep_comp_descriptor rmnet_ss_in_comp_desc = {
	.bLength =		sizeof rmnet_ss_in_comp_desc,
	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,

	/* the following 2 values can be tweaked if necessary */
	/* .bMaxBurst =		0, */
	/* .bmAttributes =	0, */
};

static struct usb_endpoint_descriptor rmnet_ss_out_desc = {
	.bLength =		USB_DT_ENDPOINT_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_OUT,
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
	.wMaxPacketSize =	__constant_cpu_to_le16(1024),
};

static struct usb_ss_ep_comp_descriptor rmnet_ss_out_comp_desc = {
	.bLength =		sizeof rmnet_ss_out_comp_desc,
	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,

	/* the following 2 values can be tweaked if necessary */
	/* .bMaxBurst =		0, */
	/* .bmAttributes =	0, */
};

static struct usb_descriptor_header *rmnet_ss_function[] = {
	(struct usb_descriptor_header *) &rmnet_interface_desc,
	(struct usb_descriptor_header *) &rmnet_ss_notify_desc,
	(struct usb_descriptor_header *) &rmnet_ss_notify_comp_desc,
	(struct usb_descriptor_header *) &rmnet_ss_in_desc,
	(struct usb_descriptor_header *) &rmnet_ss_in_comp_desc,
	(struct usb_descriptor_header *) &rmnet_ss_out_desc,
	(struct usb_descriptor_header *) &rmnet_ss_out_comp_desc,
	NULL,
};

/* String descriptors */

static struct usb_string rmnet_string_defs[] = {
	[0].s = "RmNet",
	{  } /* end of list */
};

static struct usb_gadget_strings rmnet_string_table = {
	.language =		0x0409,	/* en-us */
	.strings =		rmnet_string_defs,
};

static struct usb_gadget_strings *rmnet_strings[] = {
	&rmnet_string_table,
	NULL,
};

static void frmnet_ctrl_response_available(struct f_rmnet *dev);

/* ------- misc functions --------------------*/

static inline struct f_rmnet *func_to_rmnet(struct usb_function *f)
{
	return container_of(f, struct f_rmnet, gether_port.func);
}

static inline struct f_rmnet *port_to_rmnet(struct grmnet *r)
{
	return container_of(r, struct f_rmnet, port);
}

static struct usb_request *
frmnet_alloc_req(struct usb_ep *ep, unsigned len, gfp_t flags)
{
	struct usb_request *req;

	req = usb_ep_alloc_request(ep, flags);
	if (!req)
		return ERR_PTR(-ENOMEM);

	req->buf = kmalloc(len, flags);
	if (!req->buf) {
		usb_ep_free_request(ep, req);
		return ERR_PTR(-ENOMEM);
	}

	req->length = len;

	return req;
}

void frmnet_free_req(struct usb_ep *ep, struct usb_request *req)
{
	kfree(req->buf);
	usb_ep_free_request(ep, req);
}

static struct rmnet_ctrl_pkt *rmnet_alloc_ctrl_pkt(unsigned len, gfp_t flags)
{
	struct rmnet_ctrl_pkt *pkt;

	pkt = kzalloc(sizeof(struct rmnet_ctrl_pkt), flags);
	if (!pkt)
		return ERR_PTR(-ENOMEM);

	pkt->buf = kmalloc(len, flags);
	if (!pkt->buf) {
		kfree(pkt);
		return ERR_PTR(-ENOMEM);
	}
	pkt->len = len;

	return pkt;
}

static void rmnet_free_ctrl_pkt(struct rmnet_ctrl_pkt *pkt)
{
	kfree(pkt->buf);
	kfree(pkt);
}

/* -------------------------------------------*/

static int rmnet_gport_setup(void)
{
	int	ret;
	int	port_idx;
	int	i;
	u8 base;

	pr_debug("%s: bam ports: %u bam2bam ports: %u data hsic ports: %u data hsuart ports: %u"
		" smd ports: %u ctrl hsic ports: %u ctrl hsuart ports: %u"
		" nr_rmnet_ports: %u\n",
		__func__, no_data_bam_ports, no_data_bam2bam_ports,
		no_data_hsic_ports, no_data_hsuart_ports, no_ctrl_smd_ports,
		no_ctrl_hsic_ports, no_ctrl_hsuart_ports, nr_rmnet_ports);

	if (no_data_bam_ports || no_data_bam2bam_ports) {
		ret = gbam_setup(no_data_bam_ports,
				 no_data_bam2bam_ports);
		if (ret)
			return ret;
	}

	if (no_ctrl_smd_ports) {
		ret = gsmd_ctrl_setup(FRMNET_CTRL_CLIENT,
				no_ctrl_smd_ports, &base);
		if (ret)
			return ret;
		for (i = 0; i < nr_rmnet_ports; i++)
			if (rmnet_ports[i].port)
				rmnet_ports[i].port->port_num += base;
	}

	if (no_data_hsic_ports) {
		port_idx = ghsic_data_setup(no_data_hsic_ports,
				USB_GADGET_RMNET);
		if (port_idx < 0)
			return port_idx;
		for (i = 0; i < nr_rmnet_ports; i++) {
			if (rmnet_ports[i].data_xport ==
					USB_GADGET_XPORT_HSIC) {
				rmnet_ports[i].data_xport_num = port_idx;
				port_idx++;
			}
		}
	}

	if (no_ctrl_hsic_ports) {
		port_idx = ghsic_ctrl_setup(no_ctrl_hsic_ports,
				USB_GADGET_RMNET);
		if (port_idx < 0)
			return port_idx;
		for (i = 0; i < nr_rmnet_ports; i++) {
			if (rmnet_ports[i].ctrl_xport ==
					USB_GADGET_XPORT_HSIC) {
				rmnet_ports[i].ctrl_xport_num = port_idx;
				port_idx++;
			}
		}
	}

	if (no_data_hsuart_ports) {
		port_idx = ghsuart_data_setup(no_data_hsuart_ports,
				USB_GADGET_RMNET);
		if (port_idx < 0)
			return port_idx;
		for (i = 0; i < nr_rmnet_ports; i++) {
			if (rmnet_ports[i].data_xport ==
					USB_GADGET_XPORT_HSUART) {
				rmnet_ports[i].data_xport_num = port_idx;
				port_idx++;
			}
		}
	}

	if (no_ctrl_hsuart_ports) {
		port_idx = ghsuart_ctrl_setup(no_ctrl_hsuart_ports,
				USB_GADGET_RMNET);
		if (port_idx < 0)
			return port_idx;
		for (i = 0; i < nr_rmnet_ports; i++) {
			if (rmnet_ports[i].ctrl_xport ==
					USB_GADGET_XPORT_HSUART) {
				rmnet_ports[i].ctrl_xport_num = port_idx;
				port_idx++;
			}
		}
	}

	return 0;
}

static int gport_rmnet_connect(struct f_rmnet *dev, unsigned intf)
{
	int			ret;
	unsigned		port_num;
	enum transport_type	cxport = rmnet_ports[dev->port_num].ctrl_xport;
	enum transport_type	dxport = rmnet_ports[dev->port_num].data_xport;
	int			src_connection_idx = 0, dst_connection_idx = 0;
	struct usb_gadget	*gadget = dev->cdev->gadget;
	void *net;

	pr_debug("%s: ctrl xport: %s data xport: %s dev: %p portno: %d\n",
			__func__, xport_to_str(cxport), xport_to_str(dxport),
			dev, dev->port_num);

	port_num = rmnet_ports[dev->port_num].ctrl_xport_num;
	switch (cxport) {
	case USB_GADGET_XPORT_SMD:
		ret = gsmd_ctrl_connect(&dev->port, port_num);
		if (ret) {
			pr_err("%s: gsmd_ctrl_connect failed: err:%d\n",
					__func__, ret);
			return ret;
		}
		break;
	case USB_GADGET_XPORT_QTI:
		ret = gqti_ctrl_connect(&dev->port, port_num, intf, dxport,
							USB_GADGET_RMNET);
		if (ret) {
			pr_err("%s: gqti_ctrl_connect failed: err:%d\n",
					__func__, ret);
			return ret;
		}
		break;
	case USB_GADGET_XPORT_HSIC:
		ret = ghsic_ctrl_connect(&dev->port, port_num);
		if (ret) {
			pr_err("%s: ghsic_ctrl_connect failed: err:%d\n",
					__func__, ret);
			return ret;
		}
		break;
	case USB_GADGET_XPORT_HSUART:
		ret = ghsuart_ctrl_connect(&dev->port, port_num);
		if (ret) {
			pr_err("%s: ghsuart_ctrl_connect failed: err:%d\n",
					__func__, ret);
			return ret;
		}
		break;
	case USB_GADGET_XPORT_NONE:
		break;
	default:
		pr_err("%s: Un-supported transport: %s\n", __func__,
				xport_to_str(cxport));
		return -ENODEV;
	}

	port_num = rmnet_ports[dev->port_num].data_xport_num;

	switch (dxport) {
	case USB_GADGET_XPORT_BAM2BAM:
		src_connection_idx = usb_bam_get_connection_idx(gadget->name,
			A2_P_BAM, USB_TO_PEER_PERIPHERAL, USB_BAM_DEVICE,
			port_num);
		dst_connection_idx = usb_bam_get_connection_idx(gadget->name,
			A2_P_BAM, PEER_PERIPHERAL_TO_USB, USB_BAM_DEVICE,
			port_num);
		if (dst_connection_idx < 0 || src_connection_idx < 0) {
			pr_err("%s: usb_bam_get_connection_idx failed\n",
				__func__);
			gsmd_ctrl_disconnect(&dev->port, port_num);
			return -EINVAL;
		}
	case USB_GADGET_XPORT_BAM:
		ret = gbam_connect(&dev->port, port_num,
			dxport, src_connection_idx, dst_connection_idx);
		if (ret) {
			pr_err("%s: gbam_connect failed: err:%d\n",
				__func__, ret);
			gsmd_ctrl_disconnect(&dev->port, port_num);
			return ret;
		}
		break;
	case USB_GADGET_XPORT_BAM2BAM_IPA:
		src_connection_idx = usb_bam_get_connection_idx(gadget->name,
			IPA_P_BAM, USB_TO_PEER_PERIPHERAL, USB_BAM_DEVICE,
			port_num);
		dst_connection_idx = usb_bam_get_connection_idx(gadget->name,
			IPA_P_BAM, PEER_PERIPHERAL_TO_USB, USB_BAM_DEVICE,
			port_num);
		if (dst_connection_idx < 0 || src_connection_idx < 0) {
			pr_err("%s: usb_bam_get_connection_idx failed\n",
				__func__);
			gsmd_ctrl_disconnect(&dev->port, port_num);
			return -EINVAL;
		}
		ret = gbam_connect(&dev->port, port_num,
			dxport, src_connection_idx, dst_connection_idx);
		if (ret) {
			pr_err("%s: gbam_connect failed: err:%d\n",
					__func__, ret);
			if (cxport == USB_GADGET_XPORT_QTI)
				gqti_ctrl_disconnect(&dev->port, port_num);
			else
				gsmd_ctrl_disconnect(&dev->port, port_num);
			return ret;
		}
		break;
	case USB_GADGET_XPORT_HSIC:
		ret = ghsic_data_connect(&dev->port, port_num);
		if (ret) {
			pr_err("%s: ghsic_data_connect failed: err:%d\n",
					__func__, ret);
			ghsic_ctrl_disconnect(&dev->port, port_num);
			return ret;
		}
		break;
	case USB_GADGET_XPORT_HSUART:
		ret = ghsuart_data_connect(&dev->port, port_num);
		if (ret) {
			pr_err("%s: ghsuart_data_connect failed: err:%d\n",
					__func__, ret);
			ghsuart_ctrl_disconnect(&dev->port, port_num);
			return ret;
		}
		break;
	case USB_GADGET_XPORT_ETHER:
		net = gether_connect(&dev->gether_port);
		if (IS_ERR(net)) {
			pr_err("%s: gether_connect failed: err:%ld\n",
					__func__, PTR_ERR(net));
			if (cxport == USB_GADGET_XPORT_QTI)
				gqti_ctrl_disconnect(&dev->port, port_num);
			else
				gsmd_ctrl_disconnect(&dev->port, port_num);

			return PTR_ERR(net);
		}
		gether_update_dl_max_pkts_per_xfer(&dev->gether_port, 10);
		gether_update_dl_max_xfer_size(&dev->gether_port, 16384);
		break;
	case USB_GADGET_XPORT_NONE:
		 break;
	default:
		pr_err("%s: Un-supported transport: %s\n", __func__,
				xport_to_str(dxport));
		return -ENODEV;
	}

	return 0;
}

static int gport_rmnet_disconnect(struct f_rmnet *dev)
{
	unsigned		port_num;
	enum transport_type	cxport = rmnet_ports[dev->port_num].ctrl_xport;
	enum transport_type	dxport = rmnet_ports[dev->port_num].data_xport;

	pr_debug("%s: ctrl xport: %s data xport: %s dev: %p portno: %d\n",
			__func__, xport_to_str(cxport), xport_to_str(dxport),
			dev, dev->port_num);

	port_num = rmnet_ports[dev->port_num].ctrl_xport_num;
	switch (cxport) {
	case USB_GADGET_XPORT_SMD:
		gsmd_ctrl_disconnect(&dev->port, port_num);
		break;
	case USB_GADGET_XPORT_QTI:
		gqti_ctrl_disconnect(&dev->port, port_num);
		break;
	case USB_GADGET_XPORT_HSIC:
		ghsic_ctrl_disconnect(&dev->port, port_num);
		break;
	case USB_GADGET_XPORT_HSUART:
		ghsuart_ctrl_disconnect(&dev->port, port_num);
		break;
	case USB_GADGET_XPORT_NONE:
		break;
	default:
		pr_err("%s: Un-supported transport: %s\n", __func__,
				xport_to_str(cxport));
		return -ENODEV;
	}

	port_num = rmnet_ports[dev->port_num].data_xport_num;
	switch (dxport) {
	case USB_GADGET_XPORT_BAM:
	case USB_GADGET_XPORT_BAM2BAM:
	case USB_GADGET_XPORT_BAM2BAM_IPA:
		gbam_disconnect(&dev->port, port_num, dxport);
		break;
	case USB_GADGET_XPORT_HSIC:
		ghsic_data_disconnect(&dev->port, port_num);
		break;
	case USB_GADGET_XPORT_HSUART:
		ghsuart_data_disconnect(&dev->port, port_num);
		break;
	case USB_GADGET_XPORT_ETHER:
		gether_disconnect(&dev->gether_port);
		break;
	case USB_GADGET_XPORT_NONE:
		break;
	default:
		pr_err("%s: Un-supported transport: %s\n", __func__,
				xport_to_str(dxport));
		return -ENODEV;
	}

	return 0;
}

static void frmnet_unbind(struct usb_configuration *c, struct usb_function *f)
{
	struct f_rmnet *dev = func_to_rmnet(f);

	pr_debug("%s: portno:%d\n", __func__, dev->port_num);
	if (gadget_is_superspeed(c->cdev->gadget))
		usb_free_descriptors(f->ss_descriptors);
	if (gadget_is_dualspeed(c->cdev->gadget))
		usb_free_descriptors(f->hs_descriptors);
	usb_free_descriptors(f->fs_descriptors);

	frmnet_free_req(dev->notify, dev->notify_req);

	kfree(f->name);
}

static void frmnet_purge_responses(struct f_rmnet *dev)
{
	unsigned long flags;
	struct rmnet_ctrl_pkt *cpkt;

	pr_debug("%s: port#%d\n", __func__, dev->port_num);

	spin_lock_irqsave(&dev->lock, flags);
	while (!list_empty(&dev->cpkt_resp_q)) {
		cpkt = list_first_entry(&dev->cpkt_resp_q,
				struct rmnet_ctrl_pkt, list);

		list_del(&cpkt->list);
		rmnet_free_ctrl_pkt(cpkt);
	}
	dev->notify_count = 0;
	spin_unlock_irqrestore(&dev->lock, flags);
}

static void frmnet_suspend(struct usb_function *f)
{
	struct f_rmnet *dev = func_to_rmnet(f);
	unsigned		port_num;
	enum transport_type	dxport = rmnet_ports[dev->port_num].data_xport;
	bool			remote_wakeup_allowed;

	if (f->config->cdev->gadget->speed == USB_SPEED_SUPER)
		remote_wakeup_allowed = f->func_wakeup_allowed;
	else
		remote_wakeup_allowed = f->config->cdev->gadget->remote_wakeup;

	pr_debug("%s: data xport: %s dev: %p portno: %d remote_wakeup: %d\n",
		__func__, xport_to_str(dxport),
		dev, dev->port_num, remote_wakeup_allowed);

	usb_ep_fifo_flush(dev->notify);
	frmnet_purge_responses(dev);

	port_num = rmnet_ports[dev->port_num].data_xport_num;
	switch (dxport) {
	case USB_GADGET_XPORT_BAM:
		break;
	case USB_GADGET_XPORT_BAM2BAM:
	case USB_GADGET_XPORT_BAM2BAM_IPA:
		if (remote_wakeup_allowed) {
			gbam_suspend(&dev->port, port_num, dxport);
		} else {
			/*
			 * When remote wakeup is disabled, IPA is disconnected
			 * because it cannot send new data until the USB bus is
			 * resumed. Endpoint descriptors info is saved before it
			 * gets reset by the BAM disconnect API. This lets us
			 * restore this info when the USB bus is resumed.
			 */
			dev->in_ep_desc_backup  = dev->port.in->desc;
			dev->out_ep_desc_backup  = dev->port.out->desc;
			pr_debug("in_ep_desc_bkup = %p, out_ep_desc_bkup = %p",
			       dev->in_ep_desc_backup, dev->out_ep_desc_backup);
			pr_debug("%s(): Disconnecting\n", __func__);
			gbam_disconnect(&dev->port, port_num, dxport);
		}
		break;
	case USB_GADGET_XPORT_HSIC:
		break;
	case USB_GADGET_XPORT_HSUART:
		break;
	case USB_GADGET_XPORT_ETHER:
		break;
	case USB_GADGET_XPORT_NONE:
		break;
	default:
		pr_err("%s: Un-supported transport: %s\n", __func__,
				xport_to_str(dxport));
	}
}

static void frmnet_resume(struct usb_function *f)
{
	struct f_rmnet *dev = func_to_rmnet(f);
	unsigned		port_num;
	enum transport_type	dxport = rmnet_ports[dev->port_num].data_xport;
	struct usb_gadget	*gadget = dev->cdev->gadget;
	int  ret, src_connection_idx = 0, dst_connection_idx = 0;
	bool remote_wakeup_allowed;

	if (f->config->cdev->gadget->speed == USB_SPEED_SUPER)
		remote_wakeup_allowed = f->func_wakeup_allowed;
	else
		remote_wakeup_allowed = f->config->cdev->gadget->remote_wakeup;

	pr_debug("%s: data xport: %s dev: %p portno: %d remote_wakeup: %d\n",
		__func__, xport_to_str(dxport),
		dev, dev->port_num, remote_wakeup_allowed);

	port_num = rmnet_ports[dev->port_num].data_xport_num;
	switch (dxport) {
	case USB_GADGET_XPORT_BAM:
		break;
	case USB_GADGET_XPORT_BAM2BAM:
	case USB_GADGET_XPORT_BAM2BAM_IPA:
		if (remote_wakeup_allowed) {
			gbam_resume(&dev->port, port_num, dxport);
		} else {
			dev->port.in->desc = dev->in_ep_desc_backup;
			dev->port.out->desc = dev->out_ep_desc_backup;
			pr_debug("%s(): Connecting\n", __func__);
			src_connection_idx = usb_bam_get_connection_idx(
				gadget->name, IPA_P_BAM, USB_TO_PEER_PERIPHERAL,
				USB_BAM_DEVICE, port_num);
			dst_connection_idx = usb_bam_get_connection_idx(
				gadget->name, IPA_P_BAM, PEER_PERIPHERAL_TO_USB,
				USB_BAM_DEVICE, port_num);
			if (dst_connection_idx < 0 || src_connection_idx < 0) {
				pr_err("%s: usb_bam_get_connection_idx failed\n",
					__func__);
				return;
			}
			ret = gbam_connect(&dev->port, port_num,
				dxport, src_connection_idx, dst_connection_idx);
			if (ret) {
				pr_err("%s: gbam_connect failed: err:%d\n",
					__func__, ret);
			}
		}
		break;
	case USB_GADGET_XPORT_HSIC:
		break;
	case USB_GADGET_XPORT_HSUART:
		break;
	case USB_GADGET_XPORT_ETHER:
		break;
	case USB_GADGET_XPORT_NONE:
		break;
	default:
		pr_err("%s: Un-supported transport: %s\n", __func__,
				xport_to_str(dxport));
	}
}

static void frmnet_disable(struct usb_function *f)
{
	struct f_rmnet *dev = func_to_rmnet(f);
	enum transport_type	dxport = rmnet_ports[dev->port_num].data_xport;
	struct usb_composite_dev	*cdev = dev->cdev;

	pr_debug("%s: port#%d\n", __func__, dev->port_num);

	usb_ep_disable(dev->notify);
	dev->notify->driver_data = NULL;

	atomic_set(&dev->online, 0);

	frmnet_purge_responses(dev);

	if (dxport == USB_GADGET_XPORT_BAM2BAM_IPA &&
	    gadget_is_dwc3(cdev->gadget)) {
		msm_ep_unconfig(dev->port.out);
		msm_ep_unconfig(dev->port.in);
	}
	gport_rmnet_disconnect(dev);
}

static int
frmnet_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
	struct f_rmnet			*dev = func_to_rmnet(f);
	enum transport_type	dxport = rmnet_ports[dev->port_num].data_xport;
	struct usb_composite_dev	*cdev = dev->cdev;
	int				ret;
	struct list_head *cpkt;

	pr_debug("%s:dev:%p port#%d\n", __func__, dev, dev->port_num);

	if (dev->notify->driver_data) {
		pr_debug("%s: reset port:%d\n", __func__, dev->port_num);
		usb_ep_disable(dev->notify);
	}

	ret = config_ep_by_speed(cdev->gadget, f, dev->notify);
	if (ret) {
		dev->notify->desc = NULL;
		ERROR(cdev, "config_ep_by_speed failes for ep %s, result %d\n",
					dev->notify->name, ret);
		return ret;
	}
	ret = usb_ep_enable(dev->notify);

	if (ret) {
		pr_err("%s: usb ep#%s enable failed, err#%d\n",
				__func__, dev->notify->name, ret);
		return ret;
	}
	dev->notify->driver_data = dev;

	if (!dev->port.in->desc || !dev->port.out->desc) {
		if (config_ep_by_speed(cdev->gadget, f, dev->port.in) ||
			config_ep_by_speed(cdev->gadget, f, dev->port.out)) {
				dev->port.in->desc = NULL;
				dev->port.out->desc = NULL;
				return -EINVAL;
		}
		dev->port.gadget = dev->cdev->gadget;
		ret = gport_rmnet_connect(dev, intf);
	}

	if (dxport == USB_GADGET_XPORT_BAM2BAM_IPA &&
	    gadget_is_dwc3(cdev->gadget)) {
		if (msm_ep_config(dev->port.in) ||
		    msm_ep_config(dev->port.out)) {
			pr_err("%s: msm_ep_config failed\n", __func__);
			return -EINVAL;
		}
	} else
		pr_debug("Rmnet is being used with non DWC3 core\n");

	atomic_set(&dev->online, 1);

	/* In case notifications were aborted, but there are pending control
	   packets in the response queue, re-add the notifications */
	list_for_each(cpkt, &dev->cpkt_resp_q)
		frmnet_ctrl_response_available(dev);

	return ret;
}

static void frmnet_ctrl_response_available(struct f_rmnet *dev)
{
	struct usb_request		*req = dev->notify_req;
	struct usb_cdc_notification	*event;
	unsigned long			flags;
	int				ret;
	struct rmnet_ctrl_pkt	*cpkt;

	pr_debug("%s:dev:%p portno#%d\n", __func__, dev, dev->port_num);

	spin_lock_irqsave(&dev->lock, flags);
	if (!atomic_read(&dev->online) || !req || !req->buf) {
		spin_unlock_irqrestore(&dev->lock, flags);
		return;
	}

	if (++dev->notify_count != 1) {
		spin_unlock_irqrestore(&dev->lock, flags);
		return;
	}

	event = req->buf;
	event->bmRequestType = USB_DIR_IN | USB_TYPE_CLASS
			| USB_RECIP_INTERFACE;
	event->bNotificationType = USB_CDC_NOTIFY_RESPONSE_AVAILABLE;
	event->wValue = cpu_to_le16(0);
	event->wIndex = cpu_to_le16(dev->ifc_id);
	event->wLength = cpu_to_le16(0);
	spin_unlock_irqrestore(&dev->lock, flags);

	ret = usb_ep_queue(dev->notify, dev->notify_req, GFP_ATOMIC);
	if (ret) {
		spin_lock_irqsave(&dev->lock, flags);
		if (!list_empty(&dev->cpkt_resp_q)) {
			if (dev->notify_count > 0)
				dev->notify_count--;
			else {
				pr_debug("%s: Invalid notify_count=%lu to decrement\n",
					 __func__, dev->notify_count);
				spin_unlock_irqrestore(&dev->lock, flags);
				return;
			}
			cpkt = list_first_entry(&dev->cpkt_resp_q,
					struct rmnet_ctrl_pkt, list);
			list_del(&cpkt->list);
			rmnet_free_ctrl_pkt(cpkt);
		}
		spin_unlock_irqrestore(&dev->lock, flags);
		pr_debug("ep enqueue error %d\n", ret);
	}
}

static void frmnet_connect(struct grmnet *gr)
{
	struct f_rmnet			*dev;

	if (!gr) {
		pr_err("%s: Invalid grmnet:%p\n", __func__, gr);
		return;
	}

	dev = port_to_rmnet(gr);

	atomic_set(&dev->ctrl_online, 1);
}

static void frmnet_disconnect(struct grmnet *gr)
{
	struct f_rmnet			*dev;
	struct usb_cdc_notification	*event;
	int				status;

	if (!gr) {
		pr_err("%s: Invalid grmnet:%p\n", __func__, gr);
		return;
	}

	dev = port_to_rmnet(gr);

	atomic_set(&dev->ctrl_online, 0);

	if (!atomic_read(&dev->online)) {
		pr_debug("%s: nothing to do\n", __func__);
		return;
	}

	usb_ep_fifo_flush(dev->notify);

	event = dev->notify_req->buf;
	event->bmRequestType = USB_DIR_IN | USB_TYPE_CLASS
			| USB_RECIP_INTERFACE;
	event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
	event->wValue = cpu_to_le16(0);
	event->wIndex = cpu_to_le16(dev->ifc_id);
	event->wLength = cpu_to_le16(0);

	status = usb_ep_queue(dev->notify, dev->notify_req, GFP_ATOMIC);
	if (status < 0) {
		if (!atomic_read(&dev->online))
			return;
		pr_err("%s: rmnet notify ep enqueue error %d\n",
				__func__, status);
	}

	frmnet_purge_responses(dev);
}

static int
frmnet_send_cpkt_response(void *gr, void *buf, size_t len)
{
	struct f_rmnet		*dev;
	struct rmnet_ctrl_pkt	*cpkt;
	unsigned long		flags;

	if (!gr || !buf) {
		pr_err("%s: Invalid grmnet/buf, grmnet:%p buf:%p\n",
				__func__, gr, buf);
		return -ENODEV;
	}
	cpkt = rmnet_alloc_ctrl_pkt(len, GFP_ATOMIC);
	if (IS_ERR(cpkt)) {
		pr_err("%s: Unable to allocate ctrl pkt\n", __func__);
		return -ENOMEM;
	}
	memcpy(cpkt->buf, buf, len);
	cpkt->len = len;

	dev = port_to_rmnet(gr);

	pr_debug("%s: dev:%p port#%d\n", __func__, dev, dev->port_num);

	if (!atomic_read(&dev->online) || !atomic_read(&dev->ctrl_online)) {
		rmnet_free_ctrl_pkt(cpkt);
		return 0;
	}

	spin_lock_irqsave(&dev->lock, flags);
	list_add_tail(&cpkt->list, &dev->cpkt_resp_q);
	spin_unlock_irqrestore(&dev->lock, flags);

	frmnet_ctrl_response_available(dev);

	return 0;
}

static void
frmnet_cmd_complete(struct usb_ep *ep, struct usb_request *req)
{
	struct f_rmnet			*dev = req->context;
	struct usb_composite_dev	*cdev;
	unsigned			port_num;

	if (!dev) {
		pr_err("%s: rmnet dev is null\n", __func__);
		return;
	}

	pr_debug("%s: dev:%p port#%d\n", __func__, dev, dev->port_num);

	cdev = dev->cdev;

	if (dev->port.send_encap_cmd) {
		port_num = rmnet_ports[dev->port_num].ctrl_xport_num;
		dev->port.send_encap_cmd(port_num, req->buf, req->actual);
	}
}

static void frmnet_notify_complete(struct usb_ep *ep, struct usb_request *req)
{
	struct f_rmnet *dev = req->context;
	int status = req->status;
	unsigned long		flags;
	struct rmnet_ctrl_pkt	*cpkt;

	pr_debug("%s: dev:%p port#%d\n", __func__, dev, dev->port_num);

	switch (status) {
	case -ECONNRESET:
	case -ESHUTDOWN:
		/* connection gone */
		spin_lock_irqsave(&dev->lock, flags);
		dev->notify_count = 0;
		spin_unlock_irqrestore(&dev->lock, flags);
		break;
	default:
		pr_err("rmnet notify ep error %d\n", status);
		/* FALLTHROUGH */
	case 0:
		if (!atomic_read(&dev->ctrl_online))
			break;

		spin_lock_irqsave(&dev->lock, flags);
		if (dev->notify_count > 0) {
			dev->notify_count--;
			if (dev->notify_count == 0) {
				spin_unlock_irqrestore(&dev->lock, flags);
				break;
			}
		} else {
			pr_debug("%s: Invalid notify_count=%lu to decrement\n",
					__func__, dev->notify_count);
			spin_unlock_irqrestore(&dev->lock, flags);
			break;
		}
		spin_unlock_irqrestore(&dev->lock, flags);

		status = usb_ep_queue(dev->notify, req, GFP_ATOMIC);
		if (status) {
			spin_lock_irqsave(&dev->lock, flags);
			if (!list_empty(&dev->cpkt_resp_q)) {
				if (dev->notify_count > 0)
					dev->notify_count--;
				else {
					pr_err("%s: Invalid notify_count=%lu to decrement\n",
						__func__, dev->notify_count);
					spin_unlock_irqrestore(&dev->lock,
								flags);
					break;
				}
				cpkt = list_first_entry(&dev->cpkt_resp_q,
						struct rmnet_ctrl_pkt, list);
				list_del(&cpkt->list);
				rmnet_free_ctrl_pkt(cpkt);
			}
			spin_unlock_irqrestore(&dev->lock, flags);
			pr_debug("ep enqueue error %d\n", status);
		}
		break;
	}
}

static int
frmnet_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
{
	struct f_rmnet			*dev = func_to_rmnet(f);
	struct usb_composite_dev	*cdev = dev->cdev;
	struct usb_request		*req = cdev->req;
	unsigned			port_num;
	u16				w_index = le16_to_cpu(ctrl->wIndex);
	u16				w_value = le16_to_cpu(ctrl->wValue);
	u16				w_length = le16_to_cpu(ctrl->wLength);
	int				ret = -EOPNOTSUPP;

	pr_debug("%s:dev:%p port#%d\n", __func__, dev, dev->port_num);

	if (!atomic_read(&dev->online)) {
		pr_warning("%s: usb cable is not connected\n", __func__);
		return -ENOTCONN;
	}

	switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {

	case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
			| USB_CDC_SEND_ENCAPSULATED_COMMAND:
		pr_debug("%s: USB_CDC_SEND_ENCAPSULATED_COMMAND\n"
				 , __func__);
		ret = w_length;
		req->complete = frmnet_cmd_complete;
		req->context = dev;
		break;

	case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
			| USB_CDC_GET_ENCAPSULATED_RESPONSE:
		pr_debug("%s: USB_CDC_GET_ENCAPSULATED_RESPONSE\n", __func__);
		if (w_value) {
			pr_err("%s: invalid w_value = %04x\n",
				   __func__ , w_value);
			goto invalid;
		} else {
			unsigned len;
			struct rmnet_ctrl_pkt *cpkt;

			spin_lock(&dev->lock);
			if (list_empty(&dev->cpkt_resp_q)) {
				pr_err("ctrl resp queue empty "
					" req%02x.%02x v%04x i%04x l%d\n",
					ctrl->bRequestType, ctrl->bRequest,
					w_value, w_index, w_length);
				spin_unlock(&dev->lock);
				goto invalid;
			}

			cpkt = list_first_entry(&dev->cpkt_resp_q,
					struct rmnet_ctrl_pkt, list);
			list_del(&cpkt->list);
			spin_unlock(&dev->lock);

			len = min_t(unsigned, w_length, cpkt->len);
			memcpy(req->buf, cpkt->buf, len);
			ret = len;

			rmnet_free_ctrl_pkt(cpkt);
		}
		break;
	case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
			| USB_CDC_REQ_SET_CONTROL_LINE_STATE:
		pr_debug("%s: USB_CDC_REQ_SET\n", __func__);
		if (dev->port.notify_modem) {
			port_num = rmnet_ports[dev->port_num].ctrl_xport_num;
			dev->port.notify_modem(&dev->port, port_num, w_value);
		}
		ret = 0;

		break;
	default:

invalid:
		DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
			ctrl->bRequestType, ctrl->bRequest,
			w_value, w_index, w_length);
	}

	/* respond with data transfer or status phase? */
	if (ret >= 0) {
		VDBG(cdev, "rmnet req%02x.%02x v%04x i%04x l%d\n",
			ctrl->bRequestType, ctrl->bRequest,
			w_value, w_index, w_length);
		req->zero = (ret < w_length);
		req->length = ret;
		ret = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
		if (ret < 0)
			ERROR(cdev, "rmnet ep0 enqueue err %d\n", ret);
	}

	return ret;
}

static int frmnet_bind(struct usb_configuration *c, struct usb_function *f)
{
	struct f_rmnet			*dev = func_to_rmnet(f);
	struct usb_ep			*ep;
	struct usb_composite_dev	*cdev = c->cdev;
	int				ret = -ENODEV;
	pr_debug("%s: start binding\n", __func__);
	dev->ifc_id = usb_interface_id(c, f);
	if (dev->ifc_id < 0) {
		pr_err("%s: unable to allocate ifc id, err:%d\n",
				__func__, dev->ifc_id);
		return dev->ifc_id;
	}
	rmnet_interface_desc.bInterfaceNumber = dev->ifc_id;

	ep = usb_ep_autoconfig(cdev->gadget, &rmnet_fs_in_desc);
	if (!ep) {
		pr_err("%s: usb epin autoconfig failed\n", __func__);
		return -ENODEV;
	}
	dev->port.in = ep;
	/* Update same for u_ether which uses gether port struct */
	dev->gether_port.in_ep = ep;
	ep->driver_data = cdev;

	ep = usb_ep_autoconfig(cdev->gadget, &rmnet_fs_out_desc);
	if (!ep) {
		pr_err("%s: usb epout autoconfig failed\n", __func__);
		ret = -ENODEV;
		goto ep_auto_out_fail;
	}
	dev->port.out = ep;
	/* Update same for u_ether which uses gether port struct */
	dev->gether_port.out_ep = ep;
	ep->driver_data = cdev;

	ep = usb_ep_autoconfig(cdev->gadget, &rmnet_fs_notify_desc);
	if (!ep) {
		pr_err("%s: usb epnotify autoconfig failed\n", __func__);
		ret = -ENODEV;
		goto ep_auto_notify_fail;
	}
	dev->notify = ep;
	ep->driver_data = cdev;

	dev->notify_req = frmnet_alloc_req(ep,
				sizeof(struct usb_cdc_notification),
				GFP_KERNEL);
	if (IS_ERR(dev->notify_req)) {
		pr_err("%s: unable to allocate memory for notify req\n",
				__func__);
		ret = -ENOMEM;
		goto ep_notify_alloc_fail;
	}

	dev->notify_req->complete = frmnet_notify_complete;
	dev->notify_req->context = dev;

	ret = -ENOMEM;
	f->fs_descriptors = usb_copy_descriptors(rmnet_fs_function);

	if (!f->fs_descriptors) {
		pr_err("%s: no descriptors,usb_copy descriptors(fs)failed\n",
			__func__);
		goto fail;
	}
	if (gadget_is_dualspeed(cdev->gadget)) {
		rmnet_hs_in_desc.bEndpointAddress =
				rmnet_fs_in_desc.bEndpointAddress;
		rmnet_hs_out_desc.bEndpointAddress =
				rmnet_fs_out_desc.bEndpointAddress;
		rmnet_hs_notify_desc.bEndpointAddress =
				rmnet_fs_notify_desc.bEndpointAddress;

		/* copy descriptors, and track endpoint copies */
		f->hs_descriptors = usb_copy_descriptors(rmnet_hs_function);

		if (!f->hs_descriptors) {
			pr_err("%s: no hs_descriptors,usb_copy descriptors(hs)failed\n",
			__func__);
			goto fail;
		}
	}

	if (gadget_is_superspeed(cdev->gadget)) {
		rmnet_ss_in_desc.bEndpointAddress =
				rmnet_fs_in_desc.bEndpointAddress;
		rmnet_ss_out_desc.bEndpointAddress =
				rmnet_fs_out_desc.bEndpointAddress;
		rmnet_ss_notify_desc.bEndpointAddress =
				rmnet_fs_notify_desc.bEndpointAddress;

		/* copy descriptors, and track endpoint copies */
		f->ss_descriptors = usb_copy_descriptors(rmnet_ss_function);

		if (!f->ss_descriptors) {
			pr_err("%s: no ss_descriptors,usb_copy descriptors(ss)failed\n",
			__func__);
			goto fail;
		}
	}

	pr_debug("%s: RmNet(%d) %s Speed, IN:%s OUT:%s\n",
			__func__, dev->port_num,
			gadget_is_dualspeed(cdev->gadget) ? "dual" : "full",
			dev->port.in->name, dev->port.out->name);

	return 0;

fail:
	if (f->ss_descriptors)
		usb_free_descriptors(f->ss_descriptors);
	if (f->hs_descriptors)
		usb_free_descriptors(f->hs_descriptors);
	if (f->fs_descriptors)
		usb_free_descriptors(f->fs_descriptors);
	if (dev->notify_req)
		frmnet_free_req(dev->notify, dev->notify_req);
ep_notify_alloc_fail:
	dev->notify->driver_data = NULL;
	dev->notify = NULL;
ep_auto_notify_fail:
	dev->port.out->driver_data = NULL;
	dev->port.out = NULL;
ep_auto_out_fail:
	dev->port.in->driver_data = NULL;
	dev->port.in = NULL;

	return ret;
}

static int frmnet_bind_config(struct usb_configuration *c, unsigned portno)
{
	int			status;
	struct f_rmnet		*dev;
	struct usb_function	*f;
	unsigned long		flags;

	pr_debug("%s: usb config:%p\n", __func__, c);

	if (portno >= nr_rmnet_ports) {
		pr_err("%s: supporting ports#%u port_id:%u\n", __func__,
				nr_rmnet_ports, portno);
		return -ENODEV;
	}

	dev = rmnet_ports[portno].port;

	if (rmnet_ports[portno].data_xport == USB_GADGET_XPORT_ETHER) {
		struct eth_dev *edev = gether_setup_name(c->cdev->gadget, NULL,
							 "usb_rmnet");
		if (IS_ERR(edev)) {
			pr_err("%s: gether_setup failed\n", __func__);
			return PTR_ERR(edev);
		}
		dev->gether_port.ioport = edev;
	}

	if (rmnet_string_defs[0].id == 0) {
		status = usb_string_id(c->cdev);
		if (status < 0) {
			pr_err("%s: failed to get string id, err:%d\n",
					__func__, status);
			return status;
		}
		rmnet_string_defs[0].id = status;
	}

	spin_lock_irqsave(&dev->lock, flags);
	dev->cdev = c->cdev;
	f = &dev->gether_port.func;
	f->name = kasprintf(GFP_ATOMIC, "rmnet%d", portno);
	spin_unlock_irqrestore(&dev->lock, flags);
	if (!f->name) {
		pr_err("%s: cannot allocate memory for name\n", __func__);
		return -ENOMEM;
	}

	f->strings = rmnet_strings;
	f->bind = frmnet_bind;
	f->unbind = frmnet_unbind;
	f->disable = frmnet_disable;
	f->set_alt = frmnet_set_alt;
	f->setup = frmnet_setup;
	f->suspend = frmnet_suspend;
	f->resume = frmnet_resume;
	dev->port.send_cpkt_response = frmnet_send_cpkt_response;
	dev->port.disconnect = frmnet_disconnect;
	dev->port.connect = frmnet_connect;
	dev->gether_port.cdc_filter = 0;

	status = usb_add_function(c, f);
	if (status) {
		pr_err("%s: usb add function failed: %d\n",
				__func__, status);
		kfree(f->name);
		return status;
	}

	pr_debug("%s: complete\n", __func__);

	return status;
}

static void frmnet_unbind_config(void)
{
	int i;

	for (i = 0; i < nr_rmnet_ports; i++)
		if (rmnet_ports[i].data_xport == USB_GADGET_XPORT_ETHER) {
			gether_cleanup(rmnet_ports[i].port->gether_port.ioport);
			rmnet_ports[i].port->gether_port.ioport = NULL;
		}
}

static void frmnet_cleanup(void)
{
	int i;

	for (i = 0; i < nr_rmnet_ports; i++)
		kfree(rmnet_ports[i].port);

	gbam_cleanup();
	nr_rmnet_ports = 0;
	no_ctrl_smd_ports = 0;
	no_ctrl_qti_ports = 0;
	no_data_bam_ports = 0;
	no_data_bam2bam_ports = 0;
	no_ctrl_hsic_ports = 0;
	no_data_hsic_ports = 0;
	no_ctrl_hsuart_ports = 0;
	no_data_hsuart_ports = 0;
}

static int frmnet_init_port(const char *ctrl_name, const char *data_name,
		const char *port_name)
{
	struct f_rmnet			*dev;
	struct rmnet_ports		*rmnet_port;
	int				ret;
	int				i;

	if (nr_rmnet_ports >= NR_RMNET_PORTS) {
		pr_err("%s: Max-%d instances supported\n",
				__func__, NR_RMNET_PORTS);
		return -EINVAL;
	}

	pr_debug("%s: port#:%d, ctrl port: %s data port: %s\n",
		__func__, nr_rmnet_ports, ctrl_name, data_name);

	dev = kzalloc(sizeof(struct f_rmnet), GFP_KERNEL);
	if (!dev) {
		pr_err("%s: Unable to allocate rmnet device\n", __func__);
		return -ENOMEM;
	}

	dev->port_num = nr_rmnet_ports;
	spin_lock_init(&dev->lock);
	INIT_LIST_HEAD(&dev->cpkt_resp_q);

	rmnet_port = &rmnet_ports[nr_rmnet_ports];
	rmnet_port->port = dev;
	rmnet_port->port_num = nr_rmnet_ports;
	rmnet_port->ctrl_xport = str_to_xport(ctrl_name);
	rmnet_port->data_xport = str_to_xport(data_name);

	switch (rmnet_port->ctrl_xport) {
	case USB_GADGET_XPORT_SMD:
		rmnet_port->ctrl_xport_num = no_ctrl_smd_ports;
		no_ctrl_smd_ports++;
		break;
	case USB_GADGET_XPORT_QTI:
		rmnet_port->ctrl_xport_num = no_ctrl_qti_ports;
		no_ctrl_qti_ports++;
		break;
	case USB_GADGET_XPORT_HSIC:
		ghsic_ctrl_set_port_name(port_name, ctrl_name);
		rmnet_port->ctrl_xport_num = no_ctrl_hsic_ports;
		no_ctrl_hsic_ports++;
		break;
	case USB_GADGET_XPORT_HSUART:
		rmnet_port->ctrl_xport_num = no_ctrl_hsuart_ports;
		no_ctrl_hsuart_ports++;
		break;
	case USB_GADGET_XPORT_NONE:
		break;
	default:
		pr_err("%s: Un-supported transport: %u\n", __func__,
				rmnet_port->ctrl_xport);
		ret = -ENODEV;
		goto fail_probe;
	}

	switch (rmnet_port->data_xport) {
	case USB_GADGET_XPORT_BAM:
		rmnet_port->data_xport_num = no_data_bam_ports;
		no_data_bam_ports++;
		break;
	case USB_GADGET_XPORT_BAM2BAM:
	case USB_GADGET_XPORT_BAM2BAM_IPA:
		rmnet_port->data_xport_num = no_data_bam2bam_ports;
		no_data_bam2bam_ports++;
		break;
	case USB_GADGET_XPORT_HSIC:
		ghsic_data_set_port_name(port_name, data_name);
		rmnet_port->data_xport_num = no_data_hsic_ports;
		no_data_hsic_ports++;
		break;
	case USB_GADGET_XPORT_HSUART:
		rmnet_port->data_xport_num = no_data_hsuart_ports;
		no_data_hsuart_ports++;
		break;
	case USB_GADGET_XPORT_ETHER:
	case USB_GADGET_XPORT_NONE:
		break;
	default:
		pr_err("%s: Un-supported transport: %u\n", __func__,
				rmnet_port->data_xport);
		ret = -ENODEV;
		goto fail_probe;
	}
	nr_rmnet_ports++;

	return 0;

fail_probe:
	for (i = 0; i < nr_rmnet_ports; i++)
		kfree(rmnet_ports[i].port);

	nr_rmnet_ports = 0;
	no_ctrl_smd_ports = 0;
	no_ctrl_qti_ports = 0;
	no_data_bam_ports = 0;
	no_ctrl_hsic_ports = 0;
	no_data_hsic_ports = 0;
	no_ctrl_hsuart_ports = 0;
	no_data_hsuart_ports = 0;

	return ret;
}


text:
<?php
/**
 * Author: Taras "Dr.Wolf" Supyk (w@enigma-lab.org)
 * Date: 04.06.17
 * Time: 12:50
 */

namespace Utils;

class FileJson
{
    /**
     * @param string $path
     * @return mixed
     */
    static public function load(string $path)
    {
        return json_decode(file_get_contents($path), true);
    }

    /**
     * @param string $path
     * @param $data
     */
    static public function save(string $path, $data)
    {
        file_put_contents($path, json_encode($data));
    }
}


text:
package mcl

/*
#cgo bn256 CFLAGS:-DMCLBN_FP_UNIT_SIZE=4
#cgo bn384 CFLAGS:-DMCLBN_FP_UNIT_SIZE=6
#cgo bn384_256 CFLAGS:-DMCLBN_FP_UNIT_SIZE=6 -DMCLBN_FR_UNIT_SIZE=4
#cgo bn256 LDFLAGS:-lmclbn256 -lmcl
#cgo bn384 LDFLAGS:-lmclbn384 -lmcl
#cgo bn384_256 LDFLAGS:-lmclbn384_256 -lmcl
#include <mcl/bn.h>
*/
import "C"
import "fmt"

// Init --
// call this function before calling all the other operations
// this function is not thread safe
func Init(curve int) error {
	err := C.mclBn_init(C.int(curve), C.MCLBN_COMPILED_TIME_VAR)
	if err != 0 {
		return fmt.Errorf("ERR mclBn_init curve=%d", curve)
	}
	return nil
}


text:
package ml.shortit.shortit;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> data;
    ListView shortUrlList;
    TextView emptytext;
    FloatingActionButton newUrl;
    UrlDbHelper helper;
    ArrayAdapter<String> dataAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        shortUrlList = (ListView) findViewById(R.id.listView);
        try {
            emptytext = (TextView) findViewById(R.id.textView6);
            emptytext.setText("No Short URLs found. Create One !");
        } catch (Exception e) {
            e.printStackTrace();
        }
        shortUrlList.setEmptyView(emptytext);
        loadDataInList();

        shortUrlList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String urlToOpen = shortUrlList.getItemAtPosition(position).toString();
                Intent browser = new Intent(Intent.ACTION_VIEW);
                browser.setData(Uri.parse(urlToOpen));
                startActivity(browser);
            }
        });

        registerForContextMenu(shortUrlList);

        newUrl = (FloatingActionButton) findViewById(R.id.addUrl);

        newUrl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent add = new Intent(getApplicationContext(), AddActivity.class);
                startActivity(add);
                finish();
            }
        });
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("URL Actions");
        menu.add(0, v.getId(), 0, "Delete");
        menu.add(0, v.getId(), 0, "Copy URL");
        menu.add(0, v.getId(), 0, "View Details");
        menu.add(0, v.getId(), 0, "Share URL");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        String shortUrl = ((TextView) info.targetView).getText().toString();

        if (item.getTitle() == "Delete") {
            helper = new UrlDbHelper(getApplicationContext());
            int cnt = helper.deleteData(shortUrl);
            if (cnt > 0) {
                Toast.makeText(MainActivity.this, "Short IT URL Deleted Successfully !", Toast.LENGTH_LONG).show();
                refreshList();
            }
        } else if (item.getTitle() == "Copy URL") {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("url", shortUrl);
            clipboard.setPrimaryClip(clip);
            Toast.makeText(getApplicationContext(), "URL Copied Successfully !", Toast.LENGTH_LONG).show();
        } else if (item.getTitle() == "View Details") {
            Intent urlView = new Intent(getApplicationContext(), UrlViewActivity.class);
            urlView.putExtra("shortUrl", shortUrl);
            startActivity(urlView);
            finish();
        } else if (item.getTitle() == "Share URL") {
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, "Check This Out : " + shortUrl + "\n\n  - Shared Via Short IT App");
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
        } else {
            return false;
        }
        return true;
    }

    private int loadDataInList() {
        helper = new UrlDbHelper(getApplicationContext());
        data = (ArrayList<String>) helper.fetchShortUrls();
        dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
        shortUrlList.setAdapter(dataAdapter);
        return dataAdapter.getCount();
    }

    private void refreshList() {
        data = (ArrayList<String>) helper.fetchShortUrls();
        dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
        dataAdapter.notifyDataSetChanged();
        shortUrlList.setAdapter(dataAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
        {
            getMenuInflater().inflate(R.menu.menu_main,menu);
            return true;
        }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();
        if (id == R.id.action_wipe)
        {
            helper = new UrlDbHelper(getApplicationContext());

            if (loadDataInList() > 0) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Delete All URLs")
                        .setMessage("Are you sure you want to delete ALL the generated URLs?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                helper.wipeData();
                                refreshList();
                                Toast.makeText(getApplicationContext(), "All the generated URLs are cleaned successfully !", Toast.LENGTH_LONG).show();
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // do nothing
                            }
                        })
                        .setIcon(R.drawable.ic_warning)
                        .show();
            } else {
                Toast.makeText(getApplicationContext(), "No Data to Clear !", Toast.LENGTH_LONG).show();
            }

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("Exit")
                .setMessage("Do You Want To Quit ?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(R.drawable.ic_info)
                .show();
    }
}


text:
* Drop support for Ruby 2.4 and add support for Ruby 3.0

### 1.5.0 / 2020-01-09

* Extract error classes into a separate gem, google-cloud-errors.
* Various fixes for Core Config
    * Fix warnings on to_s!
    * Alias to_s! as inspect
    * Add send to ILLEGAL_KEYS
    * Add respond_to? as alias of field?

### 1.4.1 / 2019-10-29

#### Documentation

* Update the list of GCP environments for automatic authentication

### 1.4.0 / 2019-10-23

Now requires Ruby 2.4 or later.

### 1.3.2 / 2019-10-14

#### Bug Fixes

* Update Google::Cloud::Config#method_missing to be compatible with Ruby 2.7

### 1.3.1 / 2019-08-23

#### Documentation

* Update documentation

### 1.3.0 / 2019-01-31

* Add on_error configuration.

### 1.2.7 / 2018-09-20

* Update documentation.
  * Change documentation URL to googleapis GitHub org.

### 1.2.6 / 2018-09-12

* Add missing documentation files to package.

### 1.2.5 / 2018-09-11

* Fix for issue when auto-loading google-cloud-* gem.

### 1.2.4 / 2018-09-10

* Update documentation.

### 1.2.3 / 2018-08-21

* Update (deprecated) Credentials authentication URLs.
* Update documentation.

### 1.2.2 / 2018-07-05

* Disable warnings while auto-loading gems to avoid circular require warnings.

### 1.2.1 / 2018-06-28

* Warn when using Ruby version that is end-of-life.
* Fix google-cloud-* auto-load to load only the latest version.

### 1.2.0 / 2018-02-27

* Add Shared Configuration.

### 1.1.0 / 2017-11-14

* Rename constructor arguments to `project_id` and `credentials`.
* Document `Google::Auth::Credentials` as `credentials` value.
* Remove `googleauth` runtime dependency.
* Add the following helper methods to `Google::Cloud::Error`, which access the
  respective values on the underlying error objects.
  * `Error#status_code`
  * `Error#body`
  * `Error#header`
  * `Error#code`
  * `Error#details`
  * `Error#metadata`
  * `Error#status_details`
* Fixed mapping of `FailedPreconditionError` to 412 HTTP response code.

### 1.0.0 / 2017-03-31

* Release 1.0
* Add dependency on google-cloud-env

### 0.21.1 / 2016-11-22

* Support the new GAE Flex beta environment.

### 0.21.0 / 2016-10-20

* Updates to support new releases. No changes to the public API.

### 0.20.1 / 2016-08-26

* Fix autoloading of Google Cloud services

### 0.20.0 / 2016-08-26

This gem contains shared classes for the `google-cloud-ruby` gems. It is not intended for direct use. The `google-cloud` gem replaces the old `gcloud` gem. Legacy code can continue to use the `gcloud` gem.

* Namespace is now `Google::Cloud`
* The `google-cloud` gem is now an umbrella package for individual gems


text:
namespace mlir {
namespace iree_compiler {

/// Sets compilation configuration annotated in the incoming IR.
LogicalResult setUserConfig(func::FuncOp entryPointFn, Operation *computeOp,
                            IREE::Codegen::CompilationInfoAttr compilationInfo);

}  // namespace iree_compiler
}  // namespace mlir


text:
<?php

namespace App\JsonApi\Groups;

use App\Models\User\User;
use CloudCreativity\JsonApi\Contracts\Validators\RelationshipsValidatorInterface;
use CloudCreativity\LaravelJsonApi\Validators\AbstractValidatorProvider;

class Validators extends AbstractValidatorProvider
{

    /**
     * @inheritdoc
     */
    protected function attributeRules($resourceType, $record = null)
    {
        /** @var User $record */

        // The JSON API spec says the client does not have to send all attributes for an update request, so
        // if the record already exists we need to include a 'sometimes' before required.
        $required = $record ? 'sometimes|required' : 'required';

        // TODO Write capability validator and include here
        return [
            'name' => "$required|unique:groups,name|between:1,100",
            'member-capabilities' => "$required",
            'admin-capabilities' => "$required",
        ];
    }

    /**
     * @inheritdoc
     */
    protected function relationshipRules(
        RelationshipsValidatorInterface $relationships,
        $resourceType,
        $record = null
    ) {
    }
}