text:
package com.filebreaker.view.frames.samples;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.filebreaker.experiments.Experiment;
import com.filebreaker.experiments.ExperimentsController;
import com.filebreaker.samples.Sample;
import com.filebreaker.samples.SamplesController;
import com.filebreaker.view.dialogs.DuplicateSampleJDialog;
import com.filebreaker.view.frames.ExportFileChooserFactory;
import com.filebreaker.view.frames.RefreshableFrame;
import com.filebreaker.view.i18n.I18n;
import com.filebreaker.view.tables.IdentifiedTableModel;

public class SamplesJFrame extends JFrame implements RefreshableFrame {

	private static final long serialVersionUID = 5223108555053502278L;

	private ExperimentsController experimentsController;

	private SamplesController samplesController;

    private JButton exportButton;

    private JButton newButton;

    private JButton deleteButton;

    private JButton duplicateButton;

    private JLabel sampleLabel;

    private JScrollPane scrollPane;

    private JTable samplesTable;

    private Integer experimentId;

    private JDialog duplicateSampleDialog;

    private JFrame sampleJFrame;

    public SamplesJFrame(ExperimentsController experimentsController, SamplesController samplesController, Integer experimentId) {
    	this.experimentId = experimentId;

    	this.experimentsController = experimentsController;
    	this.samplesController = samplesController;

    	initComponents();
    }

