text:
import { joinSQLFragments } from '../../utils/join-sql-fragments';
import { AbstractQueryGenerator } from '../abstract/query-generator';
import type { TableNameOrModel } from '../abstract/query-generator-typescript';

/**
 * Temporary class to ease the TypeScript migration
 */
export class Db2QueryGeneratorTypeScript extends AbstractQueryGenerator {
  describeTableQuery(tableName: TableNameOrModel) {
    const table = this.extractTableDetails(tableName);

    return joinSQLFragments([
      'SELECT NAME AS "Name", TBNAME AS "Table", TBCREATOR AS "Schema",',
      'TRIM(COLTYPE) AS "Type", LENGTH AS "Length", SCALE AS "Scale",',
      'NULLS AS "IsNull", DEFAULT AS "Default", COLNO AS "Colno",',
      'IDENTITY AS "IsIdentity", KEYSEQ AS "KeySeq", REMARKS AS "Comment"',
      'FROM',
      'SYSIBM.SYSCOLUMNS',
      `WHERE TBNAME = ${this.escape(table.tableName)}`,
      table.schema !== '' ? `AND TBCREATOR = ${this.escape(table.schema)}` : 'AND TBCREATOR = USER',
      ';',
    ]);
  }

  showIndexesQuery(tableName: TableNameOrModel) {
    const table = this.extractTableDetails(tableName);

    return joinSQLFragments([
      'SELECT NAME AS "name", TBNAME AS "tableName", UNIQUERULE AS "keyType",',
      'COLNAMES, INDEXTYPE AS "type" FROM SYSIBM.SYSINDEXES',
      `WHERE TBNAME = ${this.escape(table.tableName)}`,
      table.schema !== '' ? `AND TBCREATOR = ${this.escape(table.schema)}` : 'AND TBCREATOR = USER',
      'ORDER BY NAME;',
    ]);
  }
}


text:
namespace Scheduler
{
	class IterativeTSPSolver : public TSPSolver
	{
	public:
		IterativeTSPSolver(const TSPSolver& backend_solver, const ScheduleCostFunction& schedule_cost_function);

		virtual void optimize(Schedule& schedule) const override;
		virtual void optimize(Run& run) const override;

		static constexpr const char* staticGetName( )
		{
			return "Iterative";
		}
		virtual const char* getName( ) const override
		{
			return staticGetName( );
		};

		void setIterationsCount(std::size_t iterations_count);

	private:
		const TSPSolver& backend_solver;
		const ScheduleCostFunction& schedule_cost_function;
		std::size_t iterations_count;
		Logger& logger;
	};
}

redpajama_set_name: RedPajamaGithub


text:
Node JS discord bot

#Add bot to server
https://discordapp.com/oauth2/authorize?scope=bot&client_id=186528372149583872


text:
//=============================================================================
/**
 *  @file   ButcherProjectMaskContainerAreaMap.cpp
 *
 *  $Id$
 *
 *  @author Rangel Reale <rreale@bol.com.br>
 *  @date   2008-02-05
 */
//=============================================================================

#include "ButcherProjectMaskContainerAreaMap.h"
#include "ButcherProjectMask.h"

/////////////////////////////////
// CLASS
//      ButcherProjectMaskContainerAreaMap
/////////////////////////////////
ButcherProjectArea::areaflags_t ButcherProjectMaskContainerAreaMap::InternalGetFlags(
    ButcherProjectArea::areaflags_t curflags)
{
    ButcherProjectArea::areaflags_t nflags=ButcherProjectMaskContainerSplit::InternalGetFlags(curflags) & ~ButcherProjectArea::AF_HAVEIMAGE;
    return nflags;
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pestalotia antennaeformis B.J. Murray

### Remarks
null


text:
namespace kudu {
namespace rpc {

// Magic number bytes sent at connection setup time.
extern const char* const kMagicNumber;

// App name for SASL library init
extern const char* const kSaslAppName;

// Current version of the RPC protocol.
static const uint32_t kCurrentRpcVersion = 9;

// From Hadoop.
static const int32_t kInvalidCallId = -2;
static const int32_t kConnectionContextCallId = -3;
static const int32_t kNegotiateCallId = -33;

static const uint8_t kMagicNumberLength = 4;
static const uint8_t kHeaderFlagsLength = 3;

// There is a 4-byte length prefix before any packet.
static const uint8_t kMsgLengthPrefixLength = 4;

// The set of RPC features that this server build supports.
// Non-const for testing.
extern std::set<RpcFeatureFlag> kSupportedServerRpcFeatureFlags;

// The set of RPC features that this client build supports.
// Non-const for testing.
extern std::set<RpcFeatureFlag> kSupportedClientRpcFeatureFlags;

} // namespace rpc
} // namespace kudu


text:
import app from 'server';
import configure from 'qconf';

const config = configure();
const port = config.get('port') || 3000;

app.listen(port, () => app.log.info(`Listening on port ${port}`));


text:
from tests.testcase import TestCase
from edmunds.console.command import Command

class TestCommand(TestCase):
    """
    Test command
    """

    def test_no_abstract(self):
        """
        Test no abstract command
        :return:    void
        """

        with self.assert_raises_regexp(TypeError, 'Can\'t instantiate abstract class'):
            MyCommandNoAbsstract('test', self.app)

    def test_command(self):
        """
        Test command
        :return:    void
        """
        command_name = 'test'

        command = MyCommand(command_name, self.app)

        self.assert_equal_deep(command.name, command_name)
        self.assert_equal_deep(command.app, self.app)

class MyCommandNoAbsstract(Command):
    pass

class MyCommand(Command):

    def run(self, *args, **kwargs):
        pass


text:
package liquibase.diff.output.changelog.core;

import liquibase.change.Change;
import liquibase.change.ColumnConfig;
import liquibase.change.ConstraintsConfig;
import liquibase.change.core.CreateTableChange;
import liquibase.database.Database;
import liquibase.database.core.InformixDatabase;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.MySQLDatabase;
import liquibase.datatype.DataTypeFactory;
import liquibase.datatype.DatabaseDataType;
import liquibase.datatype.LiquibaseDataType;
import liquibase.datatype.core.DateTimeType;
import liquibase.diff.output.DiffOutputControl;
import liquibase.diff.output.changelog.ChangeGeneratorChain;
import liquibase.diff.output.changelog.MissingObjectChangeGenerator;
import liquibase.statement.DatabaseFunction;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.Column;
import liquibase.structure.core.PrimaryKey;
import liquibase.structure.core.Table;

import java.util.Date;

public class MissingTableChangeGenerator implements MissingObjectChangeGenerator {
    @Override
    public int getPriority(Class<? extends DatabaseObject> objectType, Database database) {
        if (Table.class.isAssignableFrom(objectType)) {
            return PRIORITY_DEFAULT;
        }
        return PRIORITY_NONE;
    }

    @Override
    public Class<? extends DatabaseObject>[] runAfterTypes() {
        return null;
    }

    @Override
    public Class<? extends DatabaseObject>[] runBeforeTypes() {
        return null;
    }

    @Override
    public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) {
        Table missingTable = (Table) missingObject;

        PrimaryKey primaryKey = missingTable.getPrimaryKey();

//        if (control.diffResult.getReferenceSnapshot().getDatabase().isLiquibaseTable(missingTable.getSchema().toCatalogAndSchema(), missingTable.getName())) {
//            continue;
//        }

        CreateTableChange change = createCreateTableChange();
        change.setTableName(missingTable.getName());
        if (control.getIncludeCatalog()) {
            change.setCatalogName(missingTable.getSchema().getCatalogName());
        }
        if (control.getIncludeSchema()) {
            change.setSchemaName(missingTable.getSchema().getName());
        }
        if (missingTable.getRemarks() != null) {
            change.setRemarks(missingTable.getRemarks());
        }

        for (Column column : missingTable.getColumns()) {
            ColumnConfig columnConfig = new ColumnConfig();
            columnConfig.setName(column.getName());
            LiquibaseDataType ldt = DataTypeFactory.getInstance().from(column.getType(), comparisonDatabase);
            DatabaseDataType ddt = ldt.toDatabaseDataType(referenceDatabase);
            String typeString = ddt.toString();
            if (referenceDatabase instanceof MSSQLDatabase) {
                typeString = referenceDatabase.unescapeDataTypeString(typeString);
            }
            columnConfig.setType(typeString);

            if (column.isAutoIncrement()) {
                columnConfig.setAutoIncrement(true);
            }

            ConstraintsConfig constraintsConfig = null;
            // In MySQL, the primary key must be specified at creation for an autoincrement column
            if (column.isAutoIncrement() && primaryKey != null && primaryKey.getColumnNamesAsList().contains(column.getName())) {
                constraintsConfig = new ConstraintsConfig();
                constraintsConfig.setPrimaryKey(true);
                constraintsConfig.setPrimaryKeyTablespace(primaryKey.getTablespace());
                // MySQL sets some primary key names as PRIMARY which is invalid
                if (comparisonDatabase instanceof MySQLDatabase && "PRIMARY".equals(primaryKey.getName())) {
                    constraintsConfig.setPrimaryKeyName(null);
                } else  {
                    constraintsConfig.setPrimaryKeyName(primaryKey.getName());
                }
                control.setAlreadyHandledMissing(primaryKey);
                control.setAlreadyHandledMissing(primaryKey.getBackingIndex());
            } else if (column.isNullable() != null && !column.isNullable()) {
                constraintsConfig = new ConstraintsConfig();
                constraintsConfig.setNullable(false);
            }

            if (constraintsConfig != null) {
                columnConfig.setConstraints(constraintsConfig);
            }

            setDefaultValue(columnConfig, column, referenceDatabase);

            if (column.getRemarks() != null) {
                columnConfig.setRemarks(column.getRemarks());
            }

            change.addColumn(columnConfig);
            control.setAlreadyHandledMissing(column);
        }

        return new Change[] {
                change
        };
    }

    public static void setDefaultValue(ColumnConfig columnConfig, Column column, Database database) {
        LiquibaseDataType dataType = DataTypeFactory.getInstance().from(column.getType(), database);

        Object defaultValue = column.getDefaultValue();
        if (defaultValue == null) {
            // do nothing
        } else if (column.isAutoIncrement()) {
            // do nothing
        } else if (defaultValue instanceof Date) {
            columnConfig.setDefaultValueDate((Date) defaultValue);
        } else if (defaultValue instanceof Boolean) {
            columnConfig.setDefaultValueBoolean(((Boolean) defaultValue));
        } else if (defaultValue instanceof Number) {
            columnConfig.setDefaultValueNumeric(((Number) defaultValue));
        } else if (defaultValue instanceof DatabaseFunction) {

            DatabaseFunction function = (DatabaseFunction) defaultValue;
            if ("current".equals(function.getValue())) {
              if (database instanceof InformixDatabase) {
                if (dataType instanceof DateTimeType) {
                  if (dataType.getAdditionalInformation() == null || dataType.getAdditionalInformation().length() == 0) {
                    if (dataType.getParameters() != null && dataType.getParameters().length > 0) {

                      String parameter = String.valueOf(dataType.getParameters()[0]);

                      if ("4365".equals(parameter)) {
                        function = new DatabaseFunction("current year to fraction(3)");
                      }

                      if ("3594".equals(parameter)) {
                        function = new DatabaseFunction("current year to second");
                      }

                      if ("3080".equals(parameter)) {
                        function = new DatabaseFunction("current year to minute");
                      }

                      if ("2052".equals(parameter)) {
                        function = new DatabaseFunction("current year to day");
                      }
                    }
                  }
                }
              }
            }

            columnConfig.setDefaultValueComputed(function);
        } else {
            String defaultValueString = null;
            try {
                defaultValueString = DataTypeFactory.getInstance().from(column.getType(), database).objectToSql(defaultValue, database);
            } catch (NullPointerException e) {
                throw e;
            }
            if (defaultValueString != null) {
                defaultValueString = defaultValueString.replaceFirst("'",
                        "").replaceAll("'$", "");
            }

            columnConfig.setDefaultValue(defaultValueString);
        }
    }

    protected CreateTableChange createCreateTableChange() {
        return new CreateTableChange();
    }
}


