text:
import {readFileSync} from 'fs';
import {compile} from 'ejs';

export function render(ctx, src, data) {
  let filename = ctx.resourcePath;
  let delimiter = data.delimiter;
  let context = data.context;

  let tpl = compile(src, {filename, delimiter, context});

  return {
    rendered: tpl(data),
    deps: getDeps(tpl.dependencies, {delimiter, context})
  };
}

function getDeps(deps, opts, result=[]) {
  deps.forEach(name => {
    result.push(name);
    getDeps(getOwnDeps(name, opts), opts, result);
  });

  return result;
}

function getOwnDeps(filename, {delimiter, context}) {
  let src = readFileSync(filename, 'utf8');
  let tpl = compile(src, {filename, delimiter, context});
  return tpl.dependencies;
}


text:
<BroadcastMonitor>
  <updated>2015-08-02T15:28:41</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-02T15:28:41</startTime>
    <itemId>1000080495:0</itemId>
    <titleId>216106781</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** Sweep NEW 2 AO met ALFRED</titleName>
    <artistName>AUDIOLINK</artistName>
    <albumName></albumName>
    <CategoryCode>871</CategoryCode>
    <CategoryName>VORMGEVING</CategoryName>
    <itemDuration>5</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-02T15:32:57</startTime>
    <itemId>1000080495:1240758</itemId>
    <titleId>216038245</titleId>
    <itemCode>FJ1170</itemCode>
    <itemReference></itemReference>
    <titleName>I Take What I Want</titleName>
    <artistName>Sam & Dave</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>150</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>

redpajama_set_name: RedPajamaGithub


text:
Node *SearchEngine::findNode(const QList<Node *> nodes, QPoint position)
{
    foreach (Node *n, nodes)
    {
        bool widthMatch = abs(n->getPosition().x() - position.x()) <=
                              n->getSize().width() / 2;
        bool heightMatch = abs(n->getPosition().y() - position.y()) <=
                               n->getSize().height() / 2;
        if (widthMatch && heightMatch)
        {
            return n;
        }
    }
    return NULL;
}

Link *SearchEngine::findLink(const QList<Link *> links, QPoint position)
{
    foreach (Link *ln, links)
    {
        bool widthMatch = abs(ln->getPosition().x() - position.x()) <=
                              ln->getSize().width() / 2;
        bool heightMatch = abs(ln->getPosition().y() - position.y()) <=
                               ln->getSize().height() / 2;
        if (widthMatch && heightMatch)
        {
            return ln;
        }
    }
    return NULL;
}

Switch *SearchEngine::findSwitch(const QList<Switch *> switches, QString name)
{
    foreach (Switch *sw, switches)
    {
        if (QString::compare(sw->getName(), name) == 0)
        {
            return sw;
        }
    }
    return NULL;
}

Switch *SearchEngine::findSwitch(const QList<Switch *> switches, int groupId)
{
    foreach (Switch *sw, switches)
    {
        if (sw->getGroupId() == groupId)
        {
            return sw;
        }
    }
    return NULL;
}

QList<Node *> SearchEngine::findNodes(const QList<Node *> nodes, QPoint topLeft, QPoint bottomRight)
{
    QList<Node *> findedNodes;
    foreach (Node *n, nodes)
    {
        bool widthMatch = n->getPosition().x() > topLeft.x() &&
                          n->getPosition().x() < bottomRight.x();
        bool heightMatch = n->getPosition().y() > topLeft.y() &&
                           n->getPosition().y() < bottomRight.y();
        if (widthMatch && heightMatch)
        {
            findedNodes.append(n);
        }
    }
    return findedNodes;
}

Node *SearchEngine::findNode(const QList<Node *> nodes, QString name)
{
    foreach (Node *n, nodes)
    {
        if (QString::compare(n->getName(), name) == 0)
        {
            return n;
        }
    }
    return NULL;
}

Node *SearchEngine::findNode(const QList<Switch *> switches, int groupId)
{
    foreach (Switch *sw, switches)
    {
        if (sw->getGroupId() == groupId)
        {
            return sw;
        }
    }
    return NULL;
}


text:
#import "RPSAppDelegate.h"

#import <FacebookSDK/FacebookSDK.h>

#import "RPSCommonObjects.h"
#import "RPSDeeplyLinkedViewController.h"
#import "RPSFriendsViewController.h"
#import "RPSGameViewController.h"

@implementation RPSAppDelegate

#pragma mark - Class methods

+ (RPSCall)callFromAppLinkData:(FBAppLinkData *)appLinkData {
    NSString *fbObjectID = [appLinkData originalQueryParameters][@"fb_object_id"];

    if (fbObjectID == nil) {
        return RPSCallNone;
    }

    RPSCall call = RPSCallNone;
    NSInteger callOptionCount = sizeof(builtInOpenGraphObjects) / sizeof(builtInOpenGraphObjects[0]);
    for (RPSCall callIndex = 0; callIndex < callOptionCount; callIndex++) {
        if ([builtInOpenGraphObjects[callIndex] isEqualToString:fbObjectID]) {
            call = callIndex;
            break;
        }
    }

    if (call == RPSCallNone) {
        NSLog(@"Unexpected: deeplink was present, but did not contain a valid rock, paper or scissor fb_object_id");
    }
    return call;
}

#pragma mark - UIApplicationDelegate

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    return [FBAppCall handleOpenURL:url
                  sourceApplication:sourceApplication
                    fallbackHandler:^(FBAppCall *call) {
                        // Check for a deep link to parse out a call to show
                        RPSCall deepCall = [RPSAppDelegate callFromAppLinkData:[call appLinkData]];
                        if (deepCall != RPSCallNone) {
                            RPSDeeplyLinkedViewController *vc = [[RPSDeeplyLinkedViewController alloc] initWithCall:deepCall];
                            [self.navigationController presentViewController:vc animated:YES completion:nil];
                        }
                    }];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [FBAppEvents activateApp];
    [FBAppCall handleDidBecomeActive];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // all good things must come to an end
    // this is a good idea because things may be hanging off the session, that need
    // releasing (completion block, etc.) and other components in the app may be awaiting
    // close notification in order to do cleanup
    [FBSession.activeSession close];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.

#ifdef DEBUG
    [FBSettings enableBetaFeature:FBBetaFeaturesOpenGraphShareDialog | FBBetaFeaturesShareDialog];
#endif

    UIViewController *viewControllerGame;
    FBUserSettingsViewController *viewControllerSettings;
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        viewControllerGame = [[RPSGameViewController alloc] initWithNibName:@"RPSGameViewController_iPhone" bundle:nil];
    } else {
        viewControllerGame = [[RPSGameViewController alloc] initWithNibName:@"RPSGameViewController_iPad" bundle:nil];
    }
    viewControllerSettings = [[FBUserSettingsViewController alloc] init];
    viewControllerSettings.title = @"Facebook Settings";
    viewControllerSettings.tabBarItem.image = [UIImage imageNamed:@"second"];

    self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewControllerGame];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];

    [FBSession openActiveSessionWithAllowLoginUI:NO];

    return YES;
}

@end


text:
package org.spring.ioc;

import junit.framework.TestCase;
import org.junit.Test;

/**
 * 测试IOC容器
 * @author BYSocket
 * @since 2016-01-12 10:47:00
 */
public class IocT extends TestCase {

    @Test
    public void testIoc() {
        // 从Bean容器获取Class
        Car car = (Car) BeanContainer.getBeanMap().get(Car.class);
        System.out.println(car.getName());
        assertEquals("car",car.getName());
    }
}


text:
import datetime
import sys
from datetime import date

from django.db import models
from django.db.models import Q
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.generic import GenericRelation
from django.core.urlresolvers import reverse_lazy
from django.core.validators import MinValueValidator
from django_extensions.db.models import TimeStampedModel
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import pgettext_lazy
from django.utils import translation

from auditlog.registry import auditlog
from auditlog.models import AuditlogHistoryField
from diplomat.fields import LanguageChoiceField

from core.models import TranslatedModel
from clients.models import Client

# Contact informations

class StatusReasonCode(TranslatedModel):
    OTHER = "other"

    slug = models.SlugField()
    desc_en = models.CharField(max_length=30)
    desc_fr = models.CharField(max_length=30)

    def __unicode__(self):
        return self.get_translated_field('desc')

class ServiceDayManager(models.Manager):

    def get_meal_service_days(self):
        return super(ServiceDayManager, self).get_queryset().filter(service_type=ServiceDay.MEAL).filter(active=True)

    def get_days_for_meal_defaults(self):
        """
            Returns active service days + 'everyday' service day
            in order to build forms to get meal defaults
        """
        return super(ServiceDayManager, self).filter(
            Q(service_type=ServiceDay.MEAL),
            Q(active=True) | Q(slug=ServiceDay.SLUG_EVERYDAY)
            )

    def get_meal_service_everyday(self):
        return super(ServiceDayManager, self).filter(service_type=ServiceDay.MEAL).get(slug=ServiceDay.SLUG_EVERYDAY)

    def get_meal_service_day(self, sort_order):
        return super(ServiceDayManager, self).filter(service_type=ServiceDay.MEAL).get(sort_order=sort_order)

class ServiceDay(TranslatedModel):
    SLUG_EVERYDAY="everyday_meal" # DO NOT CHANGE
    MEAL='M'
    SERVICE_TYPE = (
                  (MEAL, _('Meal')),
                  )
    slug = models.SlugField(unique=True, default='')
    name_en = models.CharField(max_length=30)
    name_fr = models.CharField(max_length=30)
    service_type = models.CharField(max_length=1, choices=SERVICE_TYPE, default=MEAL)
    active = models.BooleanField(default=False)
    sort_order = models.PositiveIntegerField()

    objects = ServiceDayManager()

    class Meta:
        unique_together = ("service_type", "sort_order")
        ordering = ['sort_order']

    def __unicode__(self):
        return self.get_name()

class OrderManager(models.Manager):
    def get_latest_order_for_client(self, client):
        qs = OrderStatusChange.objects.filter(order__client=client).order_by("-date")

        latest_entry = list(qs[:1])
        if latest_entry:
            return latest_entry[0].order
        else:
            qs = Order.objects.filter(client=client).order_by("-created")
            return list(qs[:1])[0]