    private void initComponents() {

    	this.setResizable(false);

    	Experiment experiment = experimentsController.getExperiment(this.experimentId);
    	this.setTitle(I18n.getInstance().getString("samples.number") + " " + experiment.getName()); // NOI18N

        sampleLabel = new JLabel();
        exportButton = new JButton();
        scrollPane = new JScrollPane();
        samplesTable = new JTable();
        newButton = new JButton();
        deleteButton = new JButton();
        duplicateButton = new JButton();

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        sampleLabel.setText(I18n.getInstance().getString("samples.title"));

        exportButton.setIcon(new ImageIcon(getClass().getResource("/page_down.gif"))); // NOI18N
        exportButton.setText(I18n.getInstance().getString("samples.export"));
        exportButton.setEnabled(false);
        exportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportButtonActionPerformed(evt);
            }
        });

        samplesTable.setModel(getTableModel());
        samplesTable.addMouseListener(new MouseAdapter() {
        	@SuppressWarnings("unchecked")
			public void mouseClicked(MouseEvent e) {
        		JTable target = (JTable) e.getSource();
        		int row = target.getSelectedRow();

        		if(row != -1){
        			exportButton.setEnabled(true);
        			deleteButton.setEnabled(true);
        			duplicateButton.setEnabled(true);

        			if(e.getClickCount() > 1){
        				IdentifiedTableModel tableModel = (IdentifiedTableModel)target.getModel();
        				Map<String, Object> composedSampleId = (Map<String, Object>) tableModel.getModelId(row);
        				Integer sampleId = (Integer)composedSampleId.get("sampleId");

        				if(sampleJFrame == null || !sampleJFrame.isDisplayable()){
        					sampleJFrame = new SampleJFrame(samplesController, experimentId, sampleId);
        					sampleJFrame.setVisible(true);
        				}
        			}
        		}
        	}
		});

        scrollPane.setViewportView(samplesTable);

        newButton.setIcon(new ImageIcon(getClass().getResource("/note_new.gif"))); // NOI18N
        newButton.setText(I18n.getInstance().getString("samples.new"));
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
            }
        });

        deleteButton.setIcon(new ImageIcon(getClass().getResource("/note_delete.gif"))); // NOI18N
        deleteButton.setText(I18n.getInstance().getString("samples.delete"));
        deleteButton.setEnabled(false);
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        duplicateButton.setIcon(new ImageIcon(getClass().getResource("/note_new.gif"))); // NOI18N
        duplicateButton.setText(I18n.getInstance().getString("samples.duplicate"));
        duplicateButton.setEnabled(false);
        duplicateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                duplicateButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(scrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .add(layout.createSequentialGroup()
                                .add(sampleLabel)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(exportButton)))
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(newButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(deleteButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(duplicateButton)
                        .add(0, 239, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(exportButton)
                    .add(layout.createSequentialGroup()
                        .add(5, 5, 5)
                        .add(sampleLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(scrollPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 246, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(newButton)
                    .add(deleteButton)
                    .add(duplicateButton))
                .addContainerGap(8, Short.MAX_VALUE))
        );

        pack();
    }

    private DefaultTableModel getTableModel() {
    	List<Sample> samples = samplesController.getSamples(this.experimentId);

    	return new IdentifiedTableModel(
            getModel(samples),
            new String [] {
                I18n.getInstance().getString("samples.sample.identifier"),
                I18n.getInstance().getString("samples.sample.creationdate"),
                I18n.getInstance().getString("samples.sample.modificationdate")
            },
            getModelIds(samples)
        );
	}

	private List<Object> getModelIds(List<Sample> samples){
		List<Object> result = new ArrayList<Object>();

		for(Sample sample : samples){
			Map<String, Object> composedId = new HashMap<String, Object>();

			composedId.put("sampleId", sample.getId());
			composedId.put("experimentId", sample.getExperimentId());

			result.add(composedId);
		}

		return result;
	}

    private Object[][] getModel(List<Sample> samples){
    	Object [][] result = null;

		if(samples != null && !samples.isEmpty()){
			result = new Object[samples.size()][3];

			for(int i = 0; i < samples.size(); i++){
				Sample sample = samples.get(i);

				result[i][0] = sample.getId();
				result[i][1] = sample.getCreationDate();
				result[i][2] = sample.getModificationDate();
			}
		}

		return result;
    }

    @SuppressWarnings("unchecked")
	private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	Set<Integer> selectedSamplesId = new HashSet<Integer>();
    	int [] rows = samplesTable.getSelectedRows();
    	IdentifiedTableModel tableModel = (IdentifiedTableModel) samplesTable.getModel();
    	Integer experimentId = null;

    	for(int row : rows){
    		Map<String, Object> composedId = (Map<String, Object>)tableModel.getModelId(row);
    		selectedSamplesId.add((Integer) composedId.get("sampleId"));

    		if(experimentId == null){
    			experimentId = (Integer)composedId.get("experimentId");
    		}
    	}

    	JFileChooser fileChooser = ExportFileChooserFactory.createFileChooser();
		int returnValue = fileChooser.showSaveDialog(null);

		if (returnValue == JFileChooser.APPROVE_OPTION) {
			File saveFile = fileChooser.getSelectedFile();

			try {
				samplesController.exportSamples(selectedSamplesId, experimentId, saveFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    }

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	JFrame sampleEditorJFrame = new SampleEditorJFrame(samplesController, this.experimentId, this);
    	sampleEditorJFrame.setVisible(true);
    }

    public void refresh(){
    	samplesTable.setModel(getTableModel());

    	if(samplesTable.getSelectedRow() == -1){
    		deleteButton.setEnabled(false);
    		exportButton.setEnabled(false);
    		duplicateButton.setEnabled(false);
    	}
    }

    @SuppressWarnings("unchecked")
	private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	Set<Integer> selectedSamplesId = new HashSet<Integer>();
    	int [] rows = samplesTable.getSelectedRows();
    	IdentifiedTableModel tableModel = (IdentifiedTableModel) samplesTable.getModel();
    	Integer experimentId = null;

    	for(int row : rows){
    		Map<String, Object> composedId = (Map<String, Object>)tableModel.getModelId(row);
    		selectedSamplesId.add((Integer) composedId.get("sampleId"));

    		if(experimentId == null){
    			experimentId = (Integer)composedId.get("experimentId");
    		}
    	}

    	samplesController.deleteSamples(experimentId, selectedSamplesId);
    	refresh();
    }

    @SuppressWarnings("unchecked")
	private void duplicateButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	int row = samplesTable.getSelectedRow();

    	if(row != -1){
	    	IdentifiedTableModel tableModel = (IdentifiedTableModel) samplesTable.getModel();

	    	Map<String, Object> composedId = (Map<String, Object>)tableModel.getModelId(row);

	    	Integer sampleId = (Integer) composedId.get("sampleId");
			Integer experimentId = (Integer)composedId.get("experimentId");

			duplicateSampleDialog = new DuplicateSampleJDialog(this, true, samplesController, sampleId, experimentId);
	    	duplicateSampleDialog.setVisible(true);
    	}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.felix.dm.annotation.api;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotates a method which will be invoked when the Service is initializing.
 * All required dependencies are already injected before the annotated method is called, and
 * optional dependencies on class fields are injected with NullObjects if the optional
 * dependencies are not currently available.

 *
 * If some dependencies are declared using a named @{@link ServiceDependency} annotation,
 * then the annotated method may optionally return a Map used to dynamically configure such
 * dependencies (Please refer to @{@link ServiceDependency#name()} attribute for more
 * information about this feature).

 *
 * After the init method returns, the component is then invoked in the method annotated with
 * @{@link Start}, in order to notify that the component is about to be registered into the OSGi
 * registry (if this one provides a service). However, you can take control of when the service is registered,
 * using the @{@link LifecycleController} annotation).
 *
 *
Usage Examples

 * Here, the "VideoPlayer" init method is called after the "log" dependency is injected.
 *

 *

 *
 * @Component
 * public class VideoPlayer {
 *     @ServiceDependency
 *     LogService log;
 *
 *     @Init
 *     void init() {} // initialize our service (the "log" dependency is already injected).
 * }
 *

 *

 *
 * @author Felix Project Team
 */
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface Init
{
}


text:
using DeveloperTest.Enums;
using DeveloperTest.Exceptions;
using DeveloperTest.Logic;
using Limilabs.Client;
using Limilabs.Client.IMAP;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeveloperTest.Model.Connection
{
    abstract class MailConnection : IDisposable
    {
        private readonly string GMAIL_LOGINONBROWSER_MESSAGE = "[ALERT] Please log in via your web browser:";
        private readonly string GMAIL_DOMAIN = "gmail.com";
        protected ClientBase _connection;
        private EncryptionType _encryption;
        private string _server;
        private int _port;
        private string _username;
        private string _password;

        public bool IsConnected
        {
            get
            {
                return _connection.Connected;
            }
        }

        public MailConnection(EncryptionType encryption, string server, int port, string username, string password)
        {
            _encryption = encryption;
            _server = server.Trim();
            _port = port;
            _username = username.Trim();
            _password = password.Trim();
        }

        protected abstract ClientBase getClientObject();
        protected abstract void close();
        protected abstract void startTSL();
        protected abstract void login(string username, string password);
        public abstract IEnumerable GetUids();
        public abstract EnvelopeModel GetEnvelope(object uid);
        public abstract BodyModel GetBody(object uid);

        public void ConnectAndLogin()
        {
            if(_connection != null)
            {
                this.Dispose();
            }
            _connection = getClientObject();

            try
            {

                if (_encryption == EncryptionType.Unencrypted)
                {
                    _connection.Connect(this._server, this._port);
                }
                else
                {
                    _connection.ConnectSSL(this._server, this._port);
                    if (_encryption == EncryptionType.STARTTLS)
                        startTSL();
                }

                login(_username, _password);
            }
            catch(ImapResponseException ire)
            {
                //aditional authentication by gmail
                if (ire.Message.StartsWith(GMAIL_LOGINONBROWSER_MESSAGE, StringComparison.InvariantCultureIgnoreCase) && _server.EndsWith(GMAIL_DOMAIN, StringComparison.InvariantCultureIgnoreCase))
                {
                    //tried to open the gmail authentication page, but it doesn't help
                    //if (ire.Response.Lines.Count > 0)
                    //{
                    //    System.Diagnostics.Process.Start(ire.Response.Lines[0].Substring(ire.Response.Lines[0].IndexOf("http")));
                    //    StatusProvider.DisplayStatus("Please authenticate on the opened web page, and try again.");
                    //}
                    //switching "unsafe authentication" is needed in gmail settings, so displaying the support page describing it
                    var httpPos = ire.Message.IndexOf("http");
                    if(httpPos>-1)
                    {
                        var url = ire.Message.Substring(httpPos);
                        var spacePos = url.IndexOf(" ");
                        if (spacePos > -1)
                            url = url.Substring(0, spacePos);
                        System.Diagnostics.Process.Start(url);
                        ErrorProvider.DisplayError("Gmail authentication failed, please read the opened support page.");
                    }
                }
                else
                    throw new MailServerException(ire.Message);
            }
            catch(ServerException se)
            {
                 throw new MailServerException(se.Message);
            }
        }

        public void Dispose()
        {
            if(_connection!=null)
            {
                close();
                _connection.Dispose();
            }
        }
    }
}


text:
Sites FFJV Mutualisé

# Prerequis Package :
* cronolog
* apache2-mpm-itk
* apache2
* php5 libapache2-mod-php5
* mysql-server php5-mysql
* proftpd
* bsd-mailx / postfix

# Actions

* Creation
* Modification
* Suppresion
* Desactivation temporaire

# Creation

* Recuperer les informations necessaires :
=> Nom du club (nom.ffjv.club)
=> Contact : Mail, Tel, Nom/Prenom (Photcopie de la CNI ?)
=> Generer un ID unique
=> Creations : Vhost Apache ITK, Base de donnee SQL, Compte FTP
=> Send mail

# Modification

Les champs qui peuvent etre modifie :
=> Contact
=> Nom du club

# Suppression

=> Complete (Sauf Log access et web pendant 1an)
=> Contact

# Suspension/Activation

Desactivation d'un site :
=> Changement mot de passe FTP
=> Suppression du vhost


text:
import collections
import importlib.util
import os
import re
import sys
from typing import Dict, List

from json_data_generator.util import (GetDirNameFromPath, GetFileNameFromPath,
                                      GetFileNameWithoutExtensionFromPath,
                                      JoinPath)

_FILE_PATH = os.path.dirname(os.path.realpath(__file__))

_JSON5_PATH = os.path.join(_FILE_PATH, os.pardir, os.pardir, 'third_party',
                           'pyjson5', 'src')
sys.path.insert(1, _JSON5_PATH)
import json5

_JINJA2_PATH = os.path.join(_FILE_PATH, os.pardir, os.pardir, 'third_party')
sys.path.insert(1, _JINJA2_PATH)
import jinja2

class JSONDataGenerator(object):
    '''A generic json data generator.'''

    def __init__(self, out_dir: str):
        self.out_dir = out_dir
        self.model: Dict = {}
        # Store all json sources used in the generator.
        self.sources: List[str] = list()

    def AddJSONFilesToModel(self, paths: List[str]):
        '''Adds one or more JSON files to the model.'''
        for path in paths:
            try:
                with open(path, 'r') as f:
                    self.AddJSONToModel(path, f.read())
                    self.sources.append(path)
            except ValueError as err:
                raise ValueError('\n%s:\n    %s' % (path, err))

    def AddJSONToModel(self, json_path: str, json_string: str):
        '''Adds a |json_string| with data to the model.
        Every json file is added to |self.model| with the original file
        name as the key.
        '''
        data = json5.loads(json_string,
                           object_pairs_hook=collections.OrderedDict)
        # Use the json file name as the key of the loaded json data.
        key = GetFileNameWithoutExtensionFromPath(json_path)
        self.model[key] = data

    def GetGlobals(self, template_path: str):
        file_name_without_ext = GetFileNameWithoutExtensionFromPath(
            template_path)
        out_file_path = JoinPath(self.out_dir, file_name_without_ext)
        return {
            'model': self.model,
            'source_json_files': self.sources,
            'out_file_path': out_file_path,
        }

    def GetFilters(self):
        return {
            'to_header_guard': self._ToHeaderGuard,
        }

    def RenderTemplate(self,
                       path_to_template: str,
                       path_to_template_helper: str = None):
        template_dir = GetDirNameFromPath(path_to_template)
        template_name = GetFileNameFromPath(path_to_template)
        jinja_env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(template_dir),
            keep_trailing_newline=True)
        jinja_env.globals.update(self.GetGlobals(path_to_template))
        jinja_env.filters.update(self.GetFilters())
        if path_to_template_helper:
            template_helper_module = self._LoadTemplateHelper(
                path_to_template_helper)
            jinja_env.globals.update(
                template_helper_module.get_custom_globals(self.model))
            jinja_env.filters.update(
                template_helper_module.get_custom_filters(self.model))
        template = jinja_env.get_template(template_name)
        return template.render()

    def _LoadTemplateHelper(self, path_to_template_helper: str):
        template_helper_dir = GetDirNameFromPath(path_to_template_helper)
        try:
            sys.path.append(template_helper_dir)
            spec = importlib.util.spec_from_file_location(
                path_to_template_helper, path_to_template_helper)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            return module
        finally:
            # Restore sys.path to what it was before.
            sys.path.remove(template_helper_dir)

    def _ToHeaderGuard(self, path: str):
        return re.sub(r'[\/\.\-]+', '_', path.upper())


text:
plaso.output package
====================

Submodules
----------

plaso.output.dynamic module
---------------------------

.. automodule:: plaso.output.dynamic
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.formatting\_helper module
--------------------------------------

.. automodule:: plaso.output.formatting_helper
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.interface module
-----------------------------

.. automodule:: plaso.output.interface
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.json\_line module
------------------------------

.. automodule:: plaso.output.json_line
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.json\_out module
-----------------------------

.. automodule:: plaso.output.json_out
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.kml module
-----------------------

.. automodule:: plaso.output.kml
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.l2t\_csv module
----------------------------

.. automodule:: plaso.output.l2t_csv
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.logger module
--------------------------

.. automodule:: plaso.output.logger
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.manager module
---------------------------

.. automodule:: plaso.output.manager
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.mediator module
----------------------------

.. automodule:: plaso.output.mediator
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.null module
------------------------

.. automodule:: plaso.output.null
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.opensearch module
------------------------------

.. automodule:: plaso.output.opensearch
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.opensearch\_ts module
----------------------------------

.. automodule:: plaso.output.opensearch_ts
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.rawpy module
-------------------------

.. automodule:: plaso.output.rawpy
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.shared\_dsv module
-------------------------------

.. automodule:: plaso.output.shared_dsv
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.shared\_json module
--------------------------------

.. automodule:: plaso.output.shared_json
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.shared\_opensearch module
--------------------------------------

.. automodule:: plaso.output.shared_opensearch
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.tln module
-----------------------

.. automodule:: plaso.output.tln
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.winevt\_rc module
------------------------------

.. automodule:: plaso.output.winevt_rc
   :members:
   :undoc-members:
   :show-inheritance:

plaso.output.xlsx module
------------------------

.. automodule:: plaso.output.xlsx
   :members:
   :undoc-members:
   :show-inheritance:

Module contents
---------------

.. automodule:: plaso.output
   :members:
   :undoc-members:
   :show-inheritance:


text:
package proto.shipping;

/**
 * Created by stumeikle on 15/09/20.
 */
public class Shipping {
}


text:
typedef unsigned long ulong;

enum CTimerFlags {
  CTIMER_FLAGS_NONE      = 0,
  CTIMER_FLAGS_REPEAT    = (1<<0),
  CTIMER_FLAGS_NO_DELETE = (1<<1),
  CTIMER_FLAGS_NO_ACTIVE = (1<<2)
};

#define CTimerMgrInst CTimerMgr::getInstance()

class CTimer;

class CTimerMgr {
 public:
  static CTimerMgr *getInstance() {
    static CTimerMgr *instance;

    if (! instance)
      instance = new CTimerMgr;

    return instance;
  }

  void setExternalUpdate(bool flag) { external_update_ = flag; }

  void addTimer(CTimer *timer);

  void removeTimer(CTimer *timer);

  void tick();

 private:
  CTimerMgr();

  static void signalHandler(int sig);

  void updateTimers();

  void updateTimer(ulong msecs);
  void getTimer(ulong *msecs);
  void setTimer(ulong msecs);

 private:
  typedef std::list<CTimer *> TimerList;
  typedef std::set <CTimer *> TimerSet;

  bool             external_update_;
  bool             signal_handler_;
  TimerList        timers_;
  TimerSet         rtimers_;
  bool             itimer_active_;
  ulong            itimer_msecs_;
  bool             timer_updating_;
  struct itimerval itimer_;
  CHRTime          last_t_;
};

class CTimer {
 private:
  ulong       msecs_init_;
  ulong       msecs_left_;
  CTimerFlags flags_;

 protected:
  bool active_;

 public:
  CTimer(ulong msecs, CTimerFlags flags=CTIMER_FLAGS_NONE);

  virtual ~CTimer();

  ulong getMSecsInit() const { return msecs_init_; }
  ulong getMSecsLeft() const { return msecs_left_; }

  void setMSecsLeft(ulong msecs_left) { msecs_left_ = msecs_left; }

  void stop();

  void restart();

  void restart(ulong msecs);

  bool isActive() const { return active_; }

  void setActive(bool active) { active_ = active; }

  bool isRepeat() const { return (flags_ & CTIMER_FLAGS_REPEAT); }

  bool isDelete() const { return ! (flags_ & CTIMER_FLAGS_NO_DELETE); }

  virtual void timeOut() { }
};

#endif


text:
__author__ = "Ted Wen"
__version__ = "0.1"

import logging, random, urllib
from datetime import datetime,timedelta
from re import compile
from google.appengine.ext import db
from google.appengine.api import taskqueue
from google.appengine.api import mail
from google.appengine.api.memcache import get as from_cache,set as to_cache,delete as decache
from models import *

def get_user_by_key(uid,usecache=True):
    """ Get SuiUser entity from datastore by key_name, return None if not existent.
    @param uid: fb_1234 like
    @param usecache: if True, Get from memcache first, and Put in memcache or not, default is True.
    """
    if usecache:
        u = from_cache(uid)
    else:
        u = None
    if not u:
        logging.debug('UID %s not in memcache'%uid)
        try:
            u = SuiUser.get_by_key_name(uid)
            if u is None:
                logging.debug('User not in SuiUser')
                return u
            if usecache:
                u._cache_time = datetime.utcnow()
                to_cache(uid, u, PLAYER_CACHE_SECS)
        except Exception,e:
            logging.error('helper.get_user_by_key(%s) error:%s' % (uid,e))
            raise
    return u

def query_user_by_key(uid):
    u = from_cache(uid)
    if not u:
        u = SuiUser.get_by_key_name(uid)
    return u

def create_user(uid,fullname,emailaddr=None,save=True):
    """ Create SuiUser entity and save in datastore and memcache as well.
        Dau record is added as new-registers count of today.
        @param uid: such as "FB_1234567"
        @param fullname: such as "Ted Wen"
        @param emailaddr: user's email address is any
    """
    try:
        u = SuiUser(key_name=uid,name=fullname,email=emailaddr)
        td = datetime.utcnow()
        if save:
            u.save()
            #u.put()
            #to_cache(uid, u, PLAYER_CACHE_SECS)
        taskqueue.add(url='/task/dau',params={'act':'register','usr':uid})
        try:
            send_email('SuiComics New User: %s[%s]'%(uid, fullname or ''), 'Email: %s, Time: %s'%(emailaddr or '',datetime.utcnow()))
        except:
            logging.warning('helper.create_user(%s,%s) failed to send_email'%(uid,fullname))
            pass
        return u
    except:
        logging.error('helper.create_user() SuiUser put error')
        raise

def unregister_user(uid):
    """ Set user's active status to False because Facebook user issued a remove app, etc.
    """
    try:
        u = SuiUser.get_by_key_name(uid)
        if u:
            u.active = False
            u.put()
            decache(uid)
        else:
            logging.warning('User %s not found while de-authorizing'%uid)
    except Exception,e:
        logging.exception(e)

def load_media(keyname):
    """ Load an image from MediaStore, if a page image, return None. """
#    logging.info('loading media %s'%keyname)
    if keyname.startswith('bp'):
        return None
    mm = MediaStore.load_by_key(keyname)
#    if not mm and keyname.startswith('bkc_'):
#        mm = MediaStore.load_by_key(keyname.replace('bkc_','bk_'))
    return mm

def send_email(sbj, txt, toemail='customer@suinova.com'):
    """ email Suinova customer service group by admin upon user registration """
    try:
        mail.send_mail(sender='tedwen@suinova.com', to=toemail, subject=sbj, body=txt)
    except Exception,e:
        logging.error('error notifyOwner:%s'%e)

def notify_followers(abid,subject,body):
    """ Send email to all followers one by one via MailQueue. followers are {"uid":"email",..} """
    sfs = SuiFollower.all().filter('id =', abid).fetch(100)
    fans = {}
    for sf in sfs:
        fans.update(sf.get_fans())  #{"uid":"email",..}
    if len(fans) <= 0:
        return
    queue = Queue('MailQueue')
    for ts in fans.values():
        if mail.is_email_valid(ts):
            queue.add(Task(url='/task/mail',params={'to':rto,'sbj':subject,'bdy':body}))    #task will call send_email above

def email(request):
    """ Called by task queue /task/mail
    """
    to = self.request.get('to')
    sbj = self.request.get('sbj')
    bdy = self.request.get('bdy')
    #logging.debug('Sending %s to %s' % (sbj,to))
    send_email(sbj,bdy,to)

def log(request):
    """ taskqueue routine to log important activities.
        'usr':me.key().name(),'act':'buy %d %s'%(qty,itm),'dt':'2011-01-01 01:01:01.1234'
    """
    us = request.get('usr')
    ac = request.get('act')
    dt = request.get('dt')
    if not dt:
        dt = datetime.utcnow()
    if dt.find('.')>0:
        dt = dt[:dt.find('.')]
    t = datetime.strptime(dt,'%Y-%m-%d %H:%M:%S')
    lg = SuiLog(user=us,action=ac,donetime=t)
    lg.put()

def dau(request):
    """ New DAU routine to log a user's session.
        /task/dau?usr=uid&act=<action>
        <action>: register, login, open(book_id), buy(item_id)
    """
    usr = request.get('usr')
    act = request.get('act')
    par = request.get('par')
    qty = request.get('qty')
    SuiDau.add(usr,act,par,qty)

def add_book_to_genre(request):
    """ From task/genre """
    genres = request.get('genre')    #can be multiple separated by commas
    bkid = request.get('bkid')
    for genre in list(set(genres.split(','))):
        if not genre: continue
        g = SuiGenre.get_by_key_name(genre)
        if g:
            if g.books:
                g.books.append('%s'%bkid)
            else:
                g.books = ['%s'%bkid]
            g.put()
    SuiGenre.clear_cache()

def dau_deprecated(request):
    """ taskqueue routine to store number of daily visits. """
    nusers = nregisters = nvisits = npays = 0
    susers = request.get('users')
    if susers != '':
        try:
            nusers = int(susers)
        except: pass
    sregisters = request.get('registers')
    if sregisters != '':
        try:
            nregisters = int(sregisters)
        except: pass
    svisits = request.get('visits')
    if svisits != '':
        try:
            nvisits = int(svisits)
        except: pass
    spays = request.get('pays')
    if spays != '':
        try:
            npays = int(spays)
        except: pass
    book = request.get('book')
    if book == '': book = '-'
    dt = request.get('dt')
    if dt == '':
        dt = str(datetime.date(datetime.utcnow()))
    dt_book = '%s_%s' % (dt,book)
    def txn():
        dau = SuiDau.get_by_key_name(dt_book)
        if dau is None:
            dau = SuiDau(key_name=dt_book,visits=nvisits,users=nusers,registers=nregisters,pays=npays,book=book)
        else:
            dau.visits += nvisits
            dau.users += nusers
            dau.registers += nregisters
            dau.pays += npays
        dau.put()
    try:
        db.run_in_transaction(txn)
    except Exception,e:
        logging.error('helper.dau error:%s'%e)

def send_emails(me, toemails, msg):
    """ send email to toemails.
        TODO: this may not work since me may not be a Google Account user!
    """
    if not mail.is_email_valid(toemails):
        raise Exception('Invalid email address')
    try:
        logging.debug('Sending email to %s'%toemails)
        mail.send_mail(sender=me.email, to=toemails, subject='You are invited by your friend!', body=msg)
    except Exception,e:
        logging.error('error send_mail(%s,%s,%s,%s):%s'%(me.key().name(),toemails,'',msg,e))
        raise

def get_news():
    """ read system news if any """
    news = from_cache(gGameNewsCacheKey)
    if news is None:
        return '[]'
    newsbuf = []
    td = datetime.utcnow()
    for ns in news:
        if ns[1] > td:
            newsbuf.append(ns[0])
    return newsbuf

def get_new_stories(N=10):
    """ Load N latest stories, return [[key,title],..] """
    stories = from_cache('NewStories')
    if stories is None:
        qs = SuiStory.all().order('-postime').fetch(N)
        stories = [[str(q.key()),q.title] for q in qs]
        to_cache('NewStories',stories)  #only when new stories added, invalidate this cache
    return stories

def load_stories(game='all',cursor='',pagesize=50,sortorder='-postime'):
    """ Return a page of stories.
        This function makes use of cursor mechanism to fetch pages and cache them for efficient repeated queries.
        Once a page of SuiStory entities are loaded, they are memcached with the cursor.
        If not enough entities are loaded, cursor is None meaning no more pages.
        Stories are sorted for display by postime in descending order.
        Pages are always in memcache of 'Stories', invalidated when a new story is added.
        @param game : game key or all
        @param cursor : from which cursor to fetch, '' = first page
        @param pagesize : how many for a page, default 30
        @param sortorder : postime in descending by default, can be 'title', 'author'
        @return : ([SuiStory,...],cursor) tuple of a list of SuiStory entities or None
    """
    cachekey = 'Stories_%s_%s'%(game,cursor)
    stories = from_cache(cachekey)
    if stories is None:
        if game != 'all':
            query = SuiStory.all().filter('game =',game).order(sortorder)
        else:
            query = SuiStory.all().order(sortorder)
        if cursor != '':
            query.with_cursor(cursor)
        mstories = query.fetch(pagesize)
        if len(mstories) > 0:
            c = None
            if len(mstories) >= pagesize:
                c = query.cursor()
            stories = (mstories,c or '')
            to_cache(cachekey,stories)
        else:
            stories = ([],'')
    return stories

def filter_tag(m):
    """ Filter out HTML tags except single-letter ones such as

. """
    if len(m.group(1)) < 3:
        return m.group(0)
    else:
        return ''

XML_REPTN=compile(r'</?([^>]*)>')

def add_story(me,title,content,game):
    """ save a story in my name.
    """
    if title is None or title == '':
        logging.warning('title is empty')
        raise Exception('No title')
    if content is None or content == '':
        logging.warning('content is empty')
        raise Exception('No content')
    s = SuiStory()
    s.title = title.replace('<','<')
    #s.text = content.replace('<','<').replace('\n','
').replace('\r','')
    s.game = game
    s.author = me.key().name()
    s.aname = me.name
    s.postime = datetime.utcnow()
    s.put()
    #save content text into SuiContent
    c = SuiContent(parent=s)
    if content.find('\n')>=0:
        content = content.replace('\r\n','
').replace('\n','
');
    c.text = XML_REPTN.sub(filter_tag, content)
    c.length = len(c.text)
    c.put()
    pages = from_cache('Stories_all')
    if pages is not None:
        page1 = pages[0]
        if len(page1[0]) > 40:
            decaches(['Stories_all','NewStories'])
        else:
            page1[0].insert(0,s)
            to_cache('Stories_all',pages)
            decache('NewStories')

def load_comments(story,page=0):
    """ Load all SuiContent entities for story and return text and comments of first entity.
        @param story - key string of SuiStory
        @param page - which entity of SuiContent for this story, 0 first by default, can be 10 pages maximum.
    """
    if isinstance(story,basestring):
        skey = db.Key(story)
    else:
        skey = story
    mckey = str(skey)+'_cms'
    content = from_cache(mckey)
    if content is None:
        content = SuiContent.all().ancestor(skey).fetch(10)
        if content:
            to_cache(mckey, content)
        else:
            return None
    if len(content) > page:
        return content[page]
    else:
        return content[-1]

def load_comments0(story,page=0,pagesize=50):
    """ Load a page of comments for a story. Page of comments are also memcached until a new comment is added.
    """
    if isinstance(story,SuiStory):
        skey = story.key()
    elif isinstance(story,basestring):
        skey = db.Key(story)
    else:
        skey = story
    mckey = str(skey)+'_cms'
    comments = from_cache(mckey)
    if comments is None:
        query = SuiComment.all().filter('story =',skey).order('-postime')
        cmts = query.fetch(pagesize)
        if len(cmts) > 0:
            c = None
            if len(cmts) >= pagesize:
                c = query.cursor()
            comments = [(cmts,c)]
            to_cache(mckey, comments)
        else:
            return [([],None)]
    elif page >= len(comments) and comments[-1][1] is not None:
        query = SuiComment.all().filter('story =',skey).order('-postime')
        query.with_cursor(comments[-1][1])
        cmts = query.fetch(pagesize)
        if len(cmts) >= pagesize:
            comments.append((cmts,query.cursor()))
        else:
            comments.append((cmts,None))
        to_cache(mckey,comments)
    return comments[page]

def add_comment(me,story,comment):
    """ Add a comment """
    if isinstance(story,basestring):
        skey = db.Key(story)
    else:
        skey = story
    if not comment:
        return
    elif comment.find('\n'):
        comment = comment.replace('\r\n','
').replace('\n','
')
    mckey = str(skey)+'_cms'
    content = from_cache(mckey)
    if content is None:
        content = SuiContent.all().ancestor(skey).fetch(10)
        if not content:
            raise Exception('Story not found')
    c = content[-1]
    cp = 'c%d' % c.count
    c.count += 1
    pfx = '[%s:%s@%s]'%(me.key().name(),me.name,datetime.strftime(datetime.utcnow(),'%Y-%m-%d %H:%M:%S'))
    setattr(c, cp, '%s%s'%(pfx, XML_REPTN.sub(filter_tag, comment)))
    c.put()
    to_cache(mckey, content)

def add_comment0(me,story,content):
    """ Add a comment to a story. """
    c = SuiComment()
    c.story = db.Key(story)
    logging.debug(story)
    c.text = content
    c.author = '%s[%s]'%(me.name,me.key().name())
    c.postime = datetime.utcnow()
    c.put()
    mckey = str(story)+'_cms'
    if mckey is not None:
        pages = from_cache(mckey)
        if pages is not None:
            page1 = pages[0][0]
            if len(page1) > 60:
                decache(mckey)
            else:
                page1.insert(0,c)
                to_cache(mckey,pages)

def lock_process(lock_key):
    """ Emulate a lock to stop the code going on if the process is still going on.
        This can happen when a user repeatedly clicks on buy button that causes invalid transaction.
        If memcache is not available, this will definately raise an exception and causes the routine to fail.
        Algorithm: check whether a memcache is available, if not, add it for 30 seconds, and return, if yet, raises ServerBusy exception.
    """
    lock = from_cache(lock_key)
    if lock is None:
        if to_cache(lock_key,lock_key,30) == False:
            raise Exception('Server Error, try later')
    else:
        raise Exception('Server Busy, try later')

def unlock_process(lock_key):
    """ Unlock the process/method that's just locked.
    """
    decache(lock_key)

def add_signature(params, secret):
    """ Sort all key=value pairs in params dict and add secret string to the end and make a md5 signature hexdigest and add "sig":signature to the params.
        If params has sig key, then it is deleted.
    """
    if params is None or secret is None:
        logging.error('param or secret None')
        raise Exception('Param or secret None')
    if 'sig' in params:
        del params['sig']
    s = ''.join(['%s=%s'%(k,params[k]) for k in sorted(params.keys())])
    logging.debug('helper.add_signature, s=[%s]'%s)
    sigs = hashlib.md5(s + secret).hexdigest()
    params['sig'] = sigs
    logging.debug('secret=[%s],sig=[%s]'%(secret,sigs))

def save_page_image(u,bkid,pgid,ext,imgdata):
    """ Validate user, book author, page existence, and image size
    """
    bk = SuiBook.seek_by_id(bkid)
    if not bk:
        raise Exception('Book not found')
    if u.key().name() not in bk.authors:
        raise Exception('Author only')
    pg = SuiPage.get_by_id(int(pgid))
    if not pg:
        raise Exception('Page not found')
    imgkey = 'bp%s_%s' % (bkid,pgid)
    img = MediaStore.get_by_key_name(imgkey)
    if not img:
        img = MediaStore(key_name=imgkey,book=bkid,page=int(pgid),usage='0',format=ext.lower())
    else:
        pg.version += 1
        img.decache()
    from google.appengine.api import images
    m = images.Image(imgdata)
    if m.width > 740:
        m.resize(740)
        if ext=='jpg':
            img.stream = db.Blob(m.execute_transforms(images.JPEG))
        else:
            img.stream = db.Blob(m.execute_transforms())
    else:
        img.stream = db.Blob(imgdata)
    img.width = m.width
    img.height = m.height
    img.put()
    a = u.get_author()
    a.spaceused += len(db.model_to_protobuf(img).Encode())
#    logging.info('helper.save_page_image, image size=%d'%len(db.model_to_protobuf(img).Encode()))
    a.save()
    u.recache()

def fb_app_atoken(app_id,app_secret):
    """ Get Facebook access_token for application. """
    access_token = None
    args = {'grant_type':'client_credentials','client_id':app_id,'client_secret':app_secret}
    file = None
    try:
        file = urllib.urlopen('https://graph.facebook.com/oauth/access_token',urllib.urlencode(args))
        resp = file.read()
        if resp.startswith('access_token='):
            access_token = resp[13:]
            logging.debug('access_token=%s'%access_token)
        else:
            logging.error('Facebook access_token returned %s'%resp)
    finally:
        if file: file.close()
    return access_token

def fb_app_feed(args):
    """ post feed to the app wall """
    FACEBOOK_APP_ID = "179008415461930" #Suinova Comics (http://apps.facebook.com/suicomics)
    FACEBOOK_APP_SECRET = "9e194f115ba46d6ba6daafb1e6fe3d86"
    access_token = fb_app_atoken(FACEBOOK_APP_ID,FACEBOOK_APP_SECRET)
    if not access_token:
        return
    args['access_token']=access_token
    file = None
    try:
        file = urllib.urlopen('https://graph.facebook.com/%s/feed'%FACEBOOK_APP_ID,urllib.urlencode(args))
        resp = file.read()
        #logging.debug('post to wall return:%s'%resp)
    finally:
        if file: file.close()

def post_feed(cmd,request):
    """ Post sns feed to facebook application page.
    curl -F grant_type=client_credentials -F client_id=179008415461930 -F client_secret=9e194f115ba46d6ba6daafb1e6fe3d86 https://graph.facebook.com/oauth/access_token
    curl -d "access_token=179008415461930|lNzzs_rKfeEguA5l3Zs_vKYfcOw&message=Hello+world" https://graph.facebook.com/179008415461930/feed
    """
    if cmd == 'add_book':
        uid = request.get('uid')
        bkid = request.get('bkid')
        uname = request.get('uname')
        title = request.get('title')
        intro = request.get('intro')
        if uid and bkid and uname and title:
            args={'name':'New Book: %s'%title,'caption':'By %s'%uname}
            args['link']='http://apps.facebook.com/suicomics/book/'+bkid
            args['picture']='http://suicomics.appspot.com/mm/bk_'+bkid+'.jpg'
            args['description']=intro[:400]
            fb_app_feed(args)
    elif cmd == 'add_page':
        uname = request.get('uname')
        bkid = request.get('bkid')
        title = request.get('title')
        if uname and bkid and title:
            args={'message':'Book Update: %s by %s'%(title,uname)}
            args['actions']='{"name":"Read","link":"http://apps.facebook.com/suicomics/book/%s"}'%bkid
            fb_app_feed(args)

def remind_users(web,args=None):
    """ Weekly job to check users not login for over a week, and remind by a fb bookmark counter plus or email notification.
        If uid is fb_xxx, send bookmark counter+1, else if has email, send a note.
        Each time, fetch 1000 users.
        Not send every week, but follow this pattern: every time first month, every other time next two months, then every third time, and forth.
        After a year, stop sending anything.
        NOTE: only Facebook bookmark counter supported, no emails are sent
        TODO: use query cursor and repeated tasks to finish all updates
    """
    #web.require_admin()    #for admin or taskqueue call only
    #SEND_WEEKS = [1,2,3,4, 6,8, 10,12, 15,18,21,24, 28,32,36,40, 44,48,52]  #not used for now, just facebook supported currently
    today = datetime.utcnow()
    lastweek = today - timedelta(days=7)
    lastyear = today - timedelta(days=365)
    logging.debug('helper.remind_users: weekly task to find users to add fb count')
    usrs = SuiUser.all(keys_only=True).filter('lastime <',lastweek).filter('lastime >',lastyear).fetch(1000)
    fbus = []
    for u in usrs:
        if u.name().startswith('fb_'):
            fbus.append(u.name()[3:])
    if fbus:
        # https://api.facebook.com/method/dashboard.multiIncrementCount?uids=
        FACEBOOK_APP_ID = "179008415461930" #Suinova Comics (http://apps.facebook.com/suicomics)
        FACEBOOK_APP_SECRET = "9e194f115ba46d6ba6daafb1e6fe3d86"
        access_token = fb_app_atoken(FACEBOOK_APP_ID,FACEBOOK_APP_SECRET)
        if not access_token:
            logging.warning('helper.remind_users: failed to get APP access_token')
            return
        args = {'access_token':access_token,'uids':'[%s]'%','.join(['"%s"'%s for s in fbus])}
        file = None
        try:
            logging.debug('helper.remind_users: sending %s to multiIncrementCount'%args)
            url = 'https://api.facebook.com/method/dashboard.multiIncrementCount?%s'%(urllib.urlencode(args))
            file = urllib.urlopen(url)
#            file = urllib.urlopen('https://api.facebook.com/method/dashboard.multiIncrementCount',urllib.urlencode(args))
            resp = file.read()
            if resp and resp.find('<error_code>') > 0:
                logging.debug('helper.remind_users multiIncrementCount returned: %s'%resp)
        except:
            logging.warning('helper.remind_users urlfetch error, ignored')
        finally:
            if file: file.close()
    else:
        logging.debug('helper.remind_users: no users to remind')

def clear_fb_count(uid):
    """ if fb bookmarks count > 0, reset it. """
    FACEBOOK_APP_ID = "179008415461930"
    FACEBOOK_APP_SECRET = "9e194f115ba46d6ba6daafb1e6fe3d86"
    access_token = fb_app_atoken(FACEBOOK_APP_ID,FACEBOOK_APP_SECRET)
    url = 'https://api.facebook.com/method/dashboard.setCount?count=0&uid=%s&access_token=%s'%(uid,access_token)
    file = None
    try:
        logging.debug('helper.clear_fb_count')
        file = urllib.urlopen(url)
        resp = file.read()
        if resp and resp.find('<error_code>') > 0:
            logging.debug('helper.clear_fb_count dashboard.setCount returned: %s'%resp)
    finally:
        if file: file.close()

def load_gifts(uid=None):
    """ Load gift ids from SuiBirthdayGift entities and store in memcache by BD_GIFTS_ALL or BD_GIFTS_creatorID
        Maximum number of gifts in use for all is 10000, while any creator can have no more than 20
    """
    if uid:
        gs = from_cache('BD_GIFTS_%s'%uid)
        if not gs:
            es = SuiBirthdayGift.all(keys_only=True).filter('creator =',uid).fetch(50)
            gs = [e.id_or_name() for e in es]
            to_cache('BD_GIFTS_%s'%uid, gs)
    else:
        gs = from_cache('BD_GIFTS_ALL')
        if not gs:
            es = SuiBirthdayGift.all(keys_only=True).fetch(10000)
            gs = [e.id_or_name() for e in es]
            to_cache('BD_GIFTS_ALL', gs)
    return gs

def update_gift_cache(op,gid,uid=None):
    gs = from_cache('BD_GIFTS_ALL')
    if gs and not gid in gs:
        if op == 'add':
            gs.append(gid)
        elif op == 'del':
            gs.remove(gid)
        to_cache('BD_GIFTS_ALL', gs)
    gs = from_cache('BD_GIFTS_%s'%uid)
    if gs and not gid in gs:
        if op == 'add':
            gs.append(gid)
        elif op == 'del':
            gs.remove(gid)
        to_cache('BD_GIFTS_%s'%uid)

def run_send_as_task(web, args=None):
    taskqueue.add(url='/task/birthday',params={})

def send_birthday_gifts(web,args=None):
    """ Check a list of users friends for birthdays and send gifts accordingly.
        Called every 24 hours,
        get all registered users for sending gifts,
        issue a task for each user as /task/bdaygift?u=uid&g=gid

    """
    #web.require_admin()    #for admin or taskqueue call only
    #logging.debug('helper.send_birthday_gifts: enter')
    uq = SuiBirthdayUser.all()
    #logging.debug('helper.send_birthday_gifts: SuiBirthdayUser.all() returned')
    cursor = web.request.get('cursor')
    #logging.debug('helper.send_birthday_gifts: cursor=%s'%cursor)
    if cursor:
        uq.with_cursor(cursor)
    usrs = uq.fetch(500)
    if not usrs:
        logging.debug('helper.send_birthday_gifts: no birthday user')
        return
    today = datetime.utcnow()
    tk = '%02d-%02d' % (today.month,today.day)
    count = 0
    gs = load_gifts()
    if not gs:
        logging.debug('helper.send_birthday_gifts: no gifts available')
        return
    n = len(gs)-1
    for u in usrs:
        #if u.key().name()=='fb_669391906':
        #    logging.debug('TODO: remove this test mode')
        #    continue
        bdays = u.get_birthdays()
        excludes = u.get_excludes()
        logging.debug('helper.send_birthday_gifts: date:%s, user %s(%s) has %s birthday friends'%(tk,u.key().name(),u.name or '',len(bdays)))
        if tk in bdays:
            for uid in bdays[tk].split(','):
                if not uid: continue
                if uid[0] in ['M','F']:
                    gender = uid[0]
                    uid = uid[1:]
                else:
                    gender = 'B'
                if not uid in excludes:
                    if u.usemyown and u.mygifts:
                        mgs = u.get_mygifts()
                        if mgs and len(mgs)>0:
                            gift = get_random_gift(mgs,gender)
                        else:
                            gift = get_random_gift(gs,gender)
                    else:
                        gift = get_random_gift(gs,gender)
                    if gift:
                        logging.debug('helper.send_birthday_gifts: issue task to send gift %s to %s'%(gift,uid))
                        taskqueue.add(url='/task/bdaygift',params={'uid':uid,'at':u.access_token,'g':gift})
        count += 1
    if count >= 500:
        logging.debug('helper.send_birthday_gifts: more than 500, issue another task')
        taskqueue.add(url='/task/birthday',params={'cursor':uq.cursor()})

def get_random_gift(gs,gender):
    """ Find a same-gender gift from gs, if no same-gender one in 10 tries, randomly choose one. """
    n = len(gs)-1
    if n < 0: return None
    if gender.startswith('B'):
        return gs[random.randint(0,n)]
    for i in xrange(10):
        g = gs[random.randint(0,n)]
        if g.startswith(gender):
            return g
    return gs[random.randint(0,n)]

def send_gift(web):
    uid = web.request.get('uid')
    access_token = web.request.get('at')
    gift = web.request.get('g')
    if not uid:
        logging.debug('helper.send_gift: no uid')
        return
    if not access_token:
        logging.debug('helper.send_gift: no access_token')
        return
    if not gift:
        logging.debug('helper.send_gift: no gift')
        return
    logging.debug('helper.send_gift (task): sending gift to %s'%uid)
    args = {'access_token':access_token}
    args['message'] = 'Happy Birthday!'
    args['name'] = 'Here is a virtual gift for you!'
    args['link'] = 'http://apps.facebook.com/suicomics/gift/open?g=%s'%gift
    args['caption'] = "Open to see what's in it."
    args['picture'] = 'http://suicomics.appspot.com/img/gift.png?v=2'
    args['actions'] = '{"name":"Open it!","link":"http://apps.facebook.com/suicomics/gift/open?g=%s"}'%gift
    #args['description']=''
    file = None
    try:
        file = urllib.urlopen('https://graph.facebook.com/%s/feed'%uid,urllib.urlencode(args))
        resp = file.read()
#        logging.debug('helper.send_gift: feed posted to %s, result: %s'%(uid,resp))
    except:
        logging.warning('helper.send_gift: urlfetch error, ignored')
    finally:
        if file: file.close()

def get_friends(me,fields=None):
    """ FB Get friends using graph api with fields.
    """
    url = 'https://graph.facebook.com/me/friends?access_token=%s'%me.access_token
    if fields:
        url += '&fields=%s'%fields
    resp = None
    try:
        logging.debug('helper.get_friends, about to call graph api')
        #file = urllib.urlopen(url,urllib.urlencode(args))
        file = urllib.urlopen(url)
        resp = file.read()
        logging.debug('helper.get_friends: read=%s'%resp)
    finally:
        if file: file.close()
    return resp

GIFT_VIEW_HTML='''

This gift was designed by  for the free Birthday-Gift Agent on Suinova Comics.

<input type="checkbox" checked="checked"> I like this gift-sending agent, too! Check it out.

'''

def gen_gift_view(gid):
    """ Return a html page for gift view.
    """
    uid = None
    gs = SuiBirthdayGift.get_by_key_name(gid)
    if gs:
        uid = gs.creator
        if uid.startswith('fb_'):
            uid=uid[3:]
    if not uid: uid = '669391906'
    html = GIFT_VIEW_HTML % (gid,uid,uid)
    return html


text:
package org.apache.druid.indexing.seekablestream.supervisor;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;

import javax.annotation.Nullable;

/**
 * Defines if and when {@link SeekableStreamSupervisor} can become idle.
 */
public class IdleConfig
{
  private final boolean enabled;
  private final Long inactiveAfterMillis;

  @JsonCreator
  public IdleConfig(
      @Nullable @JsonProperty("enabled") Boolean enabled,
      @Nullable @JsonProperty("inactiveAfterMillis") Long inactiveAfterMillis
  )
  {
    Preconditions.checkArgument(
        inactiveAfterMillis == null || inactiveAfterMillis > 0,
        "inactiveAfterMillis should be a postive number"
    );
    this.enabled = enabled != null && enabled;
    this.inactiveAfterMillis = inactiveAfterMillis;
  }

  @JsonProperty
  public boolean isEnabled()
  {
    return this.enabled;
  }

  @JsonProperty
  public Long getInactiveAfterMillis()
  {
    return this.inactiveAfterMillis;
  }

  @Override
  public String toString()
  {
    return "idleConfig{" +
           "enabled=" + enabled +
           ", inactiveAfterMillis=" + inactiveAfterMillis +
           '}';
  }
}


text:
const fs = require('fs');
const ethTokens = require('./dist/tokens/eth/tokens-eth.min.json');
function generate() {
  const headers = Object.keys(ethTokens[0]).filter(itm => {
    if (itm === 'name' || itm === 'symbol' || itm === 'address') return itm;
  });
  const csv = ethTokens.map(item => {
    const arr = [];
    headers.forEach(head => {
      arr.push(item[head]);
    });

    return arr.join(',');
  });

  csv.unshift(headers.join(','));
  const returnableCsv = csv.join('\r\n');
  fs.writeFileSync('./generatedEthCSV.csv', returnableCsv, 'utf8', function(
    err
  ) {
    if (err) {
      console.log('Something went wrong! File cannot be generated!');
    } else {
      console.log('CSV created succesfully!');
    }
  });
}

generate();


text:
/*!jQuery FA multi button*/
/**
* Modern toggle, push button, dimmer or just a signal indicator
*
* Version: 1.1.1
* Requires: jQuery v1.7+
*
* Copyright (c) 2015 Mario Stephan
* Under MIT License (http://www.opensource.org/licenses/mit-license.php)
*
* Thanks to phoxoey
*/
(function ( $ ) {

$.fn.famultibutton = function(pOptions) {

	if (this.length > 1){
		this.each(function() { $(this).famultibutton(pOptions) });
		return this;
	}

	// private variables;
	var elem = this;
	var state = false;
	// private for dimmer
	var canvasScale;
	var objTimer;
	var isRunning=false;
	var resStepValues = [0, 10, 40, 80, 120, 140, 150, 160, 180, 200, 240, 260, 280, 300, 320, 420, 430, 440, 450, 460, 470];
	var dragy = 0;
	var currVal=0;
	var diff = 0;
	var baseTop = 0;
	var posy = 0;
	var isDrag = false;
	var isDown = false;

	// setup options
	var defaultOptions = {
		backgroundIcon: 'fa-circle',
		classes: ['fa-2x'],
		icon: 'fa-power-off',
		offColor: '#2A2A2A',
		offBackgroundColor: '#505050',
		onColor: '#2A2A2A',
		onBackgroundColor: '#aa6900',
		mode: 'toggle',  //toggle, push, signal, dimmer
		toggleOn: null,
		toggleOff: null,
        valueChanged: null,
        progressWidth:15,
        max:100,
        min:0,
        step:1,
	};

	var options = $.extend({}, defaultOptions, pOptions);

	// private functions;
	var intialize = function() {

		options = $.extend({}, options, elem.data());

		elem.addClass('fa-stack');

		jQuery('<i/>', {
            'id': 'bg',
            'class': 'fa fa-stack-2x'
		}).addClass(options['backgroundIcon'])
		.appendTo(elem);

		jQuery('<i/>', {
            'id': 'fg',
            'class': 'fa fa-stack-1x'
		}).addClass(options['icon']).appendTo(elem);

        if(options['classes'] && options['classes'].length > 0){
		   for(var i=0;i<options['classes'].length;i++){
				elem.addClass(options['classes'][i]);
		   }
		}

    setOff();

    if (options['mode'] == 'dimmer'){
			$('<canvas>').attr({
				id: 'scale'
			}).appendTo(elem);

			canvasScale = elem.find('canvas#scale');
				canvasScale.css({
				'height': elem.innerHeight()+4,
			});
			baseTop = parseInt(canvasScale.offset().top) - parseInt(elem.offset().top);
			drawScale();
			moveScale();
		}
        elem.o = options;
        elem.data("famultibutton", elem);

return elem;
};

	function setOn() {

        state = true;

        elem.children().filter('#bg').css( "color", options['onBackgroundColor'] );
        elem.children().filter('#fg').css( "color", options['onColor'] );
        elem.trigger('setOn');
	};

	function setOff() {

        state = false;

        elem.children().filter('#bg').css( "color", options['offBackgroundColor'] );
        elem.children().filter('#fg').css( "color", options['offColor'] );
        elem.trigger('setOff');
	};

	function fadeOff() {

			if(state){

				state = false;

				$( '<div />' ).animate({ 'width' : 100 }, {
					duration : 700,
					easing : 'swing',
					// Fade the colors in the step function
					step : function( now, fx ) {
					var completion = ( now - fx.start ) / ( fx.end - fx.start );
                    elem.children().filter('#bg').css( 'color', getGradientColor(
						options['onBackgroundColor'],
						options['offBackgroundColor'],
						completion));
                    elem.children().filter('#fg').css( 'color', getGradientColor(
						options['onColor'],
						options['offColor'],
						completion));
					},
				});
			}
	};

    function setProgressValue(value){

        var $canvasProgress = elem.find('canvas#progress');
        if (value>0){
            if ($canvasProgress.length==0){

                $canvasProgress = $('<canvas>').attr({
                      id: 'progress'
                    }).appendTo(elem);
             }
                var canvas = $canvasProgress[0];
                if (canvas){
                  canvas.height=elem.height();
                  canvas.width=elem.width();
                  var x = canvas.width / 2;
                  var y = canvas.height / 2;
                  if (canvas.getContext){
                      var c = canvas.getContext('2d');
                      c.beginPath();
                      c.strokeStyle = options.onColor;
                      c.arc(x, y, x * ((-0.4/90)*Number(options.progressWidth)+0.8), -0.5*Math.PI, (-0.5+value*2)*Math.PI, false);
                      c.lineWidth = x*0.80*options.progressWidth/100;
                      c.stroke();
                  }
             }

        }
        else {
                elem.find('canvas#progress').remove();
        }

    };

    // helper functions for color fade out
    rgbToHex = function(rgb){
     var tokens = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
     return (tokens && tokens.length === 4) ? "#" +
      ("0" + parseInt(tokens[1],10).toString(16)).slice(-2) +
      ("0" + parseInt(tokens[2],10).toString(16)).slice(-2) +
      ("0" + parseInt(tokens[3],10).toString(16)).slice(-2) : rgb;
    };

	getGradientColor = function(start_color, end_color, percent) {
	   // strip the leading # if it's there
       start_color = rgbToHex(start_color).replace(/^\s*#|\s*$/g, '');
       end_color = rgbToHex(end_color).replace(/^\s*#|\s*$/g, '');

	   // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
	   if(start_color.length == 3){
		 start_color = start_color.replace(/(.)/g, '$1$1');
	   }

	   if(end_color.length == 3){
		 end_color = end_color.replace(/(.)/g, '$1$1');
	   }

	   // get colors
	   var start_red = parseInt(start_color.substr(0, 2), 16),
		   start_green = parseInt(start_color.substr(2, 2), 16),
		   start_blue = parseInt(start_color.substr(4, 2), 16);

	   var end_red = parseInt(end_color.substr(0, 2), 16),
		   end_green = parseInt(end_color.substr(2, 2), 16),
		   end_blue = parseInt(end_color.substr(4, 2), 16);

	   // calculate new color
	   var diff_red = end_red - start_red;
	   var diff_green = end_green - start_green;
	   var diff_blue = end_blue - start_blue;

	   diff_red = ( (diff_red * percent) + start_red ).toString(16).split('.')[0];
	   diff_green = ( (diff_green * percent) + start_green ).toString(16).split('.')[0];
	   diff_blue = ( (diff_blue * percent) + start_blue ).toString(16).split('.')[0];

	   // ensure 2 digits by color
	   if( diff_red.length == 1 )
		 diff_red = '0' + diff_red

	   if( diff_green.length == 1 )
		 diff_green = '0' + diff_green

	   if( diff_blue.length == 1 )
		 diff_blue = '0' + diff_blue

	   return '#' + diff_red + diff_green + diff_blue;
	 };

function tickTimer() {
	clearTimeout(objTimer);
    currVal = (diff > 0) ? currVal-=options['step'] : currVal+=options['step'];

    if ( currVal>options['max']) currVal=options['max'];
    if ( currVal<options['min']) currVal=options['min'];

    drawScale();
    var d = (resStepValues[Math.abs(diff)]);
    objTimer= setTimeout(function () {tickTimer()}, 500-d);
 }

function drawScale() {

	var canvas = canvasScale[0];
	canvas.height=elem.innerHeight();
	canvas.width=elem.innerWidth();

	if (canvas.getContext){

		var context = canvas.getContext('2d');
		context.strokeStyle = options['offBackgroundColor'];
        var max = options['max'];
        var min = options['min'];
        var valPosition = canvas.height-Math.round(canvas.height *(currVal-min)/(max-min));

		for (var i=0;i<canvas.height;i+=4){
			context.lineWidth = 1;
			context.beginPath();
			context.moveTo(5,i);
			context.lineTo(25,i);
			context.stroke();
		}

		context.strokeStyle = (state)?options['onBackgroundColor']:
								getGradientColor(options['offBackgroundColor'],'#ffffff',0.4);
		context.lineWidth = 3;
		context.beginPath();
		context.moveTo(5,valPosition);
		context.lineTo(25,valPosition);
		context.stroke();

		context.fillStyle = getGradientColor(options['offBackgroundColor'],'#ffffff',0.4);
		context.font = "10px sans-serif";
		context.fillText(currVal, 30, canvas.height);

	  }
}

function moveScale() {

	canvasScale.css({
			position: 'absolute',
			'z-index': -1,
		});

	if (isDrag){
		canvasScale.animate({
			left:  -elem.innerWidth()*.6 +'px',
		});
	}
	else {
			canvasScale.animate({
			left: elem.innerWidth()/5 +'px',
			top: baseTop
		});
	}

}
    function getAndroidVersion(ua) {
        ua = (ua || navigator.userAgent).toLowerCase();
        var match = ua.match(/android\s([0-9\.]*)/);
        return match ? match[1] : false;
    };

    var touch_pos_x,touch_pos_y;
    var android = getAndroidVersion();
    var onlyTouch = (android && parseFloat(android)<5);
    var clickEventType = (onlyTouch) ? 'touchstart' : 'touchstart mousedown';
    var moveEventType=((onlyTouch)?'touchmove':'touchmove mousemove');
    var releaseEventType=((onlyTouch)?'touchend':'touchend mouseup');
    var leaveEventType=((onlyTouch)?'touchleave':'touchleave mouseout');

    if (options['mode'] == 'push'){
        this.on(clickEventType, function(e) {
          e.preventDefault();
          e.stopImmediatePropagation();
          touch_pos_y = $(window).scrollTop();
          touch_pos_x = $(window).scrollLeft();
        });
        this.on(releaseEventType, function(e) {
          e.preventDefault();
          e.stopImmediatePropagation();
          if(Math.abs(touch_pos_y-$(window).scrollTop())>3
                  || (Math.abs(touch_pos_x-$(window).scrollLeft())>3)) return;
          setOn();

          if(typeof options['toggleOn'] === 'function'){
              options['toggleOn'].call(this);
          }
          setTimeout( function() {
              fadeOff();
              }, 200);

          elem.trigger('clicked');

          return false;
        });
	}
    else if (options['mode'] == 'toggle'){
        this.on(clickEventType, function(e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            touch_pos_y = $(window).scrollTop();
            touch_pos_x = $(window).scrollLeft();
          });
        this.on(releaseEventType, function(e) {
            e.preventDefault();
            e.stopImmediatePropagation();

            if(Math.abs(touch_pos_y-$(window).scrollTop())>3
                    || (Math.abs(touch_pos_x-$(window).scrollLeft())>3)) return;
            if(state){

              setOff();
              if(typeof options['toggleOff'] === 'function'){
                  options['toggleOff'].call(this);
              }
            }else{

              setOn();
              if(typeof options['toggleOn'] === 'function'){
                  options['toggleOn'].call(this);
              }
            }

            elem.trigger('clicked');

            return false;
        });
	}
    else if (options['mode'] == 'dimmer'){
        this.on(clickEventType, function(e) {
            e.preventDefault();
            e.stopImmediatePropagation();
			var event = e.originalEvent;
			dragy =  event.touches ? event.touches[0].clientY :e.pageY;
			diff = 0;
			isDown = true;
		});
        this.on(leaveEventType, function(e) {
            e.preventDefault();
            e.stopImmediatePropagation();
			if (isDrag){
				isDrag = false;
				elem.animate({ top: 0 });
				clearInterval(objTimer);
				isRunning=false;
				moveScale();
			}
			isDown = false;
		});
        this.on(releaseEventType, function(e) {
            e.preventDefault();
            e.stopImmediatePropagation();
			if (isDrag){
				isDrag = false;
				elem.animate({ top: 0 });
				clearTimeout(objTimer);
				isRunning=false;
				if(typeof options['valueChanged'] === 'function'){
					options['valueChanged'].call(this,currVal);
				}
			}else {
				if(state){

					setOff();
					if(typeof options['toggleOff'] === 'function'){
						options['toggleOff'].call(this);
					}
				}else{

					setOn();
					if(typeof options['toggleOn'] === 'function'){
						options['toggleOn'].call(this);
					}
                }
            }
            isDrag = false;
            isDown = false;
            moveScale();
            drawScale();
            elem.trigger('clicked');
            return false;
		});
        this.on(moveEventType, function(e) {
            e.preventDefault();
            e.stopImmediatePropagation();
			if (isDown)
				isDrag = true;

			var event = e.originalEvent;
		  	posy =  event.touches ? event.touches[0].clientY :e.pageY;

			diff = posy - dragy;

			if (diff>20) diff=20;
			if (diff<-20) diff=-20;
			if (isDrag){
			this.style.top = diff + "px";
			if (!isRunning){
				moveScale();
				tickTimer();
				isRunning=true;
			}

			canvasScale.css({
					top: -diff+'px',
				});
			}
		});
	}
	// public functions;
	this.setOn = function() {
		setOn();
	};
	this.setOff = function() {
		setOff();
	};
	this.getState = function() {
		return state;
	};
	this.getValue= function() {
		return currVal;
	};
    this.setDimValue= function(val) {
        currVal=val;
        drawScale();
    };
    this.setProgressValue= function(val) {
        setProgressValue(val);
    };
return intialize();
}
})( jQuery );


text:
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { RecipesModule } from './recipes/recipes.module';

@Module({
  imports: [
    RecipesModule,
    GraphQLModule.forRoot({
      installSubscriptionHandlers: true,
      autoSchemaFile: 'schema.gql',
    }),
  ],
})
export class AppModule {}


text:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.m-files.com/schemas/appdef-client-v4.xsd">
	<guid>711441b6-dca0-4c9c-a04e-37bd4717e7ff</guid>
	<name>Display persistent web page</name>
	<version>0.2</version>
	<description>Shows how to display a persistent web page (e.g. an intranet) in a tab.</description>
	<publisher>M-Files Corporation</publisher>
	<copyright>(c) M-Files Corporation 2021</copyright>
	<!-- This application has been upgraded to support fast-browsing: https://developer.m-files.com/Frameworks/User-Interface-Extensibility-Framework/Fast-Browsing/ -->
	<required-mfiles-version>20.12.0.0</required-mfiles-version>
	<platforms>
		<platform>Desktop</platform>
	</platforms>
	<modules>
		<module environment="shellui" fast-browsing-compatible="true">
			<file>main.js</file>
		</module>
	</modules>
</application>


text:
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpCodes.Codes.Practice.LeetCode
{
    class Solution
    {
        public int FindPoisonedDuration(int[] timeSeries, int duration)
        {
            int sumDuration = 0;
            int lastEnd = 0;
            foreach(int v in timeSeries)
            {
                int dValue = duration;
                if (v < lastEnd)
                {
                    dValue += v - lastEnd;
                }

                sumDuration += dValue;
                lastEnd = v + duration;
            }

            return sumDuration;
        }
    }

    [TestFixture]
    public class TeemoAttackingTests
    {
        [Test]
        public void FindPoisonedDuration()
        {
            var s = new Solution();
            Assert.AreEqual(s.FindPoisonedDuration(new int[] { 1, 4 }, 2), 4);
        }
    }
}


text:
(function(module) {
  var _ = require('underscore');
  var createNamespaceTree = require('../../../scripts/createnamespacetree');
  var handlebars = require('yuidocjs').Handlebars;
  var fs = require('fs');
  var path = require('path');

  function registerPartialsInDir(partialsDir, prefix) {
    var partialPaths = fs.readdirSync(partialsDir);

    partialPaths.forEach(function(fileName) {
      var html = fs.readFileSync(path.join(partialsDir, fileName), 'utf8');
      var partialName = path.basename(fileName, '.handlebars');

      handlebars.registerPartial(prefix + '/' + partialName, html);
    });
  }

  // Register public theme partials
  // under 'public/' prefix.
  registerPartialsInDir(path.join(__dirname, '../../public/partials'), 'public');

  var helpers = {
    eachNamespace: function(classes, options) {
      var namespaces = createNamespaceTree(classes);
      var output = '';

      _.each(namespaces, function(nsObj) {
        output += options.fn(nsObj);
      });

      return output;
    },

    clean: function(text) {
      return text.split('!~YUIDOC_LINE~!')[0];
    }
  };

  module.exports = helpers;
}(module));


text:
package isdomain

// ExtendedTLDs is a set of additional "TLDs", allowing decentralized name
// systems, like TOR and Namecoin.
var ExtendedTLDs = map[string]bool{
	"BIT":    true, // namecoin.org
	"ONION":  true, // torproject.org
	"ETH":    true, // ens.domains
	"CRYPTO": true, // unstoppabledomains.com
	"ZIL":    true, // unstoppabledomains.com
	"BBS":    true, // opennic.org
	"CHAN":   true, // opennic.org
	"CYB":    true, // opennic.org
	"DYN":    true, // opennic.org
	"EPIC":   true, // opennic.org
	"GEEK":   true, // opennic.org
	"GOPHER": true, // opennic.org
	"INDY":   true, // opennic.org
	"LIBRE":  true, // opennic.org
	"NEO":    true, // opennic.org
	"NULL":   true, // opennic.org
	"O":      true, // opennic.org
	"OSS":    true, // opennic.org
	"OZ":     true, // opennic.org
	"PARODY": true, // opennic.org
	"PIRATE": true, // opennic.org
}


text:
<?php

/**
 * Epersongroup2eperson form base class.
 *
 * @method Epersongroup2eperson getObject() Returns the current form's model object
 *
 * @package    dspace
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormGeneratedTemplate.php 29553 2010-05-20 14:33:00Z Kris.Wallsmith $
 */
abstract class BaseEpersongroup2epersonForm extends BaseFormDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'               => new sfWidgetFormInputHidden(),
      'eperson_group_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Epersongroup'), 'add_empty' => true)),
      'eperson_id'       => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Eperson'), 'add_empty' => true)),
    ));

    $this->setValidators(array(
      'id'               => new sfValidatorDoctrineChoice(array('model' => $this->getModelName(), 'column' => 'id', 'required' => false)),
      'eperson_group_id' => new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName('Epersongroup'), 'required' => false)),
      'eperson_id'       => new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName('Eperson'), 'required' => false)),
    ));

    $this->widgetSchema->setNameFormat('epersongroup2eperson[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'Epersongroup2eperson';
  }

}


