text:
angular.module( 'billsync.entities', [])

.factory( 'InvoicesRes', function($resource){
  return $resource('../api/v1/invoices/:id',
    {id: '@id'},
    {
      query: {method: 'GET', isArray: true},
      update: {method: 'PUT', params: {id: '@id'}, isArray:false},
      update_all: { method: 'PUT', params: {id: 'update_all'}, isArray: true }
    });
})

.factory( 'InvoiceModerationRes', function($resource){
  return $resource('../api/v1/invoice_moderations/:id?hitId=:hitId',
    {id: '@id', hitId: '@hitId'},
    {
      query: { method: 'GET', params: { hitId: '@hitId'}, isArray: true },
      update: {method: 'PUT', params: {id: '@id', hitId: '@hitId' }, isArray:false}
    });
})

.factory( 'VendorsRes', function($resource){
  return $resource('../api/v1/vendors/:id',
    {id: '@id'},
    {
      update: {method: 'PUT', params: {id: '@id'}, isArray:false}
    });
})

.factory( 'CurrentIndividualRes', function($resource){
  return $resource('../api/v1/settings',
    {},
    {
      update: {method: 'PUT', params: {}, isArray:false}
    });
})

.factory( 'VendorInvoicesRes', function($resource){
  return $resource('../api/v1/vendors/:id/invoices',
    {id: '@id'},
    {
      query: { method: 'GET', params: { id: '@id'}, isArray: true },
      update: {method: 'PUT', params: {id: '@id'}, isArray:false},
      update_all: { method: 'PUT', params: {id: 'update_all'}, isArray: true }
    });
})

.factory( 'EmailRes', function($resource){
  return $resource('../api/v1/emails/:id',
    {id: '@id'},
    {
      query: {method: 'GET', isArray: true},
      update: {method: 'PUT', params: {id: '@id'}, isArray:false}
    });
})

.factory('NumberRes', function($resource){
  return $resource('../api/v1/numbers/:id',
    {id: '@id'},
    {
      query: {method: 'GET', isArray: true},
      update: {method: 'PUT', params: {id: '@id'}, isArray:false}
    });
})

.factory('AddressRes', function($resource){
  return $resource('../api/v1/addresses/:id',
    {id: '@id'},
    {
      query: {method: 'GET', isArray: true},
      update: {method: 'PUT', params: {id: '@id'}, isArray:false}
    });
})
// .factory('SurveyRes', function($resource) {
//   return $resource('../api/v1/surveys/:id?:hitId', { id: '@id', hitId: '@hitId'},{
//     query: { method: 'GET', isArray: true}
//   })
// })
.factory('InvoicesManager', ['$q', 'InvoicesRes', '$rootScope', function($q, InvoicesRes, $rootScope) {
  var invoicesManager = {
    _retrieveInstance: function(invoiceId, invoiceData) {
      var instance = this._search(invoiceId);

      if (instance) {
        instance = invoiceData;
      } else {
        instance = new InvoicesRes(invoiceData);
      }

      return instance;
    },
    _search: function(invoiceId) {
      return _.find($rootScope.invoices, function(invoice){ return invoice.id == invoiceId; });
    },
    _load: function(invoiceId, deferred, hitId) {
      var scope = this;

      InvoicesRes.get({id: invoiceId, hit_id: hitId}, function(invoiceData) {
        var invoice = scope._retrieveInstance(invoiceData.id, invoiceData);
        deferred.resolve(invoice);
      },
      function() {
        deferred.reject();
      });
    },
    /* Public Methods */
    /* Use this function in order to get a invoice instance by it's id */
    getInvoice: function(invoiceId, hitId) {
      var deferred = $q.defer();
      if(invoiceId){
        var invoice = this._search(invoiceId);
        if (invoice) {
          deferred.resolve(invoice);
        } else {
          this._load(invoiceId, deferred, hitId);
        }
      }else{
        deferred.resolve(new InvoicesRes());
      }
      return deferred.promise;
    },
    /* Use this function in order to get instances of all the invoices */
    loadAllInvoices: function() {
      var deferred = $q.defer();
      var scope = this;

      InvoicesRes.query(function(invoicesArray) {
          $rootScope.invoices = invoicesArray;
          deferred.resolve($rootScope.invoices);
      }, function() {
          deferred.reject();
      });

      return deferred.promise;
    },
    loadInvoicesByStatus: function(statusArray){
      return _.filter($rootScope.invoices,function(invoice){
        return _.indexOf(statusArray, invoice.status) !== -1;
      });
    },
    less_than_30: function(){
      return _.filter($rootScope.invoices,function(invoice){
        if(invoice.due_date){
          var today = new Date();
          var dd = today.getDate() - 1;
          var mm = today.getMonth()+2; //January is 0 and we need to add 1 to get next month
          var yyyy = today.getFullYear();
          var oneMonthFromToday = new Date(mm+'/'+dd+'/'+yyyy);
          var due_date_array = invoice.due_date.split("-");
          var due_date = new Date(due_date_array[1]+'/'+due_date_array[2]+'/'+due_date_array[0]);
          var timeDiff = Math.abs(due_date.getTime() - oneMonthFromToday.getTime());
          var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

          return diffDays > 0 && diffDays < 30;

        }else{
          return false;
        }
      });
    },
    more_than_30: function(){
      return _.filter($rootScope.invoices,function(invoice){
        if(invoice.due_date){
          var today = new Date();
          var dd = today.getDate() - 1;
          var mm = today.getMonth() + 2; //January is 0 and we need to add 1 to get next month
          var yyyy = today.getFullYear();
          var oneMonthFromToday = new Date(mm+'/'+dd+'/'+yyyy);
          var due_date_array = invoice.due_date.split("-");
          var due_date = new Date(due_date_array[1]+'/'+due_date_array[2]+'/'+due_date_array[0]);
          var timeDiff = Math.abs(due_date.getTime() - oneMonthFromToday.getTime());
          var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
          return diffDays > 30;

        }else{
          return false;
        }
      });
    },
    /*  This function is useful when we got somehow the invoice data and we wish to store it or update the pool and get a invoice instance in return */
    updateInvoice: function(invoice) {
      var deferred = $q.defer();
      var that = this;
      invoice.$update(function(invoice){
        that._retrieveInstance(invoice.id, invoice);
        deferred.resolve(invoice);
      },function() {
        deferred.reject();
      });
      return deferred.promise;
    },
    saveInvoice: function(invoice){
      var deferred = $q.defer();
      var that = this;
      invoice.$save(function(invoice){
        that._retrieveInstance(invoice.id, invoice);
        deferred.resolve(invoice);
      }, function(response){
        deferred.reject(response);
      });
      return deferred.promise;
    }

  };
  return invoicesManager;
}]);


text:
import error from 'http-errors'
import UserService from '../../services/oauth/user'

function UserController (dependencies = { userService: UserService() }) {
  const { userService } = dependencies

  const userController = {}

  /**
   * GET /oauth2/users
   * Find all users.
   */
  userController.index = async (req, res) => {
    const users = await userService.getUsers()
    res.status(200).json(users)
  }

  /**
   * POST /oauth2/users
   * Create a new user.
   */
  userController.create = async (req, res) => {
    const user = await userService.createUser(req.body)
    res.status(201).json(user)
  }

  /**
   * GET /oauth2/users/:id
   * Find one user by ID.
   */
  userController.show = async (req, res) => {
    const user = await userService.getUserById(req.params.id)
    if (!user) throw error(404)
    res.status(200).json(user)
  }

  /**
   * PUT /oauth2/users/:id
   * Update an existing user by ID.
   */
  userController.update = async (req, res) => {
    const user = await userService.updateUser(req.params.id, req.body)
    if (!user) throw error(404)
    res.status(200).json(user)
  }

  /**
   * DELETE /oauth2/users/:id
   * Destroy an existing user by ID.
   */
  userController.destroy = async (req, res) => {
    const user = await userService.deleteUser(req.params.id)
    if (!user) throw error(404)
    res.status(200).json({ id: user.id, deleted: true })
  }

  return userController
}

export default UserController

redpajama_set_name: RedPajamaGithub