class Order(TimeStampedModel):
    objects = OrderManager()
    history = AuditlogHistoryField()

    client = models.ForeignKey(Client)

    EPISODIC = 'E'
    ONGOING = 'O'
    ORDER_TYPES = (
        (EPISODIC, _('Episodic')),
        (ONGOING, _('Ongoing')),
        )
    type = models.CharField(_("Service type"),max_length=1, choices=ORDER_TYPES, default=ONGOING)

    #start_date = models.DateField()
    #end_date = models.DateField(null=True)

    STATUS_ACTIVE = _('Active')
    STATUS_STOPPED = _('Stopped')
    STATUS_INACTIVE = _('Inactive')

    days = models.ManyToManyField(ServiceDay, verbose_name=_("Service days"), limit_choices_to={'active': True, 'service_type':ServiceDay.MEAL})

    DEFAULTS_TYPE_EVERYDAY= { 'code' :'A', 'display':_('Same for everyday') }
    DEFAULTS_TYPE_DAY= { 'code' :'D', 'display':_('Day-specific') }
    DEFAULTS_TYPE_CHOICES = (
                             (DEFAULTS_TYPE_EVERYDAY['code'], DEFAULTS_TYPE_EVERYDAY['display']),
                             (DEFAULTS_TYPE_DAY['code'], DEFAULTS_TYPE_DAY['display'])
                             )

    def __unicode__(self):
        return _(u'%(status)s') % {'status':self.get_current_status_code() }

    def is_pending(self):
        return self.get_current_status_code() == OrderStatusChange.PENDING

    def is_active(self):
        return self.get_current_status_code() == OrderStatusChange.ACTIVE

    def is_stopped(self):
        return self.get_current_status_code() == OrderStatusChange.STOPPED

    def is_deactivated(self):
        return self.get_current_status_code() == OrderStatusChange.DEACTIVATED

    def get_current_status_code(self):
        return self.get_current_status()[0]

    def get_current_status_display(self):
        return self.get_current_status()[1]

    def get_current_status(self):
        qs = self.status.filter(date__lte=date.today()).order_by('-date')

        active_entry = list(qs[:1])
        if active_entry:
            return OrderStatusChange.ORDER_STATUS[active_entry[0].type]
        else:
            return OrderStatusChange.ORDER_STATUS[OrderStatusChange.NO_ENTRY]

    def _get_meal_defaults_type(self):
        # default is meal_defaults_type
        if not hasattr(self, 'meal_defaults_type'):
            mealdefaults = self.get_meal_defaults()
            if mealdefaults.count() == 1:
                mealdefault = mealdefaults[0]
                if mealdefault.day.slug == ServiceDay.SLUG_EVERYDAY:
                    self.meal_defaults_type = self.DEFAULTS_TYPE_EVERYDAY
                else:
                    self.meal_defaults_type = self.DEFAULTS_TYPE_DAY
            else:
                self.meal_defaults_type = self.DEFAULTS_TYPE_DAY

        return self.meal_defaults_type

    def get_meal_defaults_type_display(self):
        return self._get_meal_defaults_type()['display']

    def get_meal_defaults_type_code(self):
        return self._get_meal_defaults_type()['code']

    def has_same_defaults_everyday(self):
        return (self.get_meal_defaults_type_code () == self.DEFAULTS_TYPE_EVERYDAY)

    def get_meal_defaults(self):
        return self.mealdefault_set.order_by('day__sort_order').all()

    def get_meal_default(self, day):
        qs = self.mealdefault_set.filter(day=day)
        meal_default = list(qs[:1])
        if meal_default:
            return meal_default[0]
        else:
            return None

#             meal_defaults_type = order.get_meal_defaults_type_code()
#             if order.has_same_defaults_everyday():
#                 service_day = ServiceDay.objects.get_meal_service_everyday()
#             else:
#                 # prefix = meals_[day.sort_order] or mealsides_[day.sort_order]
#
#             meal_default = meal_defaults.get(day=service_day)

#
#     def has_stop(self):
#         stops = self.orderstop_set.filter(
#                     end_date__gte=datetime.datetime.now())
#         if stops.count() != 0:
#             return True
#         else:
#             return False
#
#     def get_stop(self):
#         return self.orderstop_set.filter(
#                     end_date__gte=datetime.datetime.now()).order_by('start_date').first()
#
#     def get_delivery_default(self):
#         return self.deliverydefault_set.get(day=DeliveryDefault.ALL)

class OrderStatusChange(TimeStampedModel):
    order = models.ForeignKey(Order, related_name='status')

    ACTIVATE = 'A' # initial start
    STOP = 'P'  # temporary stop
    RESUME = 'R' # resume after temporary stop
    END = 'E' # final stop (order cannot be reactivated past this status change
    CHANGE_TYPES = (
                    (ACTIVATE,_('Activate')),
                    (STOP, _('Stop')),
                    (RESUME, _('Resume')),
                    (END, _('Stop'))
                    )
    # Order status corresponing to the current OrderStatusChange active (ie. date < today)
    NO_ENTRY='NO_ENTRY'
    PENDING='P'
    ACTIVE='A'
    STOPPED='S'
    DEACTIVATED='D'
    ORDER_STATUS = {
                    NO_ENTRY: (PENDING, _('Pending')),
                    ACTIVATE: (ACTIVE, _('Active')),
                    STOP: (STOPPED, _('Stopped')),
                    RESUME: (ACTIVE, _('Active')),
                    END: (DEACTIVATED, _('Deactivated'))
                    }
    type = models.CharField(max_length=1, choices=CHANGE_TYPES, default=ACTIVATE)
    date = models.DateField()
    reason_code = models.ForeignKey(StatusReasonCode)

    class Meta:
        unique_together = ('order', 'type', 'date')
        ordering = ['date']

class MealSide(models.Model):
    name_en = models.CharField(max_length=30)
    name_fr = models.CharField(max_length=30)

    def __unicode__(self):
        lg = translation.get_language()
        if lg == "en":
            return self.name_en
        else:
            return self.name_fr

class MealDefault(TimeStampedModel):
    order = models.ForeignKey(Order, default='')
    day = models.ForeignKey(ServiceDay, limit_choices_to={'active': True, 'service_type':ServiceDay.MEAL})

    sides = models.ManyToManyField(MealSide, through='MealDefaultSide')

    def __unicode__(self):
        return self.day.name_en

class MealDefaultMeal(TimeStampedModel):
    meal = models.ForeignKey(MealDefault, related_name='meals')

    HALF = 'H'
    REG = 'R'
    MEAL_SIZES = (
        (HALF, _('Half')),
        (REG, _('Regular')),
    )
    size = models.CharField(max_length=1, choices=MEAL_SIZES, default=REG)

    quantity = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1)])

class MealDefaultSide(TimeStampedModel):
    meal = models.ForeignKey(MealDefault)
    side = models.ForeignKey(MealSide)
    quantity = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1)])


text:
#ifndef QWT_PLOT_MULTI_BAR_CHART_H
#define QWT_PLOT_MULTI_BAR_CHART_H

#include "qwt_global.h"
#include "qwt_plot_abstract_barchart.h"
#include "qwt_series_data.h"

class QwtColumnRect;
class QwtColumnSymbol;

/*!
  \brief QwtPlotMultiBarChart displays a series of a samples that consist
         each of a set of values.

  Each value is displayed as a bar, the bars of each set can be organized
  side by side or accumulated.

  Each bar of a set is rendered by a QwtColumnSymbol, that is set by setSymbol().
  The bars of different sets use the same symbols. Exceptions are possible
  by overloading specialSymbol() or overloading drawBar().

  Depending on its orientation() the bars are displayed horizontally
  or vertically. The bars cover the interval between the baseline()
  and the value.

  In opposite to most other plot items, QwtPlotMultiBarChart returns more
  than one entry for the legend - one for each symbol.

  \sa QwtPlotBarChart, QwtPlotHistogram
      QwtPlotSeriesItem::orientation(), QwtPlotAbstractBarChart::baseline()
 */
class QWT_EXPORT QwtPlotMultiBarChart:
    public QwtPlotAbstractBarChart, public QwtSeriesStore<QwtSetSample>
{
public:
    /*!
        \brief Chart styles.

        The default setting is QwtPlotMultiBarChart::Grouped.
        \sa setStyle(), style()
    */
    enum ChartStyle
    {
        //! The bars of a set are displayed side by side
        Grouped,

        /*!
            The bars are displayed on top of each other accumulating
            to a single bar. All values of a set need to have the same
            sign.
         */
        Stacked
    };

    explicit QwtPlotMultiBarChart( const QString &title = QString::null );
    explicit QwtPlotMultiBarChart( const QwtText &title );

    virtual ~QwtPlotMultiBarChart();

    virtual int rtti() const;

    void setBarTitles( const QList<QwtText> & );
    QList<QwtText> barTitles() const;

    void setSamples( const QVector<QwtSetSample> & );
    void setSamples( const QVector< QVector<double> > & );
    void setSamples( QwtSeriesData<QwtSetSample> * );

    void setStyle( ChartStyle style );
    ChartStyle style() const;

    void setSymbol( int barIndex, QwtColumnSymbol *symbol );
    const QwtColumnSymbol *symbol( int barIndex ) const;

    void resetSymbolMap();

    virtual void drawSeries( QPainter *painter,
        const QwtScaleMap &xMap, const QwtScaleMap &yMap,
        const QRectF &canvasRect, int from, int to ) const;

    virtual QRectF boundingRect() const;

    virtual QList<QwtLegendData> legendData() const;

    virtual QwtGraphic legendIcon( int index, const QSizeF & ) const;

protected:
    QwtColumnSymbol *symbol( int barIndex );

    virtual QwtColumnSymbol *specialSymbol(
        int sampleIndex, int valueIndex ) const;

    virtual void drawSample( QPainter *painter,
        const QwtScaleMap &xMap, const QwtScaleMap &yMap,
        const QRectF &canvasRect, const QwtInterval &boundingInterval,
        int index, const QwtSetSample& sample ) const;

    virtual void drawBar( QPainter *, int sampleIndex,
        int barIndex, const QwtColumnRect & ) const;

    void drawStackedBars( QPainter *painter,
        const QwtScaleMap &xMap, const QwtScaleMap &yMap,
        const QRectF &canvasRect, int index,
        double sampleWidth, const QwtSetSample& sample ) const;

    void drawGroupedBars( QPainter *painter,
        const QwtScaleMap &xMap, const QwtScaleMap &yMap,
        const QRectF &canvasRect, int index,
        double sampleWidth, const QwtSetSample& sample ) const;

private:
    void init();

    class PrivateData;
    PrivateData *d_data;
};

#endif


text:
/**
 * 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.
 */
package org.apache.hadoop.fs.s3a.fileContext;

import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FCStatisticsBaseTest;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.s3a.S3ATestUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;

/**
 * S3a implementation of FCStatisticsBaseTest.
 */
public class ITestS3AFileContextStatistics extends FCStatisticsBaseTest {

  @Before
  public void setUp() throws Exception {
    Configuration conf = new Configuration();
    fc = S3ATestUtils.createTestFileContext(conf);
    fc.mkdir(fileContextTestHelper.getTestRootPath(fc, "test"),
        FileContext.DEFAULT_PERM, true);
    FileContext.clearStatistics();
  }

  @After
  public void tearDown() throws Exception {
    if (fc != null) {
      fc.delete(fileContextTestHelper.getTestRootPath(fc, "test"), true);
    }
  }

  @Override
  protected void verifyReadBytes(FileSystem.Statistics stats) {
    // one blockSize for read, one for pread
    Assert.assertEquals(2 * blockSize, stats.getBytesRead());
  }

  @Override
  protected void verifyWrittenBytes(FileSystem.Statistics stats) {
    //No extra bytes are written
    Assert.assertEquals(blockSize, stats.getBytesWritten());
  }

  @Override
  protected URI getFsUri() {
    return fc.getHomeDirectory().toUri();
  }

}


text:
import torch

from allennlp.common import Params, Registrable
from allennlp.data import Vocabulary