text:
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
import Autodesk

clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager

doc = DocumentManager.Instance.CurrentDBDocument

projloc = doc.ActiveProjectLocation
position_data = projloc.ProjectPosition[XYZ.Zero]
location_data = projloc.SiteLocation
OUT = (position_data.Angle,position_data.Elevation,position_data.EastWest,position_data.NorthSouth)


text:
export default {
    isAuthenticated(state) {
        return Boolean(state.model);
    },
};


text:
using namespace concurrency;
using namespace Platform;
using namespace Windows::Foundation;
using namespace CognitiveServicesLib;
using namespace CognitiveServicesLib::Common;
using namespace CognitiveServicesLib::Speech;
using namespace Windows::Storage::Streams;
using namespace Windows::Web::Http;
using namespace Windows::Web::Http::Headers;
using namespace Windows::Data::Xml::Dom;

///<seealso cref="https://docs.microsoft.com/en-us/azure/cognitive-services/Speech/api-reference-rest/bingvoiceoutput" />
Platform::String^ SpeechClient::m_cstrSpeechendpoint = L"https://speech.platform.bing.com";
Platform::String^ SpeechClient::m_cstrSynthesizeMethod = L"/synthesize";

String^ SpeechClient::buildSSML(String^ TextToSpeak)
{
	Windows::Data::Xml::Dom::XmlDocument ^ xml = ref new Windows::Data::Xml::Dom::XmlDocument();
	//String^ strXml = L"<speak version='1.0' xml:lang='en-US'><voice xml:lang='en-US' xml:gender='Female' name='Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)'>Microsoft Bing Voice Output API</voice></speak>";
	//xml->LoadXml(strXml);

	auto xmlSpeak = xml->CreateElement(L"speak");
	xmlSpeak->SetAttribute(L"version", L"1.0");
	xmlSpeak->SetAttribute(L"xml:lang", VoiceFontHelper::GetLanguage(m_VoiceFont));

	auto xmlVoice = xml->CreateElement(L"voice");
	xmlVoice->SetAttribute(L"xml:lang", VoiceFontHelper::GetLanguage(m_VoiceFont));
	xmlVoice->SetAttribute(L"xml:gender", VoiceFontHelper::GetGender(m_VoiceFont));
	xmlVoice->SetAttribute(L"xml:name", VoiceFontHelper::GetFontName(m_VoiceFont));

	auto xmlText = xml->CreateTextNode(TextToSpeak);

	xmlVoice->AppendChild(xmlText);
	xmlSpeak->AppendChild(xmlVoice);
	xml->AppendChild(xmlSpeak);

	String^ strXml = xmlSpeak->GetXml();
	//__LOGMSG(strXml->Data());
	return strXml;
}

