text:
"""
    Last edited on July 8, 2018

    @author: matz

    comments: setup.py file for the fuelcycle module/package; copied and
    modified from:
    https://github.com/mwaskom/seaborn/blob/master/setup.py
    https://github.com/mitchnegus/seaborn/blob/master/setup.py

    For package organization see
    https://jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/
    https://github.com/kennethreitz/samplemod
    https://docs.python.org/2.4/dist/node11.html
    https://pypi.org/project/python_boilerplate_template/

"""
###############################################################################
import os
import sys
import fuelcycle
try:
    from setuptools import setup
    _has_setuptools = True
except ImportError:
    from distutils.core import setup
###############################################################################
DESCRIPTION = "Repository footprint calculator"
LONG_DESCRIPTION = """repository is a package that can be used alongside
fuelcycle to calculate the footprint for a repository for heat-generating
nuclear wastes"""
DISTNAME = 'repository'
MAINTAINER = 'Milos Atz'
MAINTAINER_EMAIL = 'milos.atz@berkeley.edu'
URL = ''
LICENSE = 'MIT'
DOWNLOAD_URL = ''# github
VERSION = '0.0'
###############################################################################
def check_dependencies():
    install_requires = []
    # Just make sure dependencies exist, I haven't rigorously
    # tested what the minimal versions that will work are
    # (help on that would be awesome)
    try:
        import numpy
    except ImportError:
        install_requires.append('numpy')
    try:
        import scipy
    except ImportError:
        install_requires.append('scipy')
    try:
        import matplotlib
    except ImportError:
        install_requires.append('matplotlib')
    try:
        import pandas
    except ImportError:
        install_requires.append('pandas')
    # others!
    return install_requires
###############################################################################
if __name__ == "__main__":
    install_requires = check_dependencies()
    setup(name=DISTNAME,
          author=MAINTAINER,
          author_email=MAINTAINER_EMAIL,
          maintainer=MAINTAINER,
          maintainer_email=MAINTAINER_EMAIL,
          description=DESCRIPTION,
          long_description=LONG_DESCRIPTION,
          license=LICENSE,
          url=URL,
          version=VERSION,
          download_url=DOWNLOAD_URL,
          install_requires=install_requires,
          packages=[''], #????
          classifiers=[
                       'Intended Audience :: Science/Research',
                       'Programming Language :: Python :: 2.7',
                       #'Programming Language :: Python :: 3.4',
                       #'Programming Language :: Python :: 3.5',
                       #'Programming Language :: Python :: 3.6',
                       #'License :: OSI Approved :: BSD License',
                       'Topic :: Scientific/Engineering :: Nuclear Energy',
                       'Topic :: Nuclear Waste :: Nuclear Fuel Cycle',
                       #'Operating System :: POSIX',
                       'Operating System :: Unix',
                       'Operating System :: MacOS'],
          )
###############################################################################


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.hello</groupId>
        <artifactId>java</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <groupId>com.hello</groupId>
    <artifactId>redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <packaging>jar</packaging>
    <name>redis</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.hello.redis.App</mainClass>
                                </transformer>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.handlers</resource>
                                </transformer>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.schemas</resource>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>ch.albasim.wegas</groupId>
        <version>4.1-SNAPSHOT</version>
        <artifactId>wegas-project</artifactId>
    </parent>
    <name>wegas-resources</name>
    <modelVersion>4.0.0</modelVersion>
    <groupId>ch.albasim.wegas</groupId>
    <artifactId>wegas-resources</artifactId>
    <packaging>war</packaging>

    <dependencies>
        <!-- YUI -->
        <!--<dependency>
            <groupId>com.yahoo.platform.yui</groupId>
            <artifactId>yui</artifactId>
            <version>2.5.0</version>
            <type>zip</type>
            <scope>runtime</scope>
        </dependency>-->
    </dependencies>

    <build>
        <finalName>Wegas-resources</finalName>

        <plugins>

            <!-- War creation -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <warName>${project.build.finalName}</warName>
                    <useCache>true</useCache>
                </configuration>
                <executions>
                    <execution>
                        <id>copy-webapp</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>exploded</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <!-- YUI JS Compression Plugin -->
            <plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>yuicompressor-maven-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <excludes>
                        <exclude>lib/qrcode/**</exclude>
                        <exclude>lib/ace/**</exclude>
                        <exclude>lib/crafty/**</exclude>
                        <exclude>lib/diffmatchpatch/**</exclude>
                        <exclude>lib/excanvas/**</exclude>
                        <exclude>lib/jsPlumb/**</exclude>
                        <exclude>lib/tiny_mce/**</exclude>
                        <exclude>lib/yui3/**</exclude>
                    </excludes>
                    <statistics>false</statistics>
                    <jswarn>false</jswarn>
                </configuration>
            </plugin>
            <!-- Convert files to UTF-8 (useless) -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <phase>prepare-package</phase>
                        <configuration>
                            <target>
                                <echo message="Convert files to ${project.build.sourceEncoding}"/>
                                <!--Has to copy twice, in place doesn't work...-->
                                <copy todir="${project.build.directory}/${project.build.finalName}/tmp" encoding="UTF-8" outputencoding="${project.build.sourceEncoding}">
                                    <fileset dir="${project.build.directory}/${project.build.finalName}/lib">
                                        <include name="**/*.js"/>
                                        <include name="/*.*"/>
                                    </fileset>
                                </copy>
                                <move todir="${project.build.directory}/${project.build.finalName}/lib" overwrite="true">
                                    <fileset dir="${project.build.directory}/${project.build.finalName}/tmp">
                                        <include name="**/*.*"/>
                                        <include name="/*.*"/>
                                    </fileset>
                                </move>
                                <delete dir="target/Wegas-resources/tmp"/>
                                <!--should we encode everything? this last is faster-->
                                <!--<move file="target/Wegas-resources/tmp" tofile="target/Wegas-resources/lib"/>-->
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
A little library to manipulate the dom

## parse

```js
jstiller.components.dom.parse('<div><p>text</p></div><button>button</button>');
```

## insert

### element
```js
var existingNode = jstiller.components.dom.find('body').firstChild,
    newNode = jstiller.components.dom.create.element('div');

jstiller.components.dom.insert.element(newNode).before(existingNode);
```

```js
var existingNode = jstiller.components.dom.find('body').firstChild,
    newNode = jstiller.components.dom.create.element('div');

jstiller.components.dom.insert.element(newNode).after(existingNode);
```

```js
var existingNode = jstiller.components.dom.find('body').firstChild,
    newNode = jstiller.components.dom.create.element('div');

jstiller.components.dom.insert.element(newNode).into(existingNode);
```

### className

```js
var existingNode = jstiller.components.dom.create.element('div');

jstiller.components.dom.insert.className('class').to(existingNode);
```

### text

```js
var existingNode = jstiller.components.dom.create.element('div');

jstiller.components.dom.insert.text('text ...').before(existingNode);
```

```js
var existingNode = jstiller.components.dom.create.element('div');

jstiller.components.dom.insert.text('text ...').after(existingNode);
```

```js
var existingNode = jstiller.components.dom.create.element('div');

jstiller.components.dom.insert.text('text ...').into(existingNode);
```

## replace

### element

```js
var mainNode = jstiller.components.dom.find('main'),
  newMainNode = jstiller.components.dom.find('main');

jstiller.components.dom.replace.element(mainNode).by(newMainNode);
```

### text

```js
var mainNode = jstiller.components.dom.find('main');

jstiller.components.dom.replace.text('text ...').of(mainNode);
```

## remove

### element

```js
var mainNode = jstiller.components.dom.find('main');
jstiller.components.dom.remove.element(mainNode);
```

### className

```js
var mainNode = jstiller.components.dom.find('main');
jstiller.components.dom.remove.className('class').from(mainNode);
```

## create

### element
```js
var mainNode = jstiller.components.dom.create.element('div', {
  align: 'left'
});
```

## find

```js
var mainNode = jstiller.components.dom.find('main');
```

```js
var mainNode = jstiller.components.dom.find('main', {
  quantity: 'all'
});
```

```js
var mainNode = jstiller.components.dom.find('main', {
  context: document,
});
```

```js
var mainNode = jstiller.components.dom.find('main', {
  quantity: 'one',
  context: document,
});
```


text:
from django.contrib import admin
from django.db import models
from taggit.managers import TaggableManager
#from django.utils.text import slugify

from django.conf import settings
from model_utils import Choices
from licensing.models import Licensed

def upload_to_resolver_for_image(instance, filename):
    return '%(name)s/images/%(filename)s' % {
        'name': instance.slug,
        'filename': filename,
    }

def upload_to_resolver(instance, filename):
    return '%(name)s/%(type)s/%(filename)s' % {
        'name': instance.slug,
        'type': instance.type,
        'filename': filename,
    }

class OpenHardware(models.Model):
    '''
    This model represents the Open Hardware device linked with all the
    available informations.
    '''

    name = models.CharField(max_length=50)
    short_description = models.CharField(max_length=150)

    url        = models.URLField(help_text=u'Main site')
    image      = models.ImageField(upload_to=upload_to_resolver_for_image) # TODO: multiple images
    slug       = models.SlugField(unique=True)

    tags = TaggableManager()

    def __unicode__(self):
        return self.name

# TODO: use code like <https://github.com/nathan-osman/django-archive/blob/master/django_archive/management/commands/archive.py#L89>
#       to create an archive of all attachments
class OpenHardwareAttachment(Licensed):
    '''
    Link some external document to the OpenHardware instance.
    '''
    TYPES = Choices(
        ('schematics', ('schematics'),),
        ('layout', ('layout'),),
    )
    oh   = models.ForeignKey(OpenHardware)
    type = models.CharField(choices=TYPES, max_length=100)
    file = models.FileField(upload_to=upload_to_resolver)
    description = models.CharField(max_length=100, help_text=u'Indicate for example what program can edit it')

    @property
    def slug(self):
        '''Use the same slug as the OH instance is attached to'''
        return self.oh.slug

class OpenHardwareLike(models.Model):
    '''
    Connect the User to the Open Hardware she likes.
    '''
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    oh   = models.ForeignKey(OpenHardware)

    @staticmethod
    def get_oh_for_user(user):
        return [_.oh for _ in OpenHardwareLike.objects.filter(user=user if user.is_authenticated() else None)]

