text:
*NOTE*  please consider the django-adminfiles application as an alternative:

https://github.com/carljm/django-adminfiles

====================
Django Admin Uploads
====================

File/media browser for Django admin interface. Designed to insert
images and files into textareas in the admin interface with a simple
GUI interface.

Currently, the following features have been written and are working:

- Django 1.3 support
- WYMeditor (bundled from master on 3rd August 2011).
    https://github.com/wymeditor/wymeditor/tree/master/src/wymeditor
- TinyMCE support (probably but not sure, still need to test)

Installation
============

#. Add the `admin_uploads` directory to your Python path.
#. Add `admin_uploads` to your `INSTALLED_APPS` setting so Django can
 find the template files and staticfiles associated with the Admin
 Uploads application.
#. Create an empty uploads folder in your MEDIA_ROOT where images will
 be saved.
#. Make sure you are using Django 1.3 convention of
 STATIC_ROOT/STATIC_URL for staticfiles and MEDIA_ROOT/MEDIA_URL for
 user generated content.

Configuration
=============

See Janis Leidel's blogpost for more comprehensive instructions on the
WYMeditor integration process in Django:
http://jannisleidel.com/2008/11/wysiwym-editor-widget-django-admin-interface/

#. Create a admin.py for any model that has a textfield for which you
 would like to apply either WYMEditor or WYMEditorUpload (with upload
 image capability). Then set the form in your Admin class, and
 register the model with the admin::

    from django import forms
    from django.db.models import get_model

    from django.contrib import admin

    from admin_uploads.widgets import WYMEditor, WYMEditorUpload

    from my_news_app.models import NewsEntry

    class NewsEntryAdminModelForm(forms.ModelForm):
        body = forms.CharField(required=False, widget=WYMEditorUpload())
        notes = forms.CharField(required=False, widget=WYMEditor())

        class Meta:
            model = NewsEntry

    class NewsEntryAdmin(admin.ModelAdmin):
        form = NewsEntryAdminModelForm
        list_display = ( "title", "status", "on_sites")
        prepopulated_fields = {"slug": ("title",)}

    admin.site.register(NewsEntry, NewsEntryAdmin)

For the javascript to work, you'll have to provide your own jQuery by creating a
template ``templates/admin/base_site.html`` and including the link to
the jQuery static file.::

    {% extends "admin/base.html" %}

    {% block extrahead %}
        <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.min.js"></script>
    {% endblock %}

I'm using jQuery 1.6.2 without issue, but it should work fine
with older versions back to at least 1.3/1.4 as well. As noted in the
issues it would be more efficient to use the bundled jQuery.

TODOs and BUGS (out of date)
============================
#. Test Cross Browser
#. Test TinyMCE (I've only yet tested WYMeditor)
#. Add setting to choose if Flickr, YouTube, options available
#. on delete, remove deleted file/image from DOM
#. get request variable in widgets.py
#. use image icon on wymeditor & TinyMCEfor uploading? (easier way to
 use default WYM settings)
#. Add way to manage WYMeditor & TinyMCE options
#. Use Django's bundled version of jQuery.

BUG
#. Doesn't insert when multiple WYMeditors on same admin.


text:
===================
django-urlconfs-xtd
===================

