text:
package me.chanjar.weixin.cp.api.impl;

import com.google.inject.Inject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import me.chanjar.weixin.cp.bean.taskcard.TaskCardButton;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;

import java.util.Arrays;

import static org.testng.Assert.assertNotNull;

/**
 * 测试任务卡片服务
 *
 * @author Jeff created on  2019-05-16
 */
@Guice(modules = ApiTestModule.class)
public class WxCpTaskCardServiceImplTest {

  @Inject
  private WxCpService wxCpService;

  /**
   * Test send task card.
   *
   * @throws WxErrorException the wx error exception
   */
  @Test
  public void testSendTaskCard() throws WxErrorException {
    TaskCardButton btn1 = TaskCardButton.builder()
      .key("key1")
      .name("同意")
      .replaceName("已同意")
      .bold(true)
      .build();
    TaskCardButton btn2 = TaskCardButton.builder()
      .key("key2")
      .name("拒绝")
      .replaceName("已拒绝")
      .color("red")
      .build();
    WxCpMessage message = WxCpMessage.TASKCARD()
      .toUser("jeff|mr.t")
      .title("有一个待审批的请求")
      .description("申请:购买图书\n金额:100 元")
      .taskId("task_1")
      .url("http://www.qq.com")
      .buttons(Arrays.asList(btn1, btn2))
      .build();

    WxCpMessageSendResult messageSendResult = this.wxCpService.getMessageService().send(message);
    assertNotNull(messageSendResult);
    System.out.println(messageSendResult);
    System.out.println(messageSendResult.getInvalidPartyList());
    System.out.println(messageSendResult.getInvalidUserList());
    System.out.println(messageSendResult.getInvalidTagList());
  }

  /**
   * Test update.
   *
   * @throws Exception the exception
   */
  @Test
  public void testUpdate() throws Exception {
    wxCpService.getTaskCardService().update(Arrays.asList("jeff", "mr.t"), "task_1", "key1");
  }

}


text:
"""
This module defines the Link object used in Link extractors.

For actual link extractors implementation see scrapy.contrib.linkextractor, or
its documentation in: docs/topics/link-extractors.rst
"""

class Link(object):
    """Link objects represent an extracted link by the LinkExtractor."""

    __slots__ = ['url', 'text', 'fragment', 'nofollow']

    def __init__(self, url, text='', fragment='', nofollow=False):
        self.url = url
        self.text = text
        self.fragment = fragment
        self.nofollow = nofollow

    def __eq__(self, other):
        return self.url == other.url and self.text == other.text and \
            self.fragment == other.fragment and self.nofollow == other.nofollow

    def __hash__(self):
        return hash(self.url) ^ hash(self.text) ^ hash(self.fragment) ^ hash(self.nofollow)

    def __repr__(self):
        return 'Link(url=%r, text=%r, fragment=%r, nofollow=%r)' % \
            (self.url, self.text, self.fragment, self.nofollow)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#ffcc0000" />
    <size
        android:width="6dp"
        android:height="6dp" />
</shape>