IHttpContent^ SpeechClient::buildRequestContent(Platform::String^ TextToSpeak)
{
	__LOGFUNC;

	String^ strSSMLContent = buildSSML(TextToSpeak);
	HttpStringContent^ requestContent = ref new HttpStringContent(strSSMLContent);
	auto headers = requestContent->Headers;
	headers->ContentType = ref new Headers::HttpMediaTypeHeaderValue(ref new String(ContentTypes::ApplicationSsmlXml));

	unsigned long long ullContentLength;
	if (requestContent->TryComputeLength(&ullContentLength))
	{
		headers->ContentLength = ullContentLength;
	}

	__LOGMSG(headers->ToString()->Data());
	__LOGMSG(strSSMLContent->Data());

	return requestContent;
}

task<HttpRequestMessage^> SpeechClient::buildHttpRequestWithHeadersAsync(HttpMethod^ method, Uri^ uri, String^ TextToSpeak)
{
	__LOGFUNC;

	HttpRequestMessage^ request = ref new HttpRequestMessage(method, uri);
	auto headers = request->Headers;
	headers->Append(ref new String(HttpHeaderName::X_Microsoft_OutputFormat), OutputFormatHelper::ToString(m_OutputFormat));
	headers->Append(ref new String(HttpHeaderName::X_Search_AppId), m_AppId);
	headers->Append(ref new String(HttpHeaderName::X_Search_ClientId), m_ClientId);
	headers->Append(ref new String(HttpHeaderName::User_Agent), L"CognitiveServicesLib");

	// since authorization requires a roundtrip to the authentication server, the web request may still be ongoing
	String^ authorization = co_await this->m_AuthorizationProvider->GetAuthorizationTokenAsync();

	headers->Append(ref new String(HttpHeaderName::Authorization), authorization);

	__LOGMSG(uri->ToString()->Data());
	__LOGMSG(headers->ToString()->Data());

	request->Content = buildRequestContent(TextToSpeak);

	co_return request;
}