**************************************
This project has moved to GitLab.com
**************************************
https://gitlab.com/kapt/open-source/django-comments-xtd

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>QName (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="javax.xml.namespace.QName class">
<meta name="keywords" content="getNamespaceURI()">
<meta name="keywords" content="getLocalPart()">
<meta name="keywords" content="getPrefix()">
<meta name="keywords" content="equals()">
<meta name="keywords" content="hashCode()">
<meta name="keywords" content="toString()">
<meta name="keywords" content="valueOf()">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.xml.namespace

Class QName

java.lang.Object

javax.xml.namespace.QName

All Implemented Interfaces:

Serializable

public class QName
extends Object
implements Serializable

QName represents a qualified name
 as defined in the XML specifications: XML Schema Part2:
 Datatypes specification, Namespaces
 in XML, Namespaces
 in XML Errata.

The value of a QName contains a Namespace
 URI, local part and
 prefix.

The prefix is included in QName to retain lexical
 information when present in an XML input source. The prefix is
 NOT used in QName.equals(Object) or to compute the QName.hashCode().  Equality and the hash code are defined using
 only the Namespace URI and local part.

If not specified, the Namespace URI is set to XMLConstants.NULL_NS_URI.
 If not specified, the prefix is set to XMLConstants.DEFAULT_NS_PREFIX.

QName is immutable.

Since:

1.5

See Also:

   XML Schema Part2: Datatypes specification,

   Namespaces in XML,

   Namespaces in XML Errata,
Serialized Form

Constructor Summary

Constructors

Constructor and Description

QName(String localPart)

QName constructor specifying the local part.

QName(String namespaceURI,
     String localPart)

QName constructor specifying the Namespace URI
 and local part.

QName(String namespaceURI,
     String localPart,
     String prefix)

QName constructor specifying the Namespace URI,
 local part and prefix.

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(Object objectToTest)

Test this QName for equality with another
 Object.

String
getLocalPart()

Get the local part of this QName.

String
getNamespaceURI()

Get the Namespace URI of this QName.

String
getPrefix()

Get the prefix of this QName.

int
hashCode()

Generate the hash code for this QName.

String
toString()

String representation of this
 QName.

static QName
valueOf(String qNameAsString)

QName derived from parsing the formatted
 String.

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Constructor Detail

QName

public QName(String namespaceURI,
     String localPart)

QName constructor specifying the Namespace URI
 and local part.

If the Namespace URI is null, it is set to
 XMLConstants.NULL_NS_URI.  This value represents no
 explicitly defined Namespace as defined by the Namespaces
 in XML specification.  This action preserves compatible
 behavior with QName 1.0.  Explicitly providing the XMLConstants.NULL_NS_URI value is the preferred coding
 style.

If the local part is null an
 IllegalArgumentException is thrown.
 A local part of "" is allowed to preserve
 compatible behavior with QName 1.0.

When using this constructor, the prefix is set to XMLConstants.DEFAULT_NS_PREFIX.

The Namespace URI is not validated as a
 URI reference.
 The local part is not validated as a
 NCName
 as specified in Namespaces
 in XML.

Parameters:

namespaceURI - Namespace URI of the QName

localPart - local part of the QName

Throws:

IllegalArgumentException - When localPart is
   null

See Also:

QName(String namespaceURI, String localPart, String
 prefix)

QName

public QName(String namespaceURI,
     String localPart,
     String prefix)

QName constructor specifying the Namespace URI,
 local part and prefix.

If the Namespace URI is null, it is set to
 XMLConstants.NULL_NS_URI.  This value represents no
 explicitly defined Namespace as defined by the Namespaces
 in XML specification.  This action preserves compatible
 behavior with QName 1.0.  Explicitly providing the XMLConstants.NULL_NS_URI value is the preferred coding
 style.

If the local part is null an
 IllegalArgumentException is thrown.
 A local part of "" is allowed to preserve
 compatible behavior with QName 1.0.

If the prefix is null, an
 IllegalArgumentException is thrown.  Use XMLConstants.DEFAULT_NS_PREFIX to explicitly indicate that no
 prefix is present or the prefix is not relevant.

The Namespace URI is not validated as a
 URI reference.
 The local part and prefix are not validated as a
 NCName
 as specified in Namespaces
 in XML.

Parameters:

namespaceURI - Namespace URI of the QName

localPart - local part of the QName

prefix - prefix of the QName

Throws:

IllegalArgumentException - When localPart
   or prefix is null

QName

public QName(String localPart)

QName constructor specifying the local part.

If the local part is null an
 IllegalArgumentException is thrown.
 A local part of "" is allowed to preserve
 compatible behavior with QName 1.0.

When using this constructor, the Namespace URI is set to
 XMLConstants.NULL_NS_URI and the prefix is set to XMLConstants.DEFAULT_NS_PREFIX.

In an XML context, all Element and Attribute names exist
 in the context of a Namespace.  Making this explicit during the
 construction of a QName helps prevent hard to
 diagnosis XML validity errors.  The constructors QName(String
 namespaceURI, String localPart) and
 QName(String namespaceURI, String localPart, String prefix)
 are preferred.

The local part is not validated as a
 NCName
 as specified in Namespaces
 in XML.

Parameters:

localPart - local part of the QName

Throws:

IllegalArgumentException - When localPart is
   null

See Also:

QName(String
 namespaceURI, String localPart),
QName(String namespaceURI, String localPart, String
 prefix)

Method Detail

getNamespaceURI

public String getNamespaceURI()

Get the Namespace URI of this QName.

Returns:

Namespace URI of this QName

getLocalPart

public String getLocalPart()

Get the local part of this QName.

Returns:

local part of this QName

getPrefix

public String getPrefix()

Get the prefix of this QName.

The prefix assigned to a QName might
 NOT be valid in a different
 context. For example, a QName may be assigned a
 prefix in the context of parsing a document but that prefix may
 be invalid in the context of a different document.

Returns:

prefix of this QName

equals

public final boolean equals(Object objectToTest)

Test this QName for equality with another
 Object.

If the Object to be tested is not a
 QName or is null, then this method
 returns false.

Two QNames are considered equal if and only if
 both the Namespace URI and local part are equal. This method
 uses String.equals() to check equality of the
 Namespace URI and local part. The prefix is
 NOT used to determine equality.

This method satisfies the general contract of Object.equals(Object)

Overrides:

equals in class Object

Parameters:

objectToTest - the Object to test for
 equality with this QName

Returns:

true if the given Object is
 equal to this QName else false

See Also:

Object.hashCode(),
HashMap

hashCode

public final int hashCode()

Generate the hash code for this QName.

The hash code is calculated using both the Namespace URI and
 the local part of the QName.  The prefix is
 NOT used to calculate the hash
 code.

This method satisfies the general contract of Object.hashCode().

Overrides:

hashCode in class Object

Returns:

hash code for this QName Object

See Also:

Object.equals(java.lang.Object),
System.identityHashCode(java.lang.Object)

toString

public String toString()

String representation of this
 QName.

The commonly accepted way of representing a QName
 as a String was
 defined
 by James Clark.  Although this is not a standard
 specification, it is in common use, e.g. Transformer.setParameter(String name, Object value).
 This implementation represents a QName as:
 "{" + Namespace URI + "}" + local part.  If the Namespace URI
 .equals(XMLConstants.NULL_NS_URI), only the
 local part is returned.  An appropriate use of this method is
 for debugging or logging for human consumption.

Note the prefix value is NOT
 returned as part of the String representation.

This method satisfies the general contract of Object.toString().

Overrides:

toString in class Object

Returns:

String representation of this QName

valueOf

public static QName valueOf(String qNameAsString)

QName derived from parsing the formatted
 String.

If the String is null or does not conform to
 QName.toString() formatting, an
 IllegalArgumentException is thrown.

The String MUST be in the
 form returned by QName.toString().

The commonly accepted way of representing a QName
 as a String was
 defined
 by James Clark.  Although this is not a standard
 specification, it is in common use, e.g. Transformer.setParameter(String name, Object value).
 This implementation parses a String formatted
 as: "{" + Namespace URI + "}" + local part.  If the Namespace
 URI .equals(XMLConstants.NULL_NS_URI), only the
 local part should be provided.

The prefix value CANNOT be
 represented in the String and will be set to
 XMLConstants.DEFAULT_NS_PREFIX.

This method does not do full validation of the resulting
 QName.

The Namespace URI is not validated as a
 URI reference.
 The local part is not validated as a
 NCName
 as specified in
 Namespaces in XML.

Parameters:

qNameAsString - String representation
 of the QName

Returns:

QName corresponding to the given String

Throws:

IllegalArgumentException - When qNameAsString is
   null or malformed

See Also:

QName.toString()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
@interface JHContentScrollView : UIScrollView

@property (nonatomic, assign) CGPoint offset;

@end


text:
import Collection from './collection';
import buffer from '../utils/buffer';
import extend from '../utils/extend';
import iterableSymbol from '../iteration/iterable-symbol';
import error, {ERROR_EMPTY_COLLECTION} from '../utils/error';

/**
* Initializes a new instance of the Stack class that that is empty or contains elements copied from the specified collection.
* @param {Iterable=} collection The collection to copy elements from.
*/
export default function Stack(collection) {
    var items = collection ? buffer(collection) : [];
    Collection.call(this, items);
}

extend(Stack, Collection, {
    /**
    * Removes all objects from the Stack.
    */
    clear: function () {
        this[iterableSymbol].length = 0;
    },

    /**
    * Determines whether an element is in the Stack.
    * @param {Object} item The object to locate in the Stack.
    * @returns {Boolean}
    */
    contains: function (item) {
        return this[iterableSymbol].indexOf(item) !== -1;
    },

    /**
    * Returns the object at the top of the Stack without removing it.
    * @returns {Object}
    */
    peek: function () {
        var items = this[iterableSymbol];

        if (items.length > 0) {
            return items[items.length - 1];
        }

        error(ERROR_EMPTY_COLLECTION);
    },

    /**
    *   Removes and returns the object at the top of the Stack.
    *   @returns {Object}
    */
    pop: function () {
        if (this.count() > 0) {
            return this[iterableSymbol].pop();
        }

        error(ERROR_EMPTY_COLLECTION);
    },

    /**
    * Inserts an object at the top of the Stack.
    * @param {Object} item The object to push onto the Stack.
    */
    push: function (item) {
        this[iterableSymbol].push(item);
    },

    toString: function () {
        return '[Stack]';
    }
});


text:
dnl  Intel Atom mpn_divexact_1 -- mpn by limb exact division.

dnl  Copyright 2011 Free Software Foundation, Inc.

dnl  This file is part of the GNU MP Library.
dnl
dnl  The GNU MP Library is free software; you can redistribute it and/or modify
dnl  it under the terms of either:
dnl
dnl    * the GNU Lesser General Public License as published by the Free
dnl      Software Foundation; either version 3 of the License, or (at your
dnl      option) any later version.
dnl
dnl  or
dnl
dnl    * the GNU General Public License as published by the Free Software
dnl      Foundation; either version 2 of the License, or (at your option) any
dnl      later version.
dnl
dnl  or both in parallel, as here.
dnl
dnl  The GNU MP Library is distributed in the hope that it will be useful, but
dnl  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
dnl  for more details.
dnl
dnl  You should have received copies of the GNU General Public License and the
dnl  GNU Lesser General Public License along with the GNU MP Library.  If not,
dnl  see https://www.gnu.org/licenses/.

include(`../config.m4')

MULFUNC_PROLOGUE(mpn_divexact_1)
include_mpn(`x86/pentium/dive_1.asm')


text:
			Home
			·
			Blog
			·
			Pricing
			·
			About
			·
			Faq
			·
			Contact

Company Name © YEAR

		<form class="form-horizontal" method="get" action="#">

					<input class="form-control" placeholder="Search our website" name="search" disabled />

		</form>


text:
/*
   -- MAGMA (version 2.1.0) --
   Univ. of Tennessee, Knoxville
   Univ. of California, Berkeley
   Univ. of Colorado, Denver
   @date August 2016

   @author Azzam Haidar
   @author Tingxing Dong

   @generated from src/zgetrf_batched.cpp, normal z -> s, Tue Aug 30 09:38:24 2016
*/
#include <cuda_runtime.h>

#include "magma_internal.h"
#include "batched_kernel_param.h"

/***************************************************************************//**
    Purpose
    -------
    SGETRF computes an LU factorization of a general M-by-N matrix A
    using partial pivoting with row interchanges.

    The factorization has the form
        A = P * L * U
    where P is a permutation matrix, L is lower triangular with unit
    diagonal elements (lower trapezoidal if m > n), and U is upper
    triangular (upper trapezoidal if m < n).

    This is the right-looking Level 3 BLAS version of the algorithm.

    This is a batched version that factors batchCount M-by-N matrices in parallel.
    dA, ipiv, and info become arrays with one entry per matrix.

    Arguments
    ---------
    @param[in]
    m       INTEGER
            The number of rows of each matrix A.  M >= 0.

    @param[in]
    n       INTEGER
            The number of columns of each matrix A.  N >= 0.

    @param[in,out]
    dA_array    Array of pointers, dimension (batchCount).
            Each is a REAL array on the GPU, dimension (LDDA,N).
            On entry, each pointer is an M-by-N matrix to be factored.
            On exit, the factors L and U from the factorization
            A = P*L*U; the unit diagonal elements of L are not stored.

    @param[in]
    ldda    INTEGER
            The leading dimension of each array A.  LDDA >= max(1,M).

    @param[out]
    ipiv_array  Array of pointers, dimension (batchCount), for corresponding matrices.
            Each is an INTEGER array, dimension (min(M,N))
            The pivot indices; for 1 <= i <= min(M,N), row i of the
            matrix was interchanged with row IPIV(i).

    @param[out]
    info_array  Array of INTEGERs, dimension (batchCount), for corresponding matrices.
      -     = 0:  successful exit
      -     < 0:  if INFO = -i, the i-th argument had an illegal value
                  or another error occured, such as memory allocation failed.
      -     > 0:  if INFO = i, U(i,i) is exactly zero. The factorization
                  has been completed, but the factor U is exactly
                  singular, and division by zero will occur if it is used
                  to solve a system of equations.

    @param[in]
    batchCount  INTEGER
                The number of matrices to operate on.

    @param[in]
    queue   magma_queue_t
            Queue to execute in.

    @ingroup magma_getrf_batched
*******************************************************************************/
extern "C" magma_int_t
magma_sgetrf_batched(
        magma_int_t m, magma_int_t n,
        float **dA_array,
        magma_int_t ldda,
        magma_int_t **ipiv_array,
        magma_int_t *info_array,
        magma_int_t batchCount, magma_queue_t queue)
{
#define A(i_, j_)  (A + (i_) + (j_)*ldda)

    magma_int_t min_mn = min(m, n);
    cudaMemset(info_array, 0, batchCount*sizeof(magma_int_t));

    /* Check arguments */
    magma_int_t arginfo = 0;
    if (m < 0)
        arginfo = -1;
    else if (n < 0)
        arginfo = -2;
    else if (ldda < max(1,m))
        arginfo = -4;

    if (arginfo != 0) {
        magma_xerbla( __func__, -(arginfo) );
        return arginfo;
    }

    /* Quick return if possible */
    if (m == 0 || n == 0)
        if (min_mn == 0 ) return arginfo;

    if ( m >  2048 || n > 2048 ) {
        #ifndef MAGMA_NOWARNING
        printf("=========================================================================================\n"
               "   WARNING batched routines are designed for small sizes. It might be better to use the\n"
               "   Native/Hybrid classical routines if you want good performance.\n"
               "=========================================================================================\n");
        #endif
    }

//#define ENABLE_TIMER3

#if defined(ENABLE_TIMER3)
    real_Double_t   tall=0.0, tloop=0., talloc=0., tdalloc=0.;
    tall   = magma_sync_wtime(queue);
    talloc = magma_sync_wtime(queue);
#endif

    float c_neg_one = MAGMA_S_NEG_ONE;
    float c_one     = MAGMA_S_ONE;
    magma_int_t nb, recnb, ib, i, k, pm, use_stream;
    magma_get_sgetrf_batched_nbparam(n, &nb, &recnb);

    magma_int_t     **dipiv_displ   = NULL;
    float **dA_displ   = NULL;
    float **dW0_displ  = NULL;
    float **dW1_displ  = NULL;
    float **dW2_displ  = NULL;
    float **dW3_displ  = NULL;
    float **dW4_displ  = NULL;
    float **dinvA_array = NULL;
    float **dwork_array = NULL;

    magma_malloc((void**)&dipiv_displ,   batchCount * sizeof(*dipiv_displ));
    magma_malloc((void**)&dA_displ,   batchCount * sizeof(*dA_displ));
    magma_malloc((void**)&dW0_displ,  batchCount * sizeof(*dW0_displ));
    magma_malloc((void**)&dW1_displ,  batchCount * sizeof(*dW1_displ));
    magma_malloc((void**)&dW2_displ,  batchCount * sizeof(*dW2_displ));
    magma_malloc((void**)&dW3_displ,  batchCount * sizeof(*dW3_displ));
    magma_malloc((void**)&dW4_displ,  batchCount * sizeof(*dW4_displ));
    magma_malloc((void**)&dinvA_array, batchCount * sizeof(*dinvA_array));
    magma_malloc((void**)&dwork_array, batchCount * sizeof(*dwork_array));

    magma_int_t invA_msize = magma_roundup( n, STRTRI_BATCHED_NB )*STRTRI_BATCHED_NB;
    magma_int_t dwork_msize = n*nb;
    magma_int_t **pivinfo_array    = NULL;
    magma_int_t *pivinfo           = NULL;
    float* dinvA      = NULL;
    float* dwork      = NULL; // dinvA and dwork are workspace in strsm
    float **cpuAarray = NULL;
    magma_smalloc( &dinvA, invA_msize * batchCount);
    magma_smalloc( &dwork, dwork_msize * batchCount );
    magma_malloc((void**)&pivinfo_array, batchCount * sizeof(*pivinfo_array));
    magma_malloc((void**)&pivinfo, batchCount * m * sizeof(magma_int_t));
    magma_malloc_cpu((void**) &cpuAarray, batchCount*sizeof(float*));

   /* check allocation */
    if ( dA_displ  == NULL || dW0_displ == NULL || dW1_displ   == NULL || dW2_displ   == NULL ||
         dW3_displ == NULL || dW4_displ == NULL || dinvA_array == NULL || dwork_array == NULL ||
         dinvA     == NULL || dwork     == NULL || cpuAarray   == NULL ||
         dipiv_displ == NULL || pivinfo_array == NULL || pivinfo == NULL) {
        magma_free(dA_displ);
        magma_free(dW0_displ);
        magma_free(dW1_displ);
        magma_free(dW2_displ);
        magma_free(dW3_displ);
        magma_free(dW4_displ);
        magma_free(dinvA_array);
        magma_free(dwork_array);
        magma_free( dinvA );
        magma_free( dwork );
        magma_free_cpu(cpuAarray);
        magma_free(dipiv_displ);
        magma_free(pivinfo_array);
        magma_free(pivinfo);
        magma_int_t info = MAGMA_ERR_DEVICE_ALLOC;
        magma_xerbla( __func__, -(info) );
        return info;
    }

    magmablas_slaset_q( MagmaFull, invA_msize, batchCount, MAGMA_S_ZERO, MAGMA_S_ZERO, dinvA, invA_msize, queue );
    magmablas_slaset_q( MagmaFull, dwork_msize, batchCount, MAGMA_S_ZERO, MAGMA_S_ZERO, dwork, dwork_msize, queue );
    magma_sset_pointer( dwork_array, dwork, 1, 0, 0, dwork_msize, batchCount, queue );
    magma_sset_pointer( dinvA_array, dinvA, STRTRI_BATCHED_NB, 0, 0, invA_msize, batchCount, queue );
    magma_iset_pointer( pivinfo_array, pivinfo, 1, 0, 0, m, batchCount, queue );

    magma_int_t streamid;
    const magma_int_t nbstreams=10;
    magma_queue_t queues[nbstreams];
    for (i=0; i < nbstreams; i++) {
        magma_device_t cdev;
        magma_getdevice( &cdev );
        magma_queue_create( cdev, &queues[i] );
    }
    magma_getvector( batchCount, sizeof(float*), dA_array, 1, cpuAarray, 1, queue);

#if defined(ENABLE_TIMER3)
    printf(" I am after malloc\n");
    talloc = magma_sync_wtime(queue) - talloc;
    tloop  = magma_sync_wtime(queue);
#endif

    for (i = 0; i < min_mn; i += nb)
    {
        ib = min(nb, min_mn-i);
        pm = m-i;
        magma_idisplace_pointers(dipiv_displ, ipiv_array, ldda, i, 0, batchCount, queue);
        magma_sdisplace_pointers(dA_displ, dA_array, ldda, i, i, batchCount, queue);
        //===============================================
        //  panel factorization
        //===============================================
        if (recnb == nb)
        {
            arginfo = magma_sgetf2_batched(
                    pm, ib,
                    dA_displ, ldda,
                    dW1_displ, dW2_displ, dW3_displ,
                    dipiv_displ,
                    info_array, i, batchCount, queue);
        }
        else {
            arginfo = magma_sgetrf_recpanel_batched(
                    pm, ib, recnb,
                    dA_displ, ldda,
                    dipiv_displ, pivinfo_array,
                    dwork_array, nb,
                    dinvA_array, invA_msize,
                    dW0_displ, dW1_displ, dW2_displ,
                    dW3_displ, dW4_displ,
                    info_array, i,
                    batchCount, queue);
        }
        if (arginfo != 0 ) goto fin;
        //===============================================
        // end of panel
        //===============================================

#define RUN_ALL
#ifdef RUN_ALL
        // setup pivinfo before adjusting ipiv
        setup_pivinfo_batched(pivinfo_array, dipiv_displ, pm, ib, batchCount, queue);
        adjust_ipiv_batched(dipiv_displ, ib, i, batchCount, queue);

        // stepinit_ipiv(pivinfo_array, pm, batchCount); // for debug and check swap, it create an ipiv

#if 0
        slaswp_batched( i, dA_displ, ldda,
                i, i+ib,
                dipiv_displ, pivinfo_array, batchCount);
#else
        magma_sdisplace_pointers(dA_displ, dA_array, ldda, i, 0, batchCount, queue);
        magma_sdisplace_pointers(dW0_displ, dA_array, ldda, i, 0, batchCount, queue);
        magma_slaswp_rowparallel_batched( i, dA_displ, ldda,
                dW0_displ, ldda,
                i, i+ib,
                pivinfo_array, batchCount, queue );

#endif

        if ( (i + ib) < n)
        {
            // swap right side and trsm
            magma_sdisplace_pointers(dA_displ, dA_array, ldda, i, i+ib, batchCount, queue);
            magma_sset_pointer( dwork_array, dwork, nb, 0, 0, dwork_msize, batchCount, queue ); // I don't think it is needed Azzam
            magma_slaswp_rowparallel_batched( n-(i+ib), dA_displ, ldda,
                    dwork_array, nb,
                    i, i+ib,
                    pivinfo_array, batchCount, queue );

            magma_sdisplace_pointers(dA_displ, dA_array, ldda, i, i, batchCount, queue);
            magma_sdisplace_pointers(dW0_displ, dA_array, ldda, i, i+ib, batchCount, queue);
            magmablas_strsm_outofplace_batched( MagmaLeft, MagmaLower, MagmaNoTrans, MagmaUnit, 1,
                    ib, n-i-ib,
                    MAGMA_S_ONE,
                    dA_displ,    ldda, // dA
                    dwork_array,  nb, // dB
                    dW0_displ,   ldda, // dX
                    dinvA_array,  invA_msize,
                    dW1_displ,   dW2_displ,
                    dW3_displ,   dW4_displ,
                    0, batchCount, queue );

            if ( (i + ib) < m)
            {
                // if gemm size is > 160 use a streamed classical cublas gemm since it is faster
                // the batched is faster only when M=N <= 160 for K40c
                //-------------------------------------------
                //          USE STREAM  GEMM
                //-------------------------------------------
                use_stream = magma_srecommend_cublas_gemm_stream(MagmaNoTrans, MagmaNoTrans, m-i-ib, n-i-ib, ib);
                if (use_stream)
                {
                    magma_queue_sync(queue);
                    for (k=0; k < batchCount; k++)
                    {
                        streamid = k%nbstreams;
                        magma_sgemm( MagmaNoTrans, MagmaNoTrans,
                                m-i-ib, n-i-ib, ib,
                                c_neg_one, cpuAarray[k] + (i+ib)+i*ldda, ldda,
                                           cpuAarray[k] + i+(i+ib)*ldda, ldda,
                                c_one,     cpuAarray[k] + (i+ib)+(i+ib)*ldda, ldda, queues[streamid] );
                    }
                    // need to synchronise to be sure that sgetf2 do not start before
                    // finishing the update at least of the next panel
                    // if queue is NULL, no need to sync
                    if ( queue != NULL ) {
                         for (magma_int_t s=0; s < nbstreams; s++)
                             magma_queue_sync(queues[s]);
                     }
                }
                //-------------------------------------------
                //          USE BATCHED GEMM
                //-------------------------------------------
                else
                {
                    magma_sdisplace_pointers(dA_displ, dA_array,  ldda, i+ib,    i, batchCount, queue);
                    magma_sdisplace_pointers(dW1_displ, dA_array, ldda,    i, i+ib, batchCount, queue);
                    magma_sdisplace_pointers(dW2_displ, dA_array, ldda, i+ib, i+ib, batchCount, queue);
                    //printf("caling batched dgemm %lld %lld %lld\n", (long long)(m-i-ib), (long long)(n-i-ib), (long long) ib );
                    magma_sgemm_batched( MagmaNoTrans, MagmaNoTrans, m-i-ib, n-i-ib, ib,
                                         c_neg_one, dA_displ,  ldda,
                                                    dW1_displ, ldda,
                                         c_one,     dW2_displ, ldda,
                                         batchCount, queue );
                } // end of batched/streamed gemm
            } // end of  if ( (i + ib) < m)
        } // end of if ( (i + ib) < n)
#endif
    }// end of for

fin:
    magma_queue_sync(queue);
#if defined(ENABLE_TIMER3)
    tloop   = magma_sync_wtime(queue) - tloop;
    tdalloc = magma_sync_wtime(queue);
#endif
    for (k=0; k < nbstreams; k++) {
        magma_queue_destroy( queues[k] );
    }

    magma_free(dA_displ);
    magma_free(dW0_displ);
    magma_free(dW1_displ);
    magma_free(dW2_displ);
    magma_free(dW3_displ);
    magma_free(dW4_displ);
    magma_free(dinvA_array);
    magma_free(dwork_array);
    magma_free( dinvA );
    magma_free( dwork );
    magma_free_cpu(cpuAarray);
    magma_free(dipiv_displ);
    magma_free(pivinfo_array);
    magma_free(pivinfo);

#if defined(ENABLE_TIMER3)
    tdalloc = magma_sync_wtime(queue) - tdalloc;
    tall = magma_sync_wtime(queue) - tall;
    printf("here is the timing from inside sgetrf_batched talloc: %10.5f  tloop: %10.5f tdalloc: %10.5f tall: %10.5f sum: %10.5f\n", talloc, tloop, tdalloc, tall, talloc+tloop+tdalloc );
#endif

    return arginfo;
}


text:
<?php

namespace Phpug\Service;

use Phpug\Cache\Populator\CountryCode;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Phpug\Cache\Cache;

/**
 * Class GeocoderFactory
 *
 * @TODO: Refactor to get the classes from the serviceLocator
 * @package Phpug\Service
 */
class CountryCodeCacheFactory implements  FactoryInterface
{

    public function createService(ServiceLocatorInterface $createService)
    {
        $countryCodeCache = new Cache();
        $countryCodeCache->setServiceManager($createService);
        $countryCodeCache->setPopulator(new CountryCode());

        return $countryCodeCache;
    }
 }


text:
#region CopyrightHeader
//
//  Copyright by Contributors
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//         http://www.apache.org/licenses/LICENSE-2.0.txt
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using Oracle.DataAccess.Client;
//using Oracle.DataAccess.Types;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.mdo.src.mdo;
//using System.Data.OracleClient;

namespace gov.va.medora.mdo.dao.oracle
{
    public class MdoOracleConnection : AbstractConnection, IDisposable
    {
        DataSource _dataSource;
        OracleConnection _cxn;
        OracleTransaction _currentTx;

        public MdoOracleConnection(DataSource src) : base(src)
        {
            validateSource(src);
            _dataSource = src;
        }

        internal OracleTransaction beginTransaction()
        {
            if (_cxn == null)
            {
                connect();
            }
            return _currentTx = _cxn.BeginTransaction();
        }

        internal void commitTransaction()
        {
            if (_currentTx != null)
            {
                _currentTx.Commit();
            }
            _currentTx = null;
        }

        internal void rollbackTransaction()
        {
            if (_currentTx != null)
            {
                _currentTx.Rollback();
            }
            _currentTx = null;
        }

        internal void validateSource(DataSource src)
        {
            if (src == null)
            {
                throw new MdoException(MdoExceptionCode.DATA_SOURCE_NULL);
            }
            if (String.IsNullOrEmpty(src.ConnectionString))
            {
                throw new MdoException(MdoExceptionCode.DATA_SOURCE_MISSING_CXN_STRING);
            }
        }

        public override ISystemFileHandler SystemFileHandler
        {
            get { throw new NotImplementedException(); }
        }

        public override void connect()
        {
            if (!IsConnected)
            {
                _cxn = new OracleConnection(_dataSource.ConnectionString);
                _cxn.Open();
                IsConnected = true;
            }
        }

        public override object authorizedConnect(AbstractCredentials credentials, AbstractPermission permission, DataSource validationDataSource = null)
        {
            throw new NotImplementedException();
        }

        public override string getWelcomeMessage()
        {
            throw new NotImplementedException();
        }

        public override bool hasPatch(string patchId)
        {
            throw new NotImplementedException();
        }

        public override string getServerTimeout()
        {
            return null;
        }

        public override object query(MdoQuery request, AbstractPermission permission = null)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Execute a query
        /// </summary>
        /// <param name="request">SQL request</param>
        /// <param name="permission"></param>
        /// <returns>OracleDataReader</returns>
        public override object query(string request, AbstractPermission permission = null)
        {
            if (!IsConnected)
            {
                connect();
            }
            OracleCommand cmd = new OracleCommand();
            cmd.Connection = _cxn;
            cmd.CommandText = request;
            if (_currentTx != null)
            {
                cmd.Transaction = _currentTx;
            }
            OracleDataReader rdr = cmd.ExecuteReader();
            return rdr;
        }

        /// <summary>
        /// Execute a SqlQuery function on the connection. SqlQuery should be of type OracleQuery
        /// </summary>
        /// <param name="request">SqlQuery with SqlCommand already built</param>
        /// <param name="functionToExecute">The SqlCommand.function to execute - should take no parameters</param>
        /// <param name="permission"></param>
        /// <returns>Returns the type returned by SqlCommand.function</returns>
        public override object query(SqlQuery request, Delegate functionToExecute, AbstractPermission permission = null)
        {
            if (!IsConnected)
            {
                connect();
            }
            if (!(request is OracleQuery))
            {
                throw new ArgumentException("request must be of type OracleQuery");
            }
            ((OracleQuery)request).Command.Connection = this._cxn;
            if (_currentTx != null)
            {
                ((OracleQuery)request).Command.Transaction = _currentTx;
            }
            return functionToExecute.DynamicInvoke(null);
        }

        public override void disconnect()
        {
            IsConnected = false;

            if (_cxn != null)
            {
                _cxn.Dispose();
            }
        }

        public void Dispose()
        {
            if (this.IsConnected)
            {
                disconnect();
            }
        }

        public override Dictionary<string, object> getState()
        {
            throw new NotImplementedException();
        }

        public override void setState(Dictionary<string, object> session)
        {
            throw new NotImplementedException();
        }
    }
}


text:
//
//  IConflictResolver.cs
//
//  Copyright (c) 2019 Couchbase, Inc All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

using System;
using System.Collections.Generic;
using System.Text;

namespace Couchbase.Lite
{
    /// <summary>
    /// Conflict Resolver Interface
    /// </summary>
    public interface IConflictResolver
    {
        /// <summary>
        /// The callback conflict resolve method, if conflict occurs.
        /// When a null document is returned, the conflict will be resolved as document deletion.
        /// If there is an exception thrown in the resolve method, the exception will be caught and handled:
        /// <list type="bullet">
        /// <item>
        /// <description>1. The conflict resolving will be skipped. The pending conflicted documents will be resolved when the replicator is restarted.</description>
        /// </item>
        /// <item>
        /// <description>2. The exception will be reported in the warning log.</description>
        /// </item>
        /// <item>
        /// <description>3. The exception will be reported in the DocumentReplicationChange event.</description>
        /// </item>
        /// </list>
        /// </summary>
        /// <exception cref="InvalidOperationException">Thrown when a document from a different database is returned.</exception>
        Document Resolve(Conflict conflict);
    }
}


text:
'use strict'

require('./age')
require('./interviewer')


text:
<?php

namespace hidev\console;

/**
 * Goal for GitHub.
 */
class GithubController extends CommonController
{
    /**
     * Create the repo on GitHub.
     * If name not given, repo for current project created.
     * @param string $repo full name
     * @return int exit code
     */
    public function actionCreate(string $repo = null)
    {
        return $this->getComponent()->createRepo($repo);
    }

    /**
     * Clone repo from github.
     * TODO this action must be run without `start`.
     * @param string $repo full name vendor/package
     * @return int exit code
     */
    public function actionClone(string $repo)
    {
        return $this->getComponent()->cloneRepo($repo);
    }

    /**
     * Checks if repo exists.
     * @param string $repo full name vendor/package defaults to this repo name
     * @return int exit code
     */
    public function actionExists($repo = null)
    {
        return $this->getComponent()->existsRepo($repo);
    }

    /**
     * Creates github release for current project repo.
     * @param string $release version number
     */
    public function actionRelease($release = null)
    {
        return $this->getComponent()->releaseRepo($repo);
    }

    public function getComponent()
    {
        return $this->take('github');
    }
}


text:
name = 'relimp.B.C'

from . import D                 # Imports relimp.B.D
from .D import X                 # Imports relimp.B.D.X
from .. import E                # Imports relimp.E
from ..F import G               # Imports relimp.F.G
from ..F import H               # Imports relimp.F.H

assert D.name == 'relimp.B.D'
assert E.name == 'relimp.E'
assert G.name == 'relimp.F.G'
assert H.name == 'relimp.F.H'


text:
from google.cloud import lifesciences_v2beta

async def sample_run_pipeline():
    # Create a client
    client = lifesciences_v2beta.WorkflowsServiceV2BetaAsyncClient()

    # Initialize request argument(s)
    request = lifesciences_v2beta.RunPipelineRequest(
    )

    # Make the request
    operation = client.run_pipeline(request=request)

    print("Waiting for operation to complete...")

    response = await operation.result()

    # Handle the response
    print(response)

# [END lifesciences_v2beta_generated_WorkflowsServiceV2Beta_RunPipeline_async]


text:
package com.francescopaolodellaquila.phonebook.DB;

import android.provider.BaseColumns;

/**
 * Created by francescopaolodellaquila on 28/05/17.
 */

public class ContactContract {
    public static final String DB_NAME = "com.francescopaolodellaquila.phonebook.DB";
    public static final int DB_VERSION = 1;

    public class TaskEntry implements BaseColumns {
        public static final String TABLE = "playlist";

        public static final String COL_CONTACT_TITLE = "title";

        public static final String COL_CONTACT_NUMBER = "number";

        public static final String COL_CONTACT_EMAIL = "email";

        public static final String COL_CONTACT_ADDRESS = "address";

        public static final String COL_CONTACT_NOTES = "notes";
    }
}


text:
'use strict';

module.exports = { a: 'object' };


text:
'use strict';

/**
 * Class representing the progress during installation of updates
 *
 */
class UpdateInstallProgress {
  /**
   * Create a UpdateInstallProgress.
   * @member {number} [percentComplete] Percentage of completion.
   * @member {number} [numberOfUpdatesToInstall] Number of updates to install.
   * @member {number} [numberOfUpdatesInstalled] Number of updates installed.
   */
  constructor() {
  }

  /**
   * Defines the metadata of UpdateInstallProgress
   *
   * @returns {object} metadata of UpdateInstallProgress
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'UpdateInstallProgress',
      type: {
        name: 'Composite',
        className: 'UpdateInstallProgress',
        modelProperties: {
          percentComplete: {
            required: false,
            serializedName: 'percentComplete',
            type: {
              name: 'Number'
            }
          },
          numberOfUpdatesToInstall: {
            required: false,
            serializedName: 'numberOfUpdatesToInstall',
            type: {
              name: 'Number'
            }
          },
          numberOfUpdatesInstalled: {
            required: false,
            serializedName: 'numberOfUpdatesInstalled',
            type: {
              name: 'Number'
            }
          }
        }
      }
    };
  }
}

module.exports = UpdateInstallProgress;


text:
*by cadian42*

##Description
Ce script implémente l'automate cellulaire de la [Fourmi de Langton](https://fr.wikipedia.org/wiki/Fourmi_de_Langton)
en python à l'aide de [pyglet](https://bitbucket.org/pyglet/pyglet/wiki/Home). La fourmi est placée au hasard à chaque lancement.

##Paramètres
- **'-wh' + entier** : hauteur de la fenêtre (pixel), défaut = 600
- **'-ww' + entier** : largeur de la fenêtre (pixel), défaut = 800
- **'-s' + entier** : taille d'une case (pixel), défaut = 10
- **'-r'** : définie la couleur des cellules aléatoirement au début, défaut = toutes les cellules sont noires


text:
import datetime
import json
import logging
import os
import urllib
import uuid
import webapp2

from google.appengine.api import taskqueue
from google.appengine.api import urlfetch
from perf_insights.endpoints.cloud_mapper import cloud_helper
from perf_insights.endpoints.cloud_mapper import job_info
from perf_insights import cloud_config

DEFAULT_TRACES_PER_INSTANCE = 64

class TaskPage(webapp2.RequestHandler):

  def _QueryForTraces(self, corpus, query):
    payload = urllib.urlencode({'q': query})
    query_url = '%s/query?%s' % (corpus, payload)

    headers = {
        'X-URLFetch-Service-Id': cloud_config.Get().urlfetch_service_id
    }

    result = urlfetch.fetch(url=query_url,
                            payload=payload,
                            method=urlfetch.GET,
                            headers=headers,
                            follow_redirects=False,
                            deadline=10)
    logging.info(result.content)

    return json.loads(result.content)

  def _DispatchTracesAndWaitForResult(self, job, traces, num_instances):
    def _slice_it(li, cols=2):
      start = 0
      for i in xrange(cols):
        stop = start + len(li[i::cols])
        yield li[start:stop]
        start = stop

    # TODO(simonhatch): In the future it might be possibly to only specify a
    # reducer and no mapper. Revisit this.
    bucket_path = cloud_config.Get().control_bucket_path + "/jobs/"
    mapper_url = '%s%s.mapper' % (bucket_path, job.key.id())
    mapper_text = job.mapper.encode('ascii', 'ignore')
    cloud_helper.WriteGCS(mapper_url, mapper_text)

    version = self._GetVersion()

    tasks = {}

    # Split the traces up into N buckets.
    for current_traces in _slice_it(traces, num_instances):
      task_id = str(uuid.uuid4())

      payload = {
          'revision': job.revision,
          'traces': json.dumps(current_traces),
          'result': '%s%s.result' % (bucket_path, task_id),
          'mapper': mapper_url,
          'mapper_function': job.mapper_function
      }
      taskqueue.add(
          queue_name='mapper-queue',
          url='/cloud_worker/task',
          target=version,
          name=task_id,
          params=payload)
      tasks[task_id] = {'status': 'IN_PROGRESS'}

    job.running_tasks = [task_id for task_id, _ in tasks.iteritems()]
    job.put()

    # On production servers, we could just sit and wait for the results, but
    # dev_server is single threaded and won't run any other tasks until the
    # current one is finished. We'll just do the easy thing for now and
    # queue a task to check for the result.
    timeout = (
        datetime.datetime.now() + datetime.timedelta(minutes=10)).strftime(
            '%Y-%m-%d %H:%M:%S')
    taskqueue.add(
        queue_name='default',
        url='/cloud_mapper/task',
        target=version,
        countdown=1,
        params={'jobid': job.key.id(),
                'type': 'check',
                'tasks': json.dumps(tasks),
                'timeout': timeout})

  def _GetVersion(self):
    version = os.environ['CURRENT_VERSION_ID'].split('.')[0]
    if cloud_config._is_devserver():
      version = taskqueue.DEFAULT_APP_VERSION
    return version

  def _CancelTasks(self, tasks):
    task_names = [task_id for task_id, _ in tasks.iteritems()]
    taskqueue.Queue('mapper-queue').delete_tasks_by_name(task_names)

  def _CheckOnResults(self, job):
    tasks = json.loads(self.request.get('tasks'))

    # TODO: There's no reducer yet, so we can't actually collapse multiple
    # results into one results file.
    results = None
    for task_id, _ in tasks.iteritems():
      task_results_path = '%s/jobs/%s.result' % (
          cloud_config.Get().control_bucket_path, task_id)
      stat_result = cloud_helper.StatGCS(task_results_path)
      if stat_result is not None:
        logging.info(str(stat_result))
        tasks[task_id]['status'] = 'DONE'
        results = task_results_path

    if not results:
      timeout = datetime.datetime.strptime(
          self.request.get('timeout'), '%Y-%m-%d %H:%M:%S')
      if datetime.datetime.now() > timeout:
        self._CancelTasks(tasks)
        job.status = 'ERROR'
        job.put()
        logging.error('Task timed out waiting for results.')
        return
      taskqueue.add(
          url='/cloud_mapper/task',
          target=self._GetVersion(),
          countdown=1,
          params={'jobid': job.key.id(),
                  'type': 'check',
                  'tasks': json.dumps(tasks),
                  'timeout': self.request.get('timeout')})
      return

    logging.info("Finished all tasks.")

    job.status = 'COMPLETE'
    job.results = results
    job.put()

  def _CalculateNumInstancesNeeded(self, num_traces):
    return 1 + int(num_traces / DEFAULT_TRACES_PER_INSTANCE)

  def _RunMappers(self, job):
    # Get all the traces to process
    traces = self._QueryForTraces(job.corpus, job.query)

    # We can probably be smarter about this down the road, maybe breaking
    # this into many smaller tasks and allowing each instance to run
    # several tasks at once. For now we'll just break it into a few big ones.
    num_instances = self._CalculateNumInstancesNeeded(len(traces))

    return self._DispatchTracesAndWaitForResult(job, traces, num_instances)

  def _CreateMapperJob(self, job):
    if job.status != 'QUEUED':
      return

    job.status = 'IN_PROGRESS'
    job.put()

    self._RunMappers(job)

  def post(self):
    self.response.headers['Content-Type'] = 'text/plain'

    jobid = self.request.get('jobid')
    job = job_info.JobInfo.get_by_id(jobid)
    if not job:
      return

    try:
      if self.request.get('type') == 'create':
        self._CreateMapperJob(job)
      elif self.request.get('type') == 'check':
        self._CheckOnResults(job)
    except Exception as e:
      job.status = 'ERROR'
      job.put()
      logging.exception('Failed job: %s' % e.message)

app = webapp2.WSGIApplication([('/cloud_mapper/task', TaskPage)])


text:
<!DOCTYPE html>

    <meta charset="utf-8">


text:
module Blogament
  class InstallGenerator < Rails::Generators::Base
    def install
      route 'mount Blogament::Engine, at: "/blog"'
      rake  'blogament:install'
    end
  end
end


text:
namespace swift {
namespace Lowering {

/// A scope that is created before arguments are emitted for an apply and is
/// popped manually immediately after the raw apply is emitted and before the
/// raw results are marshalled into managed resources.
///
/// Internally this creates a Scope and a FormalEvaluationScope. It ensures that
/// they are destroyed/initialized in the appropriate order.
class ArgumentScope {
  SILGenFunction &SGF;
  Scope normalScope;
  FormalEvaluationScope formalEvalScope;
  SILLocation loc;

public:
  ArgumentScope(SILGenFunction &SGF, SILLocation loc)
      : SGF(SGF), normalScope(SGF.Cleanups, CleanupLocation::get(loc)),
        formalEvalScope(SGF), loc(loc) {}

  ~ArgumentScope() {
    if (normalScope.isValid() || !formalEvalScope.isPopped()) {
      llvm_unreachable("ArgumentScope that wasn't popped?!");
    }
  }

  ArgumentScope() = delete;
  ArgumentScope(const ArgumentScope &) = delete;
  ArgumentScope &operator=(const ArgumentScope &) = delete;

  ArgumentScope(ArgumentScope &&other)
      : SGF(other.SGF), normalScope(std::move(other.normalScope)),
        formalEvalScope(std::move(other.formalEvalScope)), loc(other.loc) {}

  /// Deleted move assignment operator.
  ///
  /// This is done on purpose, since we only want to be able to move
  /// ArgumentScope into utility functions.
  ArgumentScope &operator=(ArgumentScope &&other) = delete;

  void pop() { popImpl(); }

  /// Pop the formal evaluation and argument scopes preserving the value mv.
  ManagedValue popPreservingValue(ManagedValue mv);

private:
  void popImpl() {
    // We must always pop the formal eval scope before the normal scope since
    // the formal eval scope may have pointers into the normal scope.
    formalEvalScope.pop();
    normalScope.pop();
  }
};

} // end namespace Lowering
} // end namespace swift

#endif


text:
package org.apache.hadoop.yarn.server.resourcemanager.webapp.dao;

import org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWSConsts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.activities.NodeAllocation;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/*
 * DAO object to display each node allocation in node heartbeat.
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NodeAllocationInfo {
  private String partition;
  private String updatedContainerId;
  private String finalAllocationState;
  private ActivityNodeInfo root = null;

  private static final Logger LOG =
      LoggerFactory.getLogger(NodeAllocationInfo.class);

  NodeAllocationInfo() {
  }

  NodeAllocationInfo(NodeAllocation allocation,
      RMWSConsts.ActivitiesGroupBy groupBy) {
    this.partition = allocation.getPartition();
    this.updatedContainerId = allocation.getContainerId();
    this.finalAllocationState = allocation.getFinalAllocationState().name();
    root = new ActivityNodeInfo(allocation.getRoot(), groupBy);
  }

  public String getPartition() {
    return partition;
  }

  public String getUpdatedContainerId() {
    return updatedContainerId;
  }

  public String getFinalAllocationState() {
    return finalAllocationState;
  }

  public ActivityNodeInfo getRoot() {
    return root;
  }
}


text:
#include "Gwen/Gwen.h"
#include "Gwen/ControlList.h"

using namespace Gwen;
using namespace Gwen::Controls;

void ControlList::Enable()
{
	for ( List::const_iterator it = list.begin(); it != list.end(); ++it )
	{
		(*it)->SetDisabled( false );
	}
}

void ControlList::Disable()
{
	for ( List::const_iterator it = list.begin(); it != list.end(); ++it )
	{
		(*it)->SetDisabled( true );
	}
}

void ControlList::Show()
{
	for ( List::const_iterator it = list.begin(); it != list.end(); ++it )
	{
		(*it)->Show();
	}
}

void ControlList::Hide()
{
	for ( List::const_iterator it = list.begin(); it != list.end(); ++it )
	{
		(*it)->Hide();
	}
}

Gwen::TextObject ControlList::GetValue()
{
	for ( List::const_iterator it = list.begin(); it != list.end(); ++it )
	{
		return (*it)->GetValue();
	}

	return "";
}

void ControlList::SetValue( const Gwen::TextObject& value )
{
	for ( List::const_iterator it = list.begin(); it != list.end(); ++it )
	{
		(*it)->SetValue( value );
	}
}

void ControlList::MoveBy( const Gwen::Point& point )
{
	for ( List::const_iterator it = list.begin(); it != list.end(); ++it )
	{
		(*it)->MoveBy( point.x, point.y );
	}
}

void ControlList::DoAction()
{
	for ( List::const_iterator it = list.begin(); it != list.end(); ++it )
	{
		(*it)->DoAction();
	}
}

void ControlList::SetActionInternal( Gwen::Event::Handler* pObject, void (Gwen::Event::Handler::*f)( Gwen::Event::Info ), const Gwen::Event::Packet& packet )
{
	for ( List::const_iterator it = list.begin(); it != list.end(); ++it )
	{
		(*it)->SetAction( pObject, f, packet );
	}
}


text:
## Задание 13 "spi_shift_reg"

### Подключение и использование сдвигового регистра

Свиговый регистр - утройство, которое часто используется для увеличения количества периферии.

![Распиновка сдвигового регистра](https://github.com/leokondrashov/stm32f0_ARM/blob/master/docs/images/74HC595-PINOUT.jpg)

Принцип его работы:

Внутри есть восьмибитный регистр. При появлении переднего фронта на входе тактирования(SH_CP) значение в нём свигаются на один бит влево, а на самый младший разряд подставляется значение с пина данных(DS) в этот момент. При появлении переднего фронта на пине защёлки(ST_CP) это состояние выводится на вывода Q0-Q7.

Оставшиеся пины: Q7' - пин переноса (если захочется каскадно подключить несколько сдвиговых регистров один за другим) - оставляем недоключеннным. ~MR - пин очистки - притягиваем к земле; ~OE - пин отключения выходов - подтягиваем к питанию, так как они нам не понадобятся.

В этой лабораторной мы будем использовать в таком режиме: выдавать подряд 8 байт с тактированием, чтобы регистр их считывал, и только после этого подаём сигнал на защёлку. Такой режим использования можно реализовать, передавая байт через SPI. Для этого будут задействованы только выход тактирования(PA5) и выход MOSI(PA7). При этом, мы не используем ни в каком виде сигнал Chip Select - он нам не нужен. Так же нам понадобится отдельный сигнал для вывода сигналя на защёлку(PC4).

![Подключение сдвигового регистра](https://github.com/leokondrashov/stm32f0_ARM/blob/master/docs/images/74HC595-CONNECT.jpg)

Итого, подключение сдвигового регистра: PA5 к пину 12(SH_CP); PA7 к пину 14(DS); PC4 к пину 11(ST_CP); к пинам 15, 1-7(Q0-Q7) - светодиоды; 8(GND), 13(~OE) - к земле; 16(VCC), 10(~MR) - к питанию

### Инициализация

1. Инициализация пинов:

```c
    /*
     * Init latch pin
     */
    LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOC);
    LL_GPIO_SetPinMode(GPIOC, LL_GPIO_PIN_4, LL_GPIO_MODE_OUTPUT);
    /*
     * Init GPIO pertained to SPI module
     */
    LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA);
    //SPI_MOSI
    LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_7, LL_GPIO_MODE_ALTERNATE);  //PA7
    LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_7, LL_GPIO_AF_0);
    LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_7, LL_GPIO_SPEED_FREQ_HIGH);
    //SPI_MISO
    LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_6, LL_GPIO_MODE_ALTERNATE);  //PA6 (unused)
    LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_6, LL_GPIO_AF_0);
    //SPI_SCK
    LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_5, LL_GPIO_MODE_ALTERNATE);  //PA5
    LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_5, LL_GPIO_AF_0);
    LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_5, LL_GPIO_SPEED_FREQ_HIGH);