class TokenEmbedder(torch.nn.Module, Registrable):
    """
    A ``TokenEmbedder`` is a ``Module`` that takes as input a tensor with integer ids that have
    been output from a :class:`~allennlp.data.TokenIndexer` and outputs a vector per token in the
    input.  The input typically has shape ``(batch_size, num_tokens)`` or ``(batch_size,
    num_tokens, num_characters)``, and the output is of shape ``(batch_size, num_tokens,
    output_dim)``.  The simplest ``TokenEmbedder`` is just an embedding layer, but for
    character-level input, it could also be some kind of character encoder.

    We add a single method to the basic ``Module`` API: :func:`get_output_dim()`.  This lets us
    more easily compute output dimensions for the :class:`~allennlp.modules.TextFieldEmbedder`,
    which we might need when defining model parameters such as LSTMs or linear layers, which need
    to know their input dimension before the layers are called.
    """
    default_implementation = "embedding"

    def get_output_dim(self) -> int:
        """
        Returns the final output dimension that this ``TokenEmbedder`` uses to represent each
        token.  This is `not` the shape of the returned tensor, but the last element of that shape.
        """
        raise NotImplementedError

    @classmethod
    def from_params(cls, vocab: Vocabulary, params: Params) -> 'TokenEmbedder':
        choice = params.pop_choice('type', cls.list_available())
        return cls.by_name(choice).from_params(vocab, params)


text:
package com.brainy.command;

import com.brainy.Session;
import com.brainy.MessageObject;
import com.brainy.NodeEvent;
import com.brainy.net.Hook;

/**
 * Created by eossth on 7/31/2017 AD.
 */
public class RegisterAdminCommandNode extends CommandNode {

    public RegisterAdminCommandNode(Session session, String [] hooks) {
        super(session, hooks, Hook.Match.Head);
    }

    @Override
    public String execute(MessageObject messageObject) {

        if (session.listener !=null) {

            String displayName = clean(messageObject.toString());
            session.listener.callback(
                    new NodeEvent(this,
                            MessageObject.build(messageObject, displayName),
                            NodeEvent.Event.RegisterAdmin));
        }

        return "";
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"
    android:layout_height="fill_parent"

    android:orientation="vertical">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3.0"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dip"

            android:text="prompt_gesture_name"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/gesture_name"
            android:layout_width="0dip"
            android:layout_weight="1.0"
            android:layout_height="wrap_content"

            android:maxLength="40"
            android:singleLine="true" />

    </LinearLayout>

    <android.gesture.GestureOverlayView
        android:id="@+id/gestures_overlay"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="3.0"

        android:gestureStrokeType="multiple" />

    <LinearLayout
        style="@android:style/ButtonBar"
        android:layout_weight="3.0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:orientation="horizontal">

        <Button
            android:id="@+id/done"

            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            android:enabled="false"

            android:onClick="addGesture"
            android:text="button_done" />

        <Button
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            android:onClick="cancelGesture"
            android:text="button_discard" />

    </LinearLayout>

</LinearLayout>


text:
jsio('from lib.javascript import Class');
jsio('import lib.Publisher');
jsio('import lib.css');

exports = Class(lib.Publisher, function(supr) {

	this.init = function() {
		supr(this, 'init');
	}

	this.getElement = function() {
		if (!this._element) {
			this._element = document.createElement('div');
			this.createContent();
		}
		return this._element;
	}

	this.createContent = function() {} // abstract method

	this.loadStyles = function(componentName) {
		lib.css.addClassName(this._element, componentName);
		lib.css.loadStyle(componentName.split('-').join('/'));
	}

	this.addClassName = function(className) {
		lib.css.addClassName(this._element, className);
	}

	this.removeClassName = function(className) {
		lib.css.removeClassName(this._element, className);
	}
})


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"text/template"
)

const (
	enforcerTypesTplFileName = "_tpl_enforce_types.vhdl"
	enforcerTplFileName      = "_tpl_enforcer.vhdl"
	enforcerTopTplFileName   = "_tpl_enforce_top.vhdl"
)

var (
	inFileName    = flag.String("i", "", "Specify the input .json file containing policies")
	outFolderName = flag.String("o", "out", "Specify the output directory to store the generated VHDL files")
)

var (
	enforcerTpls = template.Must(template.New("").Funcs(VFuncMap).ParseFiles(enforcerTplFileName, enforcerTypesTplFileName, enforcerTopTplFileName))
)

func main() {
	jb, _ := json.MarshalIndent(WaterBoilerEnforcer, "", "\t")
	strings, err := WaterBoilerEnforcer.Stringify(enforcerTpls)
	if err != nil {
		fmt.Println("An error occured:", err.Error())
	}
	strings = append(strings, EnforcerString{
		Name:     WaterBoilerEnforcer.Name + ".json",
		Contents: jb,
	})

	for _, s := range strings {
		if err := ioutil.WriteFile(*outFolderName+string(os.PathSeparator)+s.Name, s.Contents, 0644); err != nil {
			fmt.Println("Error writing file:", err.Error())
		}
		// fmt.Printf("\n---File %s---\n", s.Name)
		// fmt.Printf("%s\n", s.Contents)
	}

}


text:
<?php

interface IController
{

    /**
     * Generates a random string using OpenSSL of pseudobytes based on the supplied length.
     * This requires openssl.
     *
     * @param integer $length
     * @return string
     */
    function generateRandomStringWithPseudoBytes ();

    /**
     * Generates a random string based on the supplied length
     *
     * @param integer $length
     * @return string
     */
    function generateRandomString ($length = 8);

    /**
     * Applies a sha1 encryption on the supplied string
     * and returns it back to the user
     *
     * @param string $string
     * @return string
     */
    function encrypt ($string);

    /**
     * A static way to call the active controller instance
     * to set a view to render for the user
     *
     * @param string $paramView
     */
    static function initView ($paramView);

    /**
     * Returns a POST request ment for Arrays.
     */
    function postArray ($paramPostName);

    /**
     * Returns a POST request.
     */
    function post ($paramPostName);

    /**
     * Returns a GET request.
     */
    function get ($paramGetName);

    /**
     * Returns a GET request ment for Arrays.
     */
    function getArray ($paramGetName);

    /**
     * Redirects the user to the specified URL.
     */
    function redirect ($url, $status = 0);