text:
published: false
title: PEAR — the Good, the Bad and the Ugly.
layout: post
---
In letzter Zeit ist eine interessante Entwicklung zu beobachten. Immer
mehr entwickelt sich das Ökosystem rund um PHP Bibliotheken _weg_ von
PEAR. Das [Symfony Projekt](http://symfony.com) ist darin momentan am
aktivsten und die Community rund um [Zend Framework](http://framework.zend.com)
denkt auch über eine neue Form der Distribution nach.

Der Auslöser ist ein neues Projekt das von Jordi Boggiano und Nils
Adermann ins Leben gerufen wurde. Beide engagieren sich aktiv im Symfony
Projekt. [Composer](https://github.com/composer/composer) heißt dieses
Ding und schickt sich an ein moderner Paket Manager für PHP zu sein.

In mir wirft diese Entwicklung einige Fragen auf und ich muss zugeben
auch eine gewisse Skepsis gegenüber Composer zu haben.

Denn ein Paket Manager ist die zentralste Komponente in einem Ökosystem.
In der Ruby Welt fluchen _alle_ über Gem und es _gibt_ auch _einige_
Alternativen. Doch **keine** konnte Gem bisher ablösen.

Ich befürchte irgendwie, dass man zum einen Pakete hat, die nur über
PEAR zu installieren sind und andere die man nur über Composer beziehen
kann. Das kommt einer Spaltung gleich.

Es ist natürlich wahrscheinlich, dass Composer dem PEAR Installer
überlegen ist. Ich glaube aber auch, dass man an den Macken von PEAR
arbeiten kann.


text:
"""
The dependencies module determines which descriptions depend on which other
descriptions.
"""

from ..descriptions import *
from ..ctypedescs import *
from ..messages import *

def find_dependencies(data, opts):
    """Visit each description in `data` and figure out which other descriptions
    it depends on, putting the results in desc.requirements. Also find errors in
    ctypedecls or expressions attached to the description and transfer them to the
    description."""

    struct_names = {}
    enum_names = {}
    typedef_names = {}
    ident_names = {}

    # Start the lookup tables with names from imported modules

    for name in opts.other_known_names:
        typedef_names[name] = None
        ident_names[name] = None
        if name.startswith("struct_") or name.startswith("enum_"):
            variety = name.split("_")[0]
            tag = "_".join(name.split("_")[1:])
            struct_names[(variety, tag)] = None
        if name.startswith("enum_"):
            enum_names[name] = None

    def depend(desc, nametable, name):
        """Try to add `name` as a requirement for `desc`, looking `name` up in
        `nametable`. Returns True if found."""

        if name in nametable:
            requirement = nametable[name]
            if requirement:
                desc.add_requirements([requirement])
            return True
        else:
            return False

    def co_depend(desc, nametable, name):
        """
        Try to add `name` as a requirement for `desc`, looking `name` up in
        `nametable`.  Also try to add desc as a requirement for `name`.

        Returns Description of `name` if found.
        """

        requirement = nametable.get(name, None)
        if requirement is None:
            return

        desc.add_requirements([requirement])
        requirement.add_requirements([desc])
        return requirement

    def find_dependencies_for(desc, kind):
        """Find all the descriptions that `desc` depends on and add them as
        dependencies for `desc`. Also collect error messages regarding `desc` and
        convert unlocateable descriptions into error messages."""

        if kind == "constant":
            roots = [desc.value]
        elif kind == "struct":
            roots = []
        elif kind == "struct-body":
            roots = [desc.ctype]
        elif kind == "enum":
            roots = []
        elif kind == "typedef":
            roots = [desc.ctype]
        elif kind == "function":
            roots = desc.argtypes + [desc.restype]
        elif kind == "variable":
            roots = [desc.ctype]
        elif kind == "macro":
            if desc.expr:
                roots = [desc.expr]
            else:
                roots = []
        elif kind == "undef":
            roots = [desc.macro]

        cstructs, cenums, ctypedefs, errors, identifiers = [], [], [], [], []

        for root in roots:
            s, e, t, errs, i = visit_type_and_collect_info(root)
            cstructs.extend(s)
            cenums.extend(e)
            ctypedefs.extend(t)
            errors.extend(errs)
            identifiers.extend(i)

        unresolvables = []

        for cstruct in cstructs:
            if kind == "struct" and desc.variety == cstruct.variety and desc.tag == cstruct.tag:
                continue
            if not depend(desc, struct_names, (cstruct.variety, cstruct.tag)):
                unresolvables.append('%s "%s"' % (cstruct.variety, cstruct.tag))

        for cenum in cenums:
            if kind == "enum" and desc.tag == cenum.tag:
                continue
            if not depend(desc, enum_names, cenum.tag):
                unresolvables.append('enum "%s"' % cenum.tag)

        for ctypedef in ctypedefs:
            if not depend(desc, typedef_names, ctypedef):
                unresolvables.append('typedef "%s"' % ctypedef)

        for ident in identifiers:
            if isinstance(desc, MacroDescription) and desc.params and ident in desc.params:
                continue

            elif opts.include_undefs and isinstance(desc, UndefDescription):
                macro_desc = None
                if ident == desc.macro.name:
                    macro_desc = co_depend(desc, ident_names, ident)
                if macro_desc is None or not isinstance(macro_desc, MacroDescription):
                    unresolvables.append('identifier "%s"' % ident)

            elif not depend(desc, ident_names, ident):
                unresolvables.append('identifier "%s"' % ident)

        for u in unresolvables:
            errors.append(("%s depends on an unknown %s." % (desc.casual_name(), u), None))

        for err, cls in errors:
            err += " %s will not be output" % desc.casual_name()
            desc.error(err, cls=cls)

    def add_to_lookup_table(desc, kind):
        """Add `desc` to the lookup table so that other descriptions that use
        it can find it."""
        if kind == "struct":
            if (desc.variety, desc.tag) not in struct_names:
                struct_names[(desc.variety, desc.tag)] = desc
        if kind == "enum":
            if desc.tag not in enum_names:
                enum_names[desc.tag] = desc
        if kind == "typedef":
            if desc.name not in typedef_names:
                typedef_names[desc.name] = desc
        if kind in ("function", "constant", "variable", "macro"):
            if desc.name not in ident_names:
                ident_names[desc.name] = desc

    # Macros are handled differently from everything else because macros can
    # call other macros that are referenced after them in the input file, but
    # no other type of description can look ahead like that.

    for kind, desc in data.output_order:
        add_to_lookup_table(desc, kind)
        if kind != "macro":
            find_dependencies_for(desc, kind)

    for kind, desc in data.output_order:
        if kind == "macro":
            find_dependencies_for(desc, kind)


text:
<!DOCTYPE html>

    <link href="../stylesheets/week6_technical.css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>

DBC Blog

My Facebook

My Twitter

My Github

May 26th, 2014

You down with OOP?

I'm sure by now, many of us are aware that Ruby is an objecte-oriented programming language.  Today, I'll discuss exactly what that means.  I'll also be talking a little bit about what functional programming is and how it relates to OO languages. We'll start by talking about what makes a language like Ruby, object-oriented.

What makes a language Object-Oriented?

Object oriented languages seem to be fairly popular right now, so let's take a closer look at what makes an OO language.  "Object-oriented languages define not only the data type of a data structure, but also the types of operations that can be applied to the data structure." This basically means that data structure becomes an object.  In languages like Ruby and Java, everything is an objet.  This allows programmers to create relationship and functions between multiple objects.  Languages that are OO based also gives programmers the ability to make their programs inherit characteristics of other objects through the usage of classes.

One of the best advantages that object-oriented languages have over other languages is that programmers do not have to change variables as they create new objects. A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.

The major characteristics of functional programming:

Remember how I previously mentioned that OOP languages use objects to create data structures.  Well functional programming languages use functions, instead of objects, as the primary building block of the code. Let's take a closer look at each.

Which language should you choose:

We should now have a better understanding of how each of these languages work.  Now that we have analyzed each language, which one should we use going forward.  In short, that depends.  Both languages have their advantages.

Object-oriented languages are perfect if you have a fixed amount of operations that need to be performed. As your code progresses, you will add new objects that have similar operations.  We are able to create these new objects and methods through the usage of classes.  Classes allow us to create new objects and functions related to that class, without messing with other objects.

Functional languages are good when you have a fixed number of objects and add new functions to these objects as your code evolves. This can be accomplished by adding new functions which compute with existing data types, and the existing functions are left alone. If you still can't decide which language to learn, remember that both languages serve a purpose and will have their own place in the sun. As the saying goes, "Choose the right tool for the job."

Happy coding,

            Matt


text:
module.exports = function checkAuth( key, envelope, next ) {
	const userKey = envelope.headers.bearer;
	return ( !key || userKey === key ) ? next() : { status: 401, data: { message: "unauthorized" } };
};


text:
bool FOnlineNotificationTransportManager::SendNotification(FNotificationTransportId TransportType, const FOnlineNotification& Notification)
{
	IOnlineNotificationTransportPtr* TransportPtrPtr = TransportMap.Find(TransportType);
	if (TransportPtrPtr != NULL)
	{
		bool result = (*TransportPtrPtr)->SendNotification(Notification);
		return result;
	}
	else
	{
		return false;
	}
}

bool FOnlineNotificationTransportManager::ReceiveTransportMessage(FNotificationTransportId TransportType, const IOnlineNotificationTransportMessage& TransportMessage)
{
	IOnlineNotificationTransportPtr* TransportPtrPtr = TransportMap.Find(TransportType);
	if (TransportPtrPtr != NULL)
	{
		bool result = (*TransportPtrPtr)->ReceiveNotification(TransportMessage);
		return result;
	}
	else
	{
		return false;
	}
}

IOnlineNotificationTransportPtr FOnlineNotificationTransportManager::GetNotificationTransport(FNotificationTransportId TransportType)
{
	IOnlineNotificationTransportPtr* TransportPtrPtr = TransportMap.Find(TransportType);

	if (TransportPtrPtr != NULL)
	{
		return *TransportPtrPtr;
	}
	else
	{
		return NULL;
	}
}

void FOnlineNotificationTransportManager::AddNotificationTransport(IOnlineNotificationTransportPtr Transport)
{
	TransportMap.Add(Transport->GetNotificationTransportId(), Transport);
}

void FOnlineNotificationTransportManager::RemoveNotificationTransport(FNotificationTransportId TransportType)
{
	TransportMap.Remove(TransportType);
}

void FOnlineNotificationTransportManager::ResetNotificationTransports()
{
	TransportMap.Empty();
}


text:
package com.pushtechnology.diffusion.examples;

import static com.pushtechnology.diffusion.client.Diffusion.newTopicSpecification;
import static java.lang.String.format;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

import com.pushtechnology.diffusion.client.Diffusion;
import com.pushtechnology.diffusion.client.features.TopicUpdate;
import com.pushtechnology.diffusion.client.features.control.topics.views.TopicViews;
import com.pushtechnology.diffusion.client.session.Session;
import com.pushtechnology.diffusion.client.topics.details.TopicType;
import com.pushtechnology.diffusion.datatype.json.JSON;
import com.pushtechnology.diffusion.datatype.json.JSONDataType;

/**
 * This example shows a control client creating a topic view that uses secondary
 * keys.
 * <p>
 * It presents a simplified sportsbook and uses a topic view to create a
 * secondary key on the country sporting events take place in.
 *
 * @author Push Technology Limited
 * @since 6.3
 */
public final class CreateSecondaryKeys implements AutoCloseable {
    private final Session session;
    private final TopicUpdate topicUpdate;
    private final TopicViews topicViews;
    private final JSONDataType jsonDataType = Diffusion.dataTypes().json();
    private final AtomicInteger idGenerator = new AtomicInteger(0);

    /**
     * Constructor.
     *
     * @param serverUrl for example "ws://diffusion.example.com:80"
     */
    public CreateSecondaryKeys(String serverUrl) {
        session = Diffusion
            .sessions()
            .principal("control")
            .password("password")
            .open(serverUrl);

        topicUpdate = session.feature(TopicUpdate.class);
        topicViews = session.feature(TopicViews.class);
    }

    /**
     * Create a football event.
     *
     * @param country the country the event is in
     * @param homeTeam the home team
     * @param awayTeam the away team
     * @return future representing the creation of the event
     */
    public CompletableFuture<?> createEvent(String country, String homeTeam, String awayTeam) {
        // Create a path for the event containing a unique ID
        final String path = format("Football/All/%d", idGenerator.getAndIncrement());
        // Format the initial value describing the event
        final JSON value = jsonDataType.fromJsonString(format(
            "{\"country\":\"%s\",\"home\":\"%s\",\"away\":\"%s\"}",
            country,
            homeTeam,
            awayTeam));
        return topicUpdate.addAndSet(path, newTopicSpecification(TopicType.JSON), JSON.class, value);
    }

    /**
     * Create a secondary key that groups events by country the event is in.
     *
     * @return future representing the creation of the secondary keys
     */
    public CompletableFuture<?> createSecondaryKeyByCountry() {
        // This creates a single topic view that selects all football events
        // and maps them to a path containing their country, preserving the ID
        // generated for the topic
        return topicViews
            .createTopicView(
                "football-by-country",
                "map '?Football/All/' " +
                    "to 'Football/<scalar(/country)>/<path(2)>'");
    }

    @Override
    public void close() {
        session.close();
    }
}


text:
mkdir -vp ${PREFIX}/bin;
mkdir -vp ${PREFIX}/lib/tika-rest-server/bin;
mkdir -vp ${PREFIX}/lib/tika-rest-server/lib;

cp tika-server-1.9.jar ${PREFIX}/lib/tika-rest-server/lib/;

echo -e '#!/bin/bash\nexec java -jar $(dirname $(dirname $(which tika-rest-server)))/lib/tika-server-1.9.jar "$@"' > ${PREFIX}/lib/tika-rest-server/bin/tika-rest-server;
chmod +x "${PREFIX}/lib/tika-rest-server/bin/tika-rest-server";

echo -e '#!/bin/bash\nexec java -jar $(dirname $(dirname $(which tika-rest-server)))/lib/tika-rest-server/lib/tika-server-1.9.jar "$@"' > ${PREFIX}/bin/tika-rest-server;
chmod +x "${PREFIX}/bin/tika-rest-server";


text:
package net.minecraft.command.server;

import com.mojang.authlib.GameProfile;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.BlockPos;

public class CommandPardonPlayer extends CommandBase
{
    private static final String __OBFID = "CL_00000747";

    public String getCommandName()
    {
        return "pardon";
    }

    /**
     * Return the required permission level for this command.
     */
    public int getRequiredPermissionLevel()
    {
        return 3;
    }

    public String getCommandUsage(ICommandSender sender)
    {
        return "commands.unban.usage";
    }

    /**
     * Returns true if the given command sender is allowed to use this command.
     */
    public boolean canCommandSenderUseCommand(ICommandSender sender)
    {
        return MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().isLanServer() && super.canCommandSenderUseCommand(sender);
    }

    public void processCommand(ICommandSender sender, String[] args) throws CommandException
    {
        if (args.length == 1 && args[0].length() > 0)
        {
            MinecraftServer var3 = MinecraftServer.getServer();
            GameProfile var4 = var3.getConfigurationManager().getBannedPlayers().isUsernameBanned(args[0]);

            if (var4 == null)
            {
                throw new CommandException("commands.unban.failed", new Object[] {args[0]});
            }
            else
            {
                var3.getConfigurationManager().getBannedPlayers().removeEntry(var4);
                notifyOperators(sender, this, "commands.unban.success", new Object[] {args[0]});
            }
        }
        else
        {
            throw new WrongUsageException("commands.unban.usage", new Object[0]);
        }
    }

    public List addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos)
    {
        return args.length == 1 ? getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getConfigurationManager().getBannedPlayers().getKeys()) : null;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<bean type="com.opengamma.financial.convention.OvernightIndexConvention">
 <externalIdBundle>
  <externalIds>
   <item>CONVENTION~USDFEDFUNDS</item>
  </externalIds>
 </externalIdBundle>
 <attributes/>
 <name>USDFEDFUNDS</name>
 <dayCount>Actual/360</dayCount>
 <publicationLag>1</publicationLag>
 <currency>USD</currency>
 <regionCalendar>FINANCIAL_REGION~US</regionCalendar>
</bean>


text:
from trac.core import *
from themeengine.api import ThemeBase

__all__ = ['TracBootstrap3Theme']

class TracBootstrap3Theme(ThemeBase):
    """Bootstrap3 theme for Trac"""
    template = htdocs = screenshot = True