class OpenHardwareAttachmentAdmin(admin.TabularInline):
    model = OpenHardwareAttachment

@admin.register(OpenHardware)
class OpenHardwareAdmin(admin.ModelAdmin):
    inlines = [
        OpenHardwareAttachmentAdmin
    ]
    list_display = [
        'name',
        'short_description',
    ]
    prepopulated_fields = {'slug': ('name',)}

    # FIXME: on save move media files if slug is changed


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.suggestions.mostvisited;

import androidx.annotation.Nullable;

import org.chromium.base.annotations.CalledByNative;
import org.chromium.chrome.browser.suggestions.SiteSuggestion;
import org.chromium.chrome.browser.suggestions.tile.Tile;
import org.chromium.url.GURL;

import java.util.List;

/**
 * Methods to provide most recent urls, titles and thumbnails.
 */
public interface MostVisitedSites {
    /**
     * An interface for handling events in {@link MostVisitedSites}.
     */
    interface Observer {
        /** This is called when the list of most visited URLs is initially available or updated. */
        void onSiteSuggestionsAvailable(List<SiteSuggestion> siteSuggestions);

        /**
         * This is called when a previously uncached icon has been fetched.
         * Parameters guaranteed to be non-null.
         *
         * @param siteUrl URL of site with newly-cached icon.
         */
        void onIconMadeAvailable(GURL siteUrl);
    }

    /**
     * An interface to provide {@link MostVisitedSites} with platform-specific home page data.
     */
    interface HomepageClient {
        /**
         * @return True if homepage tile should be shown.
         */
        @CalledByNative("HomepageClient")
        boolean isHomepageTileEnabled();

        /**
         * @return The raw URL of the currently set home page.
         */
        @CalledByNative("HomepageClient")
        @Nullable
        String getHomepageUrl();
    }

    /**
     * This instance must not be used after calling destroy().
     */
    void destroy();

    /**
     * Sets the recipient for events from {@link MostVisitedSites}. The observer may be notified
     * synchronously or asynchronously.
     * @param observer The observer to be notified.
     * @param numSites The maximum number of sites to return.
     */
    void setObserver(Observer observer, int numSites);

    /**
     * Blocklists a URL from the most visited URLs list.
     */
    void addBlocklistedUrl(GURL url);

    /**
     * Removes a URL from the most visited URLs blocklist.
     */
    void removeBlocklistedUrl(GURL url);

    /**
     * Records metrics about an impression of the surface with tiles.
     * @param tilesCount Count of tiles available on the surface at the moment.
     */
    void recordPageImpression(int tilesCount);

    /**
     * Records metrics about an impression of a tile including its source (local, server, ...) and
     * its visual type.
     * @param tile Object holding the details of a tile.
     */
    void recordTileImpression(Tile tile);

    /**
     * Records the opening of a Most Visited Item.
     * @param tile Object holding the details of a tile.
     */
    void recordOpenedMostVisitedItem(Tile tile);
}


text:
sicp-clojure
============

Material from Structure and Interpretation of Computer Programs, in Clojure.

**Disclaimer**:
This is not an attempt to produce perfect code, it has been written while learning Clojure, in an effort of both reading a great Computer Science book and doing its exercises using a modern Lisp-like language.

###### License

Copyright © 2014 Andrea Richiardi

Distributed under the Eclipse Public License, the same as Clojure.


text:
package de.bytefish.fcmjava.test.responses;

import com.fasterxml.jackson.databind.ObjectMapper;
import de.bytefish.fcmjava.responses.CreateDeviceGroupMessageResponse;
import org.junit.Assert;
import org.junit.Test;

public class CreateDeviceGroupMessageResponseTest {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Test
    public void createDeviceGroupSerializationTest() {
        // https://firebase.google.com/docs/cloud-messaging/android/device-group
        String createDeviceGroupJson = "{\n" +
                "   \"notification_key\": \"APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ\"\n" +
                "}";

        CreateDeviceGroupMessageResponse response = null;
        try {
            response = mapper.readValue(createDeviceGroupJson, CreateDeviceGroupMessageResponse.class);
        } catch (Exception e) {
            // Ignore ...
        }

        Assert.assertNotNull(response);

        Assert.assertEquals(response.getNotificationKey(), "APA91bGHXQBB...9QgnYOEURwm0I3lmyqzk2TXQ");
    }

}


text:
module ActionAuthorizer
end


text:
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Untech.SharePoint.Common.CodeAnnotations;

namespace Untech.SharePoint.Common.Models
{
	/// <summary>
	/// Represents url info.
	/// </summary>
	[PublicAPI]
	[DataContract]
	public class UrlInfo
	{
		/// <summary>
		/// Gets or sets url.
		/// </summary>
		[DataMember]
		[JsonProperty("url")]
		public string Url { get; set; }

		/// <summary>
		/// Gets or sets url description.
		/// </summary>
		[DataMember]
		[JsonProperty("description")]
		public string Description { get; set; }
	}
}


text:
<?php namespace Temoa\Command\Dependency;

class ReadCommand {

    /**
     * @var string
     */
    public $id;

    /**
     * @param string id
     */
    public function __construct($id)
    {
        $this->id = $id;
    }

}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**option** | **int** | Option is an Integer value from 224-254 Required. |
**value** | **str** | Value is a String value for the Option provided Required. |

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
package hr.istratech.bixolon.driver.general;

/**
 * The tag interface for <b>printer control sequences</b>.
 *
 * @author ksaric
 */

public interface Printer extends ControlSequence {
}


text:
package com.intellij.openapi.fileEditor.ex;

import com.intellij.openapi.fileEditor.impl.IdeDocumentHistoryImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public abstract class IdeDocumentHistory {
  public static IdeDocumentHistory getInstance(Project project) {
    return project.getComponent(IdeDocumentHistory.class);
  }

  public abstract void includeCurrentCommandAsNavigation();
  public abstract void includeCurrentPlaceAsChangePlace();
  public abstract void clearHistory();

  public abstract void back();
  public abstract void forward();

  public abstract boolean isBackAvailable();
  public abstract boolean isForwardAvailable();

  public abstract void navigatePreviousChange();
  public abstract void navigateNextChange();
  public abstract boolean isNavigatePreviousChangeAvailable();
  public abstract boolean isNavigateNextChangeAvailable();

  public abstract VirtualFile[] getChangedFiles();

  public abstract List<IdeDocumentHistoryImpl.PlaceInfo> getChangePlaces();
  public abstract List<IdeDocumentHistoryImpl.PlaceInfo> getBackPlaces();

  public abstract void removeChangePlace(@NotNull IdeDocumentHistoryImpl.PlaceInfo placeInfo);
  public abstract void removeBackPlace(@NotNull IdeDocumentHistoryImpl.PlaceInfo placeInfo);

  public abstract void gotoPlaceInfo(@NotNull IdeDocumentHistoryImpl.PlaceInfo info);
}


text:
// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
    public enum ApplyChangesKind
    {
        AddProject,
        RemoveProject,
        AddProjectReference,
        RemoveProjectReference,
        AddMetadataReference,
        RemoveMetadataReference,
        AddDocument,
        RemoveDocument,
        ChangeDocument
    }
}


text:
require File.join(File.dirname(__FILE__), 'spec_helper')

describe Torrance do
  it 'should say something' do
    Torrance.speak.should start_with 'You'
  end
end


text:
import strfile
import wx
import sys, os
import locale, gettext

from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin

class TransDictListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
	"""ListCtrl for a translation dictionary"""
	def __init__(self, parent):
		wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_VIRTUAL | wx.LC_SINGLE_SEL)
		ListCtrlAutoWidthMixin.__init__(self)
		self.InsertColumn(0, _("Identification"), width=250)
		self.InsertColumn(1, _("Text"))
		self.dict = {}
		self.update()

	def update(self, onlyone=None):
		"""
		Update the list.

		If onlyone is set, only the translation with the key = onlyone will be updated
		If not, evrything will be updated
		"""
		if onlyone is None:
			self.DeleteAllItems()
			self.SetItemCount(len(self.dict))
			self.RefreshItems(0,len(self.dict))
		else:
			key, val = onlyone
			self.dict[key] = val
			self.RefreshItem(self.dict.keys().index(key))

	def set_dict(self, d):
		"""Set the translation dictionary"""
		self.dict = d
		self.update()

	def get_seclection(self):
		"""
		Get the key of the selected translation.

		If no translation is selected, an empty string will be returned
		"""
		index = self.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
		return "" if index == -1 else self.dict.keys()[index]

	def OnGetItemText(self, item, col):
		"""Basic implementation of the LC_VIRTUAL mechanism"""
		if col == 0:
			return self.dict.keys()[item]
		else:
			return self.dict.values()[item]

class new_entry_dialog(wx.Dialog):
	"""
	Dialog that prompts the user for a new translation key
	"""
	def __init__(self, parent):
		# Layout stuff
		wx.Dialog.__init__(self, parent, title=_("New entry"), size=(500,-1))

		vbox = wx.BoxSizer(wx.VERTICAL)
		vbox.Add(wx.StaticText(self, label=_("Name of your new entry:")), 0, wx.EXPAND | wx.ALL, 5)

		hbox = wx.BoxSizer(wx.HORIZONTAL)
		self.part1 = wx.TextCtrl(self)
		self.part2 = wx.TextCtrl(self)
		hbox.Add(self.part1, 2, wx.EXPAND, 0)
		hbox.Add(wx.StaticText(self, label=":"), 0, wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.LEFT, 5)
		hbox.Add(self.part2, 3, wx.EXPAND, 0)
		hbox.SetMinSize((500,-1))
		vbox.Add(hbox, 0, wx.EXPAND | wx.ALL, 5)
		vbox.Add(self.CreateButtonSizer(wx.OK | wx.CANCEL), 0, wx.EXPAND | wx.ALL, 5)

		self.SetSizer(vbox)
		vbox.Fit(self)

		self.Bind(wx.EVT_BUTTON, self.on_ok,     id=wx.OK)
		self.Bind(wx.EVT_BUTTON, self.on_cancel, id=wx.CANCEL)
		self.Bind(wx.EVT_CLOSE,  self.on_cancel)

	def get_identifier(self):
		"""
		This will return the key/identifier.
		"""
		allowed_chars = map(chr, range(ord("A"), ord("Z")+1) + range(ord("a"), ord("z")+1))+["_","-"]
		part1 = "".join(filter(lambda c: c in allowed_chars, self.part1.GetValue()))
		part2 = "".join(filter(lambda c: c in allowed_chars, self.part2.GetValue()))

		return part1 + ":" + part2

	def on_ok(self, event):
		self.EndModal(wx.ID_OK)

	def on_cancel(self, event):
		self.EndModal(wx.ID_CANCEL)