```

Происходит инициализация PA5-PA7 на альтернативные функции (как интерфейсные пины для SPI). Выходы настраиваются на высокую скорость передачи

2. Инициализация SPI:

```c
    LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_SPI1);
    LL_SPI_SetMode(SPI1, LL_SPI_MODE_MASTER); // Режим ведущего
    LL_SPI_SetBaudRatePrescaler(SPI1, LL_SPI_BAUDRATEPRESCALER_DIV8); // Частота 48MHz / 8 = 6MHz
    LL_SPI_SetTransferBitOrder(SPI1, LL_SPI_MSB_FIRST); // Старшие биты вперёд
    LL_SPI_SetDataWidth(SPI1, LL_SPI_DATAWIDTH_8BIT); // Пакеты по 8 бит
    LL_SPI_SetNSSMode(SPI1, LL_SPI_NSS_SOFT);
    LL_SPI_Enable(SPI1);

```

Про настройку NSS:

Так как мы используем не полностью весь стандарт SPI, а именно: STM32 всегда ведущий и нам нет необходимости использовать Slave Select, то можно не использовать пин `SPI_NSS`. `SPI_NSS` - пин, который используется в случае, когда мы хотим получать такой сигнал (в режиме ведомого или multi-master режиме) или хотим вывести такой сигнал (в режиме ведущего, правда, только для одного ведомого). В нашем случае, мы работаем в режиме, когда этот пин отключен от SPI, и всё управление передано в руки кода (выставить/очистить бит SSI в конфигурационном регистре SPI)

### Вывод значения через SPI

Функция `hc595_set`:

```c
static void hc595_set(uint8_t byte)
{
    uint16_t counter = 1000;

    /*
     * Send the data
     */
    LL_SPI_TransmitData8(SPI1, byte);

    /*
     * Toggle latch pin
     */
    LL_GPIO_ResetOutputPin(GPIOC, LL_GPIO_PIN_4);
    while (counter--); // Небольшая задежка перед передним фронтом
    LL_GPIO_SetOutputPin(GPIOC, LL_GPIO_PIN_4);
    return;
}
```

Сначала передаём байт, а зетем должны организовать передний фронт на пине защёлки, чтобы состояние на выходе сдвигового регистра обновилось. Для этого выставляем пин в нуль, затем есть небольшая задержка, и только после неё выставляем единицу на выходе. Именно в этот момент обновится выходное состояние. Как можно заметить, на защёлке остаётся логическая единица: это никак не влияет на работу, так как защёлка срабатывает только по переднему фронту

### Использование

Использование происходит в обработчике прерываний системного таймера, который настроен так, чтобы генерировать прерывания 1000 раз в секунду. Сам вывод на экран происходит раз в 1000 прерываний, то есть каждую секунду, так же, как и обновление значения `led_status`

В данной конфигурации, светодиоды горят по череди.

В качестве задания можно сделать так, чтобы первый светодиод мигал с одной частотой, второй - с в 2 раза меньшей, третий - в 4 раза меньшей и т.д. по степеням двойки. (Есть простое решение, для которого нужно изменить только одну строчку)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>kariminf.langpi.basic (LangPi 1.1.1 API)</title>
<meta name="date" content="2017-03-28">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package kariminf.langpi.basic

Interface Summary

Interface
Description

BasicInfo

Contains the informations about the preprocessed language

Normalizer

This interface is used for text Normalization

 To normalize a text is to replace or delete some characters,
 For example, in Arabic we delete diacritics (Tashkiil),
 in French we replace diacritics (énervé --> enerve)

Segmenter

Sentence segmentation and word tokenization for a given language.

Stemmer

Word steming: delete the prefixes, infixes and suffixes.

SWEliminator

Stop word eliminator.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
atime
==========

[![GoDoc](https://godoc.org/github.com/djherbis/atime?status.svg)](https://godoc.org/github.com/djherbis/atime)
[![Release](https://img.shields.io/github/release/djherbis/atime.svg)](https://github.com/djherbis/atime/releases/latest)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE.txt)
[![Build Status](https://travis-ci.org/djherbis/atime.svg?branch=master)](https://travis-ci.org/djherbis/atime)
[![Coverage Status](https://coveralls.io/repos/djherbis/atime/badge.svg?branch=master)](https://coveralls.io/r/djherbis/atime?branch=master)
[![Go Report Card](https://goreportcard.com/badge/github.com/djherbis/atime)](https://goreportcard.com/report/github.com/djherbis/atime)
[![Sourcegraph](https://sourcegraph.com/github.com/djherbis/atime/-/badge.svg)](https://sourcegraph.com/github.com/djherbis/atime?badge)

Usage
------------
File Access Times for #golang

Looking for ctime or btime? Checkout https://github.com/djherbis/times

Go has a hidden atime function for most platforms, this repo makes it accessible.

```go
package main