text:
[![Version](https://img.shields.io/cocoapods/v/HRMethodsAttributes.svg?style=flat)](http://cocoapods.org/pods/HRMethodsAttributes)
[![License](https://img.shields.io/cocoapods/l/HRMethodsAttributes.svg?style=flat)](http://cocoapods.org/pods/HRMethodsAttributes)
[![Platform](https://img.shields.io/cocoapods/p/HRMethodsAttributes.svg?style=flat)](http://cocoapods.org/pods/HRMethodsAttributes)

HRMethodsAttributes is a simple defines wrapper on ` __attribute__(()) `.

## Usage

Deprecated:

```objective-c
-(void)doSomething DEPRECATED;
```

Deprecated with reason:

```objective-c
-(void)makeMeCool DEPRECATED_REASON("'cause, lol");
```

Unavailable:

```objective-c
-(void)dSomething UNAVAILABLE;
```

Unavailable with reason:

```objective-c
-(void)doSomethingElse UNAVAILABLE_REASON("Old method. Use -doSmthngElse: instead");
```

## Requirements

Objective-C and iOS 7.1 or higher.

## Installation

HRMethodsAttributes is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod 'HRMethodsAttributes'
```

## Author

Ivan Shevelev, ivan.shevelev@sibers.com

## License

HRMethodsAttributes is available under the MIT license. See the LICENSE file for more info.


text:
package org.apache.pulsar.broker.service;

import static org.apache.pulsar.broker.service.BrokerService.BROKER_SERVICE_CONFIGURATION_PATH;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.fail;

import java.lang.reflect.Method;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.bookkeeper.util.ZkUtils;
import org.apache.pulsar.broker.service.BrokerService;
import org.apache.pulsar.client.api.Consumer;
import org.apache.pulsar.client.api.ConsumerConfiguration;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SubscriptionType;
import org.apache.pulsar.client.impl.ConsumerImpl;
import org.apache.pulsar.common.util.ObjectMapperFactory;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 */
public class BrokerServiceThrottlingTest extends BrokerTestBase {

    @BeforeMethod
    @Override
    protected void setup() throws Exception {
        super.baseSetup();
    }

    @AfterMethod
    @Override
    protected void cleanup() throws Exception {
        super.internalCleanup();
    }

    /**
     * Verifies: updating zk-thottling node reflects broker-maxConcurrentLookupRequest and updates semaphore.
     *
     * @throws Exception
     */
    @Test
    public void testThrottlingLookupRequestSemaphore() throws Exception {
        BrokerService service = pulsar.getBrokerService();
        assertNotEquals(service.lookupRequestSemaphore.get().availablePermits(), 0);
        admin.brokers().updateDynamicConfiguration("maxConcurrentLookupRequest", Integer.toString(0));
        Thread.sleep(1000);
        assertEquals(service.lookupRequestSemaphore.get().availablePermits(), 0);
    }

    /**
     * Broker has maxConcurrentLookupRequest = 0 so, it rejects incoming lookup request and it cause consumer creation
     * failure.
     *
     * @throws Exception
     */
    @Test
    public void testLookupThrottlingForClientByBroker0Permit() throws Exception {

        final String topicName = "persistent://prop/usw/my-ns/newTopic";

        org.apache.pulsar.client.api.ClientConfiguration clientConf = new org.apache.pulsar.client.api.ClientConfiguration();
        clientConf.setStatsInterval(0, TimeUnit.SECONDS);
        String lookupUrl = new URI("pulsar://localhost:" + BROKER_PORT).toString();
        PulsarClient pulsarClient = PulsarClient.create(lookupUrl, clientConf);

        ConsumerConfiguration consumerConfig = new ConsumerConfiguration();
        Consumer consumer = pulsarClient.subscribe(topicName, "mysub", consumerConfig);
        consumer.close();

        int newPermits = 0;
        admin.brokers().updateDynamicConfiguration("maxConcurrentLookupRequest", Integer.toString(newPermits));
        // wait config to be updated
        for (int i = 0; i < 5; i++) {
            if (pulsar.getConfiguration().getMaxConcurrentLookupRequest() != newPermits) {
                Thread.sleep(100 + (i * 10));
            } else {
                break;
            }
        }

        try {
            consumer = pulsarClient.subscribe(topicName, "mysub", consumerConfig);
            consumer.close();
            fail("It should fail as throttling should not receive any request");
        } catch (org.apache.pulsar.client.api.PulsarClientException.TooManyRequestsException e) {
            // ok as throttling set to 0
        }
    }

    /**
     * Verifies: Broker side throttling:
     *
     *

     * 1. concurrent_consumer_creation > maxConcurrentLookupRequest at broker
     * 2. few of the consumer creation must fail with TooManyLookupRequestException.
     *

     *
     * @throws Exception
     */
    @Test
    public void testLookupThrottlingForClientByBroker() throws Exception {
        final String topicName = "persistent://prop/usw/my-ns/newTopic";

        org.apache.pulsar.client.api.ClientConfiguration clientConf = new org.apache.pulsar.client.api.ClientConfiguration();
        clientConf.setStatsInterval(0, TimeUnit.SECONDS);
        clientConf.setIoThreads(20);
        clientConf.setConnectionsPerBroker(20);
        String lookupUrl = new URI("pulsar://localhost:" + BROKER_PORT).toString();
        PulsarClient pulsarClient = PulsarClient.create(lookupUrl, clientConf);

        ConsumerConfiguration consumerConfig = new ConsumerConfiguration();
        consumerConfig.setSubscriptionType(SubscriptionType.Shared);

        int newPermits = 1;
        admin.brokers().updateDynamicConfiguration("maxConcurrentLookupRequest", Integer.toString(newPermits));
        // wait config to be updated
        for (int i = 0; i < 5; i++) {
            if (pulsar.getConfiguration().getMaxConcurrentLookupRequest() != newPermits) {
                Thread.sleep(100 + (i * 10));
            } else {
                break;
            }
        }

        List<Consumer> successfulConsumers = Lists.newArrayList();
        ExecutorService executor = Executors.newFixedThreadPool(10);
        final int totalConsumers = 20;
        CountDownLatch latch = new CountDownLatch(totalConsumers);
        for (int i = 0; i < totalConsumers; i++) {
            executor.execute(() -> {
                try {
                    successfulConsumers.add(pulsarClient.subscribe(topicName, "mysub", consumerConfig));
                } catch (PulsarClientException.TooManyRequestsException e) {
                    // ok
                } catch (Exception e) {
                    fail("it shouldn't failed");
                }
                latch.countDown();
            });
        }
        latch.await();

        for (Consumer c : successfulConsumers) {
            if (c != null) {
                c.close();
            }
        }
        pulsarClient.close();
        assertNotEquals(successfulConsumers.size(), totalConsumers);
    }

    /**
     * This testcase make sure that once consumer lost connection with broker, it always reconnects with broker by
     * retrying on throttling-error exception also.
     *
     *

     * 1. all consumers get connected
     * 2. broker restarts with maxConcurrentLookupRequest = 1
     * 3. consumers reconnect and some get TooManyRequestException and again retries
     * 4. eventually all consumers will successfully connect to broker
     *

     *
     * @throws Exception
     */
    @Test
    public void testLookupThrottlingForClientByBrokerInternalRetry() throws Exception {

        final String topicName = "persistent://prop/usw/my-ns/newTopic";

        org.apache.pulsar.client.api.ClientConfiguration clientConf = new org.apache.pulsar.client.api.ClientConfiguration();
        clientConf.setStatsInterval(0, TimeUnit.SECONDS);
        clientConf.setIoThreads(20);
        clientConf.setConnectionsPerBroker(20);
        String lookupUrl = new URI("pulsar://localhost:" + BROKER_PORT).toString();
        PulsarClient pulsarClient = PulsarClient.create(lookupUrl, clientConf);
        upsertLookupPermits(100);
        ConsumerConfiguration consumerConfig = new ConsumerConfiguration();
        consumerConfig.setSubscriptionType(SubscriptionType.Shared);
        List<Consumer> consumers = Lists.newArrayList();
        ExecutorService executor = Executors.newFixedThreadPool(10);
        final int totalConsumers = 8;
        CountDownLatch latch = new CountDownLatch(totalConsumers);
        for (int i = 0; i < totalConsumers; i++) {
            executor.execute(() -> {
                try {
                    consumers.add(pulsarClient.subscribe(topicName, "mysub", consumerConfig));
                } catch (PulsarClientException.TooManyRequestsException e) {
                    // ok
                } catch (Exception e) {
                    fail("it shouldn't failed");
                }
                latch.countDown();
            });
        }
        latch.await();

        stopBroker();
        conf.setMaxConcurrentLookupRequest(1);
        startBroker();

        // wait strategically for all consumers to reconnect
        for (int i = 0; i < 5; i++) {
            if (!areAllConsumersConnected(consumers)) {
                Thread.sleep(1000 + (i * 500));
            } else {
                break;
            }
        }

        int totalConnectedConsumers = 0;
        for (int i = 0; i < consumers.size(); i++) {
            if (((ConsumerImpl) consumers.get(i)).isConnected()) {
                totalConnectedConsumers++;
            }
            consumers.get(i).close();

        }
        assertEquals(totalConnectedConsumers, totalConsumers);

        pulsarClient.close();
    }

    private boolean areAllConsumersConnected(List<Consumer> consumers) {
        for (int i = 0; i < consumers.size(); i++) {
            if (!((ConsumerImpl) consumers.get(i)).isConnected()) {
                return false;
            }
        }
        return true;
    }

    private void upsertLookupPermits(int permits) throws Exception {
        Map<String, String> throttlingMap = Maps.newHashMap();
        throttlingMap.put("maxConcurrentLookupRequest", Integer.toString(permits));
        byte[] content = ObjectMapperFactory.getThreadLocal().writeValueAsBytes(throttlingMap);
        if (mockZookKeeper.exists(BROKER_SERVICE_CONFIGURATION_PATH, false) != null) {
            mockZookKeeper.setData(BROKER_SERVICE_CONFIGURATION_PATH, content, -1);
        } else {
            ZkUtils.createFullPathOptimistic(mockZookKeeper, BROKER_SERVICE_CONFIGURATION_PATH, content,
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
    }

}


text:
package cmd

import (
	"fmt"

	"github.com/getantibody/antibody/antibodylib"
	"github.com/spf13/cobra"
)

var homeCmd = &cobra.Command{
	Use:     "home",
	Short:   "shows the current antibody home folder",
	Aliases: []string{"prefix", "p"},
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println(antibodylib.Home())
	},
}

func init() {
	RootCmd.AddCommand(homeCmd)
}


text:
package net.karlmartens.platform.io;

import static java.nio.file.StandardOpenOption.READ;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author kmartens
 *
 */
public class FileInputStream<T> implements Iterator<T> {

	private final ReadBuffer _buffer;
	private final Deserializer<T> _deserializer;

	private boolean _hasNext = true;
	private T _next;

	private FileInputStream(ReadBuffer buffer, Deserializer<T> deserializer) {
		_buffer = buffer;
		_deserializer = deserializer;
		advance();
	}

	@Override
	public boolean hasNext() {
		return _hasNext;
	}

	@Override
	public T next() {
		if (!hasNext())
			throw new NoSuchElementException();

		final T next = _next;
		advance();
		return next;
	}

	private void advance() {
		if (!_buffer.hasRemaining()) {
		        _hasNext = false;
		        _next = null;
			return;
		}

		_next = _deserializer.read(_buffer);
	}

	public static <T> FileInputStream<T> create(Path path, Deserializer<T> deserializer) {
		try {
			FileChannel channel = FileChannel.open(path, READ);
			return new FileInputStream<>(new ReadBuffer(channel), deserializer);
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}

	public static class ReadBuffer {

		private final FileChannel _channel;
		private final ByteBuffer _buffer;

		private ReadBuffer(FileChannel channel) {
			_channel = channel;
			_buffer = ByteBuffer.allocate(8096);
			_buffer.flip();
		}

		public boolean hasRemaining() {
			if (!_buffer.hasRemaining()) {
				read();
			}
			return _buffer.hasRemaining();
		}

		public byte getByte() {
			checkRequired(1);
			return _buffer.get();
		}

		public char getChar() {
			checkRequired(2);
			return _buffer.getChar();
		}

		public short getShort() {
			checkRequired(2);
			return _buffer.getShort();
		}

		public int getInt() {
			checkRequired(4);
			return _buffer.getInt();
		}

		public long getLong() {
			checkRequired(8);
			return _buffer.getLong();
		}

		public float getFloat() {
			checkRequired(4);
			return _buffer.getFloat();
		}

		public double getDouble() {
			checkRequired(8);
			return _buffer.getDouble();
		}

		public byte[] getBytes(byte[] arr) {
			int offset = 0;
			while (offset < arr.length) {
				if (!_buffer.hasRemaining())
					read();

				int length = Math.min(_buffer.remaining(), arr.length - offset);
				if (length == 0)
					throw new BufferUnderflowException();

				_buffer.get(arr, offset, length);
				offset += length;
			}
			return arr;
		}

		private void checkRequired(int numBytes) {
			if (_buffer.remaining() < numBytes) {
				read();
			}
		}

		private void read() {
			_buffer.compact();
			try {
				_channel.read(_buffer);
				_buffer.flip();
			} catch (IOException e) {
				throw new RuntimeException();
			}
		}
	}

}


text:
Sample commands to run examples:
```bash
cd examples
th toy1.lua -strict -train -datadir `pwd` -tmpdir `pwd` -adagrad -adagrad_learningRate 0.1
th toy1_fastlstmcell.lua -strict -train -datadir `pwd` -tmpdir `pwd` -adagrad -adagrad_learningRate 0.1 -cuda
```


text:
FROM alpine:3.8

LABEL maintainer "ferrari.marco@gmail.com"

RUN apk add --update \
  build-base \
  git \
  libffi \
  libffi-dev \
  musl \
  openssh-client \
  openssl \
  openssl-dev \
  python \
  python-dev \
  sshpass \
  && rm /var/cache/apk/*

# install and update pip
RUN python -m ensurepip \
  && pip install --no-cache-dir --upgrade pip

# Install Ansible dependencies
RUN pip install --no-cache-dir \
  Jinja2 \
  httplib2 \
  paramiko \
  pycrypto \
  PyYAML \
  six

RUN apk add --update \
  bash

WORKDIR /opt
RUN git clone https://github.com/ansible/ansible.git --recursive

ADD files/root/bash.bashrc /root/.bashrc

ENTRYPOINT ["/bin/bash", "-c"]
CMD ["bash"]


text:
using System.ComponentModel.Composition;
using Caliburn.Micro;
using csShared.Interfaces;

namespace csShared.FloatingElements
{
  [Export(typeof(IQrCode)), PartCreationPolicy(CreationPolicy.NonShared)]
  public class QrCodeViewModel : PropertyChangedBase, IQrCode
  {
    #region Implementation of IQrCode

    private string text;
    public string Text
    {
      get { return text; }
      set
      {
        if (text == value) return;
        text = value;
        NotifyOfPropertyChange(() => Text);
      }
    }

    #endregion
  }
}


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

<title>UpdateHabitRequest</title>
<meta name="date" content="2017-12-04">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

main.habitivity.controllers

Class UpdateHabitRequest

java.lang.Object

main.habitivity.controllers.UpdateHabitRequest

public class UpdateHabitRequest
extends java.lang.Object

An object that encapsulates all the components required to
 create a new habit. Helper function for AddHabitController

Constructor Summary

Constructors

Constructor and Description

UpdateHabitRequest()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.util.List<java.lang.Integer>
getDaysOfTheWeek()

Get the days of the week the habit reoccurs on

java.lang.String
getHabitType()

Returns the habit type

java.lang.String
getId()

Get the id of the habit

Habit
getOldHabit()

Habit
getOldId()

Gets the id of the old habit (i.e habit before editing).

java.lang.String
getReason()

Get the reason of the habit

java.util.Date
getStartDate()

Get the startDate of the habit

void
setDaysOfTheWeek(java.util.List<java.lang.Integer> daysOfTheWeek)

Sets the days of the week for the habits to reoccur on

void
setHabitType(java.lang.String type)

Sets the habit type

void
setId(java.lang.String id)

Sets the id of the habit

void
setOldHabit(Habit habit)

void
setOldId(Habit id)

Sets the id of the old habit (i.e habit before editing).

void
setReason(java.lang.String reason)

Sets the reason of the habit

void
setStartDate(java.util.Date startDate)

Sets the startDate of the habit

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

UpdateHabitRequest

public UpdateHabitRequest()

Method Detail

setOldHabit

public void setOldHabit(Habit habit)

getOldHabit

public Habit getOldHabit()

setOldId

public void setOldId(Habit id)

Sets the id of the old habit (i.e habit before editing). This is mainly used for when the user is editing
 the habit and changes the title since we're using the title as the habit's unique identifier

Parameters:

id - - id of the old habit

getOldId

public Habit getOldId()

Gets the id of the old habit (i.e habit before editing). This is mainly used for when the user is editing
 the habit and changes the title since we're using the title as the habit's unique identifier

Returns:

- the id of the old habit

getId

public java.lang.String getId()

Get the id of the habit

Returns:

id of the habit

setHabitType

public void setHabitType(java.lang.String type)

Sets the habit type

Parameters:

type - - type to set the habit to

getHabitType

public java.lang.String getHabitType()

Returns the habit type

Returns:

setId

public void setId(java.lang.String id)

Sets the id of the habit

Parameters:

id - to set

getReason

public java.lang.String getReason()

Get the reason of the habit

Returns:

reason of the habit

setReason

public void setReason(java.lang.String reason)

Sets the reason of the habit

Parameters:

reason - to set

getStartDate

public java.util.Date getStartDate()

Get the startDate of the habit

Returns:

startDate of the habit

setStartDate

public void setStartDate(java.util.Date startDate)

Sets the startDate of the habit

Parameters:

- - date to set

getDaysOfTheWeek

public java.util.List<java.lang.Integer> getDaysOfTheWeek()

Get the days of the week the habit reoccurs on

Returns:

days of the week the habit reoccurs on

setDaysOfTheWeek

public void setDaysOfTheWeek(java.util.List<java.lang.Integer> daysOfTheWeek)

Sets the days of the week for the habits to reoccur on

Parameters:

- - days of the week to reoccur

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text: When you create your pull request, put your game directory in here.


text:
1. Build transpiled javascript sources

  ```sh
  $ coffee -c -m *.coffee
  ```

2. Run the application

  ```sh
  $ node --debug app.js
  ```


text:
function sync() {
	var dropbox = require('dropbox');
	var Keys = require('keys');
	var cookiejar = require('com.kosso.cookiejar');

	var keys = new Keys();

	var client = dropbox.createClient({
		app_key : keys.dropbox_appkey,
		app_secret : keys.dropbox_appskey,
		root : 'sandbox'
	});

	var getAllData = function() {
		var db = Ti.Database.open('qute');
		var rows = db.execute('SELECT * FROM history ORDER BY id DESC');

		var fieldCount;

		fieldCount = rows.fieldCount;

		// After Ti. 3.3.0, fieldCount() had been removed from SDK
		//fieldCount is property in Android
		/*if (Ti.Platform.name === 'android') {
			fieldCount = rows.fieldCount;
		} else {
			fieldCount = rows.fieldCount();
		}*/

		var datas = [];
		// keys saves all image file name to easily search in datas
		var data_keys = [];

		while (rows.isValidRow()) {
			var obj = {};
			for (var i = 0; i < fieldCount; i++) {
				obj[rows.fieldName(i)] = rows.field(i);
			}

			datas.push(obj);
			var img_file_name = obj['img'].split('/')[1];
			console.log('img named: ' + img_file_name);
			data_keys.push(img_file_name.split('.')[0]);

			rows.next();
		}

		var deleted_rows = db.execute('SELECT * FROM _deleted');
		var deleted_keys = [];
		while (deleted_rows.isValidRow()) {
			deleted_keys.push(deleted_rows.fieldByName('deleted_key'));

			deleted_rows.next();
		}

		db.close();
		return [datas, data_keys, deleted_keys];
	};

	var importOrExport = function() {
		// TODO: Error prove to avoid error uploading
		console.log('method: importOrExport');
		// 1. Get files metadata from dropbox
		var dropbox_files = [];
		client.metadata('Content', {
			list : true,
			include_deleted : false
		}, function(stat, reply) {
			dropbox_files = reply['contents'];
			var need_recheck_photo = true;

			if (dropbox_files.length == 0) {
				pureExport();
			} else {
				//console.log('Go importOrExport one by one!\n' + JSON.stringify(reply));
				console.log('Cloud has ' + dropbox_files.length + ' files');

				// Below code too late to response!
				/*var dropbox_files_amount = dropbox_files.length;

				client.metadata('Photo', {
				list : true,
				include_deleted : false
				}, function(stat, reply) {
				console.log('[2]Cloud has ' + reply['contents'].length + ' photos');
				if (reply['contents'].length < dropbox_files_amount) {
				need_recheck_photo = true;
				}
				});*/

				// 2. Get local datas
				var datasAndKeys = getAllData();
				var datas = datasAndKeys[0];
				var data_keys = datasAndKeys[1];
				var deleted_keys = datasAndKeys[2];

				// To store ids which were updated in db
				var changed_ids = [];
				var insert_ids = [];

				// To define if all actions done
				var end_counter = 0;
				var total_amount = data_keys.length;

				console.log('Local has ' + datas.length + ' datas. And ' + data_keys.length + ' keys');
				// 3. Check if file exist in local? EXIST:continue NO:get
				dropbox_files.forEach(function(element, key, array) {
					var id2 = element['path'].split('Content/')[1];
					var id = id2.split('.')[0];

					var at = data_keys.indexOf(id);
					//console.log('Rest datas amount: ' + data_keys.length);
					console.log('Path: ' + element['path'] + ':: ID: ' + id + ':: at:' + at);
					//console.log(element['modified'] + ' = ' + (new Date(element['modified'])).getTime());
					if (at < 0) {

						// Add one more obj that shall be completed
						total_amount += 1;

						// Not existed in local. Download it
						if (deleted_keys.indexOf(id) < 0) {
							// Only if not exist in deleted_keys
							client.get(element['path'], {}, function(stat, reply, metadata) {
								console.log('metadata:' + metadata);
								var content = JSON.parse(reply);
								if (content.title) {
									var db = Ti.Database.open('qute');
									db.execute('INSERT INTO history (title, date, qrtype, content, raw, img, loved, post_id, qute_link, last_update, last_sync, from_me, sync_address) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)', content.title, content.date, content.qrtype, content.content, content.raw, content.img, content.loved, content.post_id, content.qute_link, content.last_update, content.last_sync, content.from_me, content.sync_address);
									insert_ids.push(db.lastInsertRowId);
									db.close();
									var photo_path = JSON.parse(metadata)['path'].replace('Content', 'Photo');
									photo_path = photo_path.replace('.json', '.png');
									console.log('Photo path: ' + photo_path);

									// Make sure the Qute folder in local is created
									var foldername = Ti.Filesystem.applicationDataDirectory + "Qute/";
									var folder = Ti.Filesystem.getFile(foldername);
									if (!folder.exists()) {
										folder.createDirectory();
									}

									// media can't be get by get() method
									/*client.get(photo_path, {}, function(stat, reply, metadata) {

									//Save file to local storage
									var img_name = JSON.parse(metadata)['path'].replace('/Photo','Qute'); // Get image file name
									var filename = Ti.Filesystem.applicationDataDirectory + img_name;
									var file = Ti.Filesystem.getFile(filename);
									file.write(reply);
									});*/

									// Get photo's direct url and apply to imageView to store it
									client.media(photo_path, {}, function(stat, reply) {

										var pp = photo_path;
										//Save file to local storage
										var img_name = pp.replace('/Photo', 'Qute');
										var local_img_path = Ti.Filesystem.applicationDataDirectory + img_name;
										var file = Ti.Filesystem.getFile(local_img_path);
										if (file.exists) {
											file.deleteFile();
										}

										var xhr = Ti.Network.createHTTPClient({
											onload : function(e) {
												file.write(this.responseData);
												end_counter++;
												Ti.API.info('Current end counter: ' + end_counter);
												if (end_counter >= total_amount) {
													Ti.API.info('Changed ids: ' + changed_ids + "::Inserted ids: " + insert_ids);
													Ti.App.fireEvent('end_syncing', {
														changed_ids : changed_ids,
														insert_ids : insert_ids
													});
												} else {
													// To share current sync progress
													Ti.App.fireEvent('sync_progress_changed', {
														now : end_counter,
														all : total_amount
													});
												}
											},
											onerror : function(e) {
												console.log('Get image fail! ' + e.error);
												end_counter++;
												Ti.API.info('Current end counter: ' + end_counter);
												if (end_counter >= total_amount) {
													Ti.API.info('Changed ids: ' + changed_ids + "::Inserted ids: " + insert_ids);
													Ti.App.fireEvent('end_syncing', {
														changed_ids : changed_ids,
														insert_ids : insert_ids
													});
												} else {
													Ti.App.fireEvent('sync_progress_changed', {
														now : end_counter,
														all : total_amount
													});
												}
												//TODO: More consitions to consider sync_done in HTTPClient?
											},
											timeout : 2 * 60000
										});

										xhr.open('GET', reply['url']);
										xhr.send();

										console.log('Img url is ' + reply['url'] + "::full path: " + pp);

										//temp_img.addEventListener('load',saveImage);
										//file.write(temp_img.toImage());

									});
								}
								//Ti.API.info('The file content: ' + JSON.parse(reply).title);
							});
						} else {
							// The key matched something in deleted_id
							end_counter++;
							if (end_counter >= total_amount) {
								Ti.API.info('Changed ids: ' + changed_ids + "::Inserted ids: " + insert_ids);
								Ti.App.fireEvent('end_syncing', {
									changed_ids : changed_ids,
									insert_ids : insert_ids
								});
							} else {
								Ti.App.fireEvent('sync_progress_changed', {
									now : end_counter,
									all : total_amount
								});
							}
						}

					} else {
						// File existed.
						// 4. Check if dropbox_file_date >(newer) local_file_date? YES:get EQUAL:skip NO:upload(content)
						// tolerance: Newer - 1 min. - Equal - 1 min. - Older

						// Do rest action only if there is related time flag
						if (datas[at].last_sync && datas[at].last_update && element['modified']) {
							console.log(element['modified'] + ' = ' + (new Date(element['modified'])).getTime());

							var dropbox_file_date = (new Date(element['modified'])).getTime();
							var local_file_update_date = (new Date(datas[at].last_update)).getTime();
							var local_file_sync_date = (new Date(datas[at].last_sync)).getTime();
							if (dropbox_file_date > local_file_sync_date + 60000) {
								var obj = datas[at];
								// Dropbox newer than Local. Need to download file (get content only)
								client.get(element['path'], {}, function(stat, reply, metadata) {
									console.log('metadata:' + metadata);
									var content = JSON.parse(reply);
									if (content.title) {
										//console.log('Updating data #' + datas[at]['id']);
										var db = Ti.Database.open('qute');
										// TODO:Weird error? datas[at].id undefined?
										db.execute('UPDATE history SET title=?, date=?, qrtype=?, content=?, raw=?, img=?, loved=?, post_id=?, qute_link=?, last_update=?, last_sync=?, from_me=?, sync_address=? WHERE id=?', content.title, content.date, content.qrtype, content.content, content.raw, content.img, content.loved, content.post_id, content.qute_link, content.last_update, content.last_sync, content.from_me, content.sync_address, obj.id);
										changed_ids.push(obj.id);
										db.close();
										var photo_path = JSON.parse(metadata)['path'].replace('Content', 'Photo');
										photo_path = photo_path.replace('.json', '.png');
										console.log('Photo path: ' + photo_path);

										// Make sure the Qute folder in local is created
										// TODO:Not neccessary?
										// !IMPORTANT: Not need to update image file. There shall be no way in app to update the image
										/*var foldername = Ti.Filesystem.applicationDataDirectory + "Qute/";
										 var folder = Ti.Filesystem.getFile(foldername);
										 if (!folder.exists()) {
										 folder.createDirectory();
										 }

										 // Get photo's direct url and apply to imageView to store it
										 client.media(photo_path, {}, function(stat, reply) {

										 var pp = photo_path;
										 //Save file to local storage
										 var img_name = pp.replace('/Photo', 'Qute');
										 var local_img_path = Ti.Filesystem.applicationDataDirectory + img_name;
										 var file = Ti.Filesystem.getFile(local_img_path);

										 if (file.exists){
										 file.deleteFile();
										 }

										 var xhr = Ti.Network.createHTTPClient({
										 onload : function(e) {
										 file.write(this.responseData);
										 },
										 onerror : function(e) {
										 console.log('Get image fail! ' + e.error);
										 },
										 timeout : 2 * 60000
										 });

										 xhr.open('GET', reply['url']);
										 xhr.send();

										 console.log('Img url is ' + reply['url'] + "::full path: " + pp);

										 //temp_img.addEventListener('load',saveImage);
										 //file.write(temp_img.toImage());

										 });*/
									}

									end_counter++;
									Ti.API.info('Current end counter: ' + end_counter);
									if (end_counter >= total_amount) {
										Ti.API.info('Changed ids: ' + changed_ids + "::Inserted ids: " + insert_ids);
										Ti.App.fireEvent('end_syncing', {
											changed_ids : changed_ids,
											insert_ids : insert_ids
										});
									} else {
										Ti.App.fireEvent('sync_progress_changed', {
											now : end_counter,
											all : total_amount
										});
									}
									//Ti.API.info('The file content: ' + JSON.parse(reply).title);
								});

							} else if (dropbox_file_date < local_file_update_date - 60000) {
								// Dropbox older than Local. Need to update dropbox data (upload content only)
								// TODO: Debug
								var obj = datas[at];
								console.log('[2]Uploading data #' + datas[at].id + " = " + obj['id']);
								var datetime = (new Date()).toISOString();
								obj['last_sync'] = datetime;
								var fname = obj['sync_address'];
								if (fname == 'no') {
									// fetch file name from image name
									var img_name = obj['img'].split('Qute/')[1];
									fname = img_name.split('.')[0];
								}

								client.put('Content/' + fname + '.json', JSON.stringify(obj), {
									overwrite : true
								}, function(stat, reply) {
									//Ti.API.info('stat:' + stat);
									//Ti.API.info('reply:' + JSON.stringify(reply));
									end_counter++;
									Ti.API.info('Current end counter: ' + end_counter);
									if (end_counter >= total_amount) {
										Ti.API.info('Changed ids: ' + changed_ids + "::Inserted ids: " + insert_ids);
										Ti.App.fireEvent('end_syncing', {
											changed_ids : changed_ids,
											insert_ids : insert_ids
										});
									} else {
										Ti.App.fireEvent('sync_progress_changed', {
											now : end_counter,
											all : total_amount
										});
									}
								});

								var db = Ti.Database.open('qute');
								db.execute('UPDATE history SET last_sync=? WHERE id=?', datetime, obj['id']);

							} else {
								// Equal. Nothing to do.
								end_counter++;
								Ti.API.info('Current end counter: ' + end_counter);
								if (end_counter >= total_amount) {
									Ti.API.info('Changed ids: ' + changed_ids + "::Inserted ids: " + insert_ids);
									Ti.App.fireEvent('end_syncing', {
										changed_ids : changed_ids,
										insert_ids : insert_ids
									});
								} else {
									Ti.App.fireEvent('sync_progress_changed', {
										now : end_counter,
										all : total_amount
									});
								}
							}
							// Kick out the handled obj

							// TODO:Too heavy the sync action! Don't check everytime or do check if needed (ie. content length > photo length)
							// Check if the photo missing
							// TODO:syncing progress in this situation
							console.log('need_recheck_photo? ' + need_recheck_photo + ' #' + at + '::' + datas[at]['sync_address']);
							if (need_recheck_photo) {
								var obj_p = datas[at];
								var sync_name = obj_p['sync_address'];
								if (sync_name == 'no') {
									// fetch file name from image name
									var img_name = obj_p['img'].split('Qute/')[1];
									sync_name = img_name.split('.')[0];
								}

								var photo_path = 'Photo/' + sync_name + '.png';
								client.metadata(photo_path, {}, function(stat, reply) {
									//console.log('get what? '+reply.length+'::'+JSON.stringify(reply));
									if (reply['is_deleted'] || reply['path'] === undefined) {
										var photo_file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory + obj_p['img']);
										client.put(photo_path, photo_file.read(), {}, function(stat, reply) {
											if (reply.error) {
												Ti.API.error('Re-put image ERROR! ' + reply.error);
											} else {
												Ti.API.info('Re-put image successfully!' + JSON.stringify(reply));
											}

										});
									}
								});
							}

							datas.splice(at, 1);
							data_keys.splice(at, 1);
						}

					}
				});
				// 5. The rest local data: Upload (photo+content)
				if (datas.length > 0) {
					// There are something in local and not exist in dropbox. Need to upload them (content+photo)
					var db = Ti.Database.open('qute');
					datas.forEach(function(element, key, array) {

						var photo_name = element['img'].split('/')[1];
						var sync_address = photo_name.split('.png')[0];

						var datetime = (new Date()).toISOString();
						element['last_sync'] = datetime;
						element['sync_address'] = sync_address;

						client.put('Content/' + sync_address + '.json', JSON.stringify(element), {
							overwrite : true
						}, function(stat, reply) {
							if (reply['error']) {
								Ti.API.error('Error! ' + reply['error']);
							}
						});

						var photo_file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory + element['img']);
						if (photo_file.exists()) {
							client.put('Photo/' + photo_name, photo_file.read(), {
								overwrite : true
							}, function(stat, reply) {
								if (reply['error']) {
									//TODO:error msg may cause App crash?
									Ti.API.error('Error! ' + reply['error']);
								}
								end_counter++;
								Ti.API.info('Current end counter: ' + end_counter);
								if (end_counter >= total_amount) {
									Ti.API.info('Changed ids: ' + changed_ids + "::Inserted ids: " + insert_ids);
									Ti.App.fireEvent('end_syncing', {
										changed_ids : changed_ids,
										insert_ids : insert_ids
									});
								} else {
									Ti.App.fireEvent('sync_progress_changed', {
										now : end_counter,
										all : total_amount
									});
								}
							});
						}

						db.execute('UPDATE history SET last_sync=?,sync_address=? WHERE id=?', datetime, sync_address, element['id']);

					});
					db.close();
				}
			}
		});
	};

	var pureExport = function() {
		var db = Ti.Database.open('qute');
		var rows = db.execute('SELECT * FROM history ORDER BY id DESC');
		var end_counter = 0;

		var fieldCount;

		fieldCount = rows.fieldCount;

		// After Ti 3.3.0, fieldCount() had been removed from SDK
		//fieldCount is property in Android
		/*if (Ti.Platform.name === 'android') {
			fieldCount = rows.fieldCount;
		} else {
			fieldCount = rows.fieldCount();
		}*/

		var rows_amount = rows.rowCount;

		while (rows.isValidRow()) {
			var obj = {};
			for (var i = 0; i < fieldCount; i++) {
				obj[rows.fieldName(i)] = rows.field(i);
			}

			var photo_name = obj['img'].split('/')[1];
			var unique_name = photo_name.split('.png')[0];

			// Save last sync time and sync address in local
			var datetime = new Date().toISOString();
			obj['last_sync'] = datetime;
			obj['sync_address'] = unique_name;

			client.put('Content/' + unique_name + '.json', JSON.stringify(obj), {
				overwrite : true
			}, function(stat, reply) {
				//Ti.API.info('stat:' + stat);
				//Ti.API.info('reply:' + JSON.stringify(reply));
			});

			var photo_file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory + obj['img']);
			client.put('Photo/' + photo_name, photo_file.read(), {
				overwrite : true
			}, function(stat, reply) {
				//Ti.API.info('stat:' + stat);
				//Ti.API.info('reply:' + JSON.stringify(reply));
				// Calculate how many rows are done. Fire end_syncing event whenn all rows are done.
				console.log('End counter: ' + end_counter);
				end_counter++;
				Ti.API.info('Current end counter: ' + end_counter);
				if (end_counter >= rows_amount) {
					Ti.App.fireEvent('end_syncing', {
						changed_ids : [],
						insert_ids : []
					});
				} else {
					Ti.App.fireEvent('sync_progress_changed', {
						now : end_counter,
						all : rows_amount
					});
				}
			});

			// Update last_sync in local data

			db.execute('UPDATE history SET last_sync=?,sync_address=? WHERE id=?', datetime, unique_name, obj['id']);

			rows.next();
		}
		db.close();
	};

	var doSync = function() {
		client.search('.', 'Content', {}, function(stat, reply) {
			if (reply.length > 0) {
				importOrExport();
			} else {
				pureExport();
			}
		});
	};

	var self = {
		doSync : function() {
			doSync();
		},
		logout : function() {
			// Not really logout. Or it will repeatly log in
			cookiejar.clearWebViewCookies('.dropbox.com');
			console.log('Before logout: ' + Ti.App.Properties.getString('DROPBOX_TOKENS'));
			Ti.App.Properties.setString('DROPBOX_TOKENS', null);
			Ti.App.Properties.setBool('syncing', false);
		},
		loginAndSync : function() {
			//TODO: add end_syncing event
			Ti.App.fireEvent('start_syncing', {});
			Ti.App.Properties.setString('latestSync', (new Date()).toISOString());
			//console.log('The sync date changed: '+Ti.App.Properties.getString('latestSync'));
			Ti.App.Properties.setBool('syncing', true);
			if (client.isAuthorized()) {
				console.log('Already logged in');
				//getDelta();
				doSync();
			} else {
				console.log('Go logging in');
				client.login(function(options) {
					console.log('Great! login done!' + options.toString());
					console.log('syncing: ' + Ti.App.Properties.getBool('syncing'));
					//getDelta();
					doSync();
				});
				//Ti.App.addEventListener('dropbox_login_fail',loginFailHandler);
			}
		}
	};

	return self;
};

module.exports = sync;


text:
/**
 * External dependencies
 */
import invariant from 'invariant';

// Actions
const SET_MODULE_SETTINGS_PANEL_STATE = 'SET_MODULE_SETTINGS_PANEL_STATE';

export const initialState = {
	settingsPanel: {
		currentModule: null,
		isEditing: false,
	},
};

export const actions = {
	/**
	 * Sets the module settings panel state for a given module.
	 *
	 * @since 1.22.0
	 *
	 * @param {string} slug  Module slug.
	 * @param {string} value New setting for module, one of: closed, edit, view.
	 * @return {Object} Action for SET_MODULE_SETTINGS_PANEL_STATE.
	 */
	setModuleSettingsPanelState( slug, value ) {
		invariant( slug, 'slug is required.' );
		const validValues = [ 'closed', 'edit', 'view' ];
		invariant(
			validValues.includes( value ),
			`value should be one of ${ validValues.join() } `
		);
		return {
			payload: {
				slug,
				value,
			},
			type: SET_MODULE_SETTINGS_PANEL_STATE,
		};
	},
};

export const reducer = ( state, { type, payload } ) => {
	switch ( type ) {
		case SET_MODULE_SETTINGS_PANEL_STATE: {
			const { slug, value } = payload;
			const settingsPanel = { ...state.settingsPanel };

			settingsPanel.currentModule = 'closed' === value ? null : slug;
			settingsPanel.isEditing = 'edit' === value;

			return {
				...state,
				settingsPanel,
			};
		}

		default: {
			return state;
		}
	}
};

export const selectors = {
	/**
	 * Gets the settings panel state for a given module.
	 *
	 * @since 1.22.0
	 *
	 * @param {Object} state Data store's state.
	 * @param {string} slug  Module slug.
	 * @return {string} Module settings panel state for a given module as one of: 'view', 'edit', or 'closed'.
	 */
	getModuleSettingsPanelState: ( state, slug ) => {
		invariant( slug, 'slug is required.' );

		const { currentModule, isEditing } = state.settingsPanel;

		if ( currentModule === slug ) {
			return isEditing ? 'edit' : 'view';
		}

		return 'closed';
	},

	/**
	 * Checks whether the module settings panel is open for a given module.
	 *
	 * @since 1.22.0
	 *
	 * @param {Object} state Data store's state.
	 * @param {string} slug  Module slug.
	 * @return {boolean} Whether or not the module settings panel is open for the module.
	 */
	isModuleSettingsPanelOpen: ( state, slug ) => {
		invariant( slug, 'slug is required.' );

		return slug === state.settingsPanel.currentModule;
	},

	/**
	 * Checks whether the module settings panel is closed for a given module.
	 *
	 * @since 1.22.0
	 *
	 * @param {Object} state Data store's state.
	 * @param {string} slug  Module slug.
	 * @return {boolean} Whether or not the module settings panel is closed for the module.
	 */
	isModuleSettingsPanelClosed: ( state, slug ) => {
		invariant( slug, 'slug is required.' );

		return slug !== state.settingsPanel.currentModule;
	},

	/**
	 * Checks whether the module settings panel is in edit state for a given module.
	 *
	 * @since 1.22.0
	 *
	 * @param {Object} state Data store's state.
	 * @param {string} slug  Module slug.
	 * @return {boolean} Whether or not the module settings panel is in edit state for the module.
	 */
	isModuleSettingsPanelEdit: ( state, slug ) => {
		invariant( slug, 'slug is required.' );

		const { currentModule, isEditing } = state.settingsPanel;

		return slug === currentModule && isEditing;
	},

	/**
	 * Checks whether the module settings panel is locked for a given module.
	 *
	 * @since 1.22.0
	 *
	 * @param {Object} state Data store's state.
	 * @param {string} slug  Module slug.
	 * @return {boolean} Whether or not the module settings panel is locked for the module.
	 */
	isModuleSettingsPanelLocked: ( state, slug ) => {
		invariant( slug, 'slug is required.' );

		const { currentModule, isEditing } = state.settingsPanel;

		return slug !== currentModule && isEditing;
	},
};

export default {
	actions,
	initialState,
	reducer,
	selectors,
};


text:
//@@author A0138493W
package utask.logic.commands;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import utask.commons.core.Messages;
import utask.logic.commands.exceptions.CommandException;
import utask.logic.commands.inteface.ReversibleCommand;
import utask.model.task.ReadOnlyTask;
import utask.model.task.Task;
import utask.model.task.UniqueTaskList.TaskNotFoundException;
import utask.ui.helper.DelayedExecution;

/**
 * Deletes a task identified using it's last displayed index from the uTask.
 */
public class DeleteCommand extends Command implements ReversibleCommand {

    public static final String COMMAND_WORD = "delete";
    public static final String COMMAND_FORMAT = "INDEX (must be a positive integer)";

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ": Deletes the task identified by the index number used in the last task listing.\n"
            + "Parameters: " + COMMAND_FORMAT + "\n"
            + "Example: " + COMMAND_WORD + " 1";

    public static final String MESSAGE_DELETE_TASK_SUCCESS = "Tasks have been deleted";

    ReadOnlyTask taskToDelete;
    List<ReadOnlyTask> deleteTasks;
    public final List<Integer> targetList;

    public DeleteCommand(List<Integer> targetList) {
        this.targetList = targetList;
        deleteTasks = new LinkedList<ReadOnlyTask>();
    }

    @Override
    public CommandResult execute() throws CommandException {

        for (int targetIndex : targetList) {
            checkIfGivenIndexIsValid(targetIndex);
            taskToDelete = getTaskToDelete(targetIndex);
            deleteTasks.add(taskToDelete);

            //Do selection effect for 1 task only. It will cause race condition when doing multiple effect in a loop
            if (targetList.size() == 1) {
                notifyUI(taskToDelete);
                new DelayedExecution((e)-> {
                    deleteTask(taskToDelete);
                }).run();
            } else {
                deleteTask(taskToDelete);
            }
        }

        model.addUndoCommand(this);

        return new CommandResult(String.format(MESSAGE_DELETE_TASK_SUCCESS));
    }

    private void checkIfGivenIndexIsValid(int targetIndex) throws CommandException {
        if (model.getTotalSizeOfLists() < targetIndex) {
            throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
        }
    }

    private void deleteTask(ReadOnlyTask taskToDelete) {
        try {
            model.deleteTask(taskToDelete);
        } catch (TaskNotFoundException pnfe) {
            assert false : "The target task cannot be missing";
        }
    }

    private ReadOnlyTask getTaskToDelete(int targetIndex) {
        //- 1 as helper method is using zero-based indexing
        List<ReadOnlyTask> list = model.getUnderlyingListByIndex(targetIndex - 1);

        int actualInt = model.getActualIndexFromDisplayIndex(targetIndex - 1);
        return list.get(actualInt);
    }

    @Override
    public void undo() throws Exception {
        Collections.reverse(deleteTasks); //Ensures that items are restored in previous state.
        for (int i = 0; i < deleteTasks.size(); i++) {
            model.addTask((Task) deleteTasks.get(i));
        }

        notifyUI(taskToDelete);
    }

    @Override
    public void redo() throws Exception {
        notifyUI(taskToDelete);
        Collections.reverse(deleteTasks); //Ensures that items are restored in previous state.
        //Access to deleteTask() must be delayed to prevent race condition with notifyUI
        new DelayedExecution((e)-> {
            try {
                for (int i = 0; i < deleteTasks.size(); i++) {
                    model.deleteTask((Task) deleteTasks.get(i));
                }
            } catch (TaskNotFoundException pnfe) {
                //This exception is handled as it is not possible to hit this exception with normal usage
                assert false : "The target task cannot be missing";
            }
        }).run();
    }

}


text:
require "singleton"
require 'hashie'

module Weeter
  class Configuration
    class ClientAppConfig < Hashie::Mash
      DEFAULT_SUBSCRIPTIONS_UPDATE_PORT = 7337
      InvalidConfiguration = Class.new(StandardError)

      def verify_redis_namespace_config
        !!self.redis_namespace || raise(InvalidConfiguration, 'missing `redis-namespace` config')
      end
    end
  end
end


text:
module Azure::ApiManagement::Mgmt::V2018_06_01_preview
  module Models
    #
    # Diagnostic settings for incoming/outgoing HTTP messages to the Gateway.
    #
    class PipelineDiagnosticSettings

      include MsRestAzure

      # @return [HttpMessageDiagnostic] Diagnostic settings for request.
      attr_accessor :request

      # @return [HttpMessageDiagnostic] Diagnostic settings for response.
      attr_accessor :response

      #
      # Mapper for PipelineDiagnosticSettings class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'PipelineDiagnosticSettings',
          type: {
            name: 'Composite',
            class_name: 'PipelineDiagnosticSettings',
            model_properties: {
              request: {
                client_side_validation: true,
                required: false,
                serialized_name: 'request',
                type: {
                  name: 'Composite',
                  class_name: 'HttpMessageDiagnostic'
                }
              },
              response: {
                client_side_validation: true,
                required: false,
                serialized_name: 'response',
                type: {
                  name: 'Composite',
                  class_name: 'HttpMessageDiagnostic'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" HREF="favicon.ico">
    <title>vis.js - Manipulation documentation.</title>

    <link href="../css/bootstrap.css" rel="stylesheet">

    <link href="../css/tipuesearch.css" rel="stylesheet">

    <link href="../css/style.css" rel="stylesheet">

    <link href="../css/prettify.css" type="text/css" rel="stylesheet"/>

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
                            aria-expanded="false" aria-controls="navbar">
                        Toggle navigation

                    </button>
                    vis.js

Modules

Blog

Download

Showcase

Contribute

Feature requests

License

                    <form class="navbar-form navbar-right" role="search">
                        <input name="q" id="tipue_search_input" autocomplete="off" type="text" class="form-control" placeholder="Enter keywords">
                        <button type="button" class="btn btn-default" onclick="vis.initSiteSearch(true);">Go!</button>
                    </form>

                          Found  results. Click here to jump to the first keyword occurence!

Network - manipulation

Acts as the camera that looks on the canvas. Does the animation, zooming and focusing.

Options

The options for the manipulation module have to be contained in an object titled 'manipulation'.

Click on the full options or shorthand options to show how these options are supposed to be used.

options hidden

full options

shorthand options

// these are all options in full.
var options = {
  manipulation: {
    enabled: false,
    initiallyActive: false,
    addNode: true,
    addEdge: true,
    editNode: undefined,
    editEdge: true,
    deleteNode: true,
    deleteEdge: true,
    controlNodeStyle:{
      // all node options are valid.
    }
  }
}

network.setOptions(options);

// only the options that have shorthand notations are shown.
var options = {
  manipulation: false
}

network.setOptions(options);

Name	Type	Default	Description

enabled	                    Boolean	                false	     Toggle the manipulation system on or off. Even when false, the manipulation API through the methods will still work. This property is optional. If you define any of the options below and enabled is undefined, this will be set to true.

initiallyActive	            Boolean	                true	      Toggle whether the toolbar is visible initially or if only the edit button is visible initially.

addNode	                    Boolean or Function	    true	      You can use these options to switch certain functionalities on or off of attach
            a handler function to them. These functions are called before the action is performed. If a node is going to be added through the manipulation system,
            the addNode function will be called first. With this, you can provide a gui for your users, abort the process or anything else you want to do. For all except the editNode functionality, these handler functions are optional.

            When you supply a boolean, you only toggle the 'add node' button on the GUI of the manipulation system. The lack of handling function could effect the API when using the methods.
            When a function is supplied, it will be called when the user clicks the canvas in 'addNode' mode. This function will receive two variables: the properties of the node that can be created and a callback function. If you call the callback function with the properties of the new node, the node will be added.

 Example:

var options = {
  manipulation: {
    addNode: function(nodeData,callback) {
      nodeData.label = 'hello world';
      callback(nodeData);
    }
  }
}

            This function changes the label of the new node into 'hello world'. If you do not want the node created, do not call the callback function or call the callback function null or no argument.

addEdge	                    Boolean or Function	    true	      If boolean, toggle the availability of the 'addEdge' button in the GUI, the API through the methods will still work except (obviously) there will be no handler function.
             When a function is supplied, it will be called when the user drags the new edge from one node to the next in 'addEdge' mode. This function will receive two variables: the properties of the edge that can be created and a callback function. If you call the callback function with the properties of the new edge, the edge will be added.

 Example:

var options = {
  manipulation: {
    addEdge: function(edgeData,callback) {
      if (edgeData.from === edgeData.to) {
        var r = confirm("Do you want to connect the node to itself?");
        if (r === true) {
          callback(edgeData);
        }
      }
      else {
        callback(edgeData);
      }
    }
  }
}

            This example code will show a popup if you connect a node to itself to ask you if that was what you wanted. If you do not want the edge created, do not call the callback function or call the callback function null or no argument.

editNode	                   Function	               undefined	 Editing of nodes is only possible when a handling function is supplied. If this is not the case, editing of nodes will be disabled. The function will be called when a node is selected and the 'Edit Node' button on the toolbar is pressed. This function will be called like the addNode function with the node's data and a callback function.

editEdge	                   Boolean or Function	    true	      If boolean, toggle the editing of edges in the GUI. When a function is supplied, it will be called when an edge is selected and the 'Edit Edge' button on the toolbar is pressed. This function will be called in the same way the addEdge function was called. If the callback is not performed, the edge will remain hanging where it was released. To cancel, call the callback function with null as argument or without arguments.

deleteNode	                 Boolean or Function	    true	      If boolean, toggle the deletion of nodes in the GUI. If function, it will be called when a node is selected and the 'Delete selected' button is pressed. When using a function, it will receive a callback and an object with an array of selected nodeIds and an array of selected edges Ids. These are the items that will be deleted if the callback is performed.

deleteEdge	                 Boolean or Function	    true	      If boolean, toggle the deletion of edges in the GUI. If function, it will be called when an edge is selected and the 'Delete selected' button is pressed. When using a function, it will receive a callback and an object with an array of selected nodeIds (empty) and an array of selected edges Ids. These are the items that will be deleted if the callback is performed.

controlNodeStyle	           Object	     Object	You can supply any styling information you'd like here. All fields described in the nodes module are allowed except obviously for id, x, y and fixed.

Default:

{
  shape:'dot',
  size:6,
  color: {
    background: '#ff0000',
    border: '#3c3c3c',
    highlight: {
      background: '#07f968',
      border: '#3c3c3c'
    }
  },
  borderWidth: 2,
  borderWidthSelected: 2
}


text:
.top-buffer { margin-top:20px; }
.http-method {
    margin-right: 1em;
    text-decoration: none;
    background-color: #d9edf7;
    border-radius: 5px;
    padding: 10px;
    font-size: 80%;
    display: inline-block;
}


text:
layout: post
status: publish
published: true
title: Irony
author:
  display_name: Tomas Restrepo
  login: tomasr
  email: tomas@winterdom.com
  url: http://winterdom.com/
author_login: tomasr
author_email: tomas@winterdom.com
author_url: http://winterdom.com/
wordpress_id: 472
wordpress_url: http://winterdom.com/2008/03/irony
date: '2008-03-05 04:33:17 +0000'
date_gmt: '2008-03-05 04:33:17 +0000'
categories:
- ".NET"
tags: []
comments:
- id: 328
  author: Pavel
  author_email: pavel.savara@gmail.com
  author_url: ''
  date: '2008-03-05 06:45:19 +0000'
  date_gmt: '2008-03-05 06:45:19 +0000'
  content: |
    Hi,
    there is C# implementation for super tool-set Goldparser. I used it for simple assembler language and BNF debugger of goldparser was most useful part.
    http://www.calitha.com/goldparser.html
    http://www.devincook.com/goldparser/
---

I've been playing a bit with Irony, an open source .NET compiler construction toolkit created by Roman Ivantsov. My interest in Irony was sparked after watching the video of Roman's presentation at Lang.NET 2008 (I'd link to it, but they are unavailable at the moment).

Currently, I have a little side project where I've been experimenting with the Dynamic Language Runtime, for which I was using GPPG and GPLEX to build the parser and tokenizer. The tools are OK, but it certainly requires quite a bit of manual work, you need to keep regenerating the code, and, frankly, the error messages both tools produce leave a bit to be desired.

I'm aware of ANTLR, but frankly don't want to mess around with the whole java generator thing at this time (already have way too much crap around).

Irony is pretty interesting because all the tokenizer and grammar rules are expressed directly in C# code as a simple object model built from Terminal and NontTerminal objects. The syntax is fairly intuitive because Irony overloads several operators like | and & to make the grammar definition look a lot similar to BNF. Here's a sample of what a simple expression grammar in Irony looks like: http://www.codeplex.com/irony/Wiki/View.aspx?title=Expression%20grammar%20sample

After testing a bit Irony, I'm very encouraged to give it a try on my pet project, so I've been playing around with my grammar (unfortunately broken at this time because of some ambiguities I haven't resolved yet), and its looking very nice overall.

There's also a useful "Grammar Explorer" tool included with the Irony code which can be used to experiment and diagnose a compiled Irony grammar. Unfortunately right now it just has a predefined list of a few test grammars included with the project, but extending it to use others is trivial anyway, so I've been using it to test my grammar before actually committing to it.

Another useful thing in Irony is the concept of TokenFilters, which are objects that can filter the token stream as it is produced by the scanner and can either remove/modify/add new tokens as necessary or provide extra validations. Right now Irony provides two built-in filters, but you can extend it with new ones as necessary:

CodeOutlineFilter, which can be used in languages where whitespace is significant (indentation and/or newlines).

BraceMatchingFilter for matching brace characters, for example '()' in scheme/lisp.

Technorati tags: Irony


text:
//
//  parsit_2.c
//  ViperNEC
//
//  Created by Dylan Crocker on 7/16/14.
//  Copyright 2014 Viper Science
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#include "cards.h"
#include "types.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>

#define MAX_FIELDS 12
#define BUFF_SIZE 20

/** parsit_2
 * This function (parsit_2) is a cleaned up and modified version of the function
 * generated by f2c (parsit_). Major changes include the removal of the f2c
 * FORTRAN style I/O which would read the input file, instead the line of text
 * is passed as an input variable. Additionaly, standard C functions (strtol and
 * strtod) are used to convert the numerical values from the text instead of the
 * messy code that parsed out the values manually.
 *
 * Original FORTRAN description:
 * PARSIT reads an input record and parses it.
 *
 * @param card The line of text representing the record (card) to be parsed.
 * @param maxint The total number of integers in record.
 * @param maxrea The total number of real values in record.
 * @param cmnd A two letter mnemonic code indicating the card type.
 * @param intfld Integer values from the record (card).
 * @param reafld Real values from the record (card).
 * @since v1.0
 */
void parsit_2(char *card, char *cmnd, int cmnd_len, int *maxint, int *maxrea,
              int *intfld, double *reafld) {

  // Check inputs...
  if (card == NULL) { return; }

  // Make sure the text is in upper case.
  int totcol = (int)strlen(card); // total number of columns in card text
  upcase_2(card, card, totcol);

  // Store the opcode.
  strncpy(cmnd, card, 2);

  // Clear the field arrays.
  int bgnfld[MAX_FIELDS]; // list of starting indices
  int endfld[MAX_FIELDS]; // list of ending indices
  for (int i = 0; i < *maxint; ++i) { intfld[i] = 0; }
  for (int j = 0; j < *maxrea; ++j) { reafld[j] = 0; }
  for (int k = 0; k < MAX_FIELDS; ++k) {
    bgnfld[k] = 0;
    endfld[k] = 0;
  }

  bool fldtrm = false; // flag to indicate that pointer is in field position
  int totfld = 0; // number of numeric fields
  char k; // temp variable used to hold a char from the text being parsed.

  // Find the beginning and ending of each field as well as the total number of
  // fields.
  for (ftnlen j = cmnd_len; j < totcol; ++j) {
    k = card[j]; // Get the char to analyze.
    if (k == 33) {
      // Check for end of line comment ('!'). This is a new modification to allow
      // VAX-like comments at the end of data records, e.g.,
      //       GW 1 7 0 0 0 0 0 .5 .0001 ! DIPOLE WIRE
      //       GE ! END OF GEOMETRY
      if (fldtrm) {
        // The current index is the ending symbol, the last index was the end of
        // the field (j - 1). This will never error out because fldtrm should be
        // false at the start and j should start at index 2 (cmnd_len).
        endfld[totfld - 1] = j - 1;
        fldtrm = false;
      }
    } else if (k == 32 || k == 44) {
      // Set the ending index when the character is a comma or space and the
      // pointer is in a field position (FLDTRM = TRUE).
      if (fldtrm) {
        // The current index is the ending symbol, the last index was the end of
        // the field (j - 1). This will never error out because fldtrm should be
        // false at the start and j should start at index 2 (cmnd_len).
        endfld[totfld - 1] = j - 1;
        fldtrm = false;
      }
    } else if (!fldtrm) {
      // Set the beginning index when the character is not a comma or space and
      // the pointer is not currently in a field position (FLDTRM = FALSE).
      ++totfld;
      fldtrm = true;
      bgnfld[totfld - 1] = j; // The current index starts the field.
    }
  }

  if (fldtrm) { endfld[totfld - 1] = totcol; }

  // Check to see if the total number of value fields is within the precribed
  // limits.
  if (totfld == 0) {
    return; // Some cards have no data fields (e.g., the EK card).
  } else if (totfld > (*maxrea + *maxint)) {
    // Ignore fields outside the expected number of fields. If the user is
    // stupid then the code will try to work any way...
    totfld = (*maxrea + *maxint);
  }

  // Initialize a buffer to hold the textual versions of the inputs.
  int bufflen = 20;
  char buffer[bufflen]; // text buffer.
  for (int i = 0; i < bufflen; ++i) {
    buffer[i] = '\0';
  }

  //  Parse out integer values and store into integer buffer array.
  for (int n = 0; n < fmin(totfld, *maxint); ++n) {
    int fld_len = endfld[n] - bgnfld[n] + 1; // Length of the field (must add 1).

    // Copy out the field from the original text.
    strncpy(buffer, card + bgnfld[n], fld_len);
    for (int i = fld_len; i < bufflen; ++i) {
      buffer[i] = '\0';
    }

    // The old version had code here to look for a decimal point and freak out
    // if it found one. The strtol function will stop when it gets to a decimal
    // or return 0 if the decimal is first.
    intfld[n] = (int)strtol(buffer, NULL, 0);
  }

  //  Parse out real values and store into real buffer array.
  if (totfld > *maxint) {
    for (int m = *maxint; m < totfld; ++m) {
      int fld_len = endfld[m] - bgnfld[m] + 1; // Length of the field (must add 1).

      // Copy out the field from the original text.
      strncpy(buffer, card + bgnfld[m], fld_len);
      for (int i = fld_len; i < bufflen; ++i) {
        buffer[i] = '\0';
      }

      // The old code was way more involved trying to parse the textual
      // representation of a double. The strtod function takes care of this
      // automatically.
      reafld[m - *maxint] = strtod(buffer, NULL);
    }
  }

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// Set all floors to zero points
if ( ! function_exists('delete_records'))
{
    function delete_records()
    {
        // Load database
        $helper =& get_instance();
        $helper->load->database();

		$helper->db->where('Id !=', 'NULL');
		$helper->db->delete('phoenix_records');
    }
}


text:
package images

import (
	"time"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1"
	kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
)

type pullResult struct {
	imageRef string
	err      error
}

type imagePuller interface {
	pullImage(kubecontainer.ImageSpec, []v1.Secret, chan<- pullResult, *runtimeapi.PodSandboxConfig)
}

var _, _ imagePuller = &parallelImagePuller{}, &serialImagePuller{}

type parallelImagePuller struct {
	imageService kubecontainer.ImageService
}

func newParallelImagePuller(imageService kubecontainer.ImageService) imagePuller {
	return &parallelImagePuller{imageService}
}

func (pip *parallelImagePuller) pullImage(spec kubecontainer.ImageSpec, pullSecrets []v1.Secret, pullChan chan<- pullResult, podSandboxConfig *runtimeapi.PodSandboxConfig) {
	go func() {
		imageRef, err := pip.imageService.PullImage(spec, pullSecrets, podSandboxConfig)
		pullChan <- pullResult{
			imageRef: imageRef,
			err:      err,
		}
	}()
}

// Maximum number of image pull requests than can be queued.
const maxImagePullRequests = 10

type serialImagePuller struct {
	imageService kubecontainer.ImageService
	pullRequests chan *imagePullRequest
}

func newSerialImagePuller(imageService kubecontainer.ImageService) imagePuller {
	imagePuller := &serialImagePuller{imageService, make(chan *imagePullRequest, maxImagePullRequests)}
	go wait.Until(imagePuller.processImagePullRequests, time.Second, wait.NeverStop)
	return imagePuller
}

type imagePullRequest struct {
	spec             kubecontainer.ImageSpec
	pullSecrets      []v1.Secret
	pullChan         chan<- pullResult
	podSandboxConfig *runtimeapi.PodSandboxConfig
}

func (sip *serialImagePuller) pullImage(spec kubecontainer.ImageSpec, pullSecrets []v1.Secret, pullChan chan<- pullResult, podSandboxConfig *runtimeapi.PodSandboxConfig) {
	sip.pullRequests <- &imagePullRequest{
		spec:             spec,
		pullSecrets:      pullSecrets,
		pullChan:         pullChan,
		podSandboxConfig: podSandboxConfig,
	}
}

func (sip *serialImagePuller) processImagePullRequests() {
	for pullRequest := range sip.pullRequests {
		imageRef, err := sip.imageService.PullImage(pullRequest.spec, pullRequest.pullSecrets, pullRequest.podSandboxConfig)
		pullRequest.pullChan <- pullResult{
			imageRef: imageRef,
			err:      err,
		}
	}
}


text:
'use strict';

const boom = require('boom');
const express = require('express');
const knex = require('../knex');
const { camelizeKeys } = require('humps');
const { separateDates, combineEdus } = require('../utils');
const checkAuth = require('../middleware');

// const ev = require('express-validation');
// const validations = require('../validations/applications');

const router = express.Router(); // eslint-disable-line new-cap

router.get('/edus/:appId', checkAuth, (req, res, next) => {
  const appId = Number.parseInt(req.params.appId);

  knex('edus')
    .where('application_id', appId)
    .orderBy('application_id')
    .then((rows) => {
      const edu = camelizeKeys(combineEdus(separateDates(rows))[0]);

      res.send(edu);
    })
    .catch((err) => {
      next(boom.wrap(err));
    });
});

module.exports = router;


text:
using System;
using System.Collections.Generic;
using System.Linq;
//03.	Circles Intersection
namespace IntersectionOfCircles
{
    class IntersectionOfCircles
    {
        static void Main(string[] args)
        {
            Circle one = GetCircle();
            Circle two = GetCircle();
            double distance = GetDistance(one.point, two.point);
            if (distance <= one.r + two.r)
            {
                Console.WriteLine("Yes");
            }
            else
            {
                Console.WriteLine("No");
            }

        }

        public static double GetDistance(Point point1, Point point2)
        {
            double distance = Math.Sqrt(Math.Pow(point2.x - point1.x, 2) + Math.Pow(point2.y - point1.y, 2));
            return distance;
        }

        public static Circle GetCircle()
        {
            int[] input = Console.ReadLine().Split().Select(int.Parse).ToArray();
            Point point = new Point() { x = input[0], y = input[1] };
            Circle circle = new Circle() { point = point, r = input[2] };
            return circle;

        }
    }

    class Point
    {
        public int x { get; set; }
        public int y { get; set; }
    }

    class Circle
    {
        public Point point { get; set; }
        public int r { get; set; }
    }
}


text:
package com.wuyuntao.flatbuffers.schema

import java.nio.ByteBuffer
import scala.collection.mutable.HashMap
import com.google.flatbuffers.Table

final class MessageSchema {
  private val messages = new HashMap[Int, MessageCreator]()

  def register(messageId: Int, creator: (ByteBuffer) => Table): Unit = {
    if (messages.contains(messageId))
      throw new IllegalArgumentException("Message #%d is already defined".format(messageId))

    messages.put(messageId, MessageCreator(creator))
  }

  def parse(messageId: Int, data: Array[Byte]): Message = {
    val creator = messages.get(messageId)
    if (creator.nonEmpty) {
      val body = creator.get.create(ByteBuffer.wrap(data))

      return new Message(messageId, body)
    } else {
      throw new IllegalArgumentException("Missing creator for message #%d".format(messageId))
    }
  }
}


text:
FROM microsoft/nanoserver

CMD ["powershell", "Write-Host 'Hello from Windows Nano Server!'"]


text:
using Microsoft.Bot.Builder.Dialogs;
using System;
using Chronic;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading.Tasks;
using Microsoft.Bot.Connector;
using Skyborg.Model;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Microsoft.Bot.Builder.Luis.Models;
using Microsoft.Bot.Builder.Luis;
using System.Globalization;
using Skyborg.Adapters;
using Microsoft.Bot.Builder.FormFlow;

namespace Skyborg.Dialogs
{
    [Serializable]
    public class CalendarDialog : IDialog<object>
    {
       // [NonSerialized]
        private CalendarAdapter adapter;

        private IntentModel intent;

        public CalendarDialog(UserCredential credential, IntentModel intent)
        {
            this.adapter = new CalendarAdapter(credential);
            this.intent = intent;
        }

        public async Task StartAsync(IDialogContext context)
        {
            await context.PostAsync("Welcome to the Google Calendar!");
            context.Wait(this.MessageReceivedAsync);
        }

        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
        {
            LuisResult luisresult = new LuisResult();
            luisresult.Entities = intent.Model;

            //var message = await result;

            switch (intent.IntentName)
            {
                case "list":
                    await GetEventList(context, luisresult);
                    context.Done(true);
                    //context.Wait(this.MessageReceivedAsync);
                    break;
                case "create":
                    var eventDetail = HydrateEventObject(luisresult);

                    var createEventDialog = FormDialog.FromForm(this.BuildCreateEventForm, FormOptions.PromptFieldsWithValues);
                    context.Call(createEventDialog, this.ResumeAfterEventDialog);
                    context.Done(true);

                    break;
                default:
                    await None(context);
                    context.Done<object>(null);
                    context.Wait(this.MessageReceivedAsync);
                    break;
            }

        }

        //public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
        //{
        //    LuisResult luisresult = new LuisResult();
        //    luisresult.Entities = intent.Model;

        //    var message = await result;

        //    switch(intent.IntentName)
        //    {
        //        case "list":
        //            await GetEventList(context, luisresult);
        //            break;
        //        case "create":
        //            var eventDetail = HydrateEventObject(luisresult);

        //            var createEventDialog = FormDialog.FromForm(this.BuildCreateEventForm, FormOptions.PromptFieldsWithValues);
        //            context.Call(createEventDialog, this.ResumeAfterEventDialog);

        //            break;
        //        default:
        //            await None(context);
        //            break;
        //    }
        //}

        private CalendarModel HydrateEventObject(LuisResult result)
        {
            CalendarModel eventDetail = new CalendarModel();

            var startDate = FetchDate(result);

            if (startDate != null && startDate.Start.HasValue)
            {
                eventDetail.StartDate = startDate.Start.Value;
            }

            var summary = FetchString(result, "EventName");
            if (!string.IsNullOrEmpty(summary))
            {
                eventDetail.Summary = summary;
            }

            var startTime = FetchTime(result);
            if (startTime != null && startTime.Start.HasValue)
            {
                eventDetail.StartTime = startTime.Start.Value.TimeOfDay;
            }

            return eventDetail;
        }

        private async Task ResumeAfterEventDialog(IDialogContext context, IAwaitable<CalendarModel> result)
        {
            var searchQuery = await result;

            //await context.PostAsync("Hope you liked my Work !!");
            context.Done<object>(null);
        }

        public async Task None(IDialogContext context)
        {
            await context.PostAsync("Sorry! I don't understand what you want");
        }

        public async Task GetEventList(IDialogContext context, LuisResult result)
        {
            var dateResult = FetchDate(result) ?? FetchTime(result);

            if (dateResult != null)
            {
                await context.PostAsync("Please wait, while I retrieve your schedule");

                var reply = context.MakeMessage();

                reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                reply.Attachments = this.GetEventsByDateRange(dateResult.Start.Value, dateResult.End.Value);

                await context.PostAsync(reply);
            }
            else
            {
                await context.PostAsync("Sorry! I don't understand what you want");
            }

            //context.Wait(this.MessageReceivedAsync);
        }

        public async Task CreateEvent(IDialogContext context, CalendarModel eventDetail)
        {
            await context.PostAsync("Allow me to create an event for you (y)");

            if (!string.IsNullOrEmpty(eventDetail.Summary) && eventDetail.StartDate != DateTime.MinValue)
            {
                Event calendarEvent = adapter.CreateEvent(eventDetail);

                var reply = context.MakeMessage();

                reply.Summary = "Event Created Successfully";
                reply.Text = "Access it here: " + calendarEvent.HtmlLink;

                await context.PostAsync(reply);
            }
            else
            {
                await context.PostAsync("Please provide valid summary, starttime and date");
            }

            //context.Wait(this.MessageReceivedAsync);
        }

        public IForm<CalendarModel> BuildCreateEventForm()
        {
            OnCompletionAsyncDelegate<CalendarModel> createEventtemp = async (context, state) =>
            {
                await context.PostAsync("Creating events ...");
                await CreateEvent(context, state);
            };

            return new FormBuilder<CalendarModel>()
                        .Message("Creating Event for You . . .")
                        .AddRemainingFields()
                        .OnCompletion(createEventtemp)
                        .Build();
        }

        #region "Private Helper"

        private IList<Attachment> GetEventsByDateRange(DateTime startdate, DateTime enddate)
        {
            string response = string.Empty;

            Events events = adapter.GetEventsByDateRange(startdate, enddate);
            IList<Attachment> attachments = new List<Attachment>();

            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    string eventstartdate = eventItem.Start.DateTime.ToString();
                    if (String.IsNullOrEmpty(eventstartdate))
                    {
                        eventstartdate = eventItem.Start.Date;
                    }

                    string eventenddate = eventItem.End.DateTime.ToString();
                    if (String.IsNullOrEmpty(eventenddate))
                    {
                        eventenddate = eventItem.End.Date;
                    }

                    string description = string.Empty;
                    if (!string.IsNullOrEmpty(description))
                    {
                        description = (eventItem.Description.Length > 50) ? eventItem.Description.Substring(0, 50) : eventItem.Description;
                    }

                    attachments.Add(GetHeroCard(eventItem.Summary, (eventItem.Location != null) ? "At " + eventItem.Location : string.Empty, description,
                        new CardAction(ActionTypes.OpenUrl, "View Event", value: eventItem.HtmlLink)));

                }
            }

            return attachments;
        }

        private static Attachment GetHeroCard(string title, string subtitle, string text, CardAction cardAction)
        {
            var heroCard = new HeroCard
            {
                Title = title,
                Subtitle = subtitle,
                Text = text,
                Images = null,
                Buttons = new List<CardAction>() { cardAction },
            };

            return heroCard.ToAttachment();
        }

        private static string FormatDate(string datetime)
        {
            return Convert.ToDateTime(datetime).ToString("hh:mm:ss tt", CultureInfo.InvariantCulture);
        }

        private static Span FetchDate(LuisResult result)
        {
            Parser parser = new Parser();

            EntityRecommendation dateValue = new EntityRecommendation();

            if (result.TryFindEntity("builtin.datetime.date", out dateValue))
            {
                return parser.Parse(dateValue.Entity);
            }
            return null;
        }

        private static Span FetchTime(LuisResult result)
        {
            Parser parser = new Parser();

            EntityRecommendation dateValue = new EntityRecommendation();

            if (result.TryFindEntity("builtin.datetime.time", out dateValue))
            {
                return parser.Parse(dateValue.Entity);
            }
            return null;
        }

        private static string FetchString(LuisResult result, string type)
        {
            EntityRecommendation value = new EntityRecommendation();

            result.TryFindEntity(type, out value);

            if(value != null)
            {
                return (value.Entity);
            }
            return string.Empty;
        }

        #endregion
    }
}


text:
package main

import (
	"context"

	aiplatform "cloud.google.com/go/aiplatform/apiv1beta1"
	aiplatformpb "cloud.google.com/go/aiplatform/apiv1beta1/aiplatformpb"
	"google.golang.org/api/iterator"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := aiplatform.NewDeploymentResourcePoolClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &aiplatformpb.QueryDeployedModelsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/aiplatform/apiv1beta1/aiplatformpb#QueryDeployedModelsRequest.
	}
	it := c.QueryDeployedModels(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		// TODO: Use resp.
		_ = resp
	}
}

// [END aiplatform_v1beta1_generated_DeploymentResourcePoolService_QueryDeployedModels_sync]


text:
@import Foundation;

@interface ENCCommand : NSObject

- (instancetype)initWithArguments:(NSArray <NSString *> *)arguments;
- (void)performWithCompletion:(void (^)(NSInteger returnCode))completion;

+ (NSString *)format;
+ (NSString *)helpMessage;

@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
C. F. P. von Martius et al. , Fl. bras. enum. pl. 2(1):87. 1829 (Agrost. bras. )

#### Original name
null

### Remarks
null


text:
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using SimplCommerce.Infrastructure.Data;
using SimplCommerce.Module.Core.Services;
using SimplCommerce.Module.News.Areas.News.ViewModels;
using SimplCommerce.Module.News.Models;

namespace SimplCommerce.Module.News.Areas.News.Controllers
{
    [Area("News")]
    public class NewsCategoryController : Controller
    {
        private int _pageSize;
        private readonly IRepository<NewsItem> _newsItemRepository;
        private readonly IMediaService _mediaService;
        private readonly IRepository<NewsCategory> _newsCategoryRepository;

        public NewsCategoryController(IRepository<NewsItem> newsItemRepository,
            IMediaService mediaService, IRepository<NewsCategory> newsCategoryRepository,
            IConfiguration config)
        {
            _newsItemRepository = newsItemRepository;
            _mediaService = mediaService;
            _newsCategoryRepository = newsCategoryRepository;
            _pageSize = config.GetValue<int>("News.PageSize");
        }

        public IActionResult NewsCategoryDetail(long id, int page)
        {
            var newsCategoryList = _newsCategoryRepository.Query()
                .Include(x => x.NewsItems)
                .Where(x => !x.IsDeleted)
                .Select(x => new NewsCategoryVm()
                {
                    Id = x.Id,
                    Name = x.Name,
                    Slug = x.Slug
                })
                .ToList();

            if (newsCategoryList == null)
            {
                return Redirect("~/Error/FindNotFound");
            }

            var currentNewsCategory = newsCategoryList.Select(x => new NewsCategoryVm()
            {
                Id = x.Id,
                Name = x.Name,
                Slug = x.Slug
            })
            .FirstOrDefault(x => x.Id == id);

            var model = new NewsVm()
            {
                CurrentNewsCategory = currentNewsCategory,
                NewsCategory = newsCategoryList
            };

            var query = _newsItemRepository.Query()
                .Where(x => x.Categories.Any(c => c.CategoryId == currentNewsCategory.Id) && !x.IsDeleted && x.IsPublished)
                .OrderByDescending(x => x.CreatedOn);

            model.TotalItem = query.Count();
            var currentPageNum = page <= 0 ? 1 : page;
            var offset = (_pageSize * currentPageNum) - _pageSize;
            while (currentPageNum > 1 && offset >= model.TotalItem)
            {
                currentPageNum--;
                offset = (_pageSize * currentPageNum) - _pageSize;
            }

            model.NewsItem = query.Include(x => x.ThumbnailImage).Select( x => new NewsItemThumbnail()
            {
                Id = x.Id,
                ShortContent = x.ShortContent,
                ImageUrl = _mediaService.GetMediaUrl(x.ThumbnailImage),
                PublishedOn = x.CreatedOn,
                Slug = x.Slug
            })
            .Skip(offset)
            .Take(_pageSize)
            .ToList();

            model.PageSize = _pageSize;
            model.Page = currentPageNum;
            return View(model);
        }
    }
}


text:
export interface IRawValues {
    [key: string]: any;
}
export type JSONPrimitive = boolean | string | number | null;

export interface IJSON {
    [prop: string]: (IJSON | JSONPrimitive) | (IJSON | JSONPrimitive)[];
}


text:
declare module "bme280-sensor";
declare module "node-zabbix-sender";


text:
package info.openmods.calc.symbol;

@FunctionalInterface
public interface IGettable<E> {
	public E get();
}