task<IRandomAccessStream^> SpeechClient::synthesize(String^ TextToSpeak)
{
	__LOGFUNC;

	Uri^ uri = ref new Uri(m_cstrSpeechendpoint, m_cstrSynthesizeMethod);
	HttpRequestMessage^ request = co_await buildHttpRequestWithHeadersAsync(HttpMethod::Post, uri, TextToSpeak);

	HttpResponseMessage^ response = co_await m_httpClient->SendRequestAsync( request );

	IHttpContent^ content = response->Content;

	if (!response->IsSuccessStatusCode)
	{
		std::wostringstream ss;
		ss << L"BAD REQUEST\r\nHttpStatusCode:" << (int)response->StatusCode << L", Reason:" << response->ReasonPhrase->Data();

		String^ strErrorResponse = co_await content->ReadAsStringAsync();
		if (strErrorResponse != nullptr)
		{
			ss << L", body:" << strErrorResponse->Data();
		}
		__LOGMSG(ss.str().c_str());

		String^ strError = ref new String(ss.str().c_str());
		throw ref new Platform::FailureException(strError);
	}

	IInputStream^ stream = nullptr;

	__LOGMSG(content->Headers->ToString()->Data());
	IBuffer^ buffer = co_await content->ReadAsBufferAsync();

	unsigned long long length;
	if (content->TryComputeLength(&length))
	{
		std::wostringstream ss;
		ss << L"Content-Length:" << length;
		__LOGMSG(ss.str().c_str());
	}

	InMemoryRandomAccessStream^ raStream = ref new InMemoryRandomAccessStream();

	co_await raStream->WriteAsync(buffer);
	co_await raStream->FlushAsync();
	raStream->Seek(0ull);
	co_return raStream;
}