class editor_frame(wx.Frame):
	"""
	The Frame of the editor.
	"""
	def __init__(self):
		filter_label = _("&Filter")
		self.dict = {}
		self.changed = False
		self.filename = ""

		# GUI stuff
		the_arts = wx.ArtProvider()
		wx.Frame.__init__(self, None, title=_(".str Editor"), size=(500,600))

		# menubar
		menubar = wx.MenuBar()

		m_file = wx.Menu()
		m_file.AppendItem(wx.MenuItem(m_file, wx.ID_NEW, _("&New")))
		m_file.AppendItem(wx.MenuItem(m_file, wx.ID_OPEN, _("&Open")))
		m_file.AppendItem(wx.MenuItem(m_file, wx.ID_SEPARATOR))
		m_file.AppendItem(wx.MenuItem(m_file, wx.ID_SAVE, _("&Save")))
		m_file.AppendItem(wx.MenuItem(m_file, wx.ID_SAVEAS, _("Save &As")))
		m_file.AppendItem(wx.MenuItem(m_file, wx.ID_SEPARATOR))
		m_file.AppendItem(wx.MenuItem(m_file, wx.ID_EXIT, _("&Exit")))

		m_help = wx.Menu()
		m_help.AppendItem(wx.MenuItem(m_help, wx.ID_ABOUT, _("&About")))

		menubar.Append(m_file, _("&File"))
		menubar.Append(m_help, _("&Help"))

		self.SetMenuBar(menubar)

		# toolbar
		toolbar = self.CreateToolBar()
		toolbar.AddLabelTool(wx.ID_NEW, _("New"), the_arts.GetBitmap(wx.ART_NEW, wx.ART_TOOLBAR))
		toolbar.AddLabelTool(wx.ID_OPEN, _("Open"), the_arts.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR))
		toolbar.AddLabelTool(wx.ID_SAVE, _("Save"), the_arts.GetBitmap(wx.ART_FILE_SAVE, wx.ART_TOOLBAR))
		toolbar.Realize()

		# shortcuts
		jump_to_filter_id = wx.NewId()
		filter_shortcut_char = ord(filter_label[filter_label.find("&")+1].lower())
		shortcuts = wx.AcceleratorTable([
			(wx.ACCEL_CTRL, ord('s'), wx.ID_SAVE),
			(wx.ACCEL_CTRL, ord('o'), wx.ID_OPEN),
			(wx.ACCEL_CTRL, ord('n'), wx.ID_NEW),
			(wx.ACCEL_CTRL, ord('q'), wx.ID_EXIT),
			(wx.ACCEL_CTRL, filter_shortcut_char, jump_to_filter_id)
		])
		self.SetAcceleratorTable(shortcuts)

		# the "real" GUI
		self.mainpanel = wx.Panel(self, -1)
		vbox = wx.BoxSizer(wx.VERTICAL)

		filter_hbox = wx.BoxSizer(wx.HORIZONTAL)
		self.input_filter = wx.TextCtrl(self.mainpanel)
		filter_hbox.Add(wx.StaticText(self.mainpanel, label=filter_label), 0, wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5)
		filter_hbox.Add(self.input_filter, 1, wx.EXPAND, 0)
		vbox.Add(filter_hbox, 0, wx.EXPAND | wx.ALL, 5)

		trl_hbox = wx.BoxSizer(wx.HORIZONTAL)
		self.transl_list = TransDictListCtrl(self.mainpanel)

		trl_vbox = wx.BoxSizer(wx.VERTICAL)
		trl_add_btn = wx.BitmapButton(self.mainpanel, bitmap=the_arts.GetBitmap(wx.ART_ADD_BOOKMARK, wx.ART_BUTTON))
		trl_del_btn = wx.BitmapButton(self.mainpanel, bitmap=the_arts.GetBitmap(wx.ART_DEL_BOOKMARK, wx.ART_BUTTON))
		trl_vbox.Add(trl_add_btn, 0, wx.EXPAND | wx.BOTTOM, 5)
		trl_vbox.Add(trl_del_btn, 0, wx.EXPAND, 0)

		trl_hbox.Add(self.transl_list, 1, wx.EXPAND, wx.RIGHT, 5)
		trl_hbox.Add(trl_vbox, 0, wx.EXPAND, 0)
		vbox.Add(trl_hbox, 3, wx.EXPAND | wx.ALL, 5)

		vbox.Add(wx.StaticLine(self.mainpanel, style=wx.LI_HORIZONTAL),.0, wx.EXPAND | wx.ALL, 5)

		vbox.Add(wx.StaticText(self.mainpanel, label=_("Text:")), 0, wx.EXPAND | wx.ALL, 5)
		self.trans_text_ctrl = wx.TextCtrl(self.mainpanel, style=wx.TE_MULTILINE)
		vbox.Add(self.trans_text_ctrl, 2, wx.EXPAND | wx.ALL, 5)

		self.mainpanel.SetSizer(vbox)

		cool_icon = wx.Icon(os.path.join(scriptdir, "wm-icon.ico"), wx.BITMAP_TYPE_ICO)
		self.SetIcon(cool_icon)

		# Binding events
		self.Bind(wx.EVT_MENU,   self.on_new,        id=wx.ID_NEW)
		self.Bind(wx.EVT_MENU,   self.on_open,       id=wx.ID_OPEN)
		self.Bind(wx.EVT_MENU,   self.on_save,       id=wx.ID_SAVE)
		self.Bind(wx.EVT_MENU,   self.on_saveas,     id=wx.ID_SAVEAS)
		self.Bind(wx.EVT_MENU,   self.on_close,      id=wx.ID_EXIT)
		self.Bind(wx.EVT_MENU,   self.on_about,      id=wx.ID_ABOUT)
		self.Bind(wx.EVT_TEXT,   self.on_filter,     id=self.input_filter.GetId())
		self.Bind(wx.EVT_TEXT,   self.on_textedit,   id=self.trans_text_ctrl.GetId())
		self.Bind(wx.EVT_BUTTON, self.on_add,        id=trl_add_btn.GetId())
		self.Bind(wx.EVT_BUTTON, self.on_del,        id=trl_del_btn.GetId())
		self.Bind(wx.EVT_MENU,   self.on_jmp_filter, id=jump_to_filter_id)
		self.Bind(wx.EVT_CLOSE,  self.on_close)
		self.Bind(wx.EVT_LIST_ITEM_SELECTED,   self.on_listsel,   id=self.transl_list.GetId())
		self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.on_listunsel, id=self.transl_list.GetId())

	def really_discard(self):
		"""
		If the content was modified, the user will be asked if he really wants to discard the changes

		This will return True if the calling function can continue normal work.
		"""
		if self.changed:
			dialog = wx.MessageDialog(None,
			                          message=_("You did not save your changes. Continue?"),
			                          caption=_("Unsaved changes"),
			                          style=wx.ICON_QUESTION | wx.YES_NO)
			user_ret = dialog.ShowModal()
			dialog.Destroy()
			return user_ret == wx.ID_YES
		return True

	def populate_list(self, autoselect=None):
		"""
		Populating the translation list with the filtered self.dict

		If autoselect is not None, the given translation will be selected and focussed.
		"""
		filter_str = self.input_filter.GetValue().lower()
		f_dict = {}
		for key in self.dict.iterkeys():
			if filter_str != '':
				if (filter_str not in key.lower()) and (filter_str not in self.dict[key].lower()):
					continue
			f_dict[key] = self.dict[key]
		self.transl_list.set_dict(f_dict)
		self.trans_text_ctrl.SetValue("")
		if autoselect is not None:
			self.transl_list.Select(f_dict.keys().index(autoselect))
			self.transl_list.Focus(f_dict.keys().index(autoselect))

	def form_init(self):
		"""
		Initializes / clears all formulars
		"""
		self.populate_list()
		self.input_filter.SetValue("")

	def on_close(self, event):
		if self.really_discard():
			self.Destroy()

	def on_new(self, event):
		if self.really_discard():
			self.dict = {}
			self.changed = False
			self.filename = ""
			self.form_init()

	def load_file(self, new_fn):
		if new_fn != "":
			try:
				fp = open(new_fn, "rb")
				temp_dict = strfile.dict_parse(fp.read())
				self.dict = temp_dict
				fp.close()
				self.filename = new_fn
				self.changed = False
				self.form_init()
			except:
				del dialog
				dialog = wx.MessageDialog(None,
					                  message=_("Could not open file.\nUsually that means that the file is invalid or you do not have enough privileges."),
					                  caption=_("Could not open file"),
					                  style=wx.ICON_ERROR | wx.OK)
				dialog.ShowModal()
				dialog.Destroy()

	def on_open(self, event):
		if self.really_discard():
			new_fn = ""
			dialog = wx.FileDialog(None, _("Choose a file"), wildcard=fd_wildcard, style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
			if dialog.ShowModal() == wx.ID_OK:
				new_fn = dialog.GetPath()
			dialog.Destroy()

			self.load_file(new_fn)

	def save_file(self, force_path=False):
		saveto = ""
		if force_path or self.filename=='':
			if self.filename == "":
				dialog = wx.FileDialog(None,
				                       message=_("Save to"),
				                       wildcard=fd_wildcard,
				                       style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
			else:
				def_dir, def_file = os.path.split(self.filename)
				dialog = wx.FileDialog(None,
				                       message=_("Save to"),
				                       wildcard=fd_wildcard,
				                       defaultDir=def_dir,
				                       defaultFile=def_file,
				                       style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
			if dialog.ShowModal() == wx.ID_OK:
				saveto = dialog.GetPath()
			else:
				saveto = ""
			dialog.Destroy()
		else:
			saveto = self.filename
		if saveto != "":
			try:
				fp = open(saveto, "w")
				strfile.dict_gen(self.dict, fp)
				fp.close()
			except:
				err_dialog = wx.MessageDialog(
					None,
					message=_("Can not write to file \"%s\".\nUsually that means that you do not have enough privileges or you ran out of disc memory.") % saveto,
					caption=_("Can not save file."),
					style=wx.ICON_ERROR | wx.OK)
				err_dialog.ShowModal()
				err_dialog.Close()
			self.changed = False

	def on_save(self, event):
		self.save_file()

	def on_saveas(self, event):
		self.save_file(True)

	def on_about(self, event):
		description = _(".str Editor is a tool for editing the .str files of EA's BFME2")
		licence = u"""Copyright (c) 2010-2011 \"Die Völker Mittelerdes\" Modding Crew

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."""
		info = wx.AboutDialogInfo()
		info.SetName(_('.str Editor'))
		info.SetVersion('0.1')
		info.SetDescription(description)
		info.SetCopyright(u'(C) 2010-2011 \"Die Völker Mittelerdes\" Modding Crew')
		info.SetLicence(licence)
		info.AddDeveloper('Laria Carolin Chabowski')
		info.SetIcon(wx.Icon(os.path.join(scriptdir, 'icon.png'), wx.BITMAP_TYPE_PNG))

		wx.AboutBox(info)

	def on_listsel(self, event):
		self.trans_text_ctrl.SetValue(strfile.unescape(self.dict[self.transl_list.get_seclection()]))

	def on_listunsel(self, event):
		self.trans_text_ctrl.SetValue("")

	def on_filter(self, event):
		if event.GetString() != "":
			self.populate_list()
		if len(self.transl_list.dict) == 0 and event.GetString() != "":
			self.input_filter.SetBackgroundColour(wx.Colour(255,100,100))
		else:
			self.input_filter.SetBackgroundColour(wx.NullColour)
		self.input_filter.Refresh()

	def on_textedit(self, event):
		key = self.transl_list.get_seclection()
		if key != "":
			newval = strfile.escape(self.trans_text_ctrl.GetValue())
			self.dict[key] = newval
			self.transl_list.update((key, newval))
			self.changed = True

	def on_add(self, event):
		addthis = ":"
		while addthis == ":":
			dialog = new_entry_dialog(None)
			if dialog.ShowModal() != wx.ID_OK:
				dialog.Destroy()
				return
			addthis = dialog.get_identifier()
			dialog.Destroy()
			if addthis in self.dict.keys():
				addthis = ':'
				del dialog
				dialog = wx.MessageDialog(
					None,
					message=_("This name is already in use. Choose another one."),
					caption=_("Invalid name"),
					style=wx.ICON_WARNING | wx.OK
				)
				dialog.ShowModal()
				dialog.Destroy()
			del dialog
		self.changed = True
		self.dict[addthis] = ""
		self.input_filter.SetValue("")
		self.populate_list(addthis)

	def on_del(self, event):
		delthis =  self.transl_list.get_seclection()
		if delthis != "":
			del self.dict[delthis]
			self.changed = True
			self.populate_list()

	def on_jmp_filter(self, event):
		self.input_filter.SetFocus()

class dotstr_edit_app(wx.App):
	def OnInit(self):
		app_frame = editor_frame()
		app_frame.Show()
		if len(sys.argv) > 1:
			app_frame.load_file(sys.argv[1])
		self.SetTopWindow(app_frame)
		return True

if __name__ == '__main__':
	# get directory of script / executable
	scriptdir = os.path.dirname(unicode(
		sys.executable if hasattr(sys,"frozen") and sys.frozen in ("windows_exe", "console_exe") else __file__,
		sys.getfilesystemencoding()))

	# init localisation
	if os.name == 'nt':
		# windows hack for locale setting
		lang = os.getenv('LANG')
		if lang is None:
			default_lang, default_enc = locale.getdefaultlocale()
			if default_lang:
				lang = default_lang
		if lang:
			os.environ['LANG'] = lang
	locale.setlocale(locale.LC_ALL, '')
	translator = gettext.translation('dotstr_edit', os.path.join(scriptdir, 'locale'), fallback=True)
	translator.install(True)

	fd_wildcard = _("str File")+"|*.str|*.*|*.*"

	# Start application
	app = dotstr_edit_app()
	app.MainLoop()


text:
<?php

namespace View;

use General\Formater;
use General\Templater;
use Model\Factory;

class Overview extends Base {

	protected $model = null;

	public function __construct(array $aParams) {
		parent::__construct($aParams);

        $oFactory = new Factory();

		$this->model = $oFactory->createIterator();
	}

	public function mainpage()
	{
		$oTemplate = new Templater('overview.html');

		return (string) $oTemplate;
	}
}


text:
package info.solidsoft.kata.mockito;

/**
 * For educational purposes only.
 */
public class ShipSearchCriteria {

    private final int minimumRange;
    private final int numberOfPhasers;

    public ShipSearchCriteria(int minimumRange, int numberOfPhasers) {
        this.minimumRange = minimumRange;
        this.numberOfPhasers = numberOfPhasers;
    }

    public int getMinimumRange() {
        return minimumRange;
    }

    public int getNumberOfPhasers() {
        return numberOfPhasers;
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>D-Index</title>
<meta name="date" content="2017-03-16">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G I M N O P R S T V W X

D

description - Variable in class xyz.cofe.shtrihm.hu.ECRMode

description - Variable in class xyz.cofe.shtrihm.hu.ShtrihMFunRes

Расшифровка кода

develDummy - Static variable in class xyz.cofe.shtrihm.hu.ShtrihMFunRes

Заглушка

disconnect() - Method in interface xyz.cofe.shtrihm.Driver

Освобождает COM-порт ПК, занятый под драйвер методом Connect.

disconnect() - Method in class xyz.cofe.shtrihm.hu.ShtrihMFun

Освобождает COM-порт ПК, занятый под драйвер методом Connect

disconnect() - Method in class xyz.cofe.shtrihm.jacob.ShtrihMJacobDriver

Освобождает COM-порт ПК, занятый под драйвер методом Connect.

disconnect() - Method in class xyz.cofe.shtrihm.ThreadSafeDriver

discount() - Method in interface xyz.cofe.shtrihm.Driver

Метод регистрирует скидку на сумму.

discount() - Method in class xyz.cofe.shtrihm.jacob.ShtrihMJacobDriver

Метод регистрирует скидку на сумму.

discount() - Method in class xyz.cofe.shtrihm.ThreadSafeDriver

Driver - Interface in xyz.cofe.shtrihm

Драйвер ККМ Штрих-М.

driver - Variable in class xyz.cofe.shtrihm.hu.ShtrihMFun

Ссылка на драйвер

driver - Static variable in class xyz.cofe.shtrihm.ThreadSafeDriver

DriverProperty - Annotation Type in xyz.cofe.shtrihm

Описывает свойство драйвера

drv - Variable in class xyz.cofe.shtrihm.jacob.ShtrihMJacobDriver

A B C D E F G I M N O P R S T V W X

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
@CHARSET "UTF-8";

.mainTextColor {
	color: #000000;
}

.rightConteWidth {
	width: 715px;
}

.rightConteWidth {
	width: 740px;
}

.mainTextColor {
	color: #000000;
}

.rightConteWidth {
	margin: 0 auto;
	text-align: center;
}

.rightConteWidth {
	margin: 0 auto;
	text-align: center;
}

#all_album_column .no-albums {
	display: none;
	font-weight: bold;
	margin: 15px;
}

.mainTextColor {
	color: #000000;
}

#all_album_column .albums-list {
	display: none;
}

.pro_category {
	text-align: left;
}

.pro_category {
	text-align: left;
}

.title {
	font-weight: bold;
}

.mainTextColor {
	color: #000000;
}

ul {
	list-style: none outside none;
	margin: 0;
	padding: 0;
}

li.bodyContContentAlbumLi {
	list-style: none outside none;
}

li.bodyContContentAlbumLi {
	background:
		url("http://img.china.alibaba.com/images/cn/market/danai/090210/album.png")
		no-repeat scroll 0 0 transparent;
	height: 200px;
	width: 140px;
}

.fl {
	float: left;
}

li.bodyContContentAlbumLi .albumCover {

}

li.bodyContContentAlbumLi .albumCover {
	display: table-cell;
	height: 153px;
	text-align: center;
	vertical-align: middle;
	margin:20px auto 0;
	width: 140px;
}

.textBox {
	margin: 5px auto 0;
	text-align: center;
}


text:
from datetime import date, timedelta
from couchdbkit.exceptions import MultipleResultsFound
from sqlagg.columns import SumColumn, SimpleColumn, SumWhen, CountUniqueColumn, CountColumn
from sqlagg import filters
from corehq.apps.callcenter.utils import MAPPING_NAME_CASES, MAPPING_NAME_CASE_OWNERSHIP
from corehq.apps.hqcase.utils import get_case_by_domain_hq_user_id
from corehq.apps.reportfixtures.indicator_sets import SqlIndicatorSet
from corehq.apps.reports.sqlreport import DatabaseColumn, AggregateColumn
from corehq.apps.users.models import CommCareUser
from dimagi.utils.decorators.memoized import memoized
from django.conf import settings

PCI_CHILD_FORM = 'http://openrosa.org/formdesigner/85823851-3622-4E9E-9E86-401500A39354'
PCI_MOTHER_FORM = 'http://openrosa.org/formdesigner/366434ec56aba382966f77639a2414bbc3c56cbc'
AAROHI_CHILD_FORM = 'http://openrosa.org/formdesigner/09486EF6-04C8-480C-BA11-2F8887BBBADD'
AAROHI_MOTHER_FORM = 'http://openrosa.org/formdesigner/6C63E53D-2F6C-4730-AA5E-BAD36B50A170'

NO_CASE_TAG = 'NO CASE'
TYPE_DURATION = 'duration'
TYPE_SUM = 'sum'

TABLE_PREFIX = '%s_' % settings.CTABLE_PREFIX if hasattr(settings, 'CTABLE_PREFIX') else ''

FORMDATA_TABLE = 'sofabed_formdata'

def case_table(domain):
    return '%s%s_%s' % (TABLE_PREFIX, domain, MAPPING_NAME_CASES)

def case_ownership_table(domain):
    return '%s%s_%s' % (TABLE_PREFIX, domain, MAPPING_NAME_CASE_OWNERSHIP)

PER_DOMAIN_FORM_INDICATORS = {
    'aarohi': [
        {'slug': 'motherForms', 'type': TYPE_SUM, 'xmlns': AAROHI_MOTHER_FORM},
        {'slug': 'childForms', 'type': TYPE_SUM, 'xmlns': AAROHI_CHILD_FORM},
        {'slug': 'motherDuration', 'type': TYPE_DURATION, 'xmlns': AAROHI_MOTHER_FORM},
    ],
    'pci-india': [
        {'slug': 'motherForms', 'type': TYPE_SUM, 'xmlns': PCI_MOTHER_FORM},
        {'slug': 'childForms', 'type': TYPE_SUM, 'xmlns': PCI_CHILD_FORM},
    ]
}

def filters_week0(date_field):
    return [filters.GT(date_field, 'weekago'), filters.LTE(date_field, 'today')]

def filters_week1(date_field):
    return [filters.GT(date_field, '2weekago'), filters.LTE(date_field, 'weekago')]

def filters_month0(date_field):
    return [filters.GT(date_field, '30daysago'), filters.LTE(date_field, 'today')]

def filters_month1(date_field):
    return [filters.GT(date_field, '60daysago'), filters.LTE(date_field, '30daysago')]

custom_form_ranges = {
    'Week0': filters_week0('time_end'),
    'Week1': filters_week1('time_end'),
    'Month0': filters_month0('time_end'),
}

def mean_seconds(sum, count):
    if sum and count:
        return (sum / count) / 1000
    else:
        return 0

class CallCenter(SqlIndicatorSet):
    """
    Assumes SQL table 'call_center' with the following columns:
    * user_id (string): the user id
    * date (date): the date of the indicator grain
    * submission_count (integer): number of forms submitted
    """
    name = 'call-center'

    @property
    def table_name(self):
        return FORMDATA_TABLE

    @property
    def filters(self):
        return filters_week0('date')

    @property
    def filter_values(self):
        today = date.today() + timedelta(days=1)  # set to midnight of current day
        return {
            'today': today,
            'weekago': today - timedelta(days=7),
            '2weekago': today - timedelta(days=14),
            '30daysago': today - timedelta(days=30),
            '60daysago': today - timedelta(days=60),
            'ccCaseType': self.domain.call_center_config.case_type,
            'domain': self.domain.name,
            'form_doc_type': 'XFormInstance',
        }

    @property
    def group_by(self):
        return ['user_id']

    @property
    def columns(self):
        case_table_name = case_table(self.domain.name)
        case_ownership_table_name = case_ownership_table(self.domain.name)

        case_type_filters = [filters.NOTEQ('case_type', 'ccCaseType')]
        domain_filter = [filters.EQ('domain', 'domain'), filters.EQ('doc_type', 'form_doc_type')]

        columns = [
            DatabaseColumn("case",
                           SimpleColumn(
                               'user_id',
                               filters=filters_week0('time_end') + domain_filter),
                           format_fn=self.get_user_case_id,
                           sortable=False),
            DatabaseColumn('formsSubmittedWeek0',
                           CountColumn(
                               'instance_id',
                               table_name=FORMDATA_TABLE,
                               filters=filters_week0('time_end') + domain_filter,
                               alias='formsSubmittedWeek0'),
                           sortable=False),
            DatabaseColumn('formsSubmittedWeek1',
                           CountColumn(
                               'instance_id',
                               table_name=FORMDATA_TABLE,
                               filters=filters_week1('time_end') + domain_filter,
                               alias='formsSubmittedWeek1'),
                           sortable=False),
            DatabaseColumn('formsSubmittedMonth0',
                           CountColumn(
                               'instance_id',
                               table_name=FORMDATA_TABLE,
                               filters=filters_month0('time_end') + domain_filter,
                               alias='formsSubmittedMonth0'),
                           sortable=False),
            DatabaseColumn('casesUpdatedMonth0',
                           CountUniqueColumn(
                               'case_id',
                               table_name=case_table_name,
                               filters=filters_month0('date') + case_type_filters,
                               alias='casesUpdatedMonth0'),
                           sortable=False),
            DatabaseColumn('casesUpdatedMonth1',
                           CountUniqueColumn(
                               'case_id',
                               table_name=case_table_name,
                               filters=filters_month1('date') + case_type_filters,
                               alias='casesUpdatedMonth1'),
                           sortable=False),
            DatabaseColumn('totalCases',
                           SumColumn(
                               'open_cases',
                               table_name=case_ownership_table_name,
                               filters=case_type_filters,
                               alias='totalCases'),
                           sortable=False)
        ]

        columns.extend(self._get_custom_columns())

        return columns

    def _get_custom_columns(self):
        custom_indicators = PER_DOMAIN_FORM_INDICATORS.get(self.domain.name)

        if not custom_indicators:
            return

        for meta in custom_indicators:
            for slug_suffix, filters in custom_form_ranges.items():
                if meta['type'] == TYPE_SUM:
                    yield self._get_form_sum_column(meta, slug_suffix, filters)
                elif meta['type'] == TYPE_DURATION:
                    yield self._get_form_duration_column(meta, slug_suffix, filters)

    def _get_form_sum_column(self, meta, slug_suffix, filters):
        slug = '%s%s' % (meta['slug'], slug_suffix)
        agg_col = SumWhen(
            key='xmlns',
            whens={meta['xmlns']: 1},
            else_=0,
            filters=filters,
            alias=slug)
        return DatabaseColumn(slug, agg_col, sortable=False)

    def _get_form_duration_column(self, meta, slug_suffix, filters):
        slug = '%s%s' % (meta['slug'], slug_suffix)
        when = "xmlns = '%s'" % meta['xmlns']
        dur_col = SumWhen(
            whens={when: 'duration'},
            else_=0,
            filters=filters,
            alias='%s_sum' % slug)
        count_col = SumWhen(
            key='xmlns',
            whens={meta['xmlns']: 1},
            else_=0,
            filters=filters,
            alias='%s_count' % slug)
        return AggregateColumn(slug, mean_seconds, [dur_col, count_col], sortable=False, slug=slug)

    @property
    @memoized
    def keys(self):
        results = CommCareUser.by_domain(self.domain.name)
        return [[r.get_id] for r in results]

    def get_user_case_id(self, user_id):
        try:
            case = get_case_by_domain_hq_user_id(self.domain.name, user_id)
            if case:
                return case['id']
            else:
                # No case for this user so return a tag instead to enable removing this
                # row from the results
                return NO_CASE_TAG
        except MultipleResultsFound:
            return NO_CASE_TAG

    def include_row(self, key, row):
        return not row['user_id'] == NO_CASE_TAG


text:
package com.amazonaws.services.athena.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * The information about the updates in the query results, such as output location and encryption configuration for the
 * query results.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ResultConfigurationUpdates implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The location in Amazon S3 where your query results are stored, such as s3://path/to/query/bucket/.
     * For more information, see Query Results
     * If workgroup settings override client-side settings, then the query uses the location for the query results and
     * the encryption configuration that are specified for the workgroup. The "workgroup settings override" is specified
     * in EnforceWorkGroupConfiguration (true/false) in the WorkGroupConfiguration. See
     * WorkGroupConfiguration$EnforceWorkGroupConfiguration.
     *

     */
    private String outputLocation;
    /**
     *

     * If set to "true", indicates that the previously-specified query results location (also known as a client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the OutputLocation in ResultConfigurationUpdates (the client-side setting), the
     * OutputLocation in the workgroup's ResultConfiguration will be updated with the new value. For more information,
     * see Workgroup Settings
     * Override Client-Side Settings.
     *

     */
    private Boolean removeOutputLocation;
    /**
     *

     * The encryption configuration for the query results.
     *

     */
    private EncryptionConfiguration encryptionConfiguration;
    /**
     *

     * If set to "true", indicates that the previously-specified encryption configuration (also known as the client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the EncryptionConfiguration in ResultConfigurationUpdates (the client-side setting), the
     * EncryptionConfiguration in the workgroup's ResultConfiguration will be updated with the new value. For more
     * information, see Workgroup Settings Override
     * Client-Side Settings.
     *

     */
    private Boolean removeEncryptionConfiguration;

    /**
     *

     * The location in Amazon S3 where your query results are stored, such as s3://path/to/query/bucket/.
     * For more information, see Query Results
     * If workgroup settings override client-side settings, then the query uses the location for the query results and
     * the encryption configuration that are specified for the workgroup. The "workgroup settings override" is specified
     * in EnforceWorkGroupConfiguration (true/false) in the WorkGroupConfiguration. See
     * WorkGroupConfiguration$EnforceWorkGroupConfiguration.
     *

     *
     * @param outputLocation
     *        The location in Amazon S3 where your query results are stored, such as
     *        s3://path/to/query/bucket/. For more information, see Query Results If workgroup settings
     *        override client-side settings, then the query uses the location for the query results and the encryption
     *        configuration that are specified for the workgroup. The "workgroup settings override" is specified in
     *        EnforceWorkGroupConfiguration (true/false) in the WorkGroupConfiguration. See
     *        WorkGroupConfiguration$EnforceWorkGroupConfiguration.
     */

    public void setOutputLocation(String outputLocation) {
        this.outputLocation = outputLocation;
    }

    /**
     *

     * The location in Amazon S3 where your query results are stored, such as s3://path/to/query/bucket/.
     * For more information, see Query Results
     * If workgroup settings override client-side settings, then the query uses the location for the query results and
     * the encryption configuration that are specified for the workgroup. The "workgroup settings override" is specified
     * in EnforceWorkGroupConfiguration (true/false) in the WorkGroupConfiguration. See
     * WorkGroupConfiguration$EnforceWorkGroupConfiguration.
     *

     *
     * @return The location in Amazon S3 where your query results are stored, such as
     *         s3://path/to/query/bucket/. For more information, see Query Results If workgroup settings
     *         override client-side settings, then the query uses the location for the query results and the encryption
     *         configuration that are specified for the workgroup. The "workgroup settings override" is specified in
     *         EnforceWorkGroupConfiguration (true/false) in the WorkGroupConfiguration. See
     *         WorkGroupConfiguration$EnforceWorkGroupConfiguration.
     */

    public String getOutputLocation() {
        return this.outputLocation;
    }

    /**
     *

     * The location in Amazon S3 where your query results are stored, such as s3://path/to/query/bucket/.
     * For more information, see Query Results
     * If workgroup settings override client-side settings, then the query uses the location for the query results and
     * the encryption configuration that are specified for the workgroup. The "workgroup settings override" is specified
     * in EnforceWorkGroupConfiguration (true/false) in the WorkGroupConfiguration. See
     * WorkGroupConfiguration$EnforceWorkGroupConfiguration.
     *

     *
     * @param outputLocation
     *        The location in Amazon S3 where your query results are stored, such as
     *        s3://path/to/query/bucket/. For more information, see Query Results If workgroup settings
     *        override client-side settings, then the query uses the location for the query results and the encryption
     *        configuration that are specified for the workgroup. The "workgroup settings override" is specified in
     *        EnforceWorkGroupConfiguration (true/false) in the WorkGroupConfiguration. See
     *        WorkGroupConfiguration$EnforceWorkGroupConfiguration.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResultConfigurationUpdates withOutputLocation(String outputLocation) {
        setOutputLocation(outputLocation);
        return this;
    }

    /**
     *

     * If set to "true", indicates that the previously-specified query results location (also known as a client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the OutputLocation in ResultConfigurationUpdates (the client-side setting), the
     * OutputLocation in the workgroup's ResultConfiguration will be updated with the new value. For more information,
     * see Workgroup Settings
     * Override Client-Side Settings.
     *

     *
     * @param removeOutputLocation
     *        If set to "true", indicates that the previously-specified query results location (also known as a
     *        client-side setting) for queries in this workgroup should be ignored and set to null. If set to "false" or
     *        not set, and a value is present in the OutputLocation in ResultConfigurationUpdates (the client-side
     *        setting), the OutputLocation in the workgroup's ResultConfiguration will be updated with the new value.
     *        For more information, see Workgroup Settings
     *        Override Client-Side Settings.
     */

    public void setRemoveOutputLocation(Boolean removeOutputLocation) {
        this.removeOutputLocation = removeOutputLocation;
    }

    /**
     *

     * If set to "true", indicates that the previously-specified query results location (also known as a client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the OutputLocation in ResultConfigurationUpdates (the client-side setting), the
     * OutputLocation in the workgroup's ResultConfiguration will be updated with the new value. For more information,
     * see Workgroup Settings
     * Override Client-Side Settings.
     *

     *
     * @return If set to "true", indicates that the previously-specified query results location (also known as a
     *         client-side setting) for queries in this workgroup should be ignored and set to null. If set to "false"
     *         or not set, and a value is present in the OutputLocation in ResultConfigurationUpdates (the client-side
     *         setting), the OutputLocation in the workgroup's ResultConfiguration will be updated with the new value.
     *         For more information, see Workgroup Settings
     *         Override Client-Side Settings.
     */

    public Boolean getRemoveOutputLocation() {
        return this.removeOutputLocation;
    }

    /**
     *

     * If set to "true", indicates that the previously-specified query results location (also known as a client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the OutputLocation in ResultConfigurationUpdates (the client-side setting), the
     * OutputLocation in the workgroup's ResultConfiguration will be updated with the new value. For more information,
     * see Workgroup Settings
     * Override Client-Side Settings.
     *

     *
     * @param removeOutputLocation
     *        If set to "true", indicates that the previously-specified query results location (also known as a
     *        client-side setting) for queries in this workgroup should be ignored and set to null. If set to "false" or
     *        not set, and a value is present in the OutputLocation in ResultConfigurationUpdates (the client-side
     *        setting), the OutputLocation in the workgroup's ResultConfiguration will be updated with the new value.
     *        For more information, see Workgroup Settings
     *        Override Client-Side Settings.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResultConfigurationUpdates withRemoveOutputLocation(Boolean removeOutputLocation) {
        setRemoveOutputLocation(removeOutputLocation);
        return this;
    }

    /**
     *

     * If set to "true", indicates that the previously-specified query results location (also known as a client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the OutputLocation in ResultConfigurationUpdates (the client-side setting), the
     * OutputLocation in the workgroup's ResultConfiguration will be updated with the new value. For more information,
     * see Workgroup Settings
     * Override Client-Side Settings.
     *

     *
     * @return If set to "true", indicates that the previously-specified query results location (also known as a
     *         client-side setting) for queries in this workgroup should be ignored and set to null. If set to "false"
     *         or not set, and a value is present in the OutputLocation in ResultConfigurationUpdates (the client-side
     *         setting), the OutputLocation in the workgroup's ResultConfiguration will be updated with the new value.
     *         For more information, see Workgroup Settings
     *         Override Client-Side Settings.
     */

    public Boolean isRemoveOutputLocation() {
        return this.removeOutputLocation;
    }

    /**
     *

     * The encryption configuration for the query results.
     *

     *
     * @param encryptionConfiguration
     *        The encryption configuration for the query results.
     */

    public void setEncryptionConfiguration(EncryptionConfiguration encryptionConfiguration) {
        this.encryptionConfiguration = encryptionConfiguration;
    }

    /**
     *

     * The encryption configuration for the query results.
     *

     *
     * @return The encryption configuration for the query results.
     */

    public EncryptionConfiguration getEncryptionConfiguration() {
        return this.encryptionConfiguration;
    }

    /**
     *

     * The encryption configuration for the query results.
     *

     *
     * @param encryptionConfiguration
     *        The encryption configuration for the query results.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResultConfigurationUpdates withEncryptionConfiguration(EncryptionConfiguration encryptionConfiguration) {
        setEncryptionConfiguration(encryptionConfiguration);
        return this;
    }

    /**
     *

     * If set to "true", indicates that the previously-specified encryption configuration (also known as the client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the EncryptionConfiguration in ResultConfigurationUpdates (the client-side setting), the
     * EncryptionConfiguration in the workgroup's ResultConfiguration will be updated with the new value. For more
     * information, see Workgroup Settings Override
     * Client-Side Settings.
     *

     *
     * @param removeEncryptionConfiguration
     *        If set to "true", indicates that the previously-specified encryption configuration (also known as the
     *        client-side setting) for queries in this workgroup should be ignored and set to null. If set to "false" or
     *        not set, and a value is present in the EncryptionConfiguration in ResultConfigurationUpdates (the
     *        client-side setting), the EncryptionConfiguration in the workgroup's ResultConfiguration will be updated
     *        with the new value. For more information, see Workgroup Settings
     *        Override Client-Side Settings.
     */

    public void setRemoveEncryptionConfiguration(Boolean removeEncryptionConfiguration) {
        this.removeEncryptionConfiguration = removeEncryptionConfiguration;
    }

    /**
     *

     * If set to "true", indicates that the previously-specified encryption configuration (also known as the client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the EncryptionConfiguration in ResultConfigurationUpdates (the client-side setting), the
     * EncryptionConfiguration in the workgroup's ResultConfiguration will be updated with the new value. For more
     * information, see Workgroup Settings Override
     * Client-Side Settings.
     *

     *
     * @return If set to "true", indicates that the previously-specified encryption configuration (also known as the
     *         client-side setting) for queries in this workgroup should be ignored and set to null. If set to "false"
     *         or not set, and a value is present in the EncryptionConfiguration in ResultConfigurationUpdates (the
     *         client-side setting), the EncryptionConfiguration in the workgroup's ResultConfiguration will be updated
     *         with the new value. For more information, see Workgroup Settings
     *         Override Client-Side Settings.
     */

    public Boolean getRemoveEncryptionConfiguration() {
        return this.removeEncryptionConfiguration;
    }

    /**
     *

     * If set to "true", indicates that the previously-specified encryption configuration (also known as the client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the EncryptionConfiguration in ResultConfigurationUpdates (the client-side setting), the
     * EncryptionConfiguration in the workgroup's ResultConfiguration will be updated with the new value. For more
     * information, see Workgroup Settings Override
     * Client-Side Settings.
     *

     *
     * @param removeEncryptionConfiguration
     *        If set to "true", indicates that the previously-specified encryption configuration (also known as the
     *        client-side setting) for queries in this workgroup should be ignored and set to null. If set to "false" or
     *        not set, and a value is present in the EncryptionConfiguration in ResultConfigurationUpdates (the
     *        client-side setting), the EncryptionConfiguration in the workgroup's ResultConfiguration will be updated
     *        with the new value. For more information, see Workgroup Settings
     *        Override Client-Side Settings.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ResultConfigurationUpdates withRemoveEncryptionConfiguration(Boolean removeEncryptionConfiguration) {
        setRemoveEncryptionConfiguration(removeEncryptionConfiguration);
        return this;
    }

    /**
     *

     * If set to "true", indicates that the previously-specified encryption configuration (also known as the client-side
     * setting) for queries in this workgroup should be ignored and set to null. If set to "false" or not set, and a
     * value is present in the EncryptionConfiguration in ResultConfigurationUpdates (the client-side setting), the
     * EncryptionConfiguration in the workgroup's ResultConfiguration will be updated with the new value. For more
     * information, see Workgroup Settings Override
     * Client-Side Settings.
     *

     *
     * @return If set to "true", indicates that the previously-specified encryption configuration (also known as the
     *         client-side setting) for queries in this workgroup should be ignored and set to null. If set to "false"
     *         or not set, and a value is present in the EncryptionConfiguration in ResultConfigurationUpdates (the
     *         client-side setting), the EncryptionConfiguration in the workgroup's ResultConfiguration will be updated
     *         with the new value. For more information, see Workgroup Settings
     *         Override Client-Side Settings.
     */

    public Boolean isRemoveEncryptionConfiguration() {
        return this.removeEncryptionConfiguration;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getOutputLocation() != null)
            sb.append("OutputLocation: ").append(getOutputLocation()).append(",");
        if (getRemoveOutputLocation() != null)
            sb.append("RemoveOutputLocation: ").append(getRemoveOutputLocation()).append(",");
        if (getEncryptionConfiguration() != null)
            sb.append("EncryptionConfiguration: ").append(getEncryptionConfiguration()).append(",");
        if (getRemoveEncryptionConfiguration() != null)
            sb.append("RemoveEncryptionConfiguration: ").append(getRemoveEncryptionConfiguration());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ResultConfigurationUpdates == false)
            return false;
        ResultConfigurationUpdates other = (ResultConfigurationUpdates) obj;
        if (other.getOutputLocation() == null ^ this.getOutputLocation() == null)
            return false;
        if (other.getOutputLocation() != null && other.getOutputLocation().equals(this.getOutputLocation()) == false)
            return false;
        if (other.getRemoveOutputLocation() == null ^ this.getRemoveOutputLocation() == null)
            return false;
        if (other.getRemoveOutputLocation() != null && other.getRemoveOutputLocation().equals(this.getRemoveOutputLocation()) == false)
            return false;
        if (other.getEncryptionConfiguration() == null ^ this.getEncryptionConfiguration() == null)
            return false;
        if (other.getEncryptionConfiguration() != null && other.getEncryptionConfiguration().equals(this.getEncryptionConfiguration()) == false)
            return false;
        if (other.getRemoveEncryptionConfiguration() == null ^ this.getRemoveEncryptionConfiguration() == null)
            return false;
        if (other.getRemoveEncryptionConfiguration() != null
                && other.getRemoveEncryptionConfiguration().equals(this.getRemoveEncryptionConfiguration()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getOutputLocation() == null) ? 0 : getOutputLocation().hashCode());
        hashCode = prime * hashCode + ((getRemoveOutputLocation() == null) ? 0 : getRemoveOutputLocation().hashCode());
        hashCode = prime * hashCode + ((getEncryptionConfiguration() == null) ? 0 : getEncryptionConfiguration().hashCode());
        hashCode = prime * hashCode + ((getRemoveEncryptionConfiguration() == null) ? 0 : getRemoveEncryptionConfiguration().hashCode());
        return hashCode;
    }

    @Override
    public ResultConfigurationUpdates clone() {
        try {
            return (ResultConfigurationUpdates) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.athena.model.transform.ResultConfigurationUpdatesMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
'use strict';

var querystring = require('querystring');
var https = require('https');

var apiKey = '03247e3243346fde40e43e8f337a6a3f';
var util = require('util');

function performRequest(host, endpoint, method, data, success) {
  var dataString = JSON.stringify(data);
  var headers = {};

  if (method === 'GET') {
    endpoint += '?' + querystring.stringify(data);
  }
  else {
    headers = {
      'Content-Type': 'application/json',
      'Content-Length': dataString.length
    };
  }
  var options = {
    host: host,
    path: endpoint,
    method: method,
    headers: headers
  };

  console.log('REQ : ' + host + endpoint);

  return new Promise((resolve, reject) => {
    const req = https.request(options, function(res) {
      res.setEncoding('utf-8');

      console.log('111');
      var responseString = '';
      if (res.statusCode < 200 || res.statusCode > 299) {
       reject(new Error('Failed to load page, status code: ' + res.statusCode));
     }

     res.on('data', function(data) {
      console.log('222');
      responseString += data;
    });

     res.on('end', function() {
      console.log('* OK End');

      var responseObject = JSON.parse(responseString);
        // console.log(util.inspect(responseObject, {showHidden: false, depth: null}));

        resolve(responseObject);
      });
    }); // end https.request
    console.log('333');
    req.on('error', (err) => reject(err));
    req.write(dataString);
    req.end();
    console.log('444');
  });
}

Date.prototype.yymmdd = function() {
  //var yr = this.getYear() - 100;
  var yr = this.getFullYear();
  var mm = this.getMonth() + 1;
  var dd = this.getDate()-1;

  console.log('year : ' + yr + ', mm : ' + mm + ', dd : ' + dd);

  return yr.toString() + (mm.toString().length === 2 ? mm : '0'+mm).toString() + (dd.toString().length === 2 ? dd : '0'+dd).toString();
  // return [yr, !mm[1] && '0', mm, !dd[1] && '0', dd].join('');
}

module.exports = {
  getDailyBoxOffice: function() {
    var host = 'www.kobis.or.kr';
    var today = new Date();
    console.log('today is ' + today.yymmdd());
    return performRequest(host, '/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json',
      'GET',
      {
        key : apiKey,
        targetDt : today.yymmdd()
      }, function(data) {
        console.log('Fetched ' + data);
        //prettify(data);
      });
  },

  getMovieInfoByName: function (name) {
    var host = 'apis.daum.net';
    var daumKey = '1897b74982e1e8f01c2848ebe4a94cce';
    return performRequest(host, '/contents/movie',
      'GET',
      {
        apiKey : daumKey,
        q : name,
        output : 'json'
      }, function(data) {
        console.log('Fetched ' + data);
        prettify2(data);
      });
  },

  getRemoteMovieInfo: function() {
    var bmi = require('./build-movie-info');
    var p = [];
    return new Promise((resolve, reject) => {
      bmi.getDailyBoxOffice()
      .then(function(data) {

        var theMovieList = getFirstList(data);
        console.log('----theMovieList.movies.length' + theMovieList.movies.length);
        for (var i=0; i < theMovieList.movies.length; i++) {
          console.log('++');
          p[i] = bmi.getMovieInfoByName(theMovieList.movies[i].name);
        }

        Promise.all(p).then(data => {

            // console.log('**data.length = ' + data.length);
            // console.log('**themovielist = ' + JSON.stringify(theMovieList));
            for(var i=0; i < data.length; i++) {
              theMovieList.movies[i] = getSecondList(theMovieList.movies[i], data[i]);
            }
            // console.log('*theMovieList : ' + JSON.stringify(theMovieList));
            resolve(theMovieList);
          });

      });
    });

  },

  prettify: function(data) {
    var overall = data.boxOfficeResult;
    var list = overall.dailyBoxOfficeList;
    console.log("-------------------------");

    console.log("Title : " + overall.boxofficeType);
    console.log("Date : " + overall.showRange);

    for (var i=0; i < list.length; i++) {
      console.log(list[i].rank, list[i].movieNm);
    }

    console.log("-------------------------");
  },

  prettify2: function(data) {
    var channel = data.channel;
    console.log("-------------------------");

    console.log("+Title : " + channel.title);
    console.log("result : " + channel.result);
    console.log("query string : " + channel.q);

    var list = channel.item;

    for (var i=0; i < list.length; i++) {
      console.log("+Thumbnail : " + list[i].thumbnail[0].content);
      console.log("photo1 : " + list[i].photo1.content);
      console.log("Story : " + list[i].story[0].content);

    }

    console.log("-------------------------");
  }

};

var getFirstList = function(data) {
  const overall = data.boxOfficeResult;
  const list = overall.dailyBoxOfficeList;
  var firstList = {}, movies = [];
  console.log("-1-----------------------");

  firstList.type = overall.boxofficeType;
  firstList.date = overall.showRange;

  console.log("Title : " + overall.boxofficeType);
  console.log("Date : " + overall.showRange);

  for (var i=0; i < list.length; i++) {
    var movie={};
    movie.rank = list[i].rank;
    movie.name = list[i].movieNm;
    movies.push(movie);
    console.log(list[i].rank, list[i].movieNm);
  }
  firstList.movies = movies;
  console.log("-----------------------1-");
  return firstList;
}

var getSecondList = function(first, data) {
  var movie = first;
  var channel = data.channel;
  console.log("--2----------------------");

  console.log("+Title : " + channel.title);
  console.log("result : " + channel.result);
  console.log("query string : " + channel.q);

  var item = channel.item[0];

  console.log("+Thumbnail : " + item.thumbnail[0].content);
  console.log("photo1 : " + item.photo1.content);
  console.log("Story : " + item.story[0].content);

  movie.thumbnail = item.thumbnail[0].content;
  movie.title = item.title;
  movie.photo = [item.photo1.content, item.photo2.content, item.photo3.content, item.photo4.content, item.photo5.content];
  movie.engName = item.eng_title[0].content;
  movie.year = item.year[0].content;
  movie.story = item.story[0].content;
  movie.openDay = item.open_info[0].content;
  movie.genre = item.genre;
  movie.actor = item.actor;
  movie.director = item.director;
  movie.video = item.video;
  movie.trailer = item.trailer;

  // console.log('movie: ' + JSON.stringify(movie));

  console.log("----------------------2-");
  return movie;
}

var client = function() {
  var bmi = require('./build-movie-info');
  var theMovieList = {};
  var fs=require('fs');
  var filename = './boxoffice.json';

  bmi.getRemoteMovieInfo()
  .then(function(list) {
    //console.log('+++++++++++++++++++++list = ' + JSON.stringify(list));
    console.log('aaaaaaaaaaaaaaaa');
    fs.writeFile(filename, JSON.stringify(list), function (err) {
      if (err) { console.log('error : ' + err);}
      console.log('file created : ' + filename);
    });
    console.log('bbbbbbbbbbbbbb');
  });
}

//client();


text:
<title>
Setback for Bush's war on our civil liberties
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Setback for Bush's war on our civil liberties

By Lee Sustar | July 2, 2004 | Page 2

THE BUSH administration's attempt to strip foreign prisoners of all rights suffered a major blow from the U.S. Supreme Court. A 6-3 vote by the court gave prisoners at the U.S. naval base in Guantánamo Bay, Cuba, the right to take their case to U.S. courts. This will allow the 595 prisoners--most held since the U.S. invasion of Afghanistan without being charged--to make appeals in the courts.

The ruling is the latest blow against the abusive U.S. policy in Guantánamo. In mid-June, the White House was forced to disown a legal memo, which claimed that as president, George W. Bush had the authority to dispense with the rules of the Geneva Convention governing treatment of prisoners.

Earlier investigations of the torture scandal at Abu Ghraib prison in Iraq found that the methods used on Iraqis had first been used in Guantánamo. Now that the Supreme Court ruling has cleared the way for prisoners to bring lawsuits in U.S. federal courts, details of further abuse are sure to emerge.

The Bush administration also lost in two other cases involving U.S. citizens accused of being "enemy combatants." In the case of Yaser Esam Hamdi, a Saudi-born U.S. citizen captured in Afghanistan in 2001, the court ruled 8-1 that Hamdi had the right to his day in court. "A state of war is not a blank check for the president when it comes to the rights of the nation's citizens," wrote Justice Sandra Day O'Connor.

José Padilla, a U.S. citizen arrested at O'Hare Airport on charges of conspiring to detonate a radioactive "dirty bomb," also challenged the government's attempt to hold him as an enemy combatant. Even before the Supreme Court ruling, the Padilla case was falling apart. Federal prosecutors admitted that the dirty bomb charge against him was wrong--only to claim that he was planning to blow up apartment buildings instead.

The justices decided to send the Padilla case back to lower courts for technical reasons--but the Hamdi ruling gives his appeal a powerful boost. The American Civil Liberties Union ruling called the Supreme Court rulings "a strong repudiation of the administration's arguments that its actions in the war on terrorism are beyond the rule of law and unreviewable by American courts." With the Bush administration on the defensive, now is the time to step up activism against the government's assault on civil liberties.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users.server.controller');
	var wikis = require('../../app/controllers/wikis.server.controller');

	// Wikis Routes
	app.route('/wikis')
		.get(wikis.list)
		.post(users.requiresLogin, wikis.create);

	app.route('/wikis/:wikiId')
		.get(wikis.read)
		.put(users.requiresLogin, wikis.hasAuthorization, wikis.update)
		.delete(users.requiresLogin, wikis.hasAuthorization, wikis.delete);

	// Finish by binding the Wiki middleware
	app.param('wikiId', wikis.wikiByID);
};


text:
@import CoreMotion;
#import "ViewController.h"
#import "DateRange.h"

typedef NS_ENUM(NSInteger, DateRangeOption) {
    DateRangeOptionToday,
    DateRangeOptionYesterday,
    DateRangeOptionPastWeek,
};

typedef NS_ENUM(NSInteger, TimeIntervalOption) {
    TimeIntervalOptionWholeRange,
    TimeIntervalOptionOneHour,
    TimeIntervalOptionFifteenMinutes,
    TimeIntervalOptionFiveMinutes,
    TimeIntervalOptionOneMinute,
    TimeIntervalOptionCount
};

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextView *logTextView;
@property (weak, nonatomic) IBOutlet UISegmentedControl *dateRangeControl;
@property (nonatomic) CMStepCounter *stepCounter;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    if (![CMStepCounter isStepCountingAvailable]) {
        [[[UIAlertView alloc] initWithTitle:@"Sorry" message:@"This demo only works on devices with an M7 chip" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil] show];
    }

    self.stepCounter = [[CMStepCounter alloc] init];

    self.dateRangeControl.selectedSegmentIndex = 0;
    [self performTestsWithDateRangeOption:self.dateRangeControl.selectedSegmentIndex];
}