text:
"""
This script creates and configures a linux network namespace such that an
application can be executed under the context of a virtualized network.
"""

import argparse
import socket
import sys

from instance_provisioner import Provisioner
from lxc_manager import LxcManager
from vrouter_control import interface_register

def build_network_name(project_name, network_name):
    if network_name.find(':') >= 0:
        return network_name
    return "%s:%s" % (project_name, network_name)

def get_project_name(project_name, network_name):
    network_fq_name = network_name.split(':')
    if len(network_fq_name) >= 0:
        return network_fq_name[-2]
    else:
        project_fq_name = project_name.split(':')
        return project_fq_name[-1]

def daemon_start():
    """
    Creates a virtual-machine and vmi object in the API server.
    Creates a namespace and a veth interface pair.
    Associates the veth interface in the master instance with the vrouter.
    """
    parser = argparse.ArgumentParser()
    defaults = {
        'username': None,
        'password': None,
        'api-server': '127.0.0.1',
        'api-port': 8082,
        'project': 'default-domain:default-project',
        'network': 'default-network',
        'monitor' : False,
    }
    parser.set_defaults(**defaults)
    parser.add_argument("-U", "--username", help="Username of the tenant")
    parser.add_argument("-P", "--password", help="Password for the user")
    parser.add_argument("-s", "--api-server", help="API server address")
    parser.add_argument("-p", "--api-port", type=int, help="API server port")
    parser.add_argument("--project", help="OpenStack project name")
    parser.add_argument("-n", "--network", help="Primary network")
    parser.add_argument("-o", "--outbound", help="Outbound traffic network")
    '''
    --monitor is maintained only for backward compatibility. Replug of vif's
    across vrouter-agent is not required anymore as vif info is persisted in
    files which are read upon vrouter-agent start.
    '''
    parser.add_argument("-M", "--monitor", action='store_true',
                        help="Monitor the vrouter agent connection to replug the vif's.")
    parser.add_argument("daemon", help="Deamon Name")

    arguments = parser.parse_args(sys.argv[1:])

    manager = LxcManager()
    project_name = get_project_name(arguments.project, arguments.network)
    provisioner = Provisioner(username=arguments.username,
                              password=arguments.password,
                              api_server=arguments.api_server,
                              api_port=arguments.api_port,
                              project=project_name)
    vrouter_name = socket.getfqdn()
    instance_name = '%s-%s' % (vrouter_name, arguments.daemon)
    vm = provisioner.virtual_machine_locate(vrouter_name, instance_name)

    network = build_network_name(arguments.project, arguments.network)

    vmi, project = provisioner.vmi_locate(vm, network, 'veth0')
    vmi_out = None
    if arguments.outbound:
        outbound_name = build_network_name(arguments.project,
                                           arguments.outbound)
        vmi_out, project = provisioner.vmi_locate(vm, outbound_name, 'veth1')

    manager.namespace_init(arguments.daemon)
    ifname = manager.interface_update(arguments.daemon, vmi, 'veth0')
    interface_register(vm, vmi, ifname, project=project)

    vmi_out_kwargs = {}
    if vmi_out:
        ifname = manager.interface_update(arguments.daemon, vmi_out, 'veth1')
        interface_register(vm, vmi_out, ifname, project=project)
        vmi_out_kwargs = {'vmi_out' : vmi_out,
                          'ifname_out' : ifname
                         }

    single_interface = (arguments.outbound is None)
    ip_prefix = provisioner.get_interface_ip_prefix(vmi)
    manager.interface_config(arguments.daemon, 'veth0',
                             advertise_default=single_interface,
                             ip_prefix=ip_prefix)
    if vmi_out:
        manager.interface_config(arguments.daemon, 'veth1')

# end daemon_start

if __name__ == '__main__':
    daemon_start()


text:
from sets import Set

#stores all the page data
class Page():
    def __init__(self, details):
        self.id = details['id']
        self.url = details['url']
        self.website = details['website']
        self.homepage = details['home']
        self.links = Set()

    def isHomepage(self):
        return self.homepage

    def getWebId(self):
        return self.website

    def isHomepage(self):
        return self.homepage

    def addLink(self,to):
        self.links.add(to)

    def getLinks(self):
        return self.links

    def getPageId(self):
        return self.id


text:
#ifndef SourceAlpha_h
#define SourceAlpha_h

#include "platform/graphics/filters/Filter.h"
#include "platform/graphics/filters/FilterEffect.h"

namespace WebCore {

class PLATFORM_EXPORT SourceAlpha : public FilterEffect {
public:
    static PassRefPtr<SourceAlpha> create(Filter*);

    static const AtomicString& effectName();

    virtual void determineAbsolutePaintRect();

    virtual FilterEffectType filterEffectType() const { return FilterEffectTypeSourceInput; }

    virtual TextStream& externalRepresentation(TextStream&, int indention) const;

private:
    SourceAlpha(Filter* filter)
        : FilterEffect(filter)
    {
    }

    virtual void applySoftware() OVERRIDE;
};

} // namespace WebCore

#endif // SourceAlpha_h


text:
import pickle
from section_cmab.agent import Agent
from section_cmab.algorithms.lp_solvers import primal_dual_recover
from display_rewards.rewards import display_single_

def simulate_with_(algorithm, run=False, config=None, circles=200, perf_file=None, optimal=False, **kwargs):
    """
    Simulate with parameters.

    Args:
        algorithm(function): algorithm
        run(boolean): whether to run new algorithm
        config(string): config path
        circles(int): circles
        perf_file(string): performance file
        optimal(boolean): whether to find the optimal

    """
    perf_file = perf_file or '../performance/rewards.pk'
    if run:
        config = config or '../cfg/default.cfg'
        agent = Agent.from_(config)
        if optimal:
            perf_file = agent.find_optimal_with_bnd_(algorithm, circles=circles)
        else:
            perf_file = agent.iter_with_(algorithm, circles=circles)
    rewards = pickle.load(open(perf_file, 'r+'))
    display_single_(rewards, **kwargs)

if __name__ == '__main__':
    config_path = '../cfg/algo_comp.cfg'
    current_algorithm = primal_dual_recover
    # current_algorithm = branch_and_bound
    simulate_with_(current_algorithm, optimal=False, run=True, config=config_path,
                   circles=30, all_curves=False, length=500, line_width=1.8,
                   title_size=20, label_size=16, color='#1E90FF')


text:
package com.at.graph.spring_data_neo4j.domain;

import java.util.Collection;

import org.neo4j.ogm.annotation.EndNode;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.Property;
import org.neo4j.ogm.annotation.RelationshipEntity;
import org.neo4j.ogm.annotation.StartNode;

import lombok.Data;

@Data
@RelationshipEntity(type = "ACTED_IN")
public class ActedIn{
    @Id @GeneratedValue
    private Long id;

	@Property(name="roles")
	private Collection<String> roles;
	@StartNode
	private Person person;
	@EndNode
	private Movie movie;
}


text:
package siteservice

import (
	"bytes"
	"net/http"
	"strconv"

	"github.com/gorilla/mux"
	"github.com/gorilla/sessions"
	"github.com/itsyouonline/identityserver/communication"
	"github.com/itsyouonline/identityserver/siteservice/apiconsole"
	"github.com/itsyouonline/identityserver/siteservice/middleware"
	"github.com/itsyouonline/identityserver/siteservice/website/packaged/assets"
	"github.com/itsyouonline/identityserver/siteservice/website/packaged/components"
	"github.com/itsyouonline/identityserver/siteservice/website/packaged/html"
	"github.com/itsyouonline/identityserver/siteservice/website/packaged/thirdpartyassets"
	"github.com/itsyouonline/identityserver/specifications"
	"github.com/itsyouonline/identityserver/validation"
	"github.com/justinas/alice"

	"encoding/json"

	log "github.com/Sirupsen/logrus"
	"github.com/itsyouonline/identityserver/credentials/totp"
	"github.com/itsyouonline/identityserver/identityservice"
	"github.com/itsyouonline/identityserver/tools/assetfs"
)

//Service is the identityserver http service
type Service struct {
	Sessions                      map[SessionType]*sessions.CookieStore
	smsService                    communication.SMSService
	phonenumberValidationService  *validation.IYOPhonenumberValidationService
	EmailService                  communication.EmailService
	emailaddressValidationService *validation.IYOEmailAddressValidationService
	version                       string
	testEnv                       bool
	identityService               *identityservice.Service
}