SpeechClient::SpeechClient(String^ SubscriptionKey, String^ AppId, String^ ClientId) :
	m_SubscriptionKey( SubscriptionKey ),
	m_AppId( AppId ),
	m_ClientId( ClientId ),
	m_VoiceFont( Speech::VoiceFont::DE_DE_Female_Hedda),
	m_OutputFormat( Speech::OutputFormat::Audio_16khz_32kbitrate_mono_mp3 )
{
	__LOGFUNC;

	m_AuthorizationProvider = ref new AuthorizationProvider(SubscriptionKey);
	m_httpClient = ref new HttpClient();
}

SpeechClient::~SpeechClient()
{
}

IAsyncOperation<IRandomAccessStream ^>^ SpeechClient::TextToSpeech(Platform::String ^ TextToSpeak)
{
	__LOGFUNC;

	auto action = create_async([=]() {
		return synthesize(TextToSpeak);
	});
	return action;
}


text:
from google.cloud import dialogflow_v2

async def sample_list_documents():
    # Create a client
    client = dialogflow_v2.DocumentsAsyncClient()

    # Initialize request argument(s)
    request = dialogflow_v2.ListDocumentsRequest(
        parent="parent_value",
    )

    # Make the request
    page_result = client.list_documents(request=request)

    # Handle the response
    async for response in page_result:
        print(response)