- (void)performTestsWithDateRangeOption:(DateRangeOption)dateRangeOption {
    self.dateRangeControl.enabled = NO;
    [self resetLog];
    [self logLine:[NSString stringWithFormat:@"Running tests with time period: %@", [self dateRangeStringForOption:dateRangeOption]]];
    [self performTestWithDateRange:[self dateRangeForOption:dateRangeOption] timeIntervalOption:TimeIntervalOptionWholeRange highestStepCount:0];
}

- (void)performTestWithDateRange:(DateRange *)dateRange timeIntervalOption:(TimeIntervalOption)timeIntervalOption highestStepCount:(NSUInteger)highestStepCount {
    NSTimeInterval interval = [self timeIntervalForOption:timeIntervalOption];
    [self countStepsFromDate:dateRange.start toDate:dateRange.end interval:interval handler:^(NSUInteger stepCount) {
        NSString *lostStepsString = stepCount < highestStepCount ? [NSString stringWithFormat:@" (lost %lu)", (unsigned long)(highestStepCount-stepCount)] : @"";
        [self logLine:[NSString stringWithFormat:@"Interval: %@. Steps: %lu%@", [self timeIntervalStringForOption:timeIntervalOption], (unsigned long)stepCount, lostStepsString]];

        if (timeIntervalOption+1 < TimeIntervalOptionCount) {
            [self performTestWithDateRange:dateRange timeIntervalOption:timeIntervalOption+1 highestStepCount:MAX(highestStepCount, stepCount)];
        }
        else {
            [self logLine:@"Done!"];
            self.dateRangeControl.enabled = YES;
        }
    }];
}