//NewService creates and initializes a Service
func NewService(cookieSecret string, smsService communication.SMSService, emailService communication.EmailService,
	identityservice *identityservice.Service, version string, testEnv bool) (service *Service) {
	service = &Service{smsService: smsService}

	p := &validation.IYOPhonenumberValidationService{SMSService: smsService}
	service.phonenumberValidationService = p
	e := &validation.IYOEmailAddressValidationService{EmailService: emailService}
	service.emailaddressValidationService = e

	service.identityService = identityservice

	service.version = version

	service.testEnv = testEnv

	service.initializeSessions(cookieSecret)
	return
}

//InitModels initialize persistance models
func (service *Service) InitModels() {
	service.initLoginModels()
}

//AddRoutes registers the http routes with the router
func (service *Service) AddRoutes(router *mux.Router) {
	router.Methods("GET").Path("/").HandlerFunc(service.HomePage)
	//Registration form
	router.Methods("GET").Path("/register").HandlerFunc(service.ShowRegistrationForm)
	router.Methods("POST").Path("/register").HandlerFunc(service.ProcessRegistrationForm)
	router.Methods("GET").Path("/phonevalidation").HandlerFunc(service.PhonenumberValidation)
	router.Methods("GET").Path("/phoneregistrationvalidation").HandlerFunc(service.PhonenumberRegistrationValidation)
	router.Methods("GET").Path("/pvl").HandlerFunc(service.PhonenumberValidationAndLogin)
	router.Methods("GET").Path("/emailvalidation").HandlerFunc(service.EmailValidation)
	router.Methods("GET").Path("/emailregistrationvalidation").HandlerFunc(service.EmailRegistrationValidation)
	router.Methods("GET").Path("/register/smsconfirmed").HandlerFunc(service.CheckRegistrationSMSConfirmation)
	router.Methods("GET").Path("/register/emailconfirmed").HandlerFunc(service.CheckRegistrationEmailConfirmation)
	router.Methods("POST").Path("/register/smsconfirmation").HandlerFunc(service.ProcessPhonenumberConfirmationForm)
	router.Methods("POST").Path("/register/validation").HandlerFunc(service.ValidateInfo)
	router.Handle("/register/resendvalidation", alice.New(middleware.RateLimit(middleware.DefaultRateLimitPeriod, middleware.DefaultRateLimit).Handler).Then(http.HandlerFunc(service.ResendValidationInfo))).Methods("POST")
	//Enable us to "forget" users in case we are not in production
	router.Methods("GET").Path("/register/delete").HandlerFunc(service.ServeForgetAccountPage)
	router.Methods("POST").Path("/register/delete").HandlerFunc(service.ForgetAccountHandler)
	//Login forms
	router.Methods("GET").Path("/login").HandlerFunc(service.ShowLoginForm)
	router.Methods("POST").Path("/login").HandlerFunc(service.ProcessLoginForm)
	router.Methods("GET").Path("/login/twofamethods").HandlerFunc(service.GetTwoFactorAuthenticationMethods)
	router.Methods("POST").Path("/login/totpconfirmation").HandlerFunc(service.ProcessTOTPConfirmation)
	router.Handle("/login/smscode/{phoneLabel}", alice.New(middleware.RateLimit(middleware.DefaultRateLimitPeriod, middleware.DefaultRateLimit).Handler).Then(http.HandlerFunc(service.GetSmsCode))).Methods("POST")
	router.Methods("POST").Path("/login/smsconfirmation").HandlerFunc(service.Process2FASMSConfirmation)
	router.Handle("/login/resendsms", alice.New(middleware.RateLimit(middleware.DefaultRateLimitPeriod, middleware.DefaultRateLimit).Handler).Then(http.HandlerFunc(service.LoginResendPhonenumberConfirmation))).Methods("POST")
	router.Methods("GET").Path("/sc").HandlerFunc(service.MobileSMSConfirmation)
	router.Methods("GET").Path("/login/smsconfirmed").HandlerFunc(service.Check2FASMSConfirmation)
	router.Methods("POST").Path("/login/validateemail").HandlerFunc(service.ValidateEmail)
	router.Methods("POST").Path("/login/forgotpassword").HandlerFunc(service.ForgotPassword)
	router.Methods("POST").Path("/login/resetpassword").HandlerFunc(service.ResetPassword)
	router.Methods("GET").Path("/login/organizationinvitation/{code}").HandlerFunc(service.GetOrganizationInvitation)
	//Authorize form
	router.Methods("GET").Path("/authorize").HandlerFunc(service.ShowAuthorizeForm)
	//Facebook callback
	router.Methods("GET").Path("/facebook_callback").HandlerFunc(service.FacebookCallback)
	//Github callback
	router.Methods("GET").Path("/github_callback").HandlerFunc(service.GithubCallback)
	//Logout link
	router.Methods("GET").Path("/logout").HandlerFunc(service.Logout)
	//Error page
	router.Methods("GET").Path("/error").HandlerFunc(service.ErrorPage)
	router.Methods("GET").Path("/error{errornumber}").HandlerFunc(service.ErrorPage)
	router.Methods("GET").Path("/config").HandlerFunc(service.GetConfig)

	router.Methods("GET").Path("/version").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		response := struct {
			Version string
		}{
			Version: service.version,
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(&response)
	})

	router.Methods("GET").Path("/location").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Get the header from the cloudflare IP Geolocation service. Value is the
		// country code in ISO 3166-1 Alpha 2 format.
		location := r.Header.Get("CF-IPCountry")
		log.Debug("request location: ", location)
		response := struct {
			Location string `json:"location"`
		}{
			Location: location,
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(&response)
	})

	//host the assets used in the htmlpages
	router.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/", http.FileServer(
		&assetfs.AssetFS{Asset: assets.Asset, AssetDir: assets.AssetDir, AssetInfo: assets.AssetInfo})))
	router.PathPrefix("/thirdpartyassets/").Handler(http.StripPrefix("/thirdpartyassets/", http.FileServer(
		&assetfs.AssetFS{Asset: thirdpartyassets.Asset, AssetDir: thirdpartyassets.AssetDir, AssetInfo: thirdpartyassets.AssetInfo})))
	router.PathPrefix("/components/").Handler(http.StripPrefix("/components/", http.FileServer(
		&assetfs.AssetFS{Asset: components.Asset, AssetDir: components.AssetDir, AssetInfo: components.AssetInfo})))

	//host the apidocumentation
	router.Methods("GET").Path("/apidocumentation").HandlerFunc(service.APIDocs)
	router.PathPrefix("/apidocumentation/raml/").Handler(http.StripPrefix("/apidocumentation/raml", http.FileServer(
		&assetfs.AssetFS{Asset: specifications.Asset, AssetDir: specifications.AssetDir, AssetInfo: specifications.AssetInfo})))
	router.PathPrefix("/apidocumentation/").Handler(http.StripPrefix("/apidocumentation/", http.FileServer(
		&assetfs.AssetFS{Asset: apiconsole.Asset, AssetDir: apiconsole.AssetDir, AssetInfo: apiconsole.AssetInfo})))

}

const (
	mainpageFileName      = "index.html"
	homepageFileName      = "base.html"
	errorpageFilename     = "error.html"
	apidocsPageFilename   = "apidocumentation.html"
	smsconfirmationPage   = "smsconfirmation.html"
	emailconfirmationPage = "emailconfirmation.html"
)

//ShowPublicSite shows the public website
func (service *Service) ShowPublicSite(w http.ResponseWriter, request *http.Request) {
	htmlData, err := html.Asset(mainpageFileName)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	w.Write(htmlData)
}

//APIDocs shows the api documentation
func (service *Service) APIDocs(w http.ResponseWriter, request *http.Request) {
	htmlData, err := html.Asset(apidocsPageFilename)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	w.Write(htmlData)
}

//HomePage shows the home page when logged in, if not, delegate to showing the public website
func (service *Service) HomePage(w http.ResponseWriter, request *http.Request) {

	loggedinuser, err := service.GetLoggedInUser(request, w)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if loggedinuser == "" {
		service.ShowPublicSite(w, request)
		return
	}

	htmlData, err := html.Asset(homepageFileName)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	sessions.Save(request, w)
	w.Write(htmlData)
}

//Logout logs out the user and redirect to the homepage
//TODO: csrf protection, really important here!
func (service *Service) Logout(w http.ResponseWriter, request *http.Request) {
	service.SetLoggedInUser(w, request, "")
	sessions.Save(request, w)
	http.Redirect(w, request, "", http.StatusFound)
}