# [END dialogflow_generated_dialogflow_v2_Documents_ListDocuments_async]


text:
package org.kaazing.gateway.client.impl.wseb;

import org.kaazing.gateway.client.impl.Channel;
import org.kaazing.gateway.client.impl.http.HttpRequest;
import org.kaazing.gateway.client.util.HttpURI;
import org.kaazing.gateway.client.util.WrappedByteBuffer;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.Timer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

class DownstreamChannel extends Channel {
    HttpURI location;
    public String protocol;

    final AtomicBoolean reconnecting = new AtomicBoolean(false);
    final AtomicBoolean closing = new AtomicBoolean(false);
    final AtomicBoolean attemptProxyModeFallback = new AtomicBoolean(false);
    Set<HttpRequest> outstandingRequests = new HashSet<>(5);
    Queue<WrappedByteBuffer> buffersToRead = new LinkedList<>();
    int nextMessageAt;

    //--------Idle Timeout-------------//
    final AtomicInteger idleTimeout = new AtomicInteger();
    final AtomicLong lastMessageTimestamp = new AtomicLong();
    Timer idleTimer = null;

    /** Cookie required for auth credentials */
    String cookie;

    //KG-6984 move decoder into DownstreamChannel - persist state information for each websocket downstream
    final WebSocketEmulatedDecoder<DownstreamChannel> decoder;

    public DownstreamChannel(HttpURI location, String cookie) {
        this(location, cookie, 0);
    }

    public DownstreamChannel(HttpURI location, String cookie, long sequence) {
        super(sequence);
        this.cookie = cookie;
        this.location = location;
        this.decoder = new WebSocketEmulatedDecoderImpl<>();

        attemptProxyModeFallback.set(!location.isSecure());
    }
}


text:
<?php

namespace Rhubarb\Crown\Tests\Fixtures\Codeception;