#pragma mark - Log Management

- (void)resetLog {
    NSLog(@"\n-------------------------\n");
    self.logTextView.text = nil;
}

- (void)logLine:(NSString *)line {
    NSLog(@"%@", line);
    self.logTextView.text = [self.logTextView.text stringByAppendingFormat:@"%@\n", line];
}

#pragma mark - Step Counting
// Algorithm inspired by the MapMyFitness MMDK: https://www.mapmyapi.com/sdk
- (void)countStepsFromDate:(NSDate *)startDate toDate:(NSDate *)endDate interval:(NSTimeInterval)interval handler:(void (^)(NSUInteger stepCount))handler {
    NSMutableArray *steps = [[NSMutableArray alloc] init];

    dispatch_group_t group = dispatch_group_create();
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];

    NSDate *segmentStartDate = startDate, *segmentEndDate;
    do {
        segmentEndDate = [[segmentStartDate dateByAddingTimeInterval:interval] earlierDate:endDate];

        dispatch_group_enter(group);
        [self.stepCounter queryStepCountStartingFrom:segmentStartDate to:segmentEndDate toQueue:queue withHandler:^(NSInteger numberOfSteps, NSError *error) {
            if (error) {
                NSLog(@"Error: %@", error);
            }

            [steps addObject:@(numberOfSteps)];
            dispatch_group_leave(group);
        }];

        segmentStartDate = segmentEndDate;
    } while ([endDate compare:segmentEndDate] == NSOrderedDescending);

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSUInteger totalStepCount = [[steps valueForKeyPath:@"@sum.self"] unsignedIntegerValue];
        handler(totalStepCount);
    });
}