import (
  "log"

  "github.com/djherbis/atime"
)

func main() {
  at, err := atime.Stat("myfile")
  if err != nil {
    log.Fatal(err.Error())
  }
  log.Println(at)
}
```

Installation
------------
```sh
go get github.com/djherbis/atime
```


text:
package org.jivesoftware.smackx.delay.provider;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

import org.jivesoftware.smack.packet.XmlEnvironment;
import org.jivesoftware.smack.provider.ExtensionElementProvider;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smack.xml.XmlPullParserException;

import org.jivesoftware.smackx.delay.packet.DelayInformation;

public abstract class AbstractDelayInformationProvider extends ExtensionElementProvider<DelayInformation> {

    @Override
    public final DelayInformation parse(XmlPullParser parser,
                    int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException,
                    IOException, ParseException {
        String stampString = parser.getAttributeValue("", "stamp");
        String from = parser.getAttributeValue("", "from");
        final String reason;
        XmlPullParser.Event event = parser.next();
        switch (event) {
        case TEXT_CHARACTERS:
            reason = parser.getText();
            parser.next();
            break;
        case END_ELEMENT:
            reason = null;
            break;
        default:
            // TODO: Should be SmackParseException.
            throw new IOException("Unexpected event: " + event);
        }

        Date stamp = parseDate(stampString);
        return new DelayInformation(stamp, from, reason);
    }

    protected abstract Date parseDate(String string) throws ParseException;
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*============================================================
**
**
**
** Purpose: Base class for all value classes.
**
**
===========================================================*/

using System.Runtime;

using Internal.Runtime.CompilerServices;
using Internal.Runtime.Augments;

using Debug = System.Diagnostics.Debug;

namespace System
{
    // CONTRACT with Runtime
    // Place holder type for type hierarchy, Compiler/Runtime requires this class
    [Serializable]
    [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
    public abstract class ValueType
    {
        public override String ToString()
        {
            return this.GetType().ToString();
        }

#if PROJECTN
        public override bool Equals(object obj)
        {
            return RuntimeAugments.Callbacks.ValueTypeEqualsUsingReflection(this, obj);
        }

        public override int GetHashCode()
        {
            return RuntimeAugments.Callbacks.ValueTypeGetHashCodeUsingReflection(this);
        }
#else
        private const int UseFastHelper = -1;
        private const int GetNumFields = -1;

        // An override of this method will be injected by the compiler into all valuetypes that cannot be compared
        // using a simple memory comparison.
        // This API is a bit awkward because we want to avoid burning more than one vtable slot on this.
        // When index == GetNumFields, this method is expected to return the number of fields of this
        // valuetype. Otherwise, it returns the offset and type handle of the index-th field on this type.
        internal virtual int __GetFieldHelper(int index, out EETypePtr eeType)
        {
            // Value types that don't override this method will use the fast path that looks at bytes, not fields.
            Debug.Assert(index == GetNumFields);
            eeType = default;
            return UseFastHelper;
        }

        public override bool Equals(object obj)
        {
            if (obj == null || obj.EETypePtr != this.EETypePtr)
                return false;

            int numFields = __GetFieldHelper(GetNumFields, out _);

            ref byte thisRawData = ref this.GetRawData();
            ref byte thatRawData = ref obj.GetRawData();

            if (numFields == UseFastHelper)
            {
                // Sanity check - if there are GC references, we should not be comparing bytes
                Debug.Assert(!this.EETypePtr.HasPointers);

                // Compare the memory
                int valueTypeSize = (int)this.EETypePtr.ValueTypeSize;
                for (int i = 0; i < valueTypeSize; i++)
                {
                    if (Unsafe.Add(ref thisRawData, i) != Unsafe.Add(ref thatRawData, i))
                        return false;
                }
            }
            else
            {
                // Foreach field, box and call the Equals method.
                for (int i = 0; i < numFields; i++)
                {
                    int fieldOffset = __GetFieldHelper(i, out EETypePtr fieldType);

                    // Fetch the value of the field on both types
                    object thisField = RuntimeImports.RhBoxAny(ref Unsafe.Add(ref thisRawData, fieldOffset), fieldType);
                    object thatField = RuntimeImports.RhBoxAny(ref Unsafe.Add(ref thatRawData, fieldOffset), fieldType);

                    // Compare the fields
                    if (thisField == null)
                    {
                        if (thatField != null)
                            return false;
                    }
                    else if (!thisField.Equals(thatField))
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        public override int GetHashCode()
        {
            int hashCode = this.EETypePtr.GetHashCode();

            hashCode ^= GetHashCodeImpl();

            return hashCode;
        }

        private int GetHashCodeImpl()
        {
            int numFields = __GetFieldHelper(GetNumFields, out _);

            if (numFields == UseFastHelper)
                return FastGetValueTypeHashCodeHelper(this.EETypePtr, ref this.GetRawData());

            return RegularGetValueTypeHashCode(this.EETypePtr, ref this.GetRawData(), numFields);
        }

        private static int FastGetValueTypeHashCodeHelper(EETypePtr type, ref byte data)
        {
            // Sanity check - if there are GC references, we should not be hashing bytes
            Debug.Assert(!type.HasPointers);

            int size = (int)type.ValueTypeSize;
            int hashCode = 0;

            for (int i = 0; i < size / 4; i++)
            {
                hashCode ^= Unsafe.As<byte, int>(ref Unsafe.Add(ref data, i * 4));
            }

            return hashCode;
        }

        private int RegularGetValueTypeHashCode(EETypePtr type, ref byte data, int numFields)
        {
            int hashCode = 0;

            // We only take the hashcode for the first non-null field. That's what the CLR does.
            for (int i = 0; i < numFields; i++)
            {
                int fieldOffset = __GetFieldHelper(i, out EETypePtr fieldType);
                ref byte fieldData = ref Unsafe.Add(ref data, fieldOffset);

                Debug.Assert(!fieldType.IsPointer);

                if (fieldType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4)
                {
                    hashCode = Unsafe.Read<float>(ref fieldData).GetHashCode();
                }
                else if (fieldType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8)
                {
                    hashCode = Unsafe.Read<double>(ref fieldData).GetHashCode();
                }
                else if (fieldType.IsPrimitive)
                {
                    hashCode = FastGetValueTypeHashCodeHelper(fieldType, ref fieldData);
                }
                else if (fieldType.IsValueType)
                {
                    // We have no option but to box since this value type could have
                    // GC pointers (we could find out if we want though), or fields of type Double/Single (we can't
                    // really find out). Double/Single have weird requirements around -0.0 and +0.0.
                    // If this boxing becomes a problem, we could build a piece of infrastructure that determines the slot
                    // of __GetFieldHelper, decodes the unboxing stub pointed to by the slot to the real target
                    // (we already have that part), and calls the entrypoint that expects a byref `this`, and use the
                    // data to decide between calling fast or regular hashcode helper.
                    var fieldValue = (ValueType)RuntimeImports.RhBox(fieldType, ref fieldData);
                    hashCode = fieldValue.GetHashCodeImpl();
                }
                else
                {
                    object fieldValue = Unsafe.Read<object>(ref fieldData);
                    if (fieldValue != null)
                    {
                        hashCode = fieldValue.GetHashCode();
                    }
                    else
                    {
                        // null object reference, try next
                        continue;
                    }
                }
                break;
            }

            return hashCode;
        }
#endif
    }
}


text:
printf "\n    Starting auditd\n"
sudo service auditd start

# Adding a rule to the bottom of /etc/audit/audit.rules -- Explanation of args:
#     -a to add the rule, -d to delete
#     always -- always audit the system call, as opposed to never
#     exit -- audit the system call when it exits
#     -F -- field value
#     -S -- system call to audit
#     sendto -- system call to send message to a connection-mode socket: SOCK_STREAM, SOCK_SEQPACKET

add_audit_rule()  # one parameter passed in: auditctl arguments as a string
{
    ADD_RULE_COMMAND=$1
    if [ `getconf LONG_BIT` = "64" ]; then  # 64-bit
        ADD_RULE_COMMAND="sudo auditctl -a always,exit -F arch=b64 $ADD_RULE_COMMAND"
    else   # 32-bit
        ADD_RULE_COMMAND="sudo auditctl -a always,exit -F arch=b32 $ADD_RULE_COMMAND"
    fi
    printf "\n    Adding rule '$ADD_RULE_COMMAND'"
    eval $ADD_RULE_COMMAND
}

# rules tracking syscalls for passing data through a socket
ADD_RULE_COMMAND_1="-S sendto"
ADD_RULE_COMMAND_2="-S sendmsg"
ADD_RULE_COMMAND_3="-S recvfrom"
ADD_RULE_COMMAND_4="-S recvmsg"
ADD_RULE_COMMAND_5="-S connect"
ADD_RULE_COMMAND_6="-S write"

add_audit_rule "$ADD_RULE_COMMAND_1"
add_audit_rule "$ADD_RULE_COMMAND_2"
add_audit_rule "$ADD_RULE_COMMAND_3"
add_audit_rule "$ADD_RULE_COMMAND_4"
add_audit_rule "$ADD_RULE_COMMAND_5"
add_audit_rule "$ADD_RULE_COMMAND_6"


text:
/* Includes ------------------------------------------------------------------*/
#include <string.h>
#include "ff_gen_drv.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Block Size in Bytes */
#define BLOCK_SIZE                512

/* Private variables ---------------------------------------------------------*/
/* Disk status */
static volatile DSTATUS Stat = STA_NOINIT;

/* Private function prototypes -----------------------------------------------*/
DSTATUS SD_initialize (BYTE);
DSTATUS SD_status (BYTE);
DRESULT SD_read (BYTE, BYTE*, DWORD, UINT);
#if _USE_WRITE == 1
  DRESULT SD_write (BYTE, const BYTE*, DWORD, UINT);
#endif /* _USE_WRITE == 1 */
#if _USE_IOCTL == 1
  DRESULT SD_ioctl (BYTE, BYTE, void*);
#endif  /* _USE_IOCTL == 1 */

const Diskio_drvTypeDef  SD_Driver =
{
  SD_initialize,
  SD_status,
  SD_read,
#if  _USE_WRITE == 1
  SD_write,
#endif /* _USE_WRITE == 1 */

#if  _USE_IOCTL == 1
  SD_ioctl,
#endif /* _USE_IOCTL == 1 */
};

/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Initializes a Drive
  * @param  lun : not used
  * @retval DSTATUS: Operation status
  */
DSTATUS SD_initialize(BYTE lun)
{
  Stat = STA_NOINIT;

  /* Configure the uSD device */
  if(BSP_SD_Init() == MSD_OK)
  {
    Stat &= ~STA_NOINIT;
  }

  return Stat;
}

/**
  * @brief  Gets Disk Status
  * @param  lun : not used
  * @retval DSTATUS: Operation status
  */
DSTATUS SD_status(BYTE lun)
{
  Stat = STA_NOINIT;

  if(BSP_SD_GetStatus() == MSD_OK)
  {
    Stat &= ~STA_NOINIT;
  }

  return Stat;
}

/**
  * @brief  Reads Sector(s)
  * @param  lun : not used
  * @param  *buff: Data buffer to store read data
  * @param  sector: Sector address (LBA)
  * @param  count: Number of sectors to read (1..128)
  * @retval DRESULT: Operation result
  */
DRESULT SD_read(BYTE lun, BYTE *buff, DWORD sector, UINT count)
{
  DRESULT res = RES_OK;

  if(BSP_SD_ReadBlocks((uint32_t*)buff,
                       (uint64_t) (sector * BLOCK_SIZE),
                       BLOCK_SIZE,
                       count) != MSD_OK)
  {
    res = RES_ERROR;
  }

  return res;
}

/**
  * @brief  Writes Sector(s)
  * @param  lun : not used
  * @param  *buff: Data to be written
  * @param  sector: Sector address (LBA)
  * @param  count: Number of sectors to write (1..128)
  * @retval DRESULT: Operation result
  */
#if _USE_WRITE == 1
DRESULT SD_write(BYTE lun, const BYTE *buff, DWORD sector, UINT count)
{
  DRESULT res = RES_OK;

  if(BSP_SD_WriteBlocks((uint32_t*)buff,
                        (uint64_t)(sector * BLOCK_SIZE),
                        BLOCK_SIZE, count) != MSD_OK)
  {
    res = RES_ERROR;
  }

  return res;
}
#endif /* _USE_WRITE == 1 */

/**
  * @brief  I/O control operation
  * @param  lun : not used
  * @param  cmd: Control code
  * @param  *buff: Buffer to send/receive control data
  * @retval DRESULT: Operation result
  */
#if _USE_IOCTL == 1
DRESULT SD_ioctl(BYTE lun, BYTE cmd, void *buff)
{
  DRESULT res = RES_ERROR;
  SD_CardInfo CardInfo;

  if (Stat & STA_NOINIT) return RES_NOTRDY;

  switch (cmd)
  {
  /* Make sure that no pending write process */
  case CTRL_SYNC :
    res = RES_OK;
    break;

  /* Get number of sectors on the disk (DWORD) */
  case GET_SECTOR_COUNT :
    BSP_SD_GetCardInfo(&CardInfo);
    //*(DWORD*)buff = CardInfo.CardCapacity / BLOCK_SIZE;
    res = RES_OK;
    break;

  /* Get R/W sector size (WORD) */
  case GET_SECTOR_SIZE :
    *(WORD*)buff = BLOCK_SIZE;
    res = RES_OK;
    break;

  /* Get erase block size in unit of sector (DWORD) */
  case GET_BLOCK_SIZE :
    *(DWORD*)buff = BLOCK_SIZE;
    break;

  default:
    res = RES_PARERR;
  }

  return res;
}
#endif /* _USE_IOCTL == 1 */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
namespace content {
class NavigationHandle;
}  // namespace content

namespace safe_browsing {

class SafeBrowsingUIManager;

// This throttle monitors failed requests in an outer-most main frame (i.e.
// doesn't apply for fenced-frames or portals), and if a request failed due to
// it being blocked by Safe Browsing, it creates and displays an interstitial.
// For other kinds of loads, the interstitial is navigated at the same time the
// load is canceled in BaseUIManager::DisplayBlockingPage
//
// This NavigationThrottle doesn't actually perform a SafeBrowsing check nor
// block the navigation.  That happens in SafeBrowsing's
// BrowserURLLoaderThrottle and RendererURLLoaderThrottles and related code.
// Those cause the navigation to fail which invokes this throttle to show the
// interstitial.
class SafeBrowsingNavigationThrottle : public content::NavigationThrottle {
 public:
  // |ui_manager| may be null, in which case no throttle is created.
  static std::unique_ptr<content::NavigationThrottle> MaybeCreateThrottleFor(
      content::NavigationHandle* handle,
      SafeBrowsingUIManager* ui_manager);
  ~SafeBrowsingNavigationThrottle() override = default;
  const char* GetNameForLogging() override;

  content::NavigationThrottle::ThrottleCheckResult WillFailRequest() override;

 private:
  SafeBrowsingNavigationThrottle(content::NavigationHandle* handle,
                                 SafeBrowsingUIManager* ui_manager);

  raw_ptr<SafeBrowsingUIManager> manager_;
};

}  // namespace safe_browsing

#endif  // COMPONENTS_SAFE_BROWSING_CONTENT_BROWSER_SAFE_BROWSING_NAVIGATION_THROTTLE_H_


text:
from unittest import TestCase
import sys

from mock import patch, MagicMock, Mock

from pybuilder.core import Project, Logger
from pybuilder.plugins.python.coverage_plugin import (init_coverage_properties,
                                                      _list_all_covered_modules,
                                                      _build_module_report,
                                                      _build_coverage_report,
                                                      )

if sys.version_info[0] < 3:  # if major is less than 3
    import_patch = '__builtin__.__import__'
else:
    import_patch = 'builtins.__import__'

class CoveragePluginTests(TestCase):
    def setUp(self):
        self.project = Project("basedir")

    def test_should_leave_user_specified_properties_when_initializing_plugin(self):

        expected_properties = {
            "coverage_threshold_warn": 120,
            "coverage_branch_threshold_warn": 120,
            "coverage_branch_partial_threshold_warn": 120,
            "coverage_break_build": False,
            "coverage_reload_modules": False,
            "coverage_exceptions": ["foo"],
            "coverage_fork": True
        }

        for property_name, property_value in expected_properties.items():
            self.project.set_property(property_name, property_value)

            init_coverage_properties(self.project)

        for property_name, property_value in expected_properties.items():
            self.assertEquals(
                self.project.get_property("coverage_threshold_warn"), 120)
            self.assertEquals(
                self.project.get_property("coverage_branch_threshold_warn"), 120)
            self.assertEquals(
                self.project.get_property("coverage_branch_partial_threshold_warn"), 120)
            self.assertEquals(
                self.project.get_property("coverage_break_build"), False)
            self.assertEquals(
                self.project.get_property("coverage_reload_modules"), False)
            self.assertEquals(
                self.project.get_property("coverage_exceptions"), ["foo"])
            self.assertEquals(
                self.project.get_property("coverage_fork"), True)

    def test_list_all_covered_modules_all_loaded(self):
        module_a_val = MagicMock()
        module_b_val = MagicMock()
        with patch.dict('sys.modules', module_a=module_a_val, module_b=module_b_val):
            with patch(import_patch) as import_func:
                returned_modules = _list_all_covered_modules(MagicMock(), ['module_a', 'module_b'], [])

        self.assertEquals([module_a_val, module_b_val], returned_modules)
        import_func.assert_not_called()

    def test_list_all_covered_modules_load(self):
        module_a_val = MagicMock()
        module_b_val = MagicMock()
        with patch.dict('sys.modules', module_a=module_a_val):
            with patch(import_patch) as import_func:
                import_func.return_value = module_b_val
                returned_modules = _list_all_covered_modules(MagicMock(), ['module_a', 'module_b'], [])

        self.assertEquals([module_a_val, module_b_val], returned_modules)
        import_func.assert_called_once_with('module_b')

    def test_list_all_covered_modules_duplicate(self):
        module_a_val = MagicMock()
        module_b_val = MagicMock()
        with patch.dict('sys.modules', module_a=module_a_val, module_b=module_b_val):
            with patch(import_patch) as import_func:
                returned_modules = _list_all_covered_modules(MagicMock(), ['module_a', 'module_b', 'module_a'], [])

        self.assertEquals([module_a_val, module_b_val], returned_modules)
        import_func.assert_not_called()

    def test_list_all_covered_modules_exclusions(self):
        module_a_val = MagicMock()
        module_b_val = MagicMock()
        logger = MagicMock()
        with patch.dict('sys.modules', module_a=module_a_val, module_b=module_b_val):
            with patch(import_patch) as import_func:
                returned_modules = _list_all_covered_modules(logger, ['module_a', 'module_b', 'module_c'],
                                                             ['module_c'])

        self.assertEquals([module_a_val, module_b_val], returned_modules)
        import_func.assert_not_called()
        logger.debug.assert_called_with("Module '%s' was excluded", 'module_c')

    @patch('coverage.results.Analysis')
    @patch('coverage.coverage')
    def test_build_module_report_zero_content(self, coverage, analysis):
        coverage._analyze.return_value = analysis
        n = analysis.numbers
        n.n_statements = 0
        n.n_excluded = 0
        n.n_missing = 0
        n.n_branches = 0
        n.n_partial_branches = 0
        n.n_missing_branches = 0

        report = _build_module_report(coverage, MagicMock())
        self.assertEquals(report.code_coverage, 100)
        self.assertEquals(report.branch_coverage, 100)
        self.assertEquals(report.branch_partial_coverage, 100)

    @patch('coverage.results.Analysis')
    @patch('coverage.coverage')
    def test_build_module_report_zero_coverage(self, coverage, analysis):
        coverage._analyze.return_value = analysis
        n = analysis.numbers
        n.n_statements = 10
        n.n_excluded = 0
        n.n_missing = 10
        n.n_branches = 10
        n.n_partial_branches = 10
        n.n_missing_branches = 10

        report = _build_module_report(coverage, MagicMock())
        self.assertEquals(report.code_coverage, 0)
        self.assertEquals(report.branch_coverage, 0)
        self.assertEquals(report.branch_partial_coverage, 0)

    @patch('coverage.results.Analysis')
    @patch('coverage.coverage')
    def test_build_module_report_half_coverage(self, coverage, analysis):
        coverage._analyze.return_value = analysis
        n = analysis.numbers
        n.n_statements = 10
        n.n_excluded = 0
        n.n_missing = 5
        n.n_branches = 10
        n.n_partial_branches = 5
        n.n_missing_branches = 5

        report = _build_module_report(coverage, MagicMock())
        self.assertEquals(report.code_coverage, 50)
        self.assertEquals(report.branch_coverage, 50)
        self.assertEquals(report.branch_partial_coverage, 50)

    @patch('coverage.coverage')
    def test_build_coverage_report_no_modules(self, coverage):
        execution_name = "mock coverage"
        execution_prefix = "mock_coverage"
        project = Mock()
        modules = []
        project.get_property.side_effect = [70, 70, 70, [], False, False, False]
        self.assertTrue(_build_coverage_report(project, MagicMock(Logger), execution_name, execution_prefix, coverage,
                                               modules) is None)

    @patch('pybuilder.plugins.python.coverage_plugin.render_report')
    @patch('coverage.coverage')
    def test_build_coverage_report_two_module(self, coverage, render_report):
        execution_name = "mock coverage"
        execution_prefix = "mock_coverage"
        project = Mock()
        modules = [Mock(__name__='module_a'), Mock(__name__='module_b')]

        project.get_property.side_effect = [70, 70, 70, False, False, False]

        module_a_coverage = Mock()
        module_a_coverage.statements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        module_a_coverage.excluded = []
        module_a_coverage.missing = [1, 2, 3, 4, 5]
        n = module_a_coverage.numbers
        n.n_statements = 10
        n.n_excluded = 0
        n.n_missing = 5
        n.n_branches = 8
        n.n_partial_branches = 5
        n.n_missing_branches = 5

        module_b_coverage = Mock()
        module_b_coverage.statements = [1, 2, 3, 4, 5]
        module_b_coverage.excluded = []
        module_b_coverage.missing = [1, 2]
        n = module_b_coverage.numbers
        n.n_statements = 4
        n.n_excluded = 0
        n.n_missing = 2
        n.n_branches = 8
        n.n_partial_branches = 3
        n.n_missing_branches = 3

        coverage._analyze.side_effect = [module_a_coverage, module_b_coverage]
        self.assertTrue(
            _build_coverage_report(project, MagicMock(Logger), execution_name, execution_prefix, coverage,
                                   modules) is None)
        report = render_report.call_args[0][0]
        self.assertEquals(report['overall_coverage'], 50)
        self.assertEquals(report['overall_branch_coverage'], 50)
        self.assertEquals(report['overall_branch_partial_coverage'], 50)


text:
import TrendingHeader from './trendingHeader';

export default TrendingHeader;


text:
#region License

// https://github.com/TheBerkin/Rant
//
// Copyright (c) 2017 Nicholas Fleck
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#endregion

using System;

using Rant.Core.IO;

namespace Rant.Vocabulary.Querying
{
    internal abstract class Filter
    {
        internal const ushort FILTER_NONE = 0x0000;
        internal const ushort FILTER_CLASS = 0x0001;
        internal const ushort FILTER_REGEX = 0x0002;
        internal const ushort FILTER_SYLRANGE = 0x0003;
        internal const ushort FILTER_BIT_OTHER = 0x8000;
        public abstract int Priority { get; }

        public static Filter GetFilterInstance(ushort filterTypeCode)
        {
            switch (filterTypeCode)
            {
                case FILTER_NONE:
                    return null;
                case FILTER_CLASS:
                    return Activator.CreateInstance<ClassFilter>();
                case FILTER_SYLRANGE:
                    return Activator.CreateInstance<RangeFilter>();
                case FILTER_REGEX:
                    return Activator.CreateInstance<RegexFilter>();
                default:
                    return null;
            }
        }

        /// <summary>
        /// Determines if the specified dictionary entry passes the filter.
        /// </summary>
        /// <param name="dictionary">The dictionary being queried.</param>
        /// <param name="table">The table being queried.</param>
        /// <param name="entry">The entry to test.</param>
        /// <param name="termIndex">The index of the term requested by the query.</param>
        /// <param name="query">The originating query.</param>
        /// <returns></returns>
        public abstract bool Test(RantDictionary dictionary, RantDictionaryTable table, RantDictionaryEntry entry, int termIndex, Query query);

        public abstract void Deserialize(EasyReader input);
        public abstract void Serialize(EasyWriter output);
    }
}


text:
package org.peerbox.app.manager.file.messages;

import java.util.Set;

import org.hive2hive.core.model.UserPermission;
import org.peerbox.app.manager.file.FileInfo;

public final class RemoteShareFolderMessage extends AbstractFileMessage {

	private Set<UserPermission> permissions;
	private String invitedBy;

	public RemoteShareFolderMessage(FileInfo file, Set<UserPermission> permissions, String invitedBy) {
		super(file);
		this.permissions = permissions;
		this.invitedBy = invitedBy;
	}

	public Set<UserPermission> getUserPermissions() {
		return permissions;
	}

	public String getInvitedBy() {
		return invitedBy;
	}

}


text:
module.exports = exports = function (app) {
    var request = app.utils.request;
    var cheerio = app.utils.cheerio;
    var useragent = app.utils.useragent;
    var handler = function (opt, callback) {
        if(opt.subcmd && commands[opt.subcmd]) {
            commands[opt.subcmd](opt, callback);
        }
        else {
            callback(opt.to, "Misc. cmds: "+Object.keys(commands).join(', '));
        }
    }
    var commands = {
        "quote": quote,
        "slogan": slogan,
        "conv": convStarter,
    }
    app.cmdRegister('misc', { "f": handler,
        "h": "Contains miscellaneous subcommands that didn't fit in anywhere else."
    });
    function quote(opt, callback) {
        request({
            uri: "http://www.quotationspage.com/random.php3",
            headers: { 'User-Agent': useragent }
        }, function(error, response, body) {
            if (!error && response.statusCode == 200) {
                var $ = cheerio.load(body);

                var quote = $('dt.quote').first().text();
                var author = $('dd.author').first().find('b').first().text();
                if (quote) {
                  callback(opt.to, quote+" --"+author);
                }
            }
        });
    }
    function slogan(opt, callback) {
        var word = opt.cmd.join('+');
        request({
            uri: "http://thesurrealist.co.uk/slogan?word="+(word?word:''),
            headers: { 'User-Agent': useragent }
        }, function(error, response, body) {
            if (!error && response.statusCode == 200) {
                var $ = cheerio.load(body);

                var slogan = $('a.h1a').first().text();
                if (slogan) {
                  callback(opt.to, slogan);
                }
            }
        });
    }
    function convStarter(opt, callback) {
        request({
            uri: "http://www.conversationstarters.com/generator.php",
            headers: { 'User-Agent': useragent }
        }, function(error, response, body) {
            if (!error && response.statusCode == 200) {
                var $ = cheerio.load(body);

                var randomTopic = $('div#random').text();
                if (randomTopic) {
                  callback(opt.to, randomTopic);
                }
            }
        });
    }
    return module.id;
}


text:
package main

import (
	"net/http"
	"flag"
	"github.com/golang/glog"
	"os"
	"mime/multipart"
	"io"
	"strconv"
	"github.com/iambc/xerrors"
	)

func main() {
    flag.Parse()

    /* TODO add parametrization (maybe)
	- server path to cdn TODO
	- server upload url TODO
    */

    /*
    * issues that should be solved in the second iteration:
    * files with same name can be overridden
    * there is literally no security
    */

    portNumber, err := strconv.Atoi(os.Getenv("ABC_CDN_PORTNUM"))
    if nil != err {
	glog.Fatal("Error: ", err, portNumber)
    }

    if os.Getenv("ABC_CDN_DIR") == "" {
	 glog.Fatal("Undefinfed var ABC_CDN_DIR!")
    }

    if os.Getenv("ABC_CDN_ENDPOINT_URL") == "" {
	 glog.Fatal("Undefinfed var ABC_CDN_ENDPOINT_URL!")
    }
    ABC_CDN_ENDPOINT_URL := os.Getenv("ABC_CDN_ENDPOINT_URL")

    glog.Info(`Starting File Server on port:`, os.Getenv("ABC_CDN_PORTNUM"), `path: `, os.Getenv("ABC_CDN_DIR") )
    http.Handle("/cdn/", http.StripPrefix("/cdn", http.FileServer(http.Dir(os.Getenv("ABC_CDN_DIR")))))
    glog.Info("Starting API Server...")
    http.HandleFunc("/api/upload", func(res http.ResponseWriter, req *http.Request) {
				var err error
				defer func() {
				    if nil != err {
					glog.Error("Error string: errStr", err)
					res.Write([]byte(`{"status":"error", "message":"` + err.Error()  + `"}`))
				    }
				}()
				// max bytes in mem at a time
				const _24K = (1 << 20) * 24
				err = req.ParseMultipartForm(_24K)
				if nil != err {
				    return
				}
				for _, fheaders := range req.MultipartForm.File {
				    for _, hdr := range fheaders {
					// open uploaded
					var infile multipart.File
					infile, err = hdr.Open()
					if nil != err {
					     return
					}
					// open destination
					var outfile *os.File
					outfile, err = os.Create(os.Getenv("ABC_CDN_DIR") + hdr.Filename)
					if nil != err {
					     return
					}
					var written int64
					written, err = io.Copy(outfile, infile)
					if nil != err || 0 == written {
					     return
					}
					glog.Info("Succesfully uploaded file: ", ABC_CDN_ENDPOINT_URL + hdr.Filename)
					res.Write([]byte(`{"status":"ok", "resource_url":"` + ABC_CDN_ENDPOINT_URL + hdr.Filename + `"}`))
				    }
				}
    })
    http.ListenAndServe(`:` + os.Getenv("ABC_CDN_PORTNUM"), nil)
}