    /**
     * Instructs the Loader to load the designated 404 page.
     */
    function fourOhFour ();

}


text:
HID Launcher is a remote app launcher for Android.
HID Launcher detects HID signals (Numpad 1-5) and launch the apps or functions defined by the user.
System apps have extended support and functions.

### Features
- Material design
- Volume control
- Media control
- Camera control
- Quick alarm
- Automatic calls (Phone
- Automatic messages (Phone)

### Usage
Launch the app in your phone and configure the functions asociated with the HID signals.
Select the input method "Droidmotion" in the input method manager.
Done!

### Terms and Conditions

The MIT License (MIT)

Copyright (c) 2015 Ricardo Domínguez Álvarez

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.


text:
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP                 #-}
{-# LANGUAGE TemplateHaskell     #-}

import           Control.Applicative
import           Control.Concurrent
import           Control.Lens
import qualified Control.Exception as Exception
import           Control.Monad.IO.Class
import qualified System.IO as IO
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import           Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import           Data.Time
import           Database.PostgreSQL.Simple
import           Servant.Server.Internal.SnapShims
import           Snap
import           Snap.Http.Server
import           Snap.Snaplet.Auth
import           Snap.Snaplet.Auth.Backends.PostgresqlSimple
import           Snap.Snaplet.Config
import           Snap.Snaplet.Session
import           Snap.Snaplet.Session.Backends.CookieSession
import           Snap.Snaplet.PostgresqlSimple
import           Snap.Snaplet.Heist
import           Snap.Util.FileServe
import           Servant.API
import           Servant (serveSnap, Server)
import           Text.Read
#ifdef DEVELOPMENT
--import Snap.Loader.Dynamic (loadSnapTH)
#else
import Snap.Loader.Static (loadSnapTH)
#endif
import Snap.Loader.Static (loadSnapTH)

import           Application
import           Db
import           Handler
import           Types.Poll
import           Types.Channel

--------------------------------------------------------------------------------

routes :: [(BS.ByteString, Handler Pollock Pollock ())]
routes = [ ("/"                    , handlerIndex)
         , ("/app"                 , with auth handlerDashboard)
         , ("/signup"              , with auth handlerSignup)
         , ("/login"               , with auth handlerLogin)
         , ("/logout"              , with auth handlerLogout)
         , ("/polls/new"           , with auth handlerPollNew)
         , ("/poll/view/:pollid"   , with auth handlerPollView)
         , ("/poll/delete/:pollid" , with auth handlerPollDelete)
         , ("static"               , serveDirectory "static")
         , (".well-known"          , serveDirectory ".well-known")
         ]

-- | Build a new Pollock snaplet.
appInit :: SnapletInit Pollock Pollock
appInit =
  makeSnaplet "Pollock" "Best polling system!" Nothing $ do
    h <- nestSnaplet "heist" heist $
           heistInit "templates"

    d <- nestSnaplet "db" db $
           pgsInit

    s <- nestSnaplet "sess" sess $
           initCookieSessionManager "site_key.txt" "sess" Nothing (Just 3600)

    a <- nestSnaplet "auth" auth $
           initPostgresAuth sess d

    addRoutes routes
    addAuthSplices h auth -- add <ifLoggedIn> <ifLoggedOut> tags support

    return $ Pollock { _heist = h, _sess = s, _auth = a , _db=d}

getConf :: IO (Config Snap AppConfig)
getConf = commandLineAppConfig defaultConfig

getActions :: Config Snap AppConfig -> IO (Snap (), IO ())
getActions conf = do
    (msgs, site, cleanup) <- runSnaplet (appEnvironment =<< getOther conf) appInit
    IO.hPutStrLn IO.stderr (T.unpack msgs)
    return (site, cleanup)

main :: IO ()
main = do
  (conf, site, cleanup) <- $(loadSnapTH [| getConf |] 'getActions ["snaplets/heist/templates"])
  _ <- Exception.try (httpServe conf site) :: IO (Either Exception.SomeException ())
  cleanup


text:
require 'base64'

# This module defines the base backend class for all implementations
module Compass::Canvas::Backend
  # Base abstract backend class.
  #
  # Each implementation must respond to four methods:
  # - {Compass::Canvas::Backend::Base::load_dependencies} - initializes the backend by loading third-party dependencies
  # - {Compass::Canvas::Backend::Base::read_canvas} - reads a canvas from a file
  # - {Compass::Canvas::Backend::Base::begin_canvas} - initialization code before the canvas is drawn
  # - {Compass::Canvas::Backend::Base::execute_one} - executes a single action on the canvas
  # - {Compass::Canvas::Backend::Base::to_blob} - clean up code, must return a
  #   +String+ representation of the canvas in a PNG format
  class Base < Sass::Script::Literal
    # @return [Fixnum] The width of the canvas, in pixels.
    attr_accessor :width
    # @return [Fixnum] The height of the canvas, in pixels.
    attr_accessor :height
    # @return [String] The external file where the backend will be loaded/saved in a PNG format.
    attr_accessor :file

    # Initializes a new instance of a backend class.
    #
    # @overload initialize(width, height, *actions)
    #   @param [Fixnum] width The width of the canvas, in pixels.
    #   @param [Fixnum] height The height of the canvas, in pixels.
    #   @param [Array<Object>] actions The actions to execute.
    # @overload initialize(file, width, height, *actions)
    #   @param [String] file The file where the backend will be saved in a PNG format.
    #   @param [Fixnum] width The width of the canvas, in pixels.
    #   @param [Fixnum] height The height of the canvas, in pixels.
    #   @param [Array<Object>] actions The actions to execute.
    # @overload initialize(file)
    #   @param [String] file An external file to read.
    def initialize(*args)
      load_dependencies
      if args[0].is_a?(String)
        file = args.shift
        file = Compass::Canvas.absolute_path_to(file) unless args[0].is_a?(Fixnum)
        @file = file
      end
      if args[0].is_a?(Fixnum)
        @width  = args.shift
        @height = args.shift
      end
      @actions  = args
      @executed = false
    end

    # Abstract method.
    #
    # Initializes the backend by loading third-party dependencies.
    #
    # @raise [Compass::Canvas::Exception] Backend implementation must override this method.
    def load_dependencies
      raise Compass::Canvas::Exception.new("(#{self.class}) Class must implement '#{this_method}'.")
    end

    # Abstract method.
    #
    # Reads a canvas from a file
    #
    # @raise [Compass::Canvas::Exception] Backend implementation must override this method.
    def read_canvas
      raise Compass::Canvas::Exception.new("(#{self.class}) Class must implement '#{this_method}'.")
    end

    # Abstract method.
    #
    # Initialization code before the canvas is drawn.
    #
    # @raise [Compass::Canvas::Exception] Backend implementation must override this method.
    def begin_canvas
      raise Compass::Canvas::Exception.new("(#{self.class}) Class must implement '#{this_method}'.")
    end

    # Abstract method.
    #
    # Executes a single action on the canvas.
    #
    # @raise [Compass::Canvas::Exception] Backend implementation must override this method.
    def execute_one(action, *args)
      raise Compass::Canvas::Exception.new("(#{self.class}) Class must implement '#{this_method}'.")
    end

    # Abstract method.
    #
    # Clean up code, must return a +String+ representation of the canvas in a PNG format.
    #
    # @raise [Compass::Canvas::Exception] Backend implementation must override this method.
    def to_blob
      raise Compass::Canvas::Exception.new("(#{self.class}) Class must implement '#{this_method}'.")
    end

    # Reads a property of the backend.
    #
    # This can be used to provide custom information about a backend, such as
    # width, height, the current point's position, etc.
    #
    # @param [String] name The property name.
    # @return [Object] The property value, or nil if it doesn't exist.
    def property(name)
      case name
      when :width;  return @width
      when :height; return @height
      else return nil
      end
    end

    # Creates an empty canvas and executes all stored actions.
    def execute
      return self if @executed
      if @width && @height
        begin_canvas
        execute_actions
      else
        read_canvas
      end
      @executed = true
      self
    end

    # Returns the canvas as a Base64 encoded Data URI or as a file on disk
    # depending on the configuration.
    def value
      execute
      if @file
        extension = '.png'
        filename  = @file.chomp(extension) + extension
        path      = File.join(Compass.configuration.images_path, filename)
        FileUtils.mkpath(File.dirname(path))
        File.open(path, 'wb') { |io| io << to_blob }
        filename
      else
        "url('data:image/png;base64,#{ Base64.encode64(to_blob).gsub("\n", '') }')"
      end
    end

    # Serializes the canvas as a Sass type
    def to_s(options = {})
      Sass::Script::String.new(value)
    end

    protected

    def execute_actions(actions = nil)
      actions ||= @actions
      actions.each do |child|
        if child.is_a?(Compass::Canvas::Backend::Interface::Base)
          action = child.action
          args   = child.args
        elsif child.is_a?(String)
          action = child.to_sym
          args   = []
        else
          raise Compass::Canvas::Exception.new("(#{self.class}) Unsupported action: #{child.inspect}")
        end
        execute_one(action, *args)
      end
    end

    private

    def this_method
      caller[0][/`([^']*)'/, 1]
    end
  end
end

require 'canvas/backend/interface';
require 'canvas/backend/cairo';


text:
namespace pik {

// One Newton-Raphson iteration.
template <class V>
static SIMD_ATTR SIMD_INLINE V ReciprocalNR(const V x) {
  const auto rcp = approximate_reciprocal(x);
  const auto sum = rcp + rcp;
  const auto x_rcp = x * rcp;
  return nmul_add(x_rcp, rcp, sum);
}

// Primary template: default to actual division.
template <typename T, class V>
struct FastDivision {
  SIMD_ATTR V operator()(const V n, const V d) const { return n / d; }
};
// Partial specialization for float vectors.
template <class V>
struct FastDivision<float, V> {
  SIMD_ATTR V operator()(const V n, const V d) const {
    return n * ReciprocalNR(d);
  }
};

// Returns a name for the vector/part/scalar. The type prefix is u/i/f for
// unsigned/signed/floating point, followed by the number of bits per lane;
// then 'x' followed by the number of lanes. Example: u8x16. This is useful for
// understanding which instantiation of a generic test failed.
template <class D>
inline const char* vec_name() {
  using T = typename D::T;
  constexpr size_t N = D::N;
  constexpr int kTarget = D::Target::value;

  // Avoids depending on <type_traits>.
  const bool is_float = T(2.25) != T(2);
  const bool is_signed = T(-1) < T(0);
  constexpr char prefix = is_float ? 'f' : (is_signed ? 'i' : 'u');

  constexpr size_t bits = sizeof(T) * 8;
  constexpr char bits10 = '0' + (bits / 10);
  constexpr char bits1 = '0' + (bits % 10);

  // Scalars: omit the xN suffix.
  if (kTarget == SIMD_NONE) {
    static constexpr char name1[8] = {prefix, bits1};
    static constexpr char name2[8] = {prefix, bits10, bits1};
    return sizeof(T) == 1 ? name1 : name2;
  }

  constexpr char N1 = (N < 10) ? '\0' : '0' + (N % 10);
  constexpr char N10 = (N < 10) ? '0' + (N % 10) : '0' + (N / 10);

  static constexpr char name1[8] = {prefix, bits1, 'x', N10, N1};
  static constexpr char name2[8] = {prefix, bits10, bits1, 'x', N10, N1};
  return sizeof(T) == 1 ? name1 : name2;
}

// Cache control

SIMD_INLINE void stream(const uint32_t t, uint32_t* SIMD_RESTRICT aligned) {
#if SIMD_ARCH == SIMD_ARCH_X86
  _mm_stream_si32(reinterpret_cast<int*>(aligned), t);
#else
  CopyBytes<4>(&t, aligned);
#endif
}

SIMD_INLINE void stream(const uint64_t t, uint64_t* SIMD_RESTRICT aligned) {
#if SIMD_ARCH == SIMD_ARCH_X86
  _mm_stream_si64(reinterpret_cast<long long*>(aligned), t);
#else
  CopyBytes<8>(&t, aligned);
#endif
}

// Delays subsequent loads until prior loads are visible. On Intel CPUs, also
// serves as a full fence (waits for all prior instructions to complete).
// No effect on non-x86.
SIMD_INLINE void load_fence() {
#if SIMD_ARCH == SIMD_ARCH_X86
  _mm_lfence();
#endif
}

// Ensures previous weakly-ordered stores are visible. No effect on non-x86.
SIMD_INLINE void store_fence() {
#if SIMD_ARCH == SIMD_ARCH_X86
  _mm_sfence();
#endif
}

// Begins loading the cache line containing "p".
template <typename T>
SIMD_INLINE void prefetch(const T* p) {
#if SIMD_ARCH == SIMD_ARCH_X86
  _mm_prefetch(p, _MM_HINT_T0);
#elif SIMD_ARCH == SIMD_ARCH_ARM
  __pld(p);
#endif
}

// Invalidates and flushes the cache line containing "p". No effect on non-x86.
SIMD_INLINE void flush_cacheline(const void* p) {
#if SIMD_ARCH == SIMD_ARCH_X86
  _mm_clflush(p);
#endif
}

// Call during spin loops to potentially reduce contention/power consumption.
SIMD_INLINE void pause() {
#if SIMD_ARCH == SIMD_ARCH_X86
  _mm_pause();
#endif
}

}  // namespace pik

#endif  // PIK_SIMD_SIMD_H_


text:
title: Future multi-node communications
description: >
   Initially, uibuilder was a single node. However, there was always the intent to offer wider communications from other packages and nodes
   to uibuilder-based front-end's. This document lays out a proposal for how that may happen.
created: 2021-09-29 20:04:36
lastUpdated: 2021-09-29 21:17:01
---

Status: **Draft**

uibuilder v5 will use the Node.js package [ti-common-event-handler](https://github.com/TotallyInformation/ti-common-event-handler) to create a shareable event handler
that facilitates communications between 3rd-party Node-RED nodes and uibuilder node instances (and back again).

Each uibuilder instance will act as a hub for sending data to its connected web clients and receiving messages back and routing them back to the originating node.

Two pieces of data will be required to enable this:

1. The uibuilder URL
2. A component identifier

## How it works - the component node

A component node will need to:

* Use the same event handler package. The module in the package is defined as a singleton class instance so it doesn't matter which node require's the module. All require's get exactly the same instance.
* Use a standard event naming pattern (defined below).
* Define a component identifier that front-end code will use.
* Send events to the defined event name with a standard Node-RED msg object.
* Add pre-defined metadata to the msg so that uibuilder and front-end code know how to process it. See below for details.
* Register a return event handler with a specific naming convention (defined below).
  The uibuilder instance will maintain an internal map of component-id's to return event names so that messages back from the front-end can be automatically routed back to the originating node.
* Send an initial control msg on Node-RED startup that will allow uibuilder to create the return map.
* Send a final control msg on node removal, before re-deployment and on Node-RED closedown so that all event handlers are unregistered and the map is updated.

### Front-end web components

Note that the component node does not _need_ to define any front-end components. You could just write suitable code manually for your front-end.
However, there _will_ be a set of standards that will allow a component node to make resources available to uibuilder-based front-ends.

The important thing is that messages will be automatically routed both to and from the front-end.

It is likely that there will be a mechanism in the `uibuilderfe.js` front-end library that will enable it to auto-load defined resources. Details to be defined later.

## How it works - the uibuilder node

When a uibuilder node receives the first event from a component node as defined below, it creates an entry in a mapping table.

The table maps the links between the component nodes (based on the node's Node-RED id) and the component-id.
This allows return messages from the front-end to be routed back to the correct originating node for any processing that node wishes to do.
For example, it may choose to pass the returned message to its output port. This is likely to be the most common scenario.

## Event naming standards

Event names will use the following standard to allow component nodes to send data:

```
node-red-contrib-uibuilder/<uib_url>/<component_id>
```

To facilitate return messages, the following standard will be used:

```
node-red-contrib-uibuilder/<node_instance_id>/return
```

Where:

* `<uib_url>` - is the uibuilder URL which is set in the uibuilder node and is the unique identifier for uibuilder instances.
* `<component_id>` - is a string identifier that is unique to your front-end code. It can be arbitrary. Component nodes can define defaults if preferred.
* `<node_instance_id>` - is the Node-RED node id of the instance of the component node.

## Standard msg metadata

The message metadata will take two forms:

1. Firstly, some uibuilder standard data. This will define the root property to use so that we keep the pre-defined properties to a minimum which avoids name-clashes and avoids limiting how you can use a msg object.

   There is already a standard that uibuilder uses and it is likely that this would continue to be used and extended as needed.

   A component identifier string would certainly be required. As described above, this only needs to be unique within your front-end code.

   It is likely that a "component type" property would also be used to differentiate between data schema's.

2. Secondly, some component-specific data. This would be defined by the component node's author.

   This would sit _under_ the uibuilder property so as to avoid polluting the namespace of the msg object.

   It is possible that a schema standard would be defined to help but the data would mostly be defined by the component author.

Note that uibuilder already pre-defines some metadata for some tasks including security.

## The future

Obviously, this design note only covers communication.

The approach has the strong advantage of being open. Which is to say that it doesn't tie you down to a specific framework since it does not define how your
front-end code will process the data.

However, it _does_ lay a foundation that will let nodes be created that _will_ allow authors to create nodes with front-end components and _will_ enable such nodes to fully automate both the component code delivery and the communications between the node and the front-end (and back of course).

This means that this approach is the first step towards a low-/no-code, simple to use, node-based web ui builder.

And yet, despite that, it does not break the core design principal of uibuilder which is to be framework agnostic and unopinionated.


text:
#ifndef __CHXJ_COOKIE_H__
#define __CHXJ_COOKIE_H__

#include "mod_chxj.h"
#include "apr_file_io.h"
#include "apr_tables.h"
#include "apr_time.h"

#define CHXJ_COOKIE_PARAM               "_chxj_cc"
#define CHXJ_COOKIE_NOUPDATE_PARAM      "_chxj_nc"

#define DEFAULT_COOKIE_DB_DIR           "/tmp"
#define COOKIE_DB_NAME                  "cookie.db"
#define COOKIE_DB_LOCK_NAME             "cookie.db.lock"

#define COOKIE_EXPIRE_DB_NAME           "cookie.expire.db"
#define COOKIE_EXPIRE_DB_LOCK_NAME      "cookie.expire.db.lock"

#define REFERER_COOKIE_KEY              "CHXJ_REFER"
#define CHXJ_COOKIE_PROC_MUTEX_FILE     "/tmp/chxj_cookie_mutex.lock"

/*
 * default cookie timeout is 30 minute
 */
#define DEFAULT_COOKIE_TIMEOUT          (1800)

extern apr_proc_mutex_t *global_cookie_mutex;

typedef struct cookie_t cookie_t;

struct cookie_t {
  char*               cookie_id;
  apr_array_header_t* cookie_headers;
};

extern cookie_t* chxj_save_cookie(
  request_rec*            r);

extern char* chxj_add_cookie_parameter(
  request_rec*            r,
  char*                   value,
  cookie_t*               cookie);

extern int chxj_cookie_check_host(
  request_rec*            r,
  char*                   value);

extern cookie_t* chxj_load_cookie(
  request_rec*            r,
  char*                   cookie_id);

extern apr_file_t* chxj_cookie_db_lock(
  request_rec*            r);

extern void chxj_cookie_db_unlock(
  request_rec*            r,
  apr_file_t*             file);

extern void chxj_delete_cookie(request_rec *r, const char *cookie_id);

extern char* chxj_cookie_db_name_create(
  request_rec*            r,
  const char*             dir);

extern char* chxj_cookie_db_lock_name_create(
  request_rec* r,
  const char*  dir);

extern char* chxj_cookie_expire_db_lock_name_create(
  request_rec* r,
  const char*  dir);

extern char* chxj_cookie_expire_db_name_create(
  request_rec* r,
  const char*  dir);

extern apr_file_t* chxj_cookie_expire_db_lock(
  request_rec* r);

extern void chxj_cookie_expire_db_unlock(
  request_rec* r,
  apr_file_t*  file);

extern void chxj_save_cookie_expire(
  request_rec* r,
  cookie_t*    cookie);

extern void chxj_delete_cookie_expire(
  request_rec* r,
  char*        cookie_id);

extern void chxj_cookie_expire_gc(
  request_rec* r);

extern cookie_t* chxj_update_cookie(
  request_rec* r,
  cookie_t*    old_cookie);

extern apr_time_t chxj_parse_cookie_expires(const char *s);
extern int chxj_cookie_lock(request_rec *r);
extern int chxj_cookie_unlock(request_rec *r);
#endif
/*
 * vim:ts=2 et
 */


text:
/*
 * 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.
 */
package com.veracloud.jton;

/**
 * A class representing a Jton {@code null} value.
 */
public final class JtonNull extends JtonElement {

  /**
   * singleton for JsonNull
   */
  public static final JtonNull INSTANCE = new JtonNull();

  @Override
	public JtonNull deepCopy() {
    return INSTANCE;
  }

  /**
   * All instances of JsonNull have the same hash code since they are indistinguishable
   */
  @Override
  public int hashCode() {
    return JtonNull.class.hashCode();
  }

  /**
   * All instances of JsonNull are the same
   */
  @Override
  public boolean equals(Object other) {
    return this == other || other instanceof JtonNull;
  }

}


text:
/*******************************************************************\

Module:

Author: Daniel Kroening, kroening@kroening.com

\*******************************************************************/

#include <namespace.h>

#include "expr.h"
#include <irep2.h>

exprt c_sizeof(const typet &src, const namespacet &ns);


text:
class RocketTrail;

/// This is a class that can handle cases where you have, say, ten projectiles
/// and three enemies, and you'd like each enemy to get just the number of projectiles
/// necessary to kill it. It stores a dictionary of targeted enemies, the total damage
/// to be done so far upon each of them given the allocated projectiles, and a linked
/// list of projectiles (or spell effects or what have you) allocated to each one.
class CASW_DamageAllocationMgr
{
public:
		// typedefs
	// relevant data about a given projectile: its handle, and the damage it causes
	struct ProjectileInfo_t
	{
		EHANDLE m_hHandle;
		float m_flDamage;

		ProjectileInfo_t() : m_flDamage(0) {}
		ProjectileInfo_t( CBaseEntity *pProj, float damage ) : m_hHandle(pProj),
			m_flDamage(damage) {}
	};

	// we store the chain of projectiles allocated to each target
	// as a linked list. This is actually a MULTILIST, which means
	// that many linked lists actually share the pool of spaces herein
	typedef CUtlLinkedList< ProjectileInfo_t, unsigned short, true, unsigned int > ProjectilePool_t;

	struct tuple_t
	{
		EHANDLE m_hTargeted;
		float   m_flAccumulatedDamage;
		ProjectilePool_t::IndexType_t m_nProjectiles; ///< head of linked list of projectiles targeted at this object

		tuple_t() : m_flAccumulatedDamage(0), m_nProjectiles( ProjectilePool_t::InvalidIndex() ) {};
		tuple_t( const EHANDLE &handle ) : m_hTargeted(handle),
			m_flAccumulatedDamage(0), m_nProjectiles( ProjectilePool_t::InvalidIndex() ) {};
	};

	/// an index into the targets contained herein.
	// typedeffed just in case I need to change it from being a pointer.
	typedef tuple_t* IndexType_t;

		// functions
	// get the element for a given IndexType_t
	inline tuple_t &operator[]( const IndexType_t &I ) { return Elem(I); }
	inline tuple_t &Elem( const IndexType_t &I );
	inline bool IsValid( const IndexType_t &I ) const ;
	static inline IndexType_t InvalidIndex();

	// if the object hasn't got anything allocated, returns NULL
	IndexType_t Find( const EHANDLE &handle ) ;

	// add this object to the damage allocator, with nothing allocated
	// to it yet. returns the allocated tuple_t. returns the existing one
	// if the object is already in the manager.
	IndexType_t Insert( CBaseEntity* pTarget );

	void Remove( const EHANDLE &handle );

	// allocate a projectile to a target. returns total damage being done to target so far.
	inline float Allocate(  CBaseEntity *pTarget, CBaseEntity *pProjectile, float flDamage );
	float Allocate( IndexType_t iTarget, CBaseEntity *pProjectile, float flDamage );

	// remove a projectile from a target. returns total damage being done to target so far.
	inline float Deallocate(  CBaseEntity *pTarget, CBaseEntity *pProjectile );
	float Deallocate( IndexType_t iTarget, CBaseEntity *pProjectile );

	// is the given projectile allocated to the given target?
	inline bool IsProjectileForTarget( IndexType_t iTarget, CBaseEntity *pProjectile );

	// constructor
	CASW_DamageAllocationMgr( int baseSize = 0 ) : m_Targets( 0, baseSize ), m_ProjectileLists( 0, baseSize ) {};

protected:

	// look through the projectile pool for a given target and return the index
	// of the ProjectilePool_t corresponding to the given projectile. Return
	// ProjectilePool_t::InvalidIndex if not found.
	ProjectilePool_t::IndexType_t GetProjectileIndexInTarget( IndexType_t iTarget, CBaseEntity *pProjectile );

	// rebuild consistency
	void Rebuild( IndexType_t iTarget );

	CUtlVectorConservative< tuple_t > m_Targets;
	ProjectilePool_t m_ProjectileLists;
};

inline CASW_DamageAllocationMgr::tuple_t & CASW_DamageAllocationMgr::Elem( const IndexType_t &I )
{
	return *I;
}

inline bool CASW_DamageAllocationMgr::IsProjectileForTarget( IndexType_t iTarget, CBaseEntity *pProjectile )
{
	return GetProjectileIndexInTarget( iTarget, pProjectile ) != ProjectilePool_t::InvalidIndex();
}

inline float CASW_DamageAllocationMgr::Allocate(  CBaseEntity *pTarget, CBaseEntity *pProjectile, float flDamage )
{
	IndexType_t i = Find(pTarget);
	if ( !IsValid(i) )
	{
		AssertMsg2( false, "Tried to allocate %s as a damage projectile to %s but it isn't managed\n",
			pProjectile->GetDebugName(), pTarget->GetDebugName() );
		i = Insert( pTarget );
	}
	return Allocate( i, pProjectile, flDamage );
}

inline float CASW_DamageAllocationMgr::Deallocate(  CBaseEntity *pTarget, CBaseEntity *pProjectile )
{
	IndexType_t i = Find(pTarget);
	if ( !IsValid(i) )
	{
		AssertMsg2( false, "Tried to remove %s as a damage projectile to unmanaged %s\n",
			pProjectile->GetDebugName(), pTarget->GetDebugName() );
		return 0;
	}
	else
	{
		return Deallocate( i, pProjectile );
	}
}

inline CASW_DamageAllocationMgr::IndexType_t CASW_DamageAllocationMgr::InvalidIndex()
{
	return NULL;
}

inline bool CASW_DamageAllocationMgr::IsValid( const IndexType_t &I ) const
{
	return I != InvalidIndex();
}

class CASW_Rocket : public CBaseCombatCharacter
{
	DECLARE_CLASS( CASW_Rocket, CBaseCombatCharacter );
	DECLARE_SERVERCLASS();
public:
	static const int EXPLOSION_RADIUS = 200;

	CASW_Rocket();
	virtual ~CASW_Rocket();

	Class_T Classify( void ) { return CLASS_MISSILE; }

	virtual void Spawn( void );
	virtual void Activate( void );
	virtual void StopLoopingSounds( void );
	virtual void Precache( void );

	void	MissileTouch( CBaseEntity *pOther );
	void	Explode( void );
	void	AccelerateThink( void );
	void	IgniteThink( void );
	void	SeekThink( void );
	void	DumbFire( void );
	void	SetGracePeriod( float flGracePeriod );

	int		OnTakeDamage_Alive( const CTakeDamageInfo &info );
	void	Event_Killed( const CTakeDamageInfo &info );

	virtual float	GetDamage() { return m_flDamage; }
	virtual void	SetDamage(float flDamage) { m_flDamage = flDamage; }

	unsigned int PhysicsSolidMaskForEntity( void ) const;

	static CASW_Rocket *Create( float fDamage, const Vector &vecOrigin, const QAngle &vecAngles, CBaseCombatCharacter *pentOwner = NULL , CBaseEntity * pCreatorWeapon = NULL, const char *className = "asw_rocket" );

	void CreateDangerSounds( bool bState ){ m_bCreateDangerSounds = bState; }

	void FindHomingPosition( Vector *pTarget );
	CBaseEntity *FindPotentialTarget( void ) const ; /// find a good enemy for us to target. The enemy isn't actually targeted until the result is written back to m_hHomingTarget
	void SetTarget( CBaseEntity *pTarget );
	inline CBaseEntity *GetTarget( void )  { return  m_hHomingTarget.Get(); }

	virtual void DrawDebugGeometryOverlays();

	int		m_iAttributeEffects;

	EHANDLE m_hCreatorWeapon;
	Class_T m_CreatorWeaponClass;

protected:
	virtual void DoExplosion(bool bHitwall);
	Vector		 IntegrateRocketThrust( const Vector &vTargetDir, float flDist ) const ;
	void		 ComputeWallDodge( const Vector &vCurVel ); /// if we're headed for a wall, adjust the wobble angles so we steer away

	float		 GetLifeFraction() const;

	bool IsWallDodging() const;

	EHANDLE m_hHomingTarget;

	float m_flDamage;
	float m_fSpawnTime;
	float m_fDieTime;

	const char *			m_szFlightSound;
	const char *			m_szDetonationSound;

	static CASW_DamageAllocationMgr m_RocketAssigner;

private:
	float					m_flGracePeriodEndsAt;
	float					m_flNextWobbleTime;

	QAngle					m_vWobbleAngles; ///< will approach this direction while wobbling

	bool					m_bCreateDangerSounds;
	bool					m_bFlyingWild; // has no target, is wobbling crazily

	DECLARE_DATADESC();
};

#endif // _INCLUDED_ASW_ROCKET_H


text:
require 'daemons/pid'

module Daemons
  class PidMem < Pid
    attr_accessor :pid

    def self.existing(numeric_pid)
      new_instance = PidMem.allocate

      new_instance.instance_variable_set(:@pid, numeric_pid)

      new_instance
    end
  end
end


text:
/**
 * Table 普通表头渲染器
 * @author Brian Li
 * @email lbxxlht@163.com
 * @version 0.0.2.1
 */
define(function (require) {

    var Tip = require('../../Tip.jsx');
    var React = require('react');

    return React.createClass({

        // @override
        /**
         * @properties
         * @param {Object} fieldConfig 表头所在列的配置信息
         * @param {ReactComponent} tableComponent 表格实例
         */
        getDefaultProps: function getDefaultProps() {
            return {
                fieldConfig: {},
                tableComponent: {}
            };
        },

        onSortClick: function onSortClick(e) {
            var table = this.props.tableComponent;
            var tableValue = this.props.tableComponent.___getValue___() || '{}';
            var fieldConfig = this.props.fieldConfig;
            tableValue = JSON.parse(tableValue);
            tableValue.sortField = tableValue.sortField || '';
            tableValue.sortType = tableValue.sortType || 'asc';
            if (tableValue.sortField === fieldConfig.field) {
                tableValue.sortType = tableValue.sortType === 'asc' ? 'desc' : 'asc';
            } else {
                tableValue.sortField = fieldConfig.field;
                tableValue.sortType = 'desc';
            }
            e.target.value = JSON.stringify(tableValue);
            table.___dispatchChange___(e);
        },

        render: function render() {
            var table = this.props.tableComponent;
            var tableFlags = table.props.flags || {};
            var tableValue = table.___getValue___() || '{}';
            var fieldConfig = this.props.fieldConfig;
            var sortEnable = tableFlags.sortEnable && !fieldConfig.sortDisable;
            tableValue = JSON.parse(tableValue);
            var sortField = tableValue.sortField || '';
            var sortType = tableValue.sortType || 'desc';
            if (sortField !== fieldConfig.field) {
                sortType = 'desc'; //desc 降序 asc升序
            }
            var sortButtonProp = {
                className: 'sort-button fcui2-icon ' + (sortType === 'asc' ? 'fcui2-icon-asc' : 'fcui2-icon-desc'),
                style: {
                    display: sortEnable ? 'inline-block' : 'none',
                    color: sortField !== fieldConfig.field ? '#DEDEDE' : '#2F82F5'
                },
                onClick: this.onSortClick
            };
            var rowSpan = +this.props.rowSpan;
            var thProp = {
                className: 'th-header',
                rowSpan: isNaN(rowSpan) || !rowSpan ? undefined : rowSpan,
                style: {
                    textAlign: fieldConfig.align || 'left',
                    verticalAlign: fieldConfig.verticalAlign || 'top'
                }
            };
            return React.createElement(
                'th',
                thProp,
                React.createElement(
                    'span',
                    null,
                    fieldConfig.label
                ),
                React.createElement(Tip, fieldConfig.tip),
                React.createElement('div', sortButtonProp)
            );
        }
    });
});


text:
sap.ui.define([], function() {
	"use strict";

	/**
	 * @typedef sap.ui.test.generic.GenericTestCollection.ObjectCapabilities
	 *
	 * @param {string} moduleName
	 *    Name of the module that contains the class. If not given, it is assumed that a module
	 *    with the same name as the class (dots replaced by slashes) exports the class.
	 *    When given, the module is loaded and the class is retrieved via its global name
	 * @param {boolean|function} create
	 *    Explicit false if the control can't be instantiated via constructor or factory function
	 *    expecting the following parameters: Class, mSettings
	 * @param {boolean} rendererHasDependencies
	 *    Control renderer has dependencies to parent or child controls and can't be rendered standalone
	 * @param {Object<string, sap.ui.test.generic.GenericTestCollection.ExcludeReason|any>} properties
	 *    A map containing the property name as key and either an {@link sap.ui.test.generic.GenericTestCollection.ExcludeReason ExcludeReason}
	 *    or a "value to set" as value
	 * @param {Object<string, sap.ui.test.generic.GenericTestCollection.ExcludeReason|function>} aggregations
	 *    A map containing the aggregation name as key and either an {@link sap.ui.test.generic.GenericTestCollection.ExcludeReason ExcludeReason}
	 *    or the class which should be used as value
	 * @param {int} [apiVersion=2]
	 *    The API version of the control's renderer should be set in case the renderer does not support
	 *    semantic rendering
	 * @param {object} [knownIssues=undefined]
	 *    Exceptions for known but not fixed issues
	 * @param {boolean} knownIssues.Id
	 *    Exception for known duplicate ID issues
	 * @param {boolean} knownIssues.memoryLeaks
	 *    Exception for known memory leak issues
	 *
	 * @private
	 * @ui5-restricted Only for DIST layer libraries
	 */

	/**
	 * @namespace
	 * @alias sap.ui.test.generic.GenericTestCollection
	 * @private
	 * @ui5-restricted Only for DIST layer libraries
	 * @since 1.100
	 */
	var GenericTestCollection = {
		/**
		 * Marker for exclude reasons.
		 *
		 * @enum {string}
		 * @private
		 */
		ExcludeReason: {
			/**
			 * The property or aggregation can only be changed using a binding. Using setter is not allowed.
			 * @private
			 */
			OnlyChangeableViaBinding: "OnlyChangeableViaBinding",

			/**
			 * The property or aggregation can only be set on initialisation. Using setter is not allowed.
			 * @private
			 */
			NotChangeableAfterInit: "NotChangeableAfterInit",

			/**
			 * The property or aggregation can't be filled generically. Property/aggregation specific settings are needed.
			 * @private
			 */
			SetterNeedsSpecificSettings: "SetterNeedsSpecificSettings",

			/**
			 * The default value retrieved from getter can't be used for setting the value using the corresponding setter.
			 * @private
			 */
			CantSetDefaultValue: "CantSetDefaultValue"
		},
		/**
		 * Marker for available generic Tests
		 *
		 * @enum {string}
		 * @private
		 */
		Test: {
			/**
			 * Test ControlMemoryLeaks
			 * @protected
			 */
			ControlMemoryLeaks: "ControlMemoryLeaks",

			/**
			 * Test ControlRenderer
			 * @protected
			 */
			ControlRenderer: "ControlRenderer",

			/**
			 * Test DuplicateIdCheck
			 * @protected
			 */
			DuplicateIdCheck: "DuplicateIdCheck",

			/**
			 * Test EnforceSemanticRendering
			 * @protected
			 */
			EnforceSemanticRendering: "EnforceSemanticRendering",

			/**
			 * Test SettersContextReturn
			 * @protected
			 */
			SettersContextReturn: "SettersContextReturn"
		},

		/**
		 * Create the testsuite config
		 *
		 * @param  {object} mConfig Map containing test parameters
		 * @param  {string} mConfig.library The library name
		 * @param  {object} mConfig.objectCapabilities The opt-out options per control
		 * @param  {sap.ui.test.generic.GenericTestCollection.ObjectCapabilities} mConfig.objectCapabilities.anyName The controls capability options
		 * @param  {sap.ui.test.generic.GenericTestCollection.Test[]} mConfig.skipTests List of tests which shouldn't be executed
		 * @return {object} Returns the testsuite config object
		 *
		 * @private
		 * @ui5-restricted Only for DIST layer libraries
		 * @since 1.100
		 */
		createTestsuiteConfig: function(mConfig) {
			var oSuiteConfig = {
				name: "Testsuite for Generic Control Tests for library: " + mConfig.library,
				defaults: {
					ui5: {
						libs: [mConfig.library]
					},
					qunit: {
						reorder: false,
						version: 2
					},
					testConfig: mConfig,
					module: "test-resources/sap/ui/core/qunit/generic/{name}.qunit"
				},
				tests: {
					ControlMemoryLeaks: {
						title: "QUnit Page for memory leak detection in UI5 controls"
					},
					ControlRenderer: {
						title: "QUnit Page for Control Renderer Tests"
					},
					DuplicateIdCheck: {
						title: "QUnit Page for duplicate ID issues detection in UI5 controls"
					},
					SettersContextReturn: {
						title: "All setters should return correct context (Reason: https://github.com/SAP/openui5/blob/master/docs/guidelines.md#creating-classes)"
					},
					EnforceSemanticRendering: {
						title: "QUnit Page for Semantic Rendering Coverage"
					}
				}
			};

			// Opt-out from single tests
			var aSkippedTests = mConfig.skipTests || [];
			aSkippedTests.forEach(function(sTest) {
				delete oSuiteConfig.tests[sTest];
			});

			return oSuiteConfig;
		}
	};

	return GenericTestCollection;
});


text:
layout: post
title: "Alias Sampling"
description: ""
category: Math
tags: [Math-Statistics]
---
{% include JB/setup %}

Two brilliant posts on this sampling technique:

- [Lab Notes: The Alias Method for Sampling from Discrete Distributions](https://pandasthumb.org/archives/2012/08/lab-notes-the-a.html)
- [Darts, Dice, and Coins: Sampling from a Discrete Distribution](http://www.keithschwarz.com/darts-dice-coins/)

Great thanks to the authors!


text:
<?php

// No direct access.
defined('_JEXEC') or die;

jimport('joomla.application.component.controlleradmin');

/**
 * Users list controller class.
 *
 * @package     Joomla.Administrator
 * @subpackage  com_users
 * @since       1.6
 */
class UsersControllerUsers extends JControllerAdmin
{
	/**
	 * @var    string  The prefix to use with controller messages.
	 * @since  1.6
	 */
	protected $text_prefix = 'COM_USERS_USERS';

	/**
	 * Constructor.
	 *
	 * @param   array  $config  An optional associative array of configuration settings.
	 *
	 * @return  UsersControllerUsers
	 *
	 * @since   1.6
	 * @see     JController
	 */
	public function __construct($config = array())
	{
		parent::__construct($config);

		$this->registerTask('block',		'changeBlock');
		$this->registerTask('unblock',		'changeBlock');
	}

	/**
	 * Proxy for getModel.
	 *
	 * @param   string  $name    The model name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  object  The model.
	 *
	 * @since	1.6
	 */
	public function getModel($name = 'User', $prefix = 'UsersModel', $config = array('ignore_request' => true))
	{
		return parent::getModel($name, $prefix, $config);
	}

	/**
	 * Method to change the block status on a record.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	public function changeBlock()
	{
		// Check for request forgeries.
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Initialise variables.
		$ids	= JRequest::getVar('cid', array(), '', 'array');
		$values	= array('block' => 1, 'unblock' => 0);
		$task	= $this->getTask();
		$value	= JArrayHelper::getValue($values, $task, 0, 'int');

		if (empty($ids))
		{
			JError::raiseWarning(500, JText::_('COM_USERS_USERS_NO_ITEM_SELECTED'));
		}
		else
		{
			// Get the model.
			$model = $this->getModel();

			// Change the state of the records.
			if (!$model->block($ids, $value))
			{
				JError::raiseWarning(500, $model->getError());
			}
			else
			{
				if ($value == 1)
				{
					$this->setMessage(JText::plural('COM_USERS_N_USERS_BLOCKED', count($ids)));
				}
				elseif ($value == 0)
				{
					$this->setMessage(JText::plural('COM_USERS_N_USERS_UNBLOCKED', count($ids)));
				}
			}
		}

		$this->setRedirect('index.php?option=com_users&view=users');
	}

	/**
	 * Method to activate a record.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	public function activate()
	{
		// Check for request forgeries.
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Initialise variables.
		$ids	= JRequest::getVar('cid', array(), '', 'array');

		if (empty($ids))
		{
			JError::raiseWarning(500, JText::_('COM_USERS_USERS_NO_ITEM_SELECTED'));
		}
		else
		{
			// Get the model.
			$model = $this->getModel();

			// Change the state of the records.
			if (!$model->activate($ids))
			{
				JError::raiseWarning(500, $model->getError());
			}
			else
			{
				$this->setMessage(JText::plural('COM_USERS_N_USERS_ACTIVATED', count($ids)));
			}
		}

		$this->setRedirect('index.php?option=com_users&view=users');
	}
}


text:
This example shows how you can extend Slate with plugins! The example shows plugins that perform simple operations on keypress.

Check out the [Examples readme](..) to see how to run it!


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.BasicRobot.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 * @author FrankAdmin
 */
public class AutonomousGroup extends CommandGroup {

    public AutonomousGroup() {
        addSequential(new DriveWhenHot());
    }
}


text:
#ifndef __ATM90E26_SPI_H__
#define __ATM90E26_SPI_H__

#include <Arduino.h>

#define SoftReset 0x00 // Software Reset
#define SysStatus 0x01 // System Status
#define FuncEn 0x02    // Function Enable
#define SagTh 0x03     // Voltage Sag Threshold
#define SmallPMod 0x04 // Small-Power Mode
#define LastData 0x06  // Last Read/Write SPI/UART Value
#define LSB 0x08       // RMS/Power 16-bit LSB
#define CalStart 0x20  // Calibration Start Command
#define PLconstH 0x21  // High Word of PL_Constant
#define PLconstH_Default 0x0015
#define PLconstL 0x22 // Low Word of PL_Constant
#define PLconstL_Default 0xD174
#define Lgain 0x23 // L Line Calibration Gain
#define Lgain_Default 0x0000
#define Lphi 0x24 // L Line Calibration Angle
#define Lphi_Default 0x0000
#define Ngain 0x25 // N Line Calibration Gain
#define Ngain_Default 0x0000
#define Nphi 0x26 // N Line Calibration Angle
#define Nphi_Default 0x0000
#define PStartTh 0x27 // Active Startup Power Threshold
#define PStartTh_Default 0x08BD
#define PNolTh 0x28 // Active No-Load Power Threshold
#define PNolTh_Default 0x0000
#define QStartTh 0x29 // Reactive Startup Power Threshold
#define QStartTh_Default 0x0AEC
#define QNolTh 0x2A // Reactive No-Load Power Threshold
#define QNolTh_Default 0x0000
#define MMode 0x2B // Metering Mode Configuration
#define MMode_Default 0x9422
#define CSOne 0x2C    // Checksum 1
#define AdjStart 0x30 // Measurement Calibration Start Command
#define Ugain 0x31    // Voltage rms Gain
#define Ugain_Default 0x6720
#define IgainL 0x32 // L Line Current rms Gain
#define IgainL_Default 0x7A13
#define IgainN 0x33 // N Line Current rms Gain
#define IgainN_Default 0x7530
#define Uoffset 0x34 // Voltage Offset
#define Uoffset_Default 0x0000
#define IoffsetL 0x35 // L Line Current Offset
#define IoffsetL_Default 0x0000
#define IoffsetN 0x36 // N Line Current Offse
#define IoffsetN_Default 0x0000
#define PoffsetL 0x37 // L Line Active Power Offset
#define PoffsetL_Default 0x0000
#define QoffsetL 0x38 // L Line Reactive Power Offset
#define QoffsetL_Default 0x0000
#define PoffsetN 0x39 // N Line Active Power Offset
#define PoffsetN_Default 0x0000
#define QoffsetN 0x3A // N Line Reactive Power Offset
#define QoffsetN_Default 0x0000
#define CSTwo 0x3B     // Checksum 2
#define APenergy 0x40  // Forward Active Energy
#define ANenergy 0x41  // Reverse Active Energy
#define ATenergy 0x42  // Absolute Active Energy
#define RPenergy 0x43  // Forward (Inductive) Reactive Energy
#define Rnenerg 0x44   // Reverse (Capacitive) Reactive Energy
#define Rtenergy 0x45  // Absolute Reactive Energy
#define EnStatus 0x46  // Metering Status
#define Irms 0x48      // L Line Current rms
#define Urms 0x49      // Voltage rms
#define Pmean 0x4A     // L Line Mean Active Power
#define Qmean 0x4B     // L Line Mean Reactive Power
#define Freq 0x4C      // Voltage Frequency
#define PowerF 0x4D    // L Line Power Factor
#define Pangle 0x4E    // Phase Angle between Voltage and L Line Current
#define Smean 0x4F     // L Line Mean Apparent Power
#define IrmsTwo 0x68   // N Line Current rms
#define PmeanTwo 0x6A  // N Line Mean Active Power
#define QmeanTwo 0x6B  // N Line Mean Reactive Power
#define PowerFTwo 0x6D // N Line Power Factor
#define PangleTwo 0x6E // Phase Angle between Voltage and N Line Current
#define SmeanTwo 0x6F  // N Line Mean Apparent Power

// pins used for the connection with the sensor
// the other you need are controlled by the SPI library):
// const int energy_IRQ = 2;
#if defined(ARDUINO_ESP8266_WEMOS_D1MINI) // WeMos mini and D1 R2
const int energy_CS = D8;                 // WEMOS SS pin
#elif defined(ARDUINO_ESP8266_ESP12)      // Adafruit Huzzah
const int energy_CS = 15; // HUZZAH SS pins ( 0 or 15)
#elif defined(ARDUINO_ARCH_SAMD)          // M0 board
const int energy_CS = 10; // M0 SS pin
#elif defined(__AVR_ATmega32U4__)         // 32u4 board
const int energy_CS = 10; // 32u4 SS pin
#else
const int energy_CS = SS; // Use default SS pin for unknown Arduino
#endif // defined(ARDUINO_ESP8266_WEMOS_D1MINI)

class ATM90E26_SPI {
public:
  ATM90E26_SPI(int pin = energy_CS);
  double GetLineVoltage();
  double GetLineCurrent();
  double GetActivePower();
  double GetReactivePower();
  double GetApparentPower();
  double GetPhaseAngle();
  double GetFrequency();
  double GetPowerFactor();
  double GetImportEnergy();
  double GetExportEnergy();
  void SetUGain(unsigned short);
  void SetLGain(unsigned short);
  void SetIGain(unsigned short);
  void InitEnergyIC();
  void CalibrateEnergyIC();
  unsigned short GetSysStatus();
  unsigned short GetMeterStatus();

private:
  unsigned short CommEnergyIC(unsigned char RW, unsigned char address,
                              unsigned short val);
  unsigned short CalcCheckSum(int checksum_id);
  int _cs;

  unsigned short metering[11];
  enum metering_values {
    _plconsth,
    _plconstl,
    _lgain,
    _lphi,
    _ngain,
    _nphi,
    _pstartth,
    _pnolth,
    _qstartth,
    _qnolth,
    _mmode
  };
  unsigned short _crc1;
  unsigned short measurement[10];
  enum measurement_values {
    _ugain,
    _igain,
    _igainn,
    _uoffset,
    _ioffestl,
    _ioffsetn,
    _poffestl,
    _qoffsetl,
    _poffsetn,
    _qoffsetn
  };
  unsigned short _crc2;
};

#endif


text:
using System;

namespace Manatee.Json.Tests.Test_References
{
	public class ObjectWithTwoUriProps
	{
		public Uri Test { get; set; }
		public Uri Other { get; set; }
	}
}


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.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
    [UseExportProvider]
    public class DiagnosticsSquiggleTaggerProviderTests
    {
        private static readonly TestComposition s_compositionWithMockDiagnosticService =
            EditorTestCompositions.EditorFeatures.AddExcludedPartTypes(typeof(IDiagnosticService)).AddParts(typeof(MockDiagnosticService));

        [WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task Test_TagSourceDiffer()
        {
            var analyzer = new Analyzer();
            var analyzerMap = new Dictionary<string, ImmutableArray<DiagnosticAnalyzer>>
            {
                {  LanguageNames.CSharp, ImmutableArray.Create<DiagnosticAnalyzer>(analyzer) }
            };

            using var workspace = TestWorkspace.CreateCSharp(new string[] { "class A { }", "class E { }" }, parseOptions: CSharpParseOptions.Default);
            using var wrapper = new DiagnosticTaggerWrapper<DiagnosticsSquiggleTaggerProvider, IErrorTag>(workspace, analyzerMap);
            var tagger = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer());
            using var disposable = tagger as IDisposable;
            // test first update
            await wrapper.WaitForTags();

            var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
            var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToList();
            Assert.True(spans.First().Span.Contains(new Span(0, 1)));

            // test second update
            analyzer.ChangeSeverity();

            var document = workspace.CurrentSolution.GetRequiredDocument(workspace.Documents.First().Id);
            var text = await document.GetTextAsync();
            workspace.TryApplyChanges(document.WithText(text.WithChanges(new TextChange(new TextSpan(text.Length - 1, 1), string.Empty))).Project.Solution);

            await wrapper.WaitForTags();

            snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
            spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToList();
            Assert.True(spans.First().Span.Contains(new Span(0, 1)));
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task MultipleTaggersAndDispose()
        {
            using var workspace = TestWorkspace.CreateCSharp(new string[] { "class A {" }, parseOptions: CSharpParseOptions.Default);
            using var wrapper = new DiagnosticTaggerWrapper<DiagnosticsSquiggleTaggerProvider, IErrorTag>(workspace);
            // Make two taggers.
            var tagger1 = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer());
            var tagger2 = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer());

            // But dispose the first one. We still want the second one to work.
            ((IDisposable)tagger1).Dispose();

            using var disposable = tagger2 as IDisposable;
            await wrapper.WaitForTags();

            var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
            var spans = tagger2.GetTags(snapshot.GetSnapshotSpanCollection()).ToList();
            Assert.False(spans.IsEmpty());
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task TaggerProviderCreatedAfterInitialDiagnosticsReported()
        {
            using var workspace = TestWorkspace.CreateCSharp(new string[] { "class C {" }, parseOptions: CSharpParseOptions.Default);
            using var wrapper = new DiagnosticTaggerWrapper<DiagnosticsSquiggleTaggerProvider, IErrorTag>(workspace, analyzerMap: null, createTaggerProvider: false);
            // First, make sure all diagnostics have been reported.
            await wrapper.WaitForTags();

            // Now make the tagger.
            var taggerProvider = wrapper.TaggerProvider;

            // Make a taggers.
            var tagger1 = wrapper.TaggerProvider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer());
            using var disposable = tagger1 as IDisposable;
            await wrapper.WaitForTags();

            // We should have tags at this point.
            var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
            var spans = tagger1.GetTags(snapshot.GetSnapshotSpanCollection()).ToList();
            Assert.False(spans.IsEmpty());
        }

        [WpfFact]
        public async Task TestWithMockDiagnosticService_TaggerProviderCreatedBeforeInitialDiagnosticsReported()
        {
            // This test produces diagnostics from a mock service so that we are disconnected from
            // all the asynchrony of the actual async analyzer engine.  If this fails, then the
            // issue is almost certainly in the DiagnosticsSquiggleTaggerProvider code.  If this
            // succeed, but other squiggle tests fail, then it is likely an issue with the
            // diagnostics engine not actually reporting all diagnostics properly.

            using var workspace = TestWorkspace.CreateCSharp(
                new string[] { "class A { }" },
                parseOptions: CSharpParseOptions.Default,
                composition: s_compositionWithMockDiagnosticService);

            var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>();

            var diagnosticService = Assert.IsType<MockDiagnosticService>(workspace.ExportProvider.GetExportedValue<IDiagnosticService>());
            var provider = workspace.ExportProvider.GetExportedValues<ITaggerProvider>().OfType<DiagnosticsSquiggleTaggerProvider>().Single();

            // Create the tagger before the first diagnostic event has been fired.
            var tagger = provider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer());
            Contract.ThrowIfNull(tagger);

            // Now product the first diagnostic and fire the events.
            var tree = await workspace.CurrentSolution.Projects.Single().Documents.Single().GetRequiredSyntaxTreeAsync(CancellationToken.None);
            var span = TextSpan.FromBounds(0, 5);
            diagnosticService.CreateDiagnosticAndFireEvents(workspace, Location.Create(tree, span));

            using var disposable = tagger as IDisposable;
            await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).ExpeditedWaitAsync();
            await listenerProvider.GetWaiter(FeatureAttribute.ErrorSquiggles).ExpeditedWaitAsync();

            var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
            var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToList();
            Assert.Equal(1, spans.Count);
            Assert.Equal(span.ToSpan(), spans[0].Span.Span);
        }

        [WpfFact]
        public async Task TestWithMockDiagnosticService_TaggerProviderCreatedAfterInitialDiagnosticsReported()
        {
            // This test produces diagnostics from a mock service so that we are disconnected from
            // all the asynchrony of the actual async analyzer engine.  If this fails, then the
            // issue is almost certainly in the DiagnosticsSquiggleTaggerProvider code.  If this
            // succeed, but other squiggle tests fail, then it is likely an issue with the
            // diagnostics engine not actually reporting all diagnostics properly.

            using var workspace = TestWorkspace.CreateCSharp(
                new string[] { "class A { }" },
                parseOptions: CSharpParseOptions.Default,
                composition: s_compositionWithMockDiagnosticService);

            var listenerProvider = workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>();

            var diagnosticService = Assert.IsType<MockDiagnosticService>(workspace.ExportProvider.GetExportedValue<IDiagnosticService>());
            var provider = workspace.ExportProvider.GetExportedValues<ITaggerProvider>().OfType<DiagnosticsSquiggleTaggerProvider>().Single();

            // Create and fire the diagnostic events before the tagger is even made.
            var tree = await workspace.CurrentSolution.Projects.Single().Documents.Single().GetRequiredSyntaxTreeAsync(CancellationToken.None);
            var span = TextSpan.FromBounds(0, 5);
            diagnosticService.CreateDiagnosticAndFireEvents(workspace, Location.Create(tree, span));

            var tagger = provider.CreateTagger<IErrorTag>(workspace.Documents.First().GetTextBuffer());
            Contract.ThrowIfNull(tagger);

            using var disposable = tagger as IDisposable;
            await listenerProvider.GetWaiter(FeatureAttribute.DiagnosticService).ExpeditedWaitAsync();
            await listenerProvider.GetWaiter(FeatureAttribute.ErrorSquiggles).ExpeditedWaitAsync();

            var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
            var spans = tagger.GetTags(snapshot.GetSnapshotSpanCollection()).ToList();
            Assert.Equal(1, spans.Count);
            Assert.Equal(span.ToSpan(), spans[0].Span.Span);
        }

        private class Analyzer : DiagnosticAnalyzer
        {
            private DiagnosticDescriptor _rule = new DiagnosticDescriptor("test", "test", "test", "test", DiagnosticSeverity.Error, true);

            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
            {
                get
                {
                    return ImmutableArray.Create(_rule);
                }
            }

            public override void Initialize(AnalysisContext context)
            {
                context.RegisterSyntaxTreeAction(c =>
                {
                    c.ReportDiagnostic(Diagnostic.Create(_rule, Location.Create(c.Tree, new TextSpan(0, 1))));
                });
            }

            public void ChangeSeverity()
                => _rule = new DiagnosticDescriptor("test", "test", "test", "test", DiagnosticSeverity.Warning, true);
        }
    }
}


text:
package io.netty.channel;

import static java.util.Objects.requireNonNull;

import io.netty.util.internal.StringUtil;

import java.lang.reflect.Constructor;

/**
 * A {@link ChannelFactory} that instantiates a new {@link Channel} by invoking its default constructor reflectively.
 */
public class ReflectiveChannelFactory<T extends Channel> implements ChannelFactory<T> {

    private final Constructor<? extends T> constructor;

    public ReflectiveChannelFactory(Class<? extends T> clazz) {
        requireNonNull(clazz, "clazz");
        try {
            this.constructor = clazz.getConstructor(EventLoop.class);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Class " + StringUtil.simpleClassName(clazz) +
                    " does not have a public constructor that takes an EventLoop instance", e);
        }
    }

    @Override
    public T newChannel(EventLoop eventLoop) throws Exception {
        try {
            return constructor.newInstance(eventLoop);
        } catch (Throwable t) {
            throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
        }
    }

    @Override
    public String toString() {
        return StringUtil.simpleClassName(ReflectiveChannelFactory.class) +
                '(' + StringUtil.simpleClassName(constructor.getDeclaringClass()) + ".class)";
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('data_request', '0005_pdfcontents'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='pdfcontents',
            name='content',
        ),
        migrations.AddField(
            model_name='pdfcontents',
            name='content1',
            field=models.TextField(blank=True, default='content eka'),
        ),
        migrations.AddField(
            model_name='pdfcontents',
            name='content2',
            field=models.TextField(blank=True, default='content toka'),
        ),
    ]


text:
"""
"""
from __future__ import unicode_literals
from django.conf.urls import patterns, url

from views import *

urlpatterns = patterns('',
    url(r'^list/$', FabricPackagesList.as_view(), name='fabric_packages_list'),
    url(r'^create/$', FabricPackagesCreate.as_view(), name='fabric_packages_create'),
    url(r'^(?P<pk>\d+)/$', FabricPackagesDetail.as_view(), name='fabric_packages_details'),
    url(r'^delete/(?P<pk>\d+)/$', FabricPackagesDelete.as_view(), name='fabric_packages_delete'),
    url(r'^update/(?P<pk>\d+)/$', FabricPackagesUpdate.as_view(), name='fabric_packages_update'),
)


text:
<?php

namespace Wbits\SoccerTeam\SoccerTeamBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SoccerTeamBundle extends Bundle
{
}


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_Addresses_Get_sync]
    using Google.Cloud.Compute.V1;

    public sealed partial class GeneratedAddressesClientSnippets
    {
        /// <summary>Snippet for Get</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void GetRequestObject()
        {
            // Create client
            AddressesClient addressesClient = AddressesClient.Create();
            // Initialize request argument(s)
            GetAddressRequest request = new GetAddressRequest
            {
                Region = "",
                Project = "",
                Address = "",
            };
            // Make the request
            Address response = addressesClient.Get(request);
        }
    }
    // [END compute_v1_generated_Addresses_Get_sync]
}


text:
package com.streamdata.apps.cryptochat.network;

import java.util.List;

/**
 * Generic string parser
 */
public interface Parser<T> {

    T parse(String data) throws Exception;
    List<T> parseArray(String data) throws Exception;
    String json(T data) throws Exception;
}


text:
import axios from 'axios';
const ROOT_URL = 'https://api.cryptonator.com/api/ticker/';
const TOP_URL = 'https://api.coinmarketcap.com/v1/ticker/?limit=20'
const TEST_URL= `https://cors-anywhere.herokuapp.com/http://api.coinmarketcap.com/v1/ticker/`;
const RANDOM_URL = 'https://cors-anywhere.herokuapp.com/http://www.cryptocompare.com/api/data/coinsnapshotfullbyid/?id='
const API_URL = 'http://localhost:3090;'

export const FETCH_CRYPTO = 'FETCH_CRYPTO';
export const TOP_CRYPTO = 'TOP_CRYPTO';
export const RANDOM_CRYPTO = 'RANDOM_CRYPTO';

export function fetchCrypto(ticker){
  const url = `${TEST_URL}${ticker}`;
  const request = axios.get(url);
  console.log('Request',request);

  return {
    type: FETCH_CRYPTO,
    payload: request,
  };
}

export function topCrypto(){
  const request = axios.get(TOP_URL);
  console.log('Request', request);
  return {
    type: TOP_CRYPTO,
    payload: request,
  };
}

export function randomCrypto(id){
  const url = `${RANDOM_URL}${id}`
  const request = axios.get(url);
  console.log('Request',request);

  return{
    type:RANDOM_CRYPTO,
    payload: request,
  }
}

export function signinUser( {email, password }){
  return function(dispatch){
    // submit email pw to server
    axios.post(`${API_URL}/signin`, {email, password});
    // if request is good
    // -update state to indicate user is authenticated
    // save jwt token
    // redirect to new route
    // if request is bad
    // show an error to the user
}

}


text:
package com.github.sviperll.repository4j.sql;

import java.sql.SQLException;

public interface WritableRaw {
    void setNull(String columnName, int sqlType) throws SQLException;

    void setInt(String columnName, int value) throws SQLException;

    void setLong(String columnName, long value) throws SQLException;

    void setString(String columnName, String value) throws SQLException;
}