#pragma mark - Actions

- (IBAction)dateRangeChanged:(id)sender {
    [self performTestsWithDateRangeOption:self.dateRangeControl.selectedSegmentIndex];
}

#pragma mark - Helpers

- (NSTimeInterval)timeIntervalForOption:(TimeIntervalOption)option {
    switch (option) {
        case TimeIntervalOptionOneHour:
            return 60*60;
        case TimeIntervalOptionFifteenMinutes:
            return 60*15;
        case TimeIntervalOptionFiveMinutes:
            return 60*5;
        case TimeIntervalOptionOneMinute:
            return 60;
        default:
            return 60*60*24*8;
    }
}

- (NSString *)timeIntervalStringForOption:(TimeIntervalOption)option {
    switch (option) {
        case TimeIntervalOptionOneHour:
            return @"One hour";
        case TimeIntervalOptionFifteenMinutes:
        case TimeIntervalOptionFiveMinutes:
        case TimeIntervalOptionOneMinute: {
            NSInteger minutes = (NSInteger)([self timeIntervalForOption:option]/60);
            return [NSString stringWithFormat:@"%ld minute%@", minutes, minutes==1 ? @"" : @"s"];
        }
        default:
            return @"Entire range";
    }
}

- (NSString *)dateRangeStringForOption:(DateRangeOption)option {
    switch (option) {
        case DateRangeOptionToday:
            return @"Today";
        case DateRangeOptionYesterday:
            return @"Yesterday";
        default:
            return @"Last Week";
    }
}