//ErrorPage shows the errorpage
func (service *Service) ErrorPage(w http.ResponseWriter, request *http.Request) {
	errornumber := mux.Vars(request)["errornumber"]
	log.Debug("Errorpage requested for error ", errornumber)

	htmlData, err := html.Asset(errorpageFilename)
	if err != nil {
		log.Error("ERROR rendering error page: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	// check if the error is a number to prevent XSS attacks
	errorcode, err := strconv.Atoi(errornumber)
	if err != nil {
		log.Info("Error code could not be converted to int")
		// The error page already loaded so we might as well use it
		errorcode = 400
		errornumber = "400"
	}

	// check if the error code is within the accepted 4xx client or 5xx server error range
	if errorcode > 599 || errorcode < 400 {
		log.Info("Error code out of bounds: ", errorcode)
		errorcode = 400
		errornumber = "400"
	}

	// now that we confirmed the error code is valid, we can safely use it to display on the error page
	htmlData = bytes.Replace(htmlData, []byte(`500`), []byte(errornumber), 1)
	w.Write(htmlData)
}

//renderSMSConfirmationPage renders a small mobile friendly confirmation page after a user follows a link in an sms
func (service *Service) renderSMSConfirmationPage(w http.ResponseWriter, request *http.Request, text string, extratext string) {
	htmlData, err := html.Asset(smsconfirmationPage)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	htmlData = bytes.Replace(htmlData, []byte(`{{ text }}`), []byte(text), 1)
	htmlData = bytes.Replace(htmlData, []byte(`{{ extratext }}`), []byte(extratext), 1)
	sessions.Save(request, w)
	w.Write(htmlData)
}

//renderEmailConfirmationPage renders a small mobile friendly confirmation page after a user follows a link in an email
func (service *Service) renderEmailConfirmationPage(w http.ResponseWriter, request *http.Request, text string, extratext string) {
	htmlData, err := html.Asset(emailconfirmationPage)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	htmlData = bytes.Replace(htmlData, []byte(`{{ text }}`), []byte(text), 1)
	htmlData = bytes.Replace(htmlData, []byte(`{{ extratext }}`), []byte(extratext), 1)
	sessions.Save(request, w)
	w.Write(htmlData)
}

func (service *Service) GetConfig(w http.ResponseWriter, request *http.Request) {
	token, err := totp.NewToken()
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	totpsession, err := service.GetSession(request, SessionForRegistration, "totp")
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	totpsession.Values["secret"] = token.Secret
	sessions.Save(request, w)
	data := struct {
		TotpIssuer       string `json:"totpissuer"`
		TotpSecret       string `json:"totpsecret"`
		GithubClientId   string `json:"githubclientid"`
		FacebookClientId string `json:"facebookclientid"`
	}{
		TotpIssuer: totp.GetIssuer(request),
		TotpSecret: token.Secret,
	}
	data.GithubClientId, _ = identityservice.GetOauthClientID("github")
	data.FacebookClientId, _ = identityservice.GetOauthClientID("facebook")
	json.NewEncoder(w).Encode(&data)
}


text:
package org.sagebionetworks.table.query.model;

/**
 * StringValueExpression ::= {@link CharacterValueExpression} | <bit value expression>
 */
public class StringValueExpression extends SimpleBranch {

	public StringValueExpression(
			CharacterValueExpression characterValueExpression) {
		super(characterValueExpression);
	}

}


text:
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >

    <scale
        android:duration="400"
        android:fromXScale="1.0"
        android:fromYScale="1.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toXScale="0.5"
        android:toYScale="0.5" />

    <alpha
        android:duration="400"
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />

</set>


text:
/*
 *
 */
package net.community.chest.ui.helpers.filechooser;

import java.io.File;
import java.io.FilenameFilter;

import net.community.chest.CoVariantReturn;
import net.community.chest.dom.DOMUtils;
import net.community.chest.io.filter.AbstractRootFolderFilesFilter;
import net.community.chest.lang.StringUtil;
import net.community.chest.reflect.ClassUtil;

import org.w3c.dom.Element;

/**
 *
Copyright 2008 as per GPLv2

 *
 *
Uses only one filename pattern

 * @author Lyor G.
 * @since Aug 14, 2008 11:19:46 AM
 */
public class FixedFilenameFilter extends AbstractRootFolderFilesFilter {
    private String    _fileName    /* =null */;
    public String getFileName ()
    {
        return _fileName;
    }

    public void setFileName (String fileName)
    {
        _fileName = fileName;
    }

    public FixedFilenameFilter (String description, String fileName, boolean caseSensitive)
    {
        _fileName = fileName;
        setDescription(description);
        setCaseSensitive(caseSensitive);
    }

    public FixedFilenameFilter (String description, String fileName)
    {
        this(description, fileName, false);
    }

    public FixedFilenameFilter (String fileName, boolean caseSensitive)
    {
        this(null, fileName, caseSensitive);
    }

    public FixedFilenameFilter (String fileName)
    {
        this(fileName, false);
    }

    public FixedFilenameFilter (boolean caseSensitive)
    {
        this(null, caseSensitive);
    }

    public FixedFilenameFilter ()
    {
        this(false);
    }
    /*
     * @see javax.swing.filechooser.FileFilter#accept(java.io.File)
     */
    @Override
    public boolean accept (final File f)
    {
        if (!super.accept(f))
            return false;

        if (!f.isFile())
            return true;

        final String    name=f.getName(), fixedName=getFileName();
        if ((null == fixedName) || (fixedName.length() <= 0))
            return false;    // if no specific name set accept nothing

        return (0 == StringUtil.compareDataStrings(name, fixedName, isCaseSensitive()));
    }

    public static final String    FILENAME_ATTR="fileName";
    public String setFileName (Element elem)
    {
        final String    n=elem.getAttribute(FILENAME_ATTR);
        if ((n != null) && (n.length() > 0))
            setFileName(n);

        return n;
    }
    /*
     * @see net.community.chest.swing.component.filechooser.BaseFileFilter#fromXml(org.w3c.dom.Element)
     */
    @Override
    @CoVariantReturn
    public FixedFilenameFilter fromXml (final Element elem) throws Exception
    {
        final FilenameFilter    f=super.fromXml(elem);
        if (f != this)
            throw new IllegalStateException("fromXml(" + DOMUtils.toString(elem) + " mismatched recovered instance");

        setFileName(elem);
        return this;
    }

    public FixedFilenameFilter (final Element elem) throws Exception
    {
        final FixedFilenameFilter    f=fromXml(elem);
        if (f != this)
            throw new IllegalStateException(ClassUtil.getConstructorExceptionLocation(getClass()) + " mismatched recovered instance");
    }
}


text:
import time
import json
from flask import request
from flask_restful import abort
from redash import models
from redash.wsgi import api
from redash.permissions import require_admin, require_permission
from redash.handlers.base import BaseResource, get_object_or_404

class GroupListResource(BaseResource):
    @require_admin
    def post(self):
        name = request.json['name']
        group = models.Group.create(name=name, org=self.current_org)

        self.record_event({
            'action': 'create',
            'timestamp': int(time.time()),
            'object_id': group.id,
            'object_type': 'group'
        })

        return group.to_dict()

    def get(self):
        if self.current_user.has_permission('admin'):
            groups = models.Group.all(self.current_org)
        else:
            groups = models.Group.select().where(models.Group.id << self.current_user.groups)

        return [g.to_dict() for g in groups]

class GroupResource(BaseResource):
    @require_admin
    def post(self, group_id):
        group = models.Group.get_by_id_and_org(group_id, self.current_org)

        if group.type == models.Group.BUILTIN_GROUP:
            abort(400, message="Can't modify built-in groups.")

        group.name = request.json['name']
        group.save()

        self.record_event({
            'action': 'edit',
            'timestamp': int(time.time()),
            'object_id': group.id,
            'object_type': 'group'
        })

        return group.to_dict()

    def get(self, group_id):
        print 'group_id : ',group_id
        if group_id.isdigit():
            if not (self.current_user.has_permission('admin') or int(group_id) in self.current_user.groups):
                abort(403)

            group = models.Group.get_by_id_and_org(group_id, self.current_org)

            return group.to_dict()
        elif group_id and group_id != 'undefined':
            group_id_list = json.loads(group_id)
            groups = models.Group.select().where(models.Group.id << group_id_list)
            return [g.to_dict() for g in groups]
        return ''

    @require_admin
    def delete(self, group_id):
        group = models.Group.get_by_id_and_org(group_id, self.current_org)
        if group.type == models.Group.BUILTIN_GROUP:
            abort(400, message="Can't delete built-in groups.")

        group.delete_instance(recursive=True)

class GroupMemberListResource(BaseResource):
    @require_admin
    def post(self, group_id):
        user_id = request.json['user_id']
        user = models.User.get_by_id_and_org(user_id, self.current_org)
        group = models.Group.get_by_id_and_org(group_id, self.current_org)
        user.groups.append(group.id)
        user.save()

        self.record_event({
            'action': 'add_member',
            'timestamp': int(time.time()),
            'object_id': group.id,
            'object_type': 'group',
            'member_id': user.id
        })

        return user.to_dict()

    @require_permission('list_users')
    def get(self, group_id):
        if not (self.current_user.has_permission('admin') or int(group_id) in self.current_user.groups):
            abort(403)

        members = models.Group.members(group_id)
        return [m.to_dict() for m in members]

class GroupMemberResource(BaseResource):
    @require_admin
    def delete(self, group_id, user_id):
        user = models.User.get_by_id_and_org(user_id, self.current_org)
        user.groups.remove(int(group_id))
        user.save()

        self.record_event({
            'action': 'remove_member',
            'timestamp': int(time.time()),
            'object_id': group_id,
            'object_type': 'group',
            'member_id': user.id
        })

class GroupDataSourceListResource(BaseResource):
    @require_admin
    def post(self, group_id):
        data_source_id = request.json['data_source_id']
        data_source = models.DataSource.get_by_id_and_org(data_source_id, self.current_org)
        group = models.Group.get_by_id_and_org(group_id, self.current_org)

        data_source.add_group(group)

        self.record_event({
            'action': 'add_data_source',
            'timestamp': int(time.time()),
            'object_id': group_id,
            'object_type': 'group',
            'member_id': data_source.id
        })

        return data_source.to_dict(with_permissions=True)

    @require_admin
    def get(self, group_id):
        group = get_object_or_404(models.Group.get_by_id_and_org, group_id, self.current_org)

        # TOOD: move to models
        data_sources = models.DataSource.select(models.DataSource, models.DataSourceGroup.view_only)\
            .join(models.DataSourceGroup)\
            .where(models.DataSourceGroup.group == group)

        return [ds.to_dict(with_permissions=True) for ds in data_sources]

class GroupDataSourceResource(BaseResource):
    @require_admin
    def post(self, group_id, data_source_id):
        data_source = models.DataSource.get_by_id_and_org(data_source_id, self.current_org)
        group = models.Group.get_by_id_and_org(group_id, self.current_org)
        view_only = request.json['view_only']

        data_source.update_group_permission(group, view_only)

        self.record_event({
            'action': 'change_data_source_permission',
            'timestamp': int(time.time()),
            'object_id': group_id,
            'object_type': 'group',
            'member_id': data_source.id,
            'view_only': view_only
        })

        return data_source.to_dict(with_permissions=True)

    @require_admin
    def delete(self, group_id, data_source_id):
        data_source = models.DataSource.get_by_id_and_org(data_source_id, self.current_org)
        group = models.Group.get_by_id_and_org(group_id, self.current_org)

        data_source.remove_group(group)

        self.record_event({
            'action': 'remove_data_source',
            'timestamp': int(time.time()),
            'object_id': group_id,
            'object_type': 'group',
            'member_id': data_source.id
        })

api.add_org_resource(GroupListResource, '/api/groups', endpoint='groups')
api.add_org_resource(GroupResource, '/api/groups/<group_id>', endpoint='group')
api.add_org_resource(GroupMemberListResource, '/api/groups/<group_id>/members', endpoint='group_members')
api.add_org_resource(GroupMemberResource, '/api/groups/<group_id>/members/<user_id>', endpoint='group_member')
api.add_org_resource(GroupDataSourceListResource, '/api/groups/<group_id>/data_sources', endpoint='group_data_sources')
api.add_org_resource(GroupDataSourceResource, '/api/groups/<group_id>/data_sources/<data_source_id>', endpoint='group_data_source')


text:
<?php

namespace Symfony\Component\Security\Csrf\TokenGenerator;

/**
 * Generates CSRF tokens.
 *
 * @author Bernhard Schussek <bernhard.schussek@symfony.com>
 */
class UriSafeTokenGenerator implements TokenGeneratorInterface
{
    private int $entropy;

    /**
     * Generates URI-safe CSRF tokens.
     *
     * @param int $entropy The amount of entropy collected for each token (in bits)
     */
    public function __construct(int $entropy = 256)
    {
        $this->entropy = $entropy;
    }

    /**
     * {@inheritdoc}
     */
    public function generateToken(): string
    {
        // Generate an URI safe base64 encoded string that does not contain "+",
        // "/" or "=" which need to be URL encoded and make URLs unnecessarily
        // longer.
        $bytes = random_bytes($this->entropy / 8);

        return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
    }
}


text:
package id.gits.dprkita.utils;

/**
 * Created by yatnosudar on 3/11/15.
 */
public interface ProgressListener {
    public void onStopProgress();

    public void onStartProgress();
}


text:
package com.jmperezra.solidadapter.view.football.viewmodels;

import com.jmperezra.solidadapter.view.football.visitable.ItemVisitable;
import com.jmperezra.solidadapter.view.football.visitable.TypeViewModelFactory;

public class StadiumViewModel implements ItemVisitable {

    public final String name;
    public final String image;
    public final String capacity;

    public StadiumViewModel(String name, String image, String capacity) {
        this.name = name;
        this.image = image;
        this.capacity = capacity;
    }

    @Override
    public int type(TypeViewModelFactory typeViewModelFactory) {
        return typeViewModelFactory.type(this);
    }
}


text:
<!DOCTYPE html>

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

    <link rel="shortcut icon" type="image/x-icon" href="/assets/images/favicon.png">

    <title>GSOC Journey - Midterm</title>
    <meta name="description"
          content="Yeah, 28th of June it is, Google will either make a decision to end my GSOC journey or pay me the biggest check of my life.Google chose the latter one. I pas...">

    <link rel="canonical" href="http://localhost:4000/gsoc/2016/06/29/GSOC-Journey-Midterm.html">
    <link rel="alternate" type="application/rss+xml" title="Saurabh Shah" href="http://localhost:4000/feed.xml">

    <link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="/bower_components/octicons/octicons/octicons.css">
    <link rel="stylesheet" href="/bower_components/hover/css/hover-min.css">
    <link rel="stylesheet" href="/bower_components/primer-markdown/dist/user-content.min.css">
    <link rel="stylesheet" href="/assets/css/syntax.css">

    <link rel="stylesheet" href="/assets/css/common.css">

    <link rel="stylesheet" href="/assets/css/sidebar-post-nav.css">

                Home

                Open-Source

                Blogs

                About

GSOC Journey - Midterm

                 2016/06/29

            <s>Yeah, 28th of June it is, Google will either make a decision to end my GSOC journey or pay me the biggest check of my life.</s>

Google chose the latter one. I passed! 52 conversations, personal messages and tonnes of github discussions, this was brainstorming. So on this day I decided to jot down the bittersweet memories which has impacted my life greatly.

Man of the hour

23rd April turned out to be the biggest day of my life. Getting selected for Google Summer of Code is the biggest victory ever achieved. This marked the end of continuous grapple and beginning of fresh journey. This day I realized that GSOC is not just an internship which provides a huge lot of money. It presents the opportunity to work with someone who is far more experienced and intelligent than me. I get the chance to work with  an exceptional organization and contribute a real world software. GSOC for me was full of sacrifices which turned glory.

First hurdle

I am not a long time contributer of open source world. I started contributing open source with the soul purpose of cracking GSOC. So getting selected in Ruby organization was a serious challenge.
Let's start by quoting my mentor's first message :

" Congrats on being accepted!
For a start, we should start thinking about how we would be able to quickly benchmark across multiple commits.
From my previous discussions with @sam, we want to build a docker image for each commit made to Ruby and tag it with the commit's SHA1. So a few things to think about here:
How can we automate the building of those images?
How do we build each image fast? (One solution is to build each image using the previous image as the base so we don't have to recompile every thing each time)
Are we able to store everything on Docker hub?
Once this is done, we can start thinking about how to make the magic for bisecting happen "

Agh! This was scary. Never heard any of these stuff before. Anyways, a Gsocer has to master the art of reading other's code. And that's what I did this whole period. I learnt docker and slowly figured out what each of these words meant. Went through thousands of lines of code inspecting the details.

So, starting around mid-days of community bonding period we worked around 20 days setting up the docker images for each commit in ruby. I kept on learning new features, clarifying my doubts along the way. But one day mentor messaged me :

 " As of right now, I'll like you to stop working on the Docker integration stuff because I feel that we might have assigned you a task that is too difficult for you to complete given your current level of experience. Instead we will like you to focus on … "

and assigned me a new task. I need to take that as a failure!

It's different!

Contributing open source for a short time and getting selected in Ruby which works on language itself was intimidating. During this time I observed many differences in the way other organizations operate and how I steered my journey. There are many organizations which have there prime focus on GSOC projects for development. In my case, its obvious that Ruby has many bigger activities to deal with. My mentor is mentoring two different GSOC organizations and is a core contributer of discourse along with rubybench. Again, its evident that he has greater problems to take care of. Besides, we don't follow any specific timeline.

Last shot!

My new task was :

" What if all our benchmarks are implemented in Sequel? How fast would it be? How many objects would be allocated?
I feel we should split off all "database" specs from the Rails umbrella and make the suite of tests compare "sequel" to "Active Record", as it stands it is totally unclear how much performance is left on the table cause there is nothing to compare "Active Record" to.
So start looking at our ActiveRecord benchmarks and write similar benchmarks using Sequel. "

This was my last opportunity to prove myself before midterm. Till now, no real contributions(PR's) on github. Fortunately this time, I had previous knowledge of activerecord. All I had to do was take my time to go through all the activerecord benchmarks and convert them to sequel.

6 days ago I got my greatest ever PR merged consisting of 593 additions and 29 deletions. This was exceptional and a huge relief.

Task remains to tackle frontend and my sequel benchmarks will be up and running in rubybench.org.

    Please enable JavaScript to view the comments powered by Disqus.

Post Directory

            TOP


text:
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Cogito.Web.Http.Tests.Web.Site.Controllers
{

    public class TestController :
        ApiController
    {

        [HttpGet]
        [Route("api/Test/TestString")]
        public HttpResponseMessage TestString([FromHeader("X-Value")] string value)
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpGet]
        [Route("api/Test/TestInt")]
        public HttpResponseMessage TestGuid([FromHeader("X-Value")] int value)
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpGet]
        [Route("api/Test/TestGuid")]
        public HttpResponseMessage TestGuid([FromHeader("X-Value")] Guid? value)
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpGet]
        [Route("api/Test/TestGuid2")]
        public HttpResponseMessage TestGuid2([FromUri(Name = "value")] Guid value)
        {
            return Request.CreateResponse(HttpStatusCode.OK);
        }

    }

}


text:
layout: post
title: Associative arrays - and how to use them... wisely
date: 2008-11-14T09:46:00.002Z
author: Marcus Hammarberg
tags:
  - Tools
  - .NET
modified_time: 2010-12-14T15:23:30.899Z
blogger_id: tag:blogger.com,1999:blog-36533086.post-5718087151947256210
blogger_orig_url: http://www.marcusoft.net/2008/11/associative-arrays-and-how-to-use-them.html
---

My questions in an earlier post was promptly answered by
Mark A
Williams in a great way.

So what he say pretty much confirms what I thought. Although associative
arrays are great way to "bulk in" data to the database but when it comes
to returning data the array-way might not always be right.

Since you have to allocate memory for the array and size of each element
in the array the associative arrays are best suited for situations when
you know the size of the data that is being returned. Not that often in
my experience. In other cases you'll better off with a plain old DataReader.

So now I know - thanks goes to Mark A Williams.


text:
//
// Author: Ian Davis <ian.f.davis@gmail.com> Copyright (c) 2007, Ian Davs
//
// Portions of this software were developed for NUnit. See NOTICE.txt for more
// information.
//
// 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.
//

#endregion

using Ensurance.MessageWriters;

namespace Ensurance.Constraints
{
    /// <summary>
    /// ContainsConstraint tests a whether a string contains a substring or a
    /// collection contains an object. It postpones the decision of which test
    /// to use until the type of the actual argument is known. This allows
    /// testing whether a string is contained in a collection or as a substring
    /// of another string using the same syntax.
    /// </summary>
    public class ContainsConstraint : Constraint
    {
        private object _expected;
        private Constraint _realConstraint;

        /// <summary>
        /// Initializes a new instance of the <see cref="ContainsConstraint"/>
        /// class.
        /// </summary>
        /// <param name="expected">The expected.</param>
        public ContainsConstraint( object expected )
        {
            _expected = expected;
        }

        /// <summary>
        /// Gets or sets the real constraint.
        /// </summary>
        /// <value>The real constraint.</value>
        private Constraint RealConstraint
        {
            get
            {
                if ( _realConstraint == null )
                {
                    if ( Actual is string )
                    {
                        _realConstraint = new SubstringConstraint( (string) _expected );
                    }
                    else
                    {
                        _realConstraint = new CollectionContainsConstraint( _expected );
                    }
                }

                return _realConstraint;
            }
            set { _realConstraint = value; }
        }

        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for success, false for failure</returns>
        public override bool Matches( object actual )
        {
            Actual = actual;

            if ( CaseInsensitive )
            {
                RealConstraint = RealConstraint.IgnoreCase;
            }

            return RealConstraint.Matches( actual );
        }

        /// <summary>
        /// Write the constraint description to a MessageWriter
        /// </summary>
        /// <param name="writer">The writer on which the description is displayed</param>
        public override void WriteDescriptionTo( MessageWriter writer )
        {
            RealConstraint.WriteDescriptionTo( writer );
        }
    }
}


text:
UUChatTableView
===============

Cocoa UI component for chat bubbles with text, images and audio support

## GIF 动画演示
![Flipboard playing multiple GIFs](https://github.com/ZhipingYang/UUChatTableView/raw/master/Demo/UUChatTableViewTests/ChatTableView.gif)

## 截图 - ScreenShot
![图片一](https://github.com/ZhipingYang/UUChatTableView/raw/master/Demo/UUChatTableViewTests//ScreenShot/QQ20150113-5.jpg) ![图片一](https://github.com/ZhipingYang/UUChatTableView/raw/master/Demo/UUChatTableViewTests//ScreenShot/QQ20150113-4.jpg)
### 群聊(GroupChat)效果图(新添UI细节)
![图片三](https://github.com/ZhipingYang/DataResource/raw/master/UUChat/IMG_0052.jpg)
![图片三](https://github.com/ZhipingYang/DataResource/raw/master/UUChat/IMG_0054.jpg)
##使用类介绍 - Introduce

[类名](https://github.com/ZhipingYang/UUChatTableView/tree/master/UUChat) | 作用及用法
----- | -----
[UUMessage](https://github.com/ZhipingYang/UUChatTableView/blob/master/UUChat/UUMessage.h) | 内容数据Model,储存文字、语音、头像、图片、时间等等
[UUMessageFrame](https://github.com/ZhipingYang/UUChatTableView/blob/master/UUChat/UUMessageFrame.h) | cell的model,设置气泡聊天的布局
[UUMessageCell](https://github.com/ZhipingYang/UUChatTableView/blob/master/UUChat/UUMessageContentButton.h) | 呈现UI,并做cell的事件处理(语音、图片、头像点击)
[UUMessageContentButton](https://github.com/ZhipingYang/UUChatTableView/blob/master/UUChat/) | 气泡内容的封装及copy功能
[UUInputFunctionView](https://github.com/ZhipingYang/UUChatTableView/blob/master/UUChat/UUInputFunctionView.h) | tableView底部的视图,相当于ToolBar
[UUImageAvatarBrowser](https://github.com/ZhipingYang/UUChatTableView/blob/master/UUChat/UUImageAvatarBrowser.h) | 放大图片功能,其实这是障眼法[详细查看](https://github.com/ZhipingYang/UUChatTableView/blob/master/UUChat/UUImageAvatarBrowser.m)
[UUAVAudioPlayer](https://github.com/ZhipingYang/UUChatTableView/blob/master/UUChat/UUAVAudioPlayer.h) | 语音功能封装,实现本地和线上URL播放,缺点是还没有做像[SDWebImage](https://github.com/rs/SDWebImage)那样的本地缓存
[UUProgressHUD](https://github.com/ZhipingYang/UUChatTableView/blob/master/UUChat/UUProgressHUD.h) | Window层上得HUD,功能简易

第三方库 | 说明
----- | -----
[MJRefresh](https://github.com/CoderMJLee/MJRefresh) | 下拉加载更多聊天记录
[AFNetworking](https://github.com/AFNetworking/AFNetworking) | 仅使用UIKit+AFNetworking,类似 [SDWebImage](https://github.com/rs/SDWebImage)
VoiceLib | 忘记了来自哪里的,找半天没有找到。语音录入及格式转化成MP3

##使用方法 - Usage
声明一下|
----- | -----
当前的数据是在固定模式下随机模拟的,不包含用户输入的所有可能性|
有不习惯`Xib编程`的有问题可以[问我](https://github.com/ZhipingYang/UUChatTableView/issues/new),以前我因为不会而不想去改变 |
我还没有去试iOS6下得适配,要是你测试过油问题可以修改提交或者[告诉我](https://github.com/ZhipingYang/UUChatTableView/issues/new) |
有人提到群聊功能,只需要在getDic方法添加其他人信息即可[点击查看](https://github.com/ZhipingYang/UUChatTableView/blob/master/Demo/UUChatTableView/ChatModel.m#L78)|
感谢[丁南](https://github.com/ijinmao)修复语音播放及其他的一些bug|

####添加代理

UUInputFunctionViewDelegate

	// 返回文字内容
	- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendMessage:(NSString *)message;
	// 返回图片数据
	- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendPicture:(UIImage *)image;
	// 返回语音数据和录音时长
	- (void)UUInputFunctionView:(UUInputFunctionView *)funcView sendVoice:(NSData *)voice time:(NSInteger)second;

UUMessageCellDelegate

	//cell的头像点击
	- (void)headImageDidClick:(UUMessageCell *)cell userId:(NSString *)userId;
	//图片点击可有可无
	- (void)cellContentDidClick:(UUMessageCell *)cell image:(UIImage *)contentImage;

#### Swift版
UUChatSwift  [链接地址](https://github.com/ZhipingYang/UUChatSwift)

Swift版将完全使用autolayout,storyboard及xib。

项目在一点一点完成中。。。


text:
<?xml version="1.0" encoding="utf-8" ?>

<sql>
<datatypes db="mysql">
	<group label="Numeric" color="rgb(238,238,170)">
	 	<type label="TINYINT" length="0" sql="TINYINT" quote=""/>
	 	<type label="SMALLINT" length="0" sql="SMALLINT" quote=""/>
	 	<type label="MEDIUMINT" length="0" sql="MEDIUMINT" quote=""/>
	 	<type label="INT" length="0" sql="INT" quote=""/>
		<type label="Integer" length="0" sql="INTEGER" quote=""/>
		<type label="BIGINT" length="0" sql="BIGINT" quote=""/>
		<type label="Decimal" length="1" sql="DECIMAL" re="DEC" quote=""/>
		<type label="Single precision" length="0" sql="FLOAT" quote=""/>
		<type label="Double precision" length="0" sql="DOUBLE" re="DOUBLE" quote=""/>
	</group>

	<group label="Character" color="rgb(255,200,200)">
		<type label="Char" length="1" sql="CHAR" quote="'"/>
		<type label="Varchar" length="1" sql="VARCHAR" quote="'"/>
		<type label="Text" length="0" sql="MEDIUMTEXT" re="TEXT" quote="'"/>
		<type label="Binary" length="1" sql="BINARY" quote="'"/>
		<type label="Varbinary" length="1" sql="VARBINARY" quote="'"/>
		<type label="BLOB" length="0" sql="BLOB" re="BLOB" quote="'"/>
	</group>

	<group label="Date & Time" color="rgb(200,255,200)">
		<type label="Date" length="0" sql="DATE" quote="'"/>
		<type label="Time" length="0" sql="TIME" quote="'"/>
		<type label="Datetime" length="0" sql="DATETIME" quote="'"/>
		<type label="Year" length="0" sql="YEAR" quote=""/>
		<type label="Timestamp" length="0" sql="TIMESTAMP" quote="'"/>
	</group>

	<group label="Miscellaneous" color="rgb(200,200,255)">
		<type label="ENUM" length="1" sql="ENUM" quote=""/>
		<type label="SET" length="1" sql="SET" quote=""/>
		<type label="Bit" length="0" sql="bit" quote=""/>
	</group>
</datatypes>

<row name="id" null="0" autoincrement="1">
<datatype>INTEGER</datatype>
<relation table="sessions" row="user_id" />
</row>
<row name="email" null="0" autoincrement="0">
<datatype>VARCHAR</datatype>
</row>
<row name="handle" null="0" autoincrement="0">
<datatype>VARCHAR</datatype>
</row>
<row name="pass_hash" null="0" autoincrement="0">
<datatype>CHAR(60)</datatype>
</row>
<row name="reset_token" null="0" autoincrement="0">
<datatype>CHAR(32)</datatype>
</row>
<row name="ap" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<default>0</default></row>
<row name="rp" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
</row>
<row name="first_name" null="1" autoincrement="0">
<datatype>VARCHAR</datatype>
<default>NULL</default></row>
<row name="last_name" null="1" autoincrement="0">
<datatype>VARCHAR</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
<key type="UNIQUE" name="">
<part>email</part>
</key>
<key type="UNIQUE" name="">
<part>handle</part>
</key>
<key type="UNIQUE" name="">
<part>reset_token</part>
</key>
<key type="INDEX" name="">
<part>first_name</part>
<part>last_name</part>
</key>
<key type="INDEX" name="">
<part>last_name</part>
</key>

<row name="id" null="0" autoincrement="0">
<datatype>VARCHAR(32)</datatype>
</row>
<row name="user_id" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<row name="ts" null="0" autoincrement="0">
<datatype>INT</datatype>
</row>
<row name="data" null="0" autoincrement="0">
<datatype>MEDIUMTEXT</datatype>
</row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
<key type="UNIQUE" name="">
<part>user_id</part>
</key>

<row name="id" null="0" autoincrement="1">
<datatype>INTEGER</datatype>
</row>
<row name="parent_id" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="categories" row="id" />
</row>
<row name="name" null="0" autoincrement="0">
<datatype>VARCHAR</datatype>
</row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
<key type="INDEX" name="">
<part>parent_id</part>
</key>
<key type="UNIQUE" name="">
<part>name</part>
</key>

<row name="id" null="1" autoincrement="1">
<datatype>TINYINT</datatype>
<default>NULL</default></row>
<row name="name" null="0" autoincrement="0">
<datatype>VARCHAR</datatype>
</row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
<key type="UNIQUE" name="">
<part>name</part>
</key>

<row name="id" null="0" autoincrement="1">
<datatype>BIGINT</datatype>
</row>
<row name="user_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="users" row="id" />
</row>
<row name="minutes" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
</row>
<row name="created_ts" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
</row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
<key type="INDEX" name="">
<part>user_id</part>
</key>

<row name="timelog_id" null="0" autoincrement="0">
<datatype>BIGINT</datatype>
<relation table="timelogs" row="id" />
</row>
<row name="category_id" null="0" autoincrement="0">
<datatype>BIGINT</datatype>
<relation table="categories" row="id" />
</row>
<key type="PRIMARY" name="">
<part>timelog_id</part>
<part>category_id</part>
</key>

<row name="timelog_id" null="0" autoincrement="0">
<datatype>BIGINT</datatype>
<relation table="timelogs" row="id" />
</row>
<row name="tag_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="tags" row="id" />
</row>
<key type="PRIMARY" name="">
<part>timelog_id</part>
<part>tag_id</part>
</key>

<row name="id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="users" row="id" />
</row>
<row name="user_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
</row>
<row name="content" null="1" autoincrement="0">
<datatype>MEDIUMTEXT</datatype>
<default>NULL</default></row>
<row name="created_ts" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
</row>
<row name="modified_ts" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
<key type="INDEX" name="">
<part>user_id</part>
</key>

<row name="post_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="posts" row="id" />
</row>
<row name="timelog_id" null="0" autoincrement="0">
<datatype>BIGINT</datatype>
<relation table="timelogs" row="id" />
</row>
<key type="PRIMARY" name="">
<part>post_id</part>
<part>timelog_id</part>
</key>

<row name="post_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="posts" row="id" />
</row>
<row name="category_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="categories" row="id" />
</row>
<key type="PRIMARY" name="">
<part>post_id</part>
<part>category_id</part>
</key>

<row name="post_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="posts" row="id" />
</row>
<row name="tag_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="tags" row="id" />
</row>
<key type="PRIMARY" name="">
<part>post_id</part>
<part>tag_id</part>
</key>

<row name="id" null="0" autoincrement="1">
<datatype>BIGINT</datatype>
</row>
<row name="user_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
</row>
<row name="post_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="posts" row="id" />
</row>
<row name="content" null="0" autoincrement="0">
<datatype>MEDIUMTEXT</datatype>
</row>
<row name="created_ts" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
</row>
<row name="modified_ts" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="">
<part>id</part>
</key>
<key type="INDEX" name="">
<part>user_id</part>
</key>
<key type="INDEX" name="">
<part>post_id</part>
</key>

<row name="user_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="users" row="id" />
</row>
<row name="post_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="posts" row="id" />
</row>
<key type="PRIMARY" name="">
<part>user_id</part>
<part>post_id</part>
</key>

<row name="user_id" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<relation table="users" row="id" />
</row>
<row name="comment_id" null="0" autoincrement="0">
<datatype>BIGINT</datatype>
<relation table="comments" row="id" />
</row>
<key type="PRIMARY" name="">
<part>user_id</part>
<part>comment_id</part>
</key>

</sql>


text:
package net.ozwolf.mockserver.raml.internal.validator.body;

import net.ozwolf.mockserver.raml.exception.NoValidActionException;
import net.ozwolf.mockserver.raml.internal.domain.ApiExpectation;
import net.ozwolf.mockserver.raml.internal.domain.BodySpecification;
import net.ozwolf.mockserver.raml.internal.domain.ValidationErrors;
import net.ozwolf.mockserver.raml.internal.validator.Validator;
import org.apache.commons.lang.StringUtils;
import org.raml.model.Action;
import org.raml.model.MimeType;

import javax.ws.rs.core.MediaType;
import java.util.Map;
import java.util.Optional;

public class RequestBodyValidator implements Validator {
    private final ApiExpectation expectation;

    public RequestBodyValidator(ApiExpectation expectation) {
        this.expectation = expectation;
    }

    @Override
    public ValidationErrors validate() {
        ValidationErrors errors = new ValidationErrors();

        Action action = expectation.getAction()
                .orElseThrow(() -> new NoValidActionException(expectation));

        if (!action.hasBody())
            return errors;

        Optional<String> requestBody = expectation.getRequestBody();

        if (action.hasBody() && !requestBody.isPresent()) {
            errors.addMessage("[ request ] Has an expected request body but none provided.");
            return errors;
        }

        MediaType contentType = expectation.getRequestContentType();

        if (contentType.isWildcardType()) {
            errors.addMessage("[ request ] Wildcard or no content type provided in request.");
            return errors;
        }

        Optional<BodySpecification> body = expectation.getRequestBodySpecification();

        if (!body.isPresent()) {
            errors.addMessage("[ request ] No request specification exists for [ %s ].  Acceptable content types are [ %s ]", contentType, getAllowedContentTypes(action.getBody()));
            return errors;
        }

        errors.combineWith(body.get().validate(requestBody.get()));
        return errors;
    }

    private String getAllowedContentTypes(Map<String, MimeType> contentTypes) {
        if (contentTypes == null)
            return "n/a";

        return StringUtils.join(contentTypes.keySet(), ", ");
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import ReactRouter from 'react-router';

export default class Disque extends React.Component {

	componentDidMount() {

		var disqus_config = function () {
			this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
			this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
		};
		(function() { // DON'T EDIT BELOW THIS LINE
			var d = document, s = d.createElement('script');
			s.src = '//vizjust-tw.disqus.com/embed.js';
			s.setAttribute('data-timestamp', +new Date());
			(d.head || d.body).appendChild(s);
		})();

	}

	render() {
		return (

				Please enable JavaScript to view the comments powered by Disqus.

		)
	}

}


text:
SVD++
=====

SVD++ is matrix factorization model which makes use of implicit feedback
information.

User's predictions are defined as follows:

.. math::
	\hat { r }_{ ui } = \mu + b_u + b_i + \left(p_u + \frac{1}{\sqrt{|N(u)|}}\sum_{j\in N(u)} y_j \right)^T q_i

We learn the values of involved parameters by minimizing the regularized squared error function associated with:

.. math::
    \begin{split}
    \min _{ p*,q*,y*,b* }&{\sum _{ (u,i\in k) }{ { ({ r }_{ ui }-\mu -b_{ u }-b_{ i }-{ q }_{ i }^{ T }\left( p_{ u }+\frac { 1 }{ \sqrt { |N(u)| }  } \sum _{ j\in N(u) } y_{ j } \right) ) }^{ 2 }}} \\
    &+\lambda ({ { { b }_{ u } }^{ 2 }+{ { b }_{ i } }^{ 2 }+\left\| { p }_{ u } \right\|  }^{ 2 }+{ \left\| q_{ i } \right\|  }^{ 2 }+\sum _{ j\in N(u) }{ \left\| y_{ j } \right\|  } ^{ 2 })
    \end{split}

Example
-------

.. code-block:: python
   :linenos:

   import Orange
   from orangecontrib.recommendation import SVDPlusPlusLearner

   # Load data and train the model
   data = Orange.data.Table('movielens100k.tab')
   learner = SVDPlusPlusLearner(num_factors=15, num_iter=25, learning_rate=0.07, lmbda=0.1)
   recommender = learner(data)

   # Make predictions
   prediction = recommender(data[:3])
   print(prediction)

.. autoclass:: SVDPlusPlusLearner
   :members:
   :special-members: __init__


text:
require 'test/helper'

class Admin::PostsControllerTest < ActionController::TestCase

  def setup_for_no_root
    @typus_user = typus_users(:editor)
    @request.session[:typus_user_id] = @typus_user.id
    assert @typus_user.is_not_root?
  end

  ##
  # Tests around what happens with records with typus_user_id when editing
  # and showing.
  ##

  def test_should_verify_root_can_edit_any_record

    assert @typus_user.is_root?

    Post.find(:all).each do |post|
      get :edit, { :id => post.id }
      assert_response :success
      assert_template 'edit'
    end

  end

  def test_should_verify_editor_can_show_any_record

    setup_for_no_root

    Post.find(:all).each do |post|
      get :show, { :id => post.id }
      assert_response :success
      assert_template 'show'
    end

  end

  def test_should_verify_editor_can_not_edit_all_records

    setup_for_no_root

    # Editor tries to edit a post owned by hiself.
    post = posts(:owned_by_editor)
    get :edit, { :id => post.id }
    assert_response :success

    # Editor tries to edit a post owned by the admin.
    @request.env['HTTP_REFERER'] = '/admin/posts'
    post = posts(:owned_by_admin)
    get :edit, { :id => post.id }
    assert_response :redirect
    assert_redirected_to @request.env['HTTP_REFERER']
    assert_equal "You don't have permission to access this item.", flash[:notice]

    # Editor tries to show a post owned by the admin.
    post = posts(:owned_by_admin)
    get :show, { :id => post.id }
    assert_response :success
    assert_template 'show'

    # Editor tries to show a post owned by the admin.
    options = Typus::Configuration.options.merge(:only_user_items => true)
    Typus::Configuration.stubs(:options).returns(options)
    post = posts(:owned_by_admin)
    get :show, { :id => post.id }
    assert_response :redirect
    assert_redirected_to @request.env['HTTP_REFERER']

  end

  ##
  # Tests around what happens with the typus_user_id when creating items.
  ##

  def test_should_verify_typus_user_id_of_item_when_creating_record

    setup_for_no_root

    post :create, { :post => { :title => "Chunky Bacon", :body => "Lorem ipsum ..." } }
    post_ = Post.find_by_title("Chunky Bacon")

    assert_equal @request.session[:typus_user_id], post_.typus_user_id

  end

  ##
  # Tests around what happens with the typus_user_id when updating items.
  ##

  def test_should_verify_admin_updating_an_item_does_not_change_typus_user_id_if_not_defined

    assert @typus_user.is_root?

    post_ = posts(:owned_by_editor)
    post :update, { :id => post_.id, :post => { :title => 'Updated by admin' } }
    post_updated = Post.find(post_.id)
    assert_equal post_.typus_user_id, post_updated.typus_user_id

  end

  def test_should_verify_admin_updating_an_item_does_change_typus_user_id_to_whatever_admin_wants

    assert @typus_user.is_root?

    post_ = posts(:owned_by_editor)
    post :update, { :id => post_.id, :post => { :title => 'Updated', :typus_user_id => 108 } }
    post_updated = Post.find(post_.id)
    assert_equal 108, post_updated.typus_user_id

  end

  def test_should_verify_editor_updating_an_item_does_not_change_typus_user_id

    setup_for_no_root

    [ 108, nil ].each do |typus_user_id|
      post_ = posts(:owned_by_editor)
      post :update, { :id => post_.id, :post => { :title => 'Updated', :typus_user_id => typus_user_id } }
      post_updated = Post.find(post_.id)
      assert_equal  @request.session[:typus_user_id], post_updated.typus_user_id
    end

  end

end


text:
import {PostHTML} from 'posthtml';
import {URL} from 'url';
import {isValidScript, ScriptNode} from '../utilities/script';
import {CDNURLToLocalDistURL} from '../utilities/cdn';

/**
 * Append a Module Script for a ScriptNode.
 * @param head
 * @param script
 */
function appendModuleScript(head: PostHTML.Node, script: ScriptNode): void {
  const modulePath = CDNURLToLocalDistURL(
    new URL(script.attrs.src || ''),
    undefined,
    '.mjs'
  ).toString();

  const insert: ScriptNode = {
    ...script,
    attrs: {
      ...script.attrs,
      src: modulePath,
      type: 'module',
    },
  };
  delete insert.attrs.nomodule;

  (head.content || []).push(insert);
}

/**
 *
 */
export default function(tree: PostHTML.Node): void {
  let head: PostHTML.Node | undefined = undefined;
  const scripts: Array<ScriptNode> = [];
  tree.walk(node => {
    if (node.tag === 'head') {
      head = node;
    }
    if (!isValidScript(node)) {
      return node;
    }

    // Mark the existing valid scripts with `nomodule` attributes.
    node.attrs.nomodule = '';
    scripts.push(node);
    return node;
  });

  if (head === undefined) {
    console.log('Could not find a head element in the document');
    return;
  }

  for (const script of scripts) {
    appendModuleScript(head, script);
  }
}


text:
using namespace ci;
using namespace Cinder::Pipeline;

// Taken from Brad Larson's GPUImage https://github.com/BradLarson/GPUImage/blob/master/framework/Source/GPUImageHighlightShadowFilter.m
const std::string FragmentShaderVibrance = R"(
    #version 150
    uniform sampler2D image;
    uniform float shadows;
    uniform float highlights;
    uniform float mixAmount;

    in vec2 vTexCoord0;

    out vec4 oFragColor;

    const vec3 luminanceWeighting = vec3(0.3, 0.3, 0.3);

    void main() {
        vec4 color = texture(image, vTexCoord0);

        float luminance = dot(color.rgb, luminanceWeighting);

        float shadow = clamp((pow(luminance, 1.0/(shadows+1.0)) + (-0.76)*pow(luminance, 2.0/(shadows+1.0))) - luminance, 0.0, 1.0);
        float highlight = clamp((1.0 - (pow(1.0-luminance, 1.0/(2.0-highlights)) + (-0.8)*pow(1.0-luminance, 2.0/(2.0-highlights)))) - luminance, -1.0, 0.0);
        vec3 r = vec3(0.0, 0.0, 0.0) + ((luminance + shadow + highlight) - 0.0) * ((color.rgb - vec3(0.0, 0.0, 0.0))/(luminance - 0.0));
        vec4 result = vec4(r, color.a);

        oFragColor = mix(color, result, mixAmount);
    }
)";

ShadowsHighlightsNode::ShadowsHighlightsNode() {
    std::vector<NodePortRef> inputPorts = {
        NodePort::create(NodeInputPortKeyImage, NodePortType::FBOImage),
        NodePort::create(ShadowsHighlightsNodeInputPortKeyShadows, NodePortType::Float, "Shadows", 0.0f, 0.0f, 1.0f),
        NodePort::create(ShadowsHighlightsNodeInputPortKeyHighlights, NodePortType::Float, "Highlights", 1.0f, 0.0f, 1.0f),
        NodePort::create(ShadowsHighlightsNodeInputPortKeyMixAmount, NodePortType::Float, "Mix", 1.0f, 0.0f, 1.0f),
    };
    setInputPorts(inputPorts);
    // NB - output port "image" of type NodePortType::FBOImage is already present

    setupShader(sVertexShaderPassThrough, FragmentShaderVibrance);
}

ShadowsHighlightsNode::~ShadowsHighlightsNode() {
}

void ShadowsHighlightsNode::render(const FBOImageRef& outputFBOImage) {
    FBOImageRef inputFBOImage = getValueForInputPortKey<FBOImageRef>(NodeInputPortKeyImage);
    float shadows = getValueForInputPortKey<float>(ShadowsHighlightsNodeInputPortKeyShadows);
    float highlights = getValueForInputPortKey<float>(ShadowsHighlightsNodeInputPortKeyHighlights);
    float mixAmount = getValueForInputPortKey<float>(ShadowsHighlightsNodeInputPortKeyMixAmount);

    gl::ScopedTextureBind texture(inputFBOImage->getTexture(), 0);
    gl::ScopedGlslProg shader(mShader);

    mShader->uniform(NodeInputPortKeyImage, 0);
    mShader->uniform(ShadowsHighlightsNodeInputPortKeyShadows, shadows);
    mShader->uniform(ShadowsHighlightsNodeInputPortKeyHighlights, highlights);
    mShader->uniform(ShadowsHighlightsNodeInputPortKeyMixAmount, mixAmount);
    gl::drawSolidRect(outputFBOImage->getFBO()->getBounds());
}


text:
/* $Id$ $Revision$ */
/* vim:set shiftwidth=4 ts=8: */

/*************************************************************************
 * Copyright (c) 2011 AT&T Intellectual Property
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors: See CVS logs. Details at http://www.graphviz.org/
 *************************************************************************/

#ifdef __cplusplus
extern "C" {
#endif

#ifndef _DIJKSTRA_H_
#define _DIJKSTRA_H_

#include "defs.h"

#ifdef __cplusplus
    void dijkstra(int vertex, vtx_data * graph, int n, DistType * dist);

/* Dijkstra bounded to nodes in *unweighted* radius */
    void dijkstra_bounded(int vertex, vtx_data * graph, int n,
			  DistType * dist, int bound, int *visited_nodes,
			  int &num_visited_nodes);

#else
    extern void dijkstra(int, vtx_data *, int, DistType *);
    extern void dijkstra_f(int, vtx_data *, int, float *);

    /* Dijkstra bounded to nodes in *unweighted* radius */
    extern int dijkstra_bounded(int, vtx_data *, int, DistType *, int,
				int *);
#endif

#endif

#ifdef __cplusplus
}
#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>daily-mindfulness-blog</title>
    <meta name="description" content="">
    <meta name="author" content="">

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

    <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">

    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css">
    <link rel="stylesheet" type="text/css" href="css/design2webblog.css">

    <link rel="icon" type="image/png" href="images/favicon.png">

Daily mindfulness blog

                    Home

Listening.

                      I have had a great opportunity to practice mindful listening this weekend as I have taken some friends up to the tropical KC. They have spent two months traveling around the south island and have had a truly wonderful experience. They have so many tales to tell of their trip and also of news/gossip from home to share with my wife, as she spent a few years over there.

  I didn't let them in on the fact that I was doing it to begin with to be fair but I'm sure they wouldn't have minded. It was interesting to watch the dynamic of the three of them all trying to share their thoughts simultaneously. In an innocent and non competitive way to be sure, but still I wondered how much information was lost as the conversation skipped and jumped to one subject to another. Some threads followed and some potentially fascinating ones lost entirely.
 Afterwards I practiced in earnest with da missus for the three minutes and after a brief feeling of self consciousness we really enjoyed it.

Walking.

                    I also had the luxury of Waikanae beach to practice mindful walking. I walk a lot. In fact I decided  at age 15 not to ever have credit cards or car keys. So I walk a lot.
Back in the day I read about a group of Zen monks in japan who practiced walking meditation (as well as gravel raking) and the aim was to reach a stage where there was no differentiation between the monk, the path or anything else really. There was just 'walking'. I have always remembered that and am glad that it's now part of my homework.
 I generally spend my walking time to gather my thoughts and mull over things ( as well as being mindful of pesky distractions like traffic ) but this week I have had a good crack at not thinking. Instead of concentrating on just breathing I used the sound of the waves which is probably cheating but hey use it or lose it right ?


text:
package com.lachesis.mnis.core.documents.repository.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.lachesis.mnis.core.documents.entity.DocumentInfo;
import com.lachesis.mnis.core.documents.repository.DocumentsRepository;
import com.lachesis.mnis.core.mybatis.mapper.DocumentsMapper;

@Repository("documentsRepository")
public class DocumentsRepositoryImpl implements DocumentsRepository{

	@Autowired
	private DocumentsMapper documentsMapper;

	@Override
	public List<DocumentInfo> selectLiquorDocument(String patientId,
			Date startDate,Date endDate) {
		return documentsMapper.selectLiquorDocument(patientId, startDate,endDate);
	}

	@Override
	public List<DocumentInfo> selectPersralDocument(List<String> orderSubNos,String patientId,
			Date startDate,Date endDate) {
		return documentsMapper.selectPersralDocument(orderSubNos,patientId, startDate,endDate);
	}

	@Override
	public List<DocumentInfo> selectDrugBagDocument(
			String patientId, Date startDate, Date endDate) {
		return documentsMapper.selectDrugBagDocument( patientId, startDate, endDate);
	}

}


text:
var WindowManager = require('helper/WindowManager');
var Utils = require('helper/Utils');
var Cloud = require('ti.cloud');
WindowManager.include(

    '/windows/users/loginStatus',
    '/windows/users/create',
    '/windows/users/login',
    '/windows/users/logout',
    '/windows/users/query',
    '/windows/users/remove',
    '/windows/users/requestResetPassword',
    '/windows/users/resendConfirmation',
    '/windows/users/search',
    '/windows/users/show',
    '/windows/users/showMe',
    '/windows/users/update',
	'/windows/users/secureIdentity'
);
exports['Users'] = function (evt) {
    var win = WindowManager.createWindow({
        backgroundColor: 'white'
    });
    var table = Ti.UI.createTableView({
        backgroundColor: '#fff',
        top: 0,
        data: Utils.createRows([
            'Login Status',
            'Create User',
            'Login User',
	        'Secure Identity',
            'Request Reset Password',
            'Resend Confirmation',
            'Show Current User',
            'Update Current User',
            'Remove Current User',
            'Logout Current User',
            'Query User',
            'Search User'
        ])
    });
    table.addEventListener('click', WindowManager.handleOpenWindow);
    win.add(table);
    return win;
};


text: from kubric.renderer.blender import Blender


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Softengi.UbClient.Linq
{
	internal class UbQueryProvider : IQueryProvider
	{
		public IQueryable CreateQuery(Expression expression)
		{
			var elementType = TypeSystem.GetElementType(expression.Type);
			try
			{
				var genericType = typeof(QueryableUbData<>).MakeGenericType(elementType);
				return (IQueryable) Activator.CreateInstance(genericType, this, expression);
			}
			catch (TargetInvocationException tie)
			{
				throw tie.InnerException;
			}
		}

		/// <summary>
		/// Queryable's collection-returning standard query operators call this method.
		/// </summary>
		public IQueryable<TResult> CreateQuery<TResult>(Expression expression)
		{
			return new QueryableUbData<TResult>(this, expression);
		}

		public object Execute(Expression expression)
		{
			return UbQueryContext.Execute(expression, false);
		}

		/// <summary>
		/// Queryable's "single value" standard query operators call this method.
		/// It is also called from <see cref="QueryableUbData{T}.GetEnumerator"/>.
		/// </summary>
		public TResult Execute<TResult>(Expression expression)
		{
			var isEnumerable = typeof(TResult).Name == "IEnumerable`1";
			return (TResult) UbQueryContext.Execute(expression, isEnumerable);
		}
	}
}