use Codeception\Lib\Framework;
use Codeception\TestCase;
use PHPUnit_Framework_Assert;

class RhubarbFramework extends Framework
{
    public function _initialize()
    {
        $this->client = new RhubarbConnector();
    }

    public function seeHeader($header, $headerValue = null)
    {
        $response = $this->client->getInternalResponse();
        PHPUnit_Framework_Assert::assertContains($header, $response->getHeaders());

        if ($headerValue != null) {
            PHPUnit_Framework_Assert::assertEquals($headerValue, $response->getHeader($header));
        }
    }
}


text:
package io.crate.metadata;

import io.crate.planner.symbol.Function;
import io.crate.types.DataType;

import java.util.List;

/**
 * resolver for methods that take a variable number of arguments or work with a lots of different arguments
 */
public interface DynamicFunctionResolver {

    /**
     * returns the function implementation for the given types.
     *
     * @throws java.lang.IllegalArgumentException thrown if there is no function that can handle the given types.
     */
    public FunctionImplementation<Function> getForTypes(List<DataType> dataTypes) throws IllegalArgumentException;
}


text:
package alexa;

import com.amazon.speech.slu.Intent;
import com.amazon.speech.speechlet.*;
import hue.LightingClient;
import projector.ProjectorClient;

/**
 * This sample shows how to create a simple speechlet for handling intent requests and managing
 * session interactions.
 */
public class ProjectorSpeechlet extends BaseSpeechlet {

    public SpeechletResponse onLaunch(final LaunchRequest request, final Session session)
            throws SpeechletException {

        return buildSpeechletResponse("Uber",
                "Hello, do you want to call an uber?",
                "Say a command.",
                false);
    }

    public SpeechletResponse onIntent(final IntentRequest request, final Session session)
            throws SpeechletException {

        Intent intent = request.getIntent();
        String intentName = (intent != null) ? intent.getName() : null;

        if ("WatchTVIntent".equals(intentName)) {
            return handleTurnOn(intent);
        }
        else if ("WatchTVOffIntent".equals(intentName)) {
            return handleTurnOff(intent);
        }
        else {
            throw new SpeechletException("Invalid Intent");
        }
    }

    public SpeechletResponse handleTurnOn(Intent intent) {
        ProjectorClient.turnOn();
        LightingClient.fireDimAllLightsRequest(false, 60000);

        return buildSpeechletResponse("Projector",
                "Warming up the projector. Lighting will dim in one minute.",
                "", true);
    }

    public SpeechletResponse handleTurnOff(Intent intent) {
        ProjectorClient.turnOff();
        LightingClient.fireDimAllLightsRequest(true, 10000);
        return buildSpeechletResponse("Uber",
                "Okay",
                "", true);
    }

}


text:
package main

import (
	"time"
)

type time string

func main() {
	var t time = "hello"
	println(t)
}

// Error:
// ../_test/redeclaration-global4.go:7:6: time redeclared in this block


text:
module Genetic.Population where

import Data.Function
import Data.List
import Control.Applicative
import Control.Arrow
import Control.Monad.Random
import Control.Monad

import Genetic.Coroutine
import Genetic.Individ
import Genetic.Options

type Population a = [a]
type Fitness a = a -> Float

-- | Fetching best solution from populations
findBest :: Individ a => Fitness a -> [Population a] -> (Float, a)
findBest fitness pops = maximumBy (compare `on` fst) $ findPopBest fitness <$> pops

-- | Fetching best solution from population
findPopBest :: Individ a => Fitness a -> Population a -> (Float, a)
findPopBest fitness pop = maximumBy (compare `on` fst) $ first fitness <$> zip pop pop

-- | Creating population with m chromosomes with length n
initPopulation :: Individ a => IndividOptions a -> Int -> PauseableRand (Population a)
initPopulation iopts n = replicateM n $ initIndivid iopts

-- | Helper to choose between two elements with provided chance of the first one
randChoice :: Rational -> PauseableRand a -> PauseableRand a -> PauseableRand a
randChoice chance th els = join (fromList [(th, chance), (els, 1 - chance)])

-- | Caclulates next generation of population
nextPopulation :: Individ a => IndividOptions a -> Fitness a -> GeneticOptions -> Population a -> PauseableRand (Population a)
nextPopulation iopts fitness opts pop = do
  newPop' <- liftM concat $ forM [1 .. ceiling $ fromIntegral nonEliteCount / 2] $ \i -> do
    when (i `mod` 10 == 0) pause
    a1 <- takeChr
    b1 <- takeChr
    (a2, b2) <- crossover iopts a1 b1
    a3 <- applyMutation a2
    b3 <- applyMutation b2
    return [a3, b3]
  let newPop = elite ++ newPop'
  return $ if length newPop <= length pop then newPop else init newPop
  where fits = toRational . fitness <$> pop
        maxfit = maximum fits
        chances = zip pop ((/maxfit) <$> fits)
        takeChr = fromList chances
        mutChance = toRational $ mutationChance opts
        applyMutation c = randChoice mutChance (mutation iopts c) (return c)
        bests = snd <$> sortBy (flip compare `on` fst) (first fitness <$> zip pop pop)
        elite = take (ceiling $ fromIntegral (length bests) * elitePart opts) bests
        nonEliteCount = length pop - length elite


text:
layout: link
category: evento
title: Torneo Iberoamericano de Go por Internet 2017
link: http://iberogo.torneosdego.com/
comment:  8 de mayo al 2 de junio de 2017
tag: [torneo]
---


text:
<?php $this->load->view('headeradmin');?>

DATA SUKSES TERUPLOAD !

                    <?php echo form_open_multipart('Gejala/tambah_gejala');?>
                    <button class="btn btn_">kembali ke TAMBAH GEJALA</button>

<?php $this->load->view('footeradmin');?>


text:
'use babel';

//*********************** Not Used *********************************************

export default class Angular2ComponentGeneratorView {

  constructor(serializedState) {
    // // Create root element
    // var self = this;
    // this.element = document.createElement('div');
    // this.element.classList.add('angular2-component-generator');
    //
    // // Create message element
    // const message = document.createElement('div');
    // message.textContent = 'The Angular2ComponentGenerator package is Alive! It\'s ALIVE!';
    // message.classList.add('message');
    // this.element.appendChild(message);
    // message2 = document.createElement('input');
    //
    // message2.classList.add('.find-and-replace');
    // message2.classList.add('input-block');
    // message2.classList.add('native-key-bindings');
    //
    // message2.addEventListener("keyup", (event) => {
    //     event.preventDefault();
    //     if (event.keyCode == 13) {
    //         // document.getElementById("id_of_button").click();
    //         console.log('enter');
    //         self.element.onClose(event.target.value);
    //     }
    //   });
    //
    // this.element.appendChild(message2);

  }

  // Returns an object that can be retrieved when package is activated
  serialize() {}

  // Tear down any state and detach
  destroy() {
    this.element.remove();
  }

  getElement() {
    return this.element;
  }

  // onClose() {
  //
  // }

}


text:
exports.local= "English";

exports.lang = {
    defaultMsg: "This field is not valid.",
    loadingMsg: "Validating...",

    digits: "Please enter only digits.",

    required: "This field is required.",
    remote: "{0} is already in use.",

    integer_nzp: "Please enter an integer.",
    integer_p: "Please enter a positive integer.",
    integer_pz: "Please enter a positive integer or 0.",
    integer_n: "Please enter a negative integer.",
    integer_nz: "Please enter a negative integer or 0.",

    match_eq: "{0} must be equal to {1}.",
    match_neq: "{0} must be not equal to {1}.",
    match_lt: "{0} must be less than {1}.",
    match_gt: "{0} must be greater than {1}.",
    match_lte: "{0} must be less than or equal to {1}.",
    match_gte: "{0} must be greater than or equal to {1}.",

    range_rg: "Please enter a number between {1} and {2}.",
    range_gt: "Please enter a number greater than or equal to {1}.",
    range_lt: "Please enter a number less than or equal to {1}.",

    checked_eq: "Please check {1} items.",
    checked_rg: "Please check between {1} and {2} items.",
    checked_gt: "Please check at least {1} items.",
    checked_lt: "Please check no more than {1} items.",

    length_eq: "Please enter {1} characters.",
    length_rg: "Please enter a value between {1} and {2} characters long.",
    length_gt: "Please enter at least {1} characters.",
    length_lt: "Please enter no more than {1} characters.",
    length_eq_2: "",
    length_lt_2: "",
    length_gt_2: "",
    length_lt_2: ""
};


text:
package ru.fastcards.recipientselectors;

import java.util.ArrayList;
import java.util.List;

import ru.fastcards.ListContacts;
import ru.fastcards.R;
import ru.fastcards.SimpleItemAdapter;
import ru.fastcards.SwipeDismissListViewTouchListener;
import ru.fastcards.common.ISendableItem;
import ru.fastcards.common.SimpleItem;
import ru.fastcards.utils.Constants;
import ru.fastcards.utils.DataBaseHelper;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

	public class PreviewListActivity extends SelectorActivity {

		private static final String TAG = "ContactJoinFragment";
		private String groupId;

		private Context context;
		private ListContacts groupRec;
//		private EditText nameEditText;
//		private String previousNick;

		private DataBaseHelper dbHelper;
		private TextView countTv;
//		private String flag;

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_preview_list_contacts);
			context = this;
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);

			getExtras();

			dbHelper = DataBaseHelper.getInstance(context);
			if (groupId != null) {
				groupRec = dbHelper.getContactsList(groupId);
			getRecipients();
			}

			initializeUi();

			listView = (ListView) findViewById(R.id.list_view);

			setAdapter(new SimpleItemAdapter(context, itemsList));
		}

		private void setAdapter(ArrayAdapter<SimpleItem> mAdapter) {
			if (itemsList == null){
				itemsList = new ArrayList();
			}
			this.adapter = mAdapter;

			listView.setAdapter(adapter);
		}

		private void getExtras() {
			groupId = getIntent().getStringExtra(Constants.EXTRA_ID);
//			flag = getIntent().getStringExtra(Constants.EXTRA_FLAG);

		}

		private void getRecipients() {
			itemsList = (List<ISendableItem>) (List<?>) dbHelper.getRecipientsListByGroupId(groupId);
		}

		private void initializeUi() {
			TextView nameTv = (TextView) findViewById(R.id.tv_title);
			if (groupRec != null)
				nameTv.setText(groupRec.getName());

			countTv = (TextView) findViewById(R.id.tv_contacts_count);
			setCountTv();
		}

		private void setCountTv() {
			int size = 0;
			if (itemsList != null)
				size = itemsList.size();
			countTv.setText(size + " "	+ context.getString(R.string.str_users));

		}

		private void deleteGroup() {
			Toast.makeText(context, "sgfjasdjfasdj", Toast.LENGTH_SHORT).show();

		}

		@Override
		public void addRecipients(Intent data, int origin) {
			super.addRecipients(data, origin);
			setCountTv();
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			switch (item.getItemId()) {

		    case android.R.id.home:
		    	finish();
		        return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}

		@Override
		public void onItemRemove() {}

	}


text:
package ac.at.tuwien.infosys.visp.runtime.datasources;

import ac.at.tuwien.infosys.visp.runtime.datasources.entities.VISPInstance;
import org.springframework.data.repository.CrudRepository;

public interface VISPInstanceRepository extends CrudRepository<VISPInstance, Long> {

    VISPInstance findFirstByIp(String ip);

}