- (DateRange *)dateRangeForOption:(DateRangeOption)option {
    switch (option) {
        case DateRangeOptionToday:
            return [DateRange dateRangeWithStart:[self beginningOfDaysAgo:0] end:[NSDate date]];
        case DateRangeOptionYesterday:
            return [DateRange dateRangeWithStart:[self beginningOfDaysAgo:1] end:[self endOfDaysAgo:1]];
        default:
            return [DateRange dateRangeWithStart:[NSDate dateWithTimeIntervalSinceNow:-60*60*24*7] end:[NSDate date]];
    }
}

- (NSDate *)beginningOfDaysAgo:(NSInteger)daysAgo {
    NSDateComponents *daysAgoComponents = [[NSDateComponents alloc] init];
    daysAgoComponents.day = -daysAgo;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *date = [calendar dateByAddingComponents:daysAgoComponents toDate:[NSDate date] options:0];

    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    return [calendar dateFromComponents:components];
}

- (NSDate *)endOfDaysAgo:(NSInteger)daysAgo {
    NSDateComponents *daysAgoComponents = [[NSDateComponents alloc] init];
    daysAgoComponents.day = -daysAgo;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *date = [calendar dateByAddingComponents:daysAgoComponents toDate:[NSDate date] options:0];

    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    components.hour = 23;
    components.minute = 59;
    components.second = 59;
    return [calendar dateFromComponents:components];
}

@end


text:
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace Uaaa.Data.Sql.Extensions
{
    /// <summary>
    /// SqlDataReader extension methods.
    /// </summary>
    public static class SqlDataReaderExtensions
    {
        /// <summary>
        /// Reads single record from provided SqlDataReader object.
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static async Task<DataRecord> ReadSingle(this SqlDataReader reader)
        {
            try
            {
                if (reader.HasRows && await reader.ReadAsync())
                {
                    var item = new DataRecord();
                    for (var idx = 0; idx < reader.FieldCount; idx++)
                        item[reader.GetName(idx)] = !reader.IsDBNull(idx) ? reader.GetValue(idx) : null;
                    return item;
                }
                return null;
            }
            finally
            {
                (reader as IDataReader)?.Close();
            }
        }
        /// <summary>
        /// Reads all records from provided SqlDataReader object.
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static async Task<IEnumerable<DataRecord>> ReadAll(this SqlDataReader reader)
        {
            try
            {
                var records = new List<DataRecord>();
                if (reader.HasRows)
                {
                    while (await reader.ReadAsync())
                    {
                        var item = new DataRecord();
                        for (var idx = 0; idx < reader.FieldCount; idx++)
                            item[reader.GetName(idx)] = !reader.IsDBNull(idx) ? reader.GetValue(idx) : null;
                        records.Add(item);
                    }
                }
                return records;
            }
            finally
            {
                (reader as IDataReader)?.Close();
            }
        }
    }
}