text:
<?php

namespace Pascal\FeedGathererBundle\Service;

use \Pascal\FeedGathererBundle\Entity\TwitterUser;
use \Pascal\FeedGathererBundle\Entity\Feed;

class TwitterFeedService implements FeedService
{

	private static $config = array(
		'consumer_key' => 'BlR9tlw0CDzFSLcMJuMhRA',
		'consumer_secret' => 'yD9DjMKXudMMWz7Yff61pFDGo0mmSZjNZzgjqOxjPQ'
	);

	/**
	 * @var \Doctrine\ORM\EntityManager
	 */
	protected $entityManager;

	/**
	 * @var \tmhOAuth
	 */
	protected $twitter;

	public function __construct()
	{
	}

	/**
	 * @param \Symfony\Bundle\DoctrineBundle\Registry $doctrine
	 */
	public function setEntityManager(\Symfony\Bundle\DoctrineBundle\Registry $doctrine)
	{
		$this->entityManager = $doctrine->getEntityManager();
	}

	/**
	 * @param \tmhOAuth $twitter
	 */
	public function setTwitter($twitter)
	{
		$this->twitter = $twitter;
	}

	public function getServiceType()
	{
		return 'twitter';
	}

	public function downloadFeed(Feed $feed, \DateTime $lastUpdateTime)
	{
		$twitter = $this->getTwitter();
		$twitterUser = $this->getTwitterUser($feed);

		$twitter->setConfigValue('user_token', $twitterUser->getOauthToken());
		$twitter->setConfigValue('user_secret', $twitterUser->getOauthTokenSecret());

		$code = $twitter->request('GET', $twitter->url('1/statuses/home_timeline'), array(
			'include_entities' => true
		));

		$response = $twitter->getResponse();
		if ($code == 200)
		{
			$timeline = json_decode($response['response'], true);
			$feedEntries = $this->processItems($timeline, $twitterUser, $feed, $lastUpdateTime);
			$this->saveItems($feedEntries);
		}
	}

	/**
	 * @param \Pascal\FeedGathererBundle\Entity\Feed $feed
	 * @return \Pascal\FeedGathererBundle\Entity\TwitterUser[]
	 */
	protected function getTwitterUser(Feed $feed)
	{
		$dql = "
			SELECT t
			FROM PascalFeedGathererBundle:TwitterUser t
			WHERE t.id=:id";

		$query = $this->entityManager
			->createQuery($dql)
			->setParameter("id", $feed->getTypeId());

		$twitterUser = $query->getSingleResult();
		return $twitterUser;
	}

	/**
	 * @return \tmhOAuth
	 */
	protected function getTwitter()
	{
		$twitter = $this->twitter;
		$twitter->load(self::$config);
		return $twitter;
	}

	/**
	 * Process all twitter entries by checking them for links.
	 *
	 * @param array $items
	 * @param \Pascal\FeedGathererBundle\Entity\TwitterUser $twitterUser
	 * @param \Pascal\FeedGathererBundle\Entity\Feed $feed
	 * @param \DateTime $lastUpdateTime
	 */
	protected function processItems($items, TwitterUser $twitterUser, Feed $feed, \DateTime $lastUpdateTime)
	{
		$feedEntries = array();

		foreach($items as $item)
		{
			// TODO: Add time check
			// TODO: ADD used link check

			// whitelist/blacklist user check
			$username = $item['user']['username'];
			if ($this->isUserOnBlacklist($twitterUser->getBlacklistUsernames(), $username))
				continue;

			$urls = $item['entities']['urls'];
			if (empty($urls))
				continue;

			$author = $item['user']['name'];
			$text = $item['text'];
			$createdAt = $item['created_at'];
			$dateTime = new \DateTime($createdAt);

			foreach($urls as $url)
			{
				$feedEntry = new \Pascal\FeedGathererBundle\Entity\FeedEntry();
				$feedEntry->setAuthor($author);
				$feedEntry->setDescription($text);
				$feedEntry->setTitle('Link shared by ' . $author);
				$feedEntry->setUrl($url['expanded_url']);
				$feedEntry->setLastUpdateTime($dateTime);
				$feedEntry->setFeed($feed);

				$feedEntries[] = $feedEntry;
			}
		}

		return $feedEntries;
	}

	/**
	 * Save the given FeedEntry items
	 * @param \Pascal\FeedGathererBundle\Entity\FeedEntry[]  $items
	 */
	protected function saveItems(array $items)
	{
		foreach($items as $feedEntry)
		{
			$this->entityManager->persist($feedEntry);
		}

		$this->entityManager->flush();
	}

	/**
	 * Return whether or not if the given username exists in the array of blacklisted usernames.
	 *
	 * @param $blacklist
	 * @param $username
	 * @return bool
	 */
	protected function isUserOnBlacklist($blacklist, $username)
	{
		if (is_null($blacklist) || !is_array($blacklist))
			return false;

		return in_array($username, $blacklist);
	}
}


text:
#include <unistd.h>
#include <string>
#include <iostream>
#include <sstream>
#include <cmath>
#include <chrono>
#include <thread>
#include <deque>
#include <vector>

// This sample application serves as a quick test framework for ParseDraw,
// and serves as an example on how to use PD, highlighting a few key
// applications which I needed for some work I was doing.

/* MathGL script examples:
 * http://udav.sourceforge.net/mgl_en.html/mgl_en_2.html
 *
 * Command syntax:
 * http://mathgl.sourceforge.net/doc_en/Command-options.html#Command-options
 */

// Test configuration
#define TEST_ENABLED  1
#define TEST_DISABLED 0
#define ANIM_TEST_ENABLED               TEST_ENABLED
#define ANIM_WRITEIMG_TEST_ENABLED      TEST_DISABLED
#define IQ_TEST_ENABLED                 TEST_ENABLED
/* TODO: logic analyzer, oscope */

// Protocol message defines
static const std::string Start =     "!_ML,";
static const std::string Update =    "UPDATE";
static const std::string Clear =     "CLEAR";
static const std::string Reset =     "RESET";
static const std::string Exit =      "EXIT";
static const std::string WriteImg =  "WRITEIMG";
static const std::string Send =      "SEND,";
static const std::string Sleep=      "SLEEP,";
static const std::string SetVar =    "SET_VAR,";
static const std::string DelVar =    "DEL_VAR,";

// Output our command so that ParseDraw can pick it up on cin
static void OutputParseDrawCommand(std::string Command)
{
  std::string outString = Start + Command;
  std::cout << outString << std::endl;
}

// Hold the image for some number of seconds (Demo)
// Reset all variables, command queue
// Clear the screen
static void ClearParseDraw()
{
#define HOLD_IMAGE_MS 5000 // 5s
  OutputParseDrawCommand(Sleep + std::to_string(HOLD_IMAGE_MS));
  OutputParseDrawCommand(Update);
  OutputParseDrawCommand(Reset);
  OutputParseDrawCommand(Clear);
}

static void RunAnimationTest(void)
{
#if (ANIM_TEST_ENABLED == TEST_ENABLED)
  // Shows an animated sinusoidal surface, captures PNGs during the animation
  std::cout << "Animation Test" << std::endl;
  // Making waves
  float f;
  std::stringstream tempCmd;
  OutputParseDrawCommand(Clear);
  OutputParseDrawCommand(Reset);
  for(f = 0; f < 2.0; f += .01)
  {
    tempCmd.str("");
    tempCmd << "new a 50 40: modify a '0.6*sin(2*pi*x*" << f << ")*sin(3*pi*y*" << f << ") + 0.4*cos(3*pi*(x*y*" << f << "))';";
    OutputParseDrawCommand(Send + tempCmd.str());
    OutputParseDrawCommand(Send + "rotate 40 60");
    OutputParseDrawCommand(Send + "light on");
    OutputParseDrawCommand(Send + "box");
    OutputParseDrawCommand(Send + "surf a");
    OutputParseDrawCommand(Send + "text 0 1.5 1 'Animation Test'");
#if (ANIM_TEST_WRITEIMG_ENABLED == TEST_ENABLED)
    if(f == 0.0) // write first image
    {
      OutputParseDrawCommand(WriteImg);
    }
#endif
    OutputParseDrawCommand(Update);
    OutputParseDrawCommand(Reset);
  }
#if (ANIM_TEST_WRITEIMG_ENABLED == TEST_ENABLED)
  OutputParseDrawCommand(WriteImg); // write last image
  OutputParseDrawCommand(Update);
#endif
  ClearParseDraw();
#endif
}

static void RunIQTest(void)
{
#if (IQ_TEST_ENABLED == TEST_ENABLED)
  // Simluates IQ plot input; for some of my radio work
  std::cout << "Variable IQ Test" << std::endl;
  std::stringstream iSet;
  std::stringstream qSet;
  uint32_t iqIters;
#define IQ_ITERATIONS_MAX 100
  for(iqIters = 0; iqIters < IQ_ITERATIONS_MAX; iqIters++)
  {
    uint32_t ii,qi;
    iSet.str("");
    qSet.str("");
#define IQ_POINTS_PER 100 // Points per iteration
    // Set our marker size
    OutputParseDrawCommand(Send + "new markVar " + std::to_string(IQ_POINTS_PER));
    // I in-phase (x-axis variable)
    for(ii = 0; ii < IQ_POINTS_PER-1; ii++)
      iSet << (((float)std::rand())/RAND_MAX) * 2.0 - 1 << ",";
    iSet << (((float)std::rand())/RAND_MAX) * 2.0 - 1.0;
    // Q quadrature (y-axis variable)
    for(qi = 0; qi < IQ_POINTS_PER-1; qi++)
      qSet << (((float)std::rand())/RAND_MAX) * 2.0 - 1.0 << ",";
    qSet << (((float)std::rand())/RAND_MAX) * 2.0 - 1.0;

    OutputParseDrawCommand(SetVar + "iVar," + iSet.str());
    OutputParseDrawCommand(SetVar + "qVar," + qSet.str());
    OutputParseDrawCommand(Send + "mark iVar qVar markVar 'b+'");
    OutputParseDrawCommand(Send + "xtick 0.5 4");
    OutputParseDrawCommand(Send + "ytick 0.5 4");
    OutputParseDrawCommand(Send + "box");
    OutputParseDrawCommand(Send + "axis 'xy': grid");
    OutputParseDrawCommand(Send + "xlabel 'I'");
    OutputParseDrawCommand(Send + "ylabel 'Q'");
    OutputParseDrawCommand(Send + "text 0 1.3 1 'IQ Plot Test'");
    OutputParseDrawCommand(Update);
    OutputParseDrawCommand(Reset);
  }
  ClearParseDraw();
#endif
}

int main(int argc, char* argv[])
{
  (void)argc;
  (void)argv;
  std::srand(std::time(0));

  RunAnimationTest();
  RunIQTest();
  // TODO: logic analyzer, oscope

  OutputParseDrawCommand(Exit);

  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
namespace planning {

struct RotationConstraints {
    RotationConstraints()
        : max_speed(constraints::PARAM_max_rotational_speed),
          max_accel(constraints::PARAM_max_rotational_accel) {}
    double max_speed;
    double max_accel;
};

}  // namespace planning


text:
@interface GPUImageMonochromeFilter : GPUImageFilter
{
    GLint intensityUniform, filterColorUniform;
}

@property(readwrite, nonatomic) CGFloat intensity;
@property(readwrite, nonatomic) GPUVector4 color;
//@property(readwrite, nonatomic) CIColor* color;
- (void)setColorRed:(GLfloat)redComponent green:(GLfloat)greenComponent blue:(GLfloat)blueComponent;

@end


text:
#include <aws/core/endpoint/EndpointProviderBase.h>

namespace Aws
{
namespace Endpoint
{
/**
 * Export endpoint provider symbols from DLL
 */
template class AWS_CORE_API EndpointProviderBase<Aws::Client::GenericClientConfiguration<false>,
            Aws::Endpoint::BuiltInParameters,
            Aws::Endpoint::ClientContextParameters>;

} // namespace Endpoint
} // namespace Aws


text:
<?php namespace Nwidart\ForecastPhp;

use GuzzleHttp\Client;

class Forecast
{
    /**
     * @var string
     */
    private $apiKey;

    /**
     * @var string
     */
    private $endpoint = 'https://api.forecast.io/forecast';

    /**
     * @var Client
     */
    private $client;
    /**
     * @var array
     */
    private $options;

    public function __construct($apiKey)
    {
        $this->apiKey = $apiKey;
    }

    /**
     * Get the weather for the given latitude and longitude
     * Optionally pass in a time for the query
     * @param null|string $latitude
     * @param null|string $longitude
     * @param null|string $time
     * @return array
     */
    public function get($latitude = null, $longitude = null, $time = null)
    {
        $this->guardAgainstEmptyArgument($latitude, 'latitude');
        $this->guardAgainstEmptyArgument($longitude, 'longitude');

        $url = $this->getUrl($latitude, $longitude, $time);

        $forecast = $this->getClient()->get($url);

        return $forecast->json();
    }

    /**
     * Set options on the request to be made to Forecast
     * @param array $options
     * @return $this
     */
    public function setOptions(array $options)
    {
        $this->options = $options;

        return $this;
    }

    /**
     * Set the http client to use
     * @param $client
     */
    public function setClient($client)
    {
        $this->client = $client;
    }

    /**
     * Get the guzzle client
     * @return Client
     */
    private function getClient()
    {
        if ($this->client) {
            return $this->client;
        }

        return new Client();
    }

    /**
     * Guard against empty arguments
     * @param string $argument
     * @param string $argumentName
     */
    private function guardAgainstEmptyArgument($argument, $argumentName)
    {
        if (empty($argument)) {
            throw new \InvalidArgumentException("$argumentName is required.");
        }
    }

    /**
     * @param string $latitude
     * @param string $longitude
     * @param string $time
     * @return string
     */
    private function getUrl($latitude, $longitude, $time)
    {
        $url = "{$this->endpoint}/{$this->apiKey}/$latitude,$longitude";

        if ($time) {
            $url .= ",$time";
        }

        if (! empty($this->options)) {
            $url .= '?' . http_build_query($this->options);
        }

        return $url;
    }
}


text:
<component name="libraryTable">
  <library name="support-compat-25.3.1">
    <CLASSES>
      <root url="file://$USER_HOME$/.android/build-cache/22ca3b422f9c0ee15ec3bbfee9708fc5a692bf82/output/res" />
      <root url="jar://$USER_HOME$/.android/build-cache/22ca3b422f9c0ee15ec3bbfee9708fc5a692bf82/output/jars/classes.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://D:/Android/AppData/Android/Sdk/extras/android/m2repository/com/android/support/support-compat/25.3.1/support-compat-25.3.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
@implementation UIViewController (SEGScreen)

+ (void)seg_swizzleViewDidAppear
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];

        SEL originalSelector = @selector(viewDidAppear:);
        SEL swizzledSelector = @selector(seg_viewDidAppear:);

        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

        BOOL didAddMethod =
            class_addMethod(class,
                            originalSelector,
                            method_getImplementation(swizzledMethod),
                            method_getTypeEncoding(swizzledMethod));

        if (didAddMethod) {
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

+ (UIViewController *)seg_rootViewControllerFromView:(UIView *)view
{
    UIViewController *root = view.window.rootViewController;
    return [self seg_topViewController:root];
}

+ (UIViewController *)seg_topViewController:(UIViewController *)rootViewController
{
    UIViewController *nextRootViewController = [self seg_nextRootViewController:rootViewController];
    if (nextRootViewController) {
        return [self seg_topViewController:nextRootViewController];
    }

    return rootViewController;
}

+ (UIViewController *)seg_nextRootViewController:(UIViewController *)rootViewController
{
    UIViewController *presentedViewController = rootViewController.presentedViewController;
    if (presentedViewController != nil) {
        return presentedViewController;
    }

    if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UIViewController *lastViewController = ((UINavigationController *)rootViewController).viewControllers.lastObject;
        return lastViewController;
    }

    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        __auto_type *currentTabViewController = ((UITabBarController*)rootViewController).selectedViewController;
        if (currentTabViewController != nil) {
            return currentTabViewController;
        }
    }

    if (rootViewController.childViewControllers.count > 0) {
        if ([rootViewController conformsToProtocol:@protocol(SEGScreenReporting)] && [rootViewController respondsToSelector:@selector(seg_mainViewController)]) {
            __auto_type screenReporting = (UIViewController<SEGScreenReporting>*)rootViewController;
            return screenReporting.seg_mainViewController;
        }

        // fall back on first child UIViewController as a "best guess" assumption
        __auto_type *firstChildViewController = rootViewController.childViewControllers.firstObject;
        if (firstChildViewController != nil) {
            return firstChildViewController;
        }
    }

    return nil;
}

- (void)seg_viewDidAppear:(BOOL)animated
{
    UIViewController *top = [[self class] seg_rootViewControllerFromView:self.view];
    if (!top) {
        SEGLog(@"Could not infer screen.");
        return;
    }

    NSString *name = [[[top class] description] stringByReplacingOccurrencesOfString:@"ViewController" withString:@""];

    if (!name || name.length == 0) {
        // if no class description found, try view controller's title.
        name = [top title];
        // Class name could be just "ViewController".
        if (name.length == 0) {
            SEGLog(@"Could not infer screen name.");
            name = @"Unknown";
        }
    }

    if ([top conformsToProtocol:@protocol(SEGScreenReporting)] && [top respondsToSelector:@selector(seg_trackScreen:name:)]) {
        __auto_type screenReporting = (UIViewController<SEGScreenReporting>*)top;
        [screenReporting seg_trackScreen:top name:name];
        return;
    }

    [[SEGAnalytics sharedAnalytics] screen:name properties:nil options:nil];

    [self seg_viewDidAppear:animated];
}

@end
#endif


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import <Foundation/Foundation.h>
#import "JSONModel.h"
#import "MOZUAdminCategory.h"

@protocol MOZUAdminCategoryPagedCollection
@end

/**
	The container for paged lists of related site-specific product category properties.
*/
@interface MOZUAdminCategoryPagedCollection : JSONModel<MOZUAdminCategoryPagedCollection>

/**
The number of pages returned based on the startIndex and pageSize values specified. This value is system-supplied and read-only.
*/
@property(nonatomic) NSInteger pageCount;

/**
The number of results to display on each page when creating paged results from a query. The maximum value is 200.
*/
@property(nonatomic) NSInteger pageSize;

@property(nonatomic) NSInteger startIndex;

/**
The number of results listed in the query collection, represented by a signed 64-bit (8-byte) integer. This value is system-supplied and read-only.
*/
@property(nonatomic) NSInteger totalCount;

/**
An array list of objects in the returned collection.
*/
@property(nonatomic) NSArray<MOZUAdminCategory> *items;

@end


text:
class AddIsStarredStatusForStories < ActiveRecord::Migration
  def change
    add_column :stories, :is_starred, :boolean, default: false
  end
end


text:
import Manager from "./manager";
//recognizer
import TapRecognizer from './recognizers/tap';
import PressRecognizer from './recognizers/press';
import PanRecognizer from './recognizers/pan';
//utils
import splitStr from './utils/split-str';
import each from './utils/each';
import ifUndefined from './utils/if-undefined';

import { DIRECTION_HORIZONTAL, DIRECTION_VERTICAL, DIRECTION_ALL } from './inputjs/input-consts';

export default class Guesture {
  constructor(options) {
    options = options || {};
    options.recognizers = ifUndefined(
      options.recognizers,
      Guesture.defaults.preset
    );
    return new Manager(options);
  }
}

Guesture.defaults = {
  nativeEvents: false,
  preset: [
    [TapRecognizer],
    [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']],
    [PressRecognizer],
    [PanRecognizer, { direction: DIRECTION_HORIZONTAL }],
  ]
};

Guesture.Manager = Manager;

Guesture.Tap = TapRecognizer;
Guesture.Press = PressRecognizer;
Guesture.Pan = PanRecognizer;
Guesture.DIRECTION = {
  DIRECTION_HORIZONTAL,
  DIRECTION_VERTICAL,
  DIRECTION_ALL
}


text:
package helper

import (
	"fmt"
	"github.com/eaciit/knot/knot.v1"
	"github.com/eaciit/toolkit"
	"io"
	"os"
	"path/filepath"
	"strings"
)

var (
	DebugMode bool
)

func HandleError(err error, optionalArgs ...interface{}) bool {
	if err != nil {
		fmt.Printf("error occured: %s", err.Error())

		if len(optionalArgs) > 0 {
			optionalArgs[0].(func(bool))(false)
		}

		return false
	}

	if len(optionalArgs) > 0 {
		optionalArgs[0].(func(bool))(true)
	}

	return true
}

func CreateResult(success bool, data interface{}, message string) map[string]interface{} {
	if !success {
		fmt.Println("ERROR! ", message)
		if DebugMode {
			panic(message)
		}
	}

	return map[string]interface{}{
		"data":    data,
		"success": success,
		"message": message,
	}
}

func ImageUploadHandler(r *knot.WebContext, filename, dstpath string) (error, string) {
	file, handler, err := r.Request.FormFile(filename)
	if err != nil {
		return err, ""
	}
	defer file.Close()

	newImageName := toolkit.RandomString(32) + filepath.Ext(handler.Filename)
	dstSource := dstpath + toolkit.PathSeparator + newImageName
	f, err := os.OpenFile(dstSource, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		return err, ""
	}
	defer f.Close()
	io.Copy(f, file)

	return nil, newImageName
}

func UploadFileHandler(r *knot.WebContext, tempfile, dstpath, filename string) (error, string, string, string) {
	file, handler, err := r.Request.FormFile(tempfile)
	if err != nil {
		return err, "", "", ""
	}
	defer file.Close()

	ext := filepath.Ext(handler.Filename)
	newFileName := filename + ext
	dstSource := dstpath + toolkit.PathSeparator + newFileName
	f, err := os.OpenFile(dstSource, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		return err, "", "", ""
	}
	defer f.Close()
	io.Copy(f, file)

	return nil, handler.Filename, newFileName, strings.Split(ext, ".")[1]
}

func UploadHandler(r *knot.WebContext, filename, dstpath string) (error, string) {
	file, handler, err := r.Request.FormFile(filename)
	if err != nil {
		return err, ""
	}
	defer file.Close()

	dstSource := dstpath + toolkit.PathSeparator + handler.Filename
	f, err := os.OpenFile(dstSource, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		return err, ""
	}
	defer f.Close()
	_, err = io.Copy(f, file)
	if err!=nil {
		return err, ""
	}
	fmt.Println("Write file: " + dstSource)
	return nil, handler.Filename
}


text:
package dmillerw.camera.helper;

import cpw.mods.fml.common.FMLCommonHandler;
import net.minecraftforge.common.MinecraftForge;

/**
 * @author dmillerw
 */
public class EventBusHelper {

    public static enum Type {
        FORGE,
        FML,
        BOTH
    }

    public static void register(Object handler, Type type) {
        if (type == Type.FORGE || type == Type.BOTH) {
            MinecraftForge.EVENT_BUS.register(handler);
        }

        if (type == Type.FML || type == Type.BOTH) {
            FMLCommonHandler.instance().bus().register(handler);
        }
    }
}


text:
package org.openhubframework.openhub.api.common.quartz;

import java.util.concurrent.TimeUnit;

import org.springframework.util.Assert;

/**
 * Contains all time unit in which can be saved repeat interval for {@link QuartzSimpleTrigger} in property
 * ({@link QuartzSimpleTrigger#repeatIntervalProperty()}).
 * <p>
 * Unit can be set in {@link QuartzSimpleTrigger#intervalPropertyUnit()}.
 * </p>
 *
 * @author Roman Havlicek
 * @see QuartzJob
 * @see QuartzSimpleTrigger#intervalPropertyUnit()
 * @since 2.0
 */
public enum SimpleTriggerPropertyUnit {

    /**
     * Interval in property {@link QuartzSimpleTrigger#repeatIntervalProperty()} is saved in millis.
     */
    MILLIS(new MillisConverter() {
        @Override
        public long convertIntervalToMillis(long interval) {
            return interval;
        }
    }),

    /**
     * Interval in property {@link QuartzSimpleTrigger#repeatIntervalProperty()} is saved in seconds.
     */
    SECONDS(new MillisConverter() {
        @Override
        public long convertIntervalToMillis(long interval) {
            return TimeUnit.SECONDS.toMillis(interval);
        }
    }),

    /**
     * Interval in property {@link QuartzSimpleTrigger#repeatIntervalProperty()} is saved in minutes.
     */
    MINUTES(new MillisConverter() {
        @Override
        public long convertIntervalToMillis(long interval) {
            return TimeUnit.MINUTES.toMillis(interval);
        }
    });

    /**
     * Converter time interval into millis.
     */
    private final MillisConverter millisConverter;

    /**
     * New instance.
     *
     * @param millisConverter converter time unit into millis
     */
    SimpleTriggerPropertyUnit(MillisConverter millisConverter) {
        Assert.notNull(millisConverter, "millisConverter must not be null");

        this.millisConverter = millisConverter;
    }

    /**
     * Gets time unit interval in millis.
     *
     * @param interval unit repeat interval (in millis, or seconds...)
     * @return repeat interval in millis
     */
    public long getIntervalInMillis(long interval) {
        return millisConverter.convertIntervalToMillis(interval);
    }

    //---------------------------------------------- PRIVATE CLASS -----------------------------------------------------

    /**
     * Converter for convert repeat interval in millis, seconds or minutes into millis.
     */
    private interface MillisConverter {

        /**
         * Convert time repeat interval into millis.
         *
         * @param interval time repeat interval in millis, seconds or minutes...
         * @return interval in millis
         */
        long convertIntervalToMillis(long interval);
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ms.portalv1.controllers;

import com.ms.common.cofig.ResourceProject;
import com.ms.common.cofig.UserSessionData;
import com.ms.portalv1.interfacedaos.UserInterfaceDao;
import com.ms.portalv1.models.UserProfile;
import com.ms.portalv1.validators.UserProfileValidator;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Noe Martinez
 * gpmarsan@gmail.com
 * 01/julio/2014
 */
@Controller
@SessionAttributes({"user"})
@RequestMapping("/edit_profile")
public class UserEditProfileController {
    ResourceProject resource = new ResourceProject();
    UserProfileValidator userProfileValidator = new UserProfileValidator();

    @Autowired
    @Qualifier("daoUser")
    private UserInterfaceDao UserDao;

    public UserInterfaceDao getUserDao() {
        return UserDao;
    }

    public ResourceProject getResource() {
        return resource;
    }

    public UserProfileValidator getUserProfileValidator() {
        return userProfileValidator;
    }

    public void setUserProfileValidator(UserProfileValidator userProfileValidator) {
        this.userProfileValidator = userProfileValidator;
    }

    @Autowired
    public UserEditProfileController(UserProfileValidator userProfileValidator) {
        this.setUserProfileValidator(userProfileValidator);
        resource.setLayout(resource.getDirLayout() +"perseo.vm");
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initForm(HttpServletRequest request, @ModelAttribute("user") UserSessionData userSessionData, ModelMap model){
        UserProfile usrProfile = new UserProfile();
        HashMap<String, String> dataUser = new HashMap<String, String>();
        HashMap<String, Object> data = new HashMap<>();

        dataUser = this.getUserDao().getUserDataByIdEncod(userSessionData.getUserIdCod());
        usrProfile.setAlias(dataUser.get("alias"));
        usrProfile.setEmail(dataUser.get("email"));

        //Mostrar aciones
        data.put("create_account", false);
        data.put("login", false);
        data.put("panel", true);
        data.put("profile", true);
        data.put("logout", true);

        //Command object
        model.addAttribute("userp", usrProfile);
        model.addAttribute("layout", resource.getLayout());
        model.addAttribute("view",resource.getDirViews()+"user/editprofile.vm" );
        model.addAttribute("username", userSessionData.getUserName());
        model.addAttribute("data","editpasswd");

        //return form view
        return "index";
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView updateProfile(@ModelAttribute("user") UserSessionData userSessionData, @ModelAttribute("userp") UserProfile userProfile, BindingResult result, SessionStatus status, Model model) {
        ModelAndView x = null;
        HashMap<String, Object> data = new HashMap<>();

        userProfile.setId(userSessionData.getUserIdCod());

        this.getUserProfileValidator().initValidator(this.getUserDao());

        this.getUserProfileValidator().validate(userProfile, result);

        if (result.hasErrors()) {
            //Mostrar aciones
            data.put("create_account", false);
            data.put("login", false);
            data.put("panel", true);
            data.put("profile", true);
            data.put("logout", true);

            x = new ModelAndView("index", "title", "Editar Perfil - Portal Perseo");
            x = x.addObject("layout", resource.getLayout());
            x = x.addObject("view",resource.getDirViews()+"user/editprofile.vm" );
            x = x.addObject("data",data);

            return x;
        }else{
            if(!userProfile.getId().equals("0")){
                //Actualizar
                //status.setComplete();

                String retorno="";
                String actualizo="0";
                String commandd_selected = "edit_profile";
                //Generar codigo de verificacion
                String milis = String.valueOf(System.currentTimeMillis());
                String code=milis.substring(milis.length()-4, milis.length());

                String data_string = commandd_selected +"___"+ userProfile.getId()+"___"+userProfile.getEmail()+"___"+userProfile.getAlias()+"___"+" "+"___"+" "+"___"+" "+"___"+" ";

                actualizo = this.getUserDao().callStoredProcedureAddUser(data_string);

                if(actualizo.equals("1")){
                    System.out.println("SE ACTUALIZO EL EMAIL, ALIAS");
                }

                //form success
                HashMap<String, String> dataUser = new HashMap<String, String>();
                dataUser = this.getUserDao().getUserDataByIdEncod(userSessionData.getUserIdCod());

                //Mostrar aciones
                data.put("create_account", false);
                data.put("login", false);
                data.put("panel", true);
                data.put("profile", false);
                data.put("logout", true);

                x = new ModelAndView("index");
                x = x.addObject("userp", dataUser);
                x = x.addObject("layout", resource.getLayout());
                x = x.addObject("view",resource.getDirViews()+"user/profile.vm" );
                x = x.addObject("data","profile");

                return x;
            }
        }

        return x;
    }

}


text:
package griffon.pivot.support.adapters;

import groovy.lang.Closure;

/**
 * @author Andres Almiray
 */
public class SuggestionPopupCloseAdapter implements GriffonPivotAdapter, org.apache.pivot.wtk.SuggestionPopupCloseListener {
    private Closure suggestionPopupClosed;

    public Closure getSuggestionPopupClosed() {
        return this.suggestionPopupClosed;
    }

    public void setSuggestionPopupClosed(Closure suggestionPopupClosed) {
        this.suggestionPopupClosed = suggestionPopupClosed;
        if (this.suggestionPopupClosed != null) {
            this.suggestionPopupClosed.setDelegate(this);
            this.suggestionPopupClosed.setResolveStrategy(Closure.DELEGATE_FIRST);
        }
    }

    public void suggestionPopupClosed(org.apache.pivot.wtk.SuggestionPopup arg0) {
        if (suggestionPopupClosed != null) {
            suggestionPopupClosed.call(arg0);
        }
    }

}


text:
package com.mpush.api.srd;

import com.mpush.api.service.Service;

/**
 * Created by ohun on 2016/12/19.
 *
 * @author ohun@live.cn (夜色)
 */
public interface ServiceRegistry extends Service {

    void register(ServiceNode node);

    void deregister(ServiceNode node);
}


text:
<?php
namespace Jd\Request;
class EclpOrderQueryOrderStatusRequest
{
	private $apiParas = array();

	public function getApiMethodName(){
	  return "jingdong.eclp.order.queryOrderStatus";
	}

	public function getApiParas(){
		return json_encode($this->apiParas);
	}

	public function check(){

	}

	public function putOtherTextParam($key, $value){
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
                                    	                   			private $eclpSoNo;

	public function setEclpSoNo($eclpSoNo){
		$this->eclpSoNo = $eclpSoNo;
         $this->apiParas["eclpSoNo"] = $eclpSoNo;
	}

	public function getEclpSoNo(){
	  return $this->eclpSoNo;
	}

                        	}


text:
package org.fogbeam.jenatutorial.rdfs;

import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.InfModel;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.reasoner.Reasoner;
import org.apache.jena.reasoner.ReasonerRegistry;
import org.apache.jena.sparql.util.QueryExecUtils;
import org.apache.jena.util.FileManager;
import org.apache.jena.vocabulary.ReasonerVocabulary;

public class RDFSLabels
{

	public static void main( String[] args )
	{
		// load some data that uses RDFS
		Model data = FileManager.get().loadModel("file:data/input/turtle/ex13-data.ttl");

		Reasoner reasoner = ReasonerRegistry.getRDFSReasoner();
		reasoner.setParameter(ReasonerVocabulary.PROPsetRDFSLevel,
                ReasonerVocabulary.RDFS_DEFAULT);
		InfModel infmodel = ModelFactory.createInfModel(reasoner, data );

		/* Do a SPARQL Query over the data in the model */
		String queryString = "SELECT ?x ?z WHERE { ?x <http://www.w3.org/2000/01/rdf-schema#label> ?z }";

		/* Now create and execute the query using a Query object */
		Query query = QueryFactory.create(queryString) ;
		QueryExecution qexec = QueryExecutionFactory.create(query, infmodel) ;

		QueryExecUtils.executeQuery(qexec);

		System.out.println( "done" );

	}
}


text:
<!DOCTYPE html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<script>
description('This test checks that the Overwrite mode is: 1) not exposed to JavaScript 2) queryCommandState returns false.');

shouldBeFalse("document.queryCommandSupported('OverWrite')");
shouldBeFalse("document.queryCommandState('OverWrite')");

var successfullyParsed = true;
</script>
</body>
</html>


text:
/*
    C++ ECHO socket server
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <poll.h>
#include <unistd.h>
#include "base.h"
using namespace std;

extern const int BUF_SIZE;
extern const char SERVER_IP[];
extern const int SERVER_PORT;
extern const int BACKLOG;
extern const unsigned int MAX_CLIENT_NUM;

vector<pollfd> poll_sets;

void add_client(int client_sock)
{
    pollfd client_pollfd;
    client_pollfd.fd = client_sock;
    client_pollfd.events = POLLIN;
    poll_sets.push_back(client_pollfd);
    print_conn(client_sock);
    printf("now_client_num: %u\n", (unsigned int)poll_sets.size()-1);
}

void del_client(vector<pollfd>::iterator it)
{
    poll_sets.erase(it);
    print_dconn(it->fd);
    close(it->fd);
    printf("now_client_num: %u\n", (unsigned int)poll_sets.size()-1);
}

int main(int argc, char *argv[])
{
    // create socket
    int listen_sock = get_listen_socket();

    // set reuse
    set_reuse_addr(listen_sock);

    // bind
    listen_socket_bind(listen_sock);

    // listen
    listen_socket_listen(listen_sock);

    // start success
    print_start();

    // socklen_t addr_size = sizeof(sockaddr_in);
    pollfd listen_pollfd;
    listen_pollfd.fd = listen_sock;
    listen_pollfd.events = POLLIN;
    poll_sets.push_back(listen_pollfd);

    while (1)
    {
        int ret = poll((pollfd *)&poll_sets[0], (unsigned int)poll_sets.size(), -1);

        if (ret <= 0)
        {
            // timeout is error
            perror("poll error");
            exit(1);
        }

        // check every pool in the set
        vector<pollfd>::iterator it;
        vector<pollfd>::iterator end = poll_sets.end();
        for (it = poll_sets.begin(); it != end; it++)
        {
            if (it->revents & POLLIN)
            {
                if (it->fd == listen_sock)
                {
                    // new client
                    int client_sock = accept_socket(listen_sock);
                    if (client_sock == -1)
                    {
                        perror("accept failed");
                        continue;
                    }

                    if (poll_sets.size()-1 < MAX_CLIENT_NUM)
                    {
                        // add to pool set
                        add_client(client_sock);
                    }
                    else
                    {
                        too_many_clients(client_sock);
                    }
                }
                else
                {
                    // client echo message
                    char message[BUF_SIZE];
                    int read_size = recv(it->fd, message, BUF_SIZE, 0);

                    if (read_size <= 0)
                    {
                        // client close
                        del_client(it);
                    }
                    else
                    {
                        // receive data
                        print_recv(it->fd, message);
                        //Send the message back to client
                        send(it->fd, message, strlen(message)+1, 0);
                        print_send(it->fd, message);
                    }
                }
            }
            else if (it->revents & POLLERR)
            {
                if (it->fd == listen_sock)
                {
                    // listen socket error
                    perror("listen socket error");
                    exit(1);
                }
                else
                {
                    // client error
                    del_client(it);
                }
            }
        }
    }
}


text:
package org.elasticsearch.script;

import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.AbstractSerializingTestCase;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class StoredScriptSourceTests extends AbstractSerializingTestCase<StoredScriptSource> {

    @Override
    protected StoredScriptSource createTestInstance() {
        String lang = randomAlphaOfLengthBetween(1, 20);
        XContentType xContentType = randomFrom(XContentType.JSON, XContentType.YAML);
        try {
            XContentBuilder template = XContentBuilder.builder(xContentType.xContent());
            template.startObject();
            template.startObject("query");
            template.startObject("match");
            template.field("title", "{{query_string}}");
            template.endObject();
            template.endObject();
            template.endObject();
            Map<String, String> options = new HashMap<>();
            if (randomBoolean()) {
                options.put(Script.CONTENT_TYPE_OPTION, xContentType.mediaType());
            }
            return StoredScriptSource.parse(template.bytes(), xContentType);
        } catch (IOException e) {
            throw new AssertionError("Failed to create test instance", e);
        }
    }

    @Override
    protected StoredScriptSource doParseInstance(XContentParser parser) throws IOException {
        return StoredScriptSource.fromXContent(parser);
    }

    @Override
    protected Reader<StoredScriptSource> instanceReader() {
        return StoredScriptSource::new;
    }

}


text:
<!DOCTYPE html>
<title>Canvas test: 2d.imageData.put.alpha</title>

<link rel="stylesheet" href="../tests.css">
<link rel="prev" href="2d.imageData.put.cross.html" title="2d.imageData.put.cross">
<link rel="next" href="2d.imageData.put.modified.html" title="2d.imageData.put.modified">

 <
 [index]
 >

2d.imageData.put.alpha

putImageData() puts non-solid image data correctly

References:

2d.imageData.put.normal

Actual output:

<canvas id="c" class="output" width="100" height="50">
FAIL (fallback content)
</canvas>

Expected output:


text:
#include <QFile>
#include <QHostInfo>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkProxy>
#include <QSysInfo>
#include "de_web_plugin_private.h"
#include "json.h"
#ifdef Q_OS_LINUX
#include <unistd.h>
#include <sys/time.h>
#endif

/*! Inits the internet discovery manager.
 */
void DeRestPluginPrivate::initInternetDicovery()
{
    Q_ASSERT(inetDiscoveryManager == 0);
    inetDiscoveryManager = new QNetworkAccessManager;
    connect(inetDiscoveryManager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(internetDiscoveryFinishedRequest(QNetworkReply*)));

    DBG_Assert(gwAnnounceInterval >= 0);
    if (gwAnnounceInterval < 0)
    {
        gwAnnounceInterval = ANNOUNCE_INTERVAL;
    }

    gwAnnounceVital = 0;
    inetDiscoveryTimer = new QTimer(this);
    inetDiscoveryTimer->setSingleShot(false);

    {
        QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(gwAnnounceUrl));

        if (!proxies.isEmpty())
        {
            const QNetworkProxy &proxy = proxies.first();
            if (proxy.type() == QNetworkProxy::HttpProxy || proxy.type() == QNetworkProxy::HttpCachingProxy)
            {
                gwProxyPort = proxy.port();
                gwProxyAddress = proxy.hostName();
                inetDiscoveryManager->setProxy(proxy);
                QHostInfo::lookupHost(proxy.hostName(),
                                      this, SLOT(inetProxyHostLookupDone(QHostInfo)));
            }
        }
    }

    connect(inetDiscoveryTimer, SIGNAL(timeout()),
            this, SLOT(internetDiscoveryTimerFired()));

    setInternetDiscoveryInterval(gwAnnounceInterval);

    // force first run
    if (gwAnnounceInterval > 0)
    {
        QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired()));
    }

    {
        QFile f("/etc/os-release");
        if (f.exists() && f.open(QFile::ReadOnly))
        {
            QTextStream stream(&f);

            while (!stream.atEnd())
            {
                QString line = stream.readLine(200);
                QStringList lineLs = line.split(QChar('='));

                if (lineLs.size() != 2)
                {
                    continue;
                }

                if (lineLs[0] == QLatin1String("PRETTY_NAME"))
                {
                    osPrettyName = lineLs[1];
                    osPrettyName.remove(QChar('"'));
                }
            }
        }
    }
#ifdef ARCH_ARM
    { // get raspberry pi revision
        QFile f("/proc/cpuinfo");
        if (f.exists() && f.open(QFile::ReadOnly))
        {
            QByteArray arr = f.readAll();
            QTextStream stream(arr);

            while (!stream.atEnd())
            {
                QString line = stream.readLine(200);
                QStringList lineLs = line.split(QChar(':'));

                if (lineLs.size() != 2)
                {
                    continue;
                }

                if (lineLs[0].startsWith(QLatin1String("Revision")))
                {
                    piRevision = lineLs[1].trimmed();
                    break;
                }
            }
        }
    }
#endif // ARCH_ARM

    if (osPrettyName.isEmpty())
    {
#ifdef Q_OS_WIN
        switch (QSysInfo::WindowsVersion)
        {
        case QSysInfo::WV_XP:         osPrettyName = QLatin1String("WinXP"); break;
        case QSysInfo::WV_WINDOWS7:   osPrettyName = QLatin1String("Win7"); break;
        case QSysInfo::WV_WINDOWS8:   osPrettyName = QLatin1String("Win8"); break;
        case QSysInfo::WV_WINDOWS8_1: osPrettyName = QLatin1String("Win8.1"); break;
        case QSysInfo::WV_WINDOWS10:  osPrettyName = QLatin1String("Win10"); break;
        default:
            osPrettyName = QLatin1String("Win");
            break;
        }
#endif
#ifdef Q_OS_OSX
        osPrettyName = "Mac";
#endif
#ifdef Q_OS_LINUX
        osPrettyName = "Linux";
#endif
    }
}

/*! Sets the announce interval for internet discovery.

    \param minutes a value between 0..180 min
    \return true on success
 */
bool DeRestPluginPrivate::setInternetDiscoveryInterval(int minutes)
{
    if ((minutes < 0) || (minutes > 180))
    {
        DBG_Printf(DBG_INFO, "discovery ignored invalid announce interval (%d minutes)\n", minutes);
        return false;
    }

    inetDiscoveryTimer->stop();
    if (gwAnnounceInterval != minutes)
    {
        DBG_Printf(DBG_INFO, "discovery updated announce interval to %d minutes\n", minutes);
    }

    gwAnnounceInterval = minutes;

    if (gwAnnounceInterval > 0)
    {
        int msec = 1000 * 60 * gwAnnounceInterval;
        inetDiscoveryTimer->start(msec);
    }
    return true;
}

/*! Handle announce trigger timer.
 */
void DeRestPluginPrivate::internetDiscoveryTimerFired()
{
    if (gwAnnounceInterval <= 0)
    {
        return;
    }

    if (gwSwUpdateState == swUpdateState.transferring || gwSwUpdateState == swUpdateState.installing)
    {
        return; // don't interfere with running operations
    }

    int i = 0;
    const deCONZ::Node *node;
    deCONZ::ApsController *ctrl = deCONZ::ApsController::instance();

    while (ctrl && ctrl->getNode(i, &node) == 0)
    {
      i++;
    }

    QVariantMap map;
    map["name"] = gwName;
    map["mac"] = gwBridgeId;
    map["internal_ip"] = gwConfig["ipaddress"].toString();
    map["internal_port"] = gwConfig["port"].toDouble();
    map["interval"] = gwAnnounceInterval;
    map["swversion"] = gwConfig["swversion"].toString();
    map["fwversion"] = gwConfig["fwversion"].toString();
    map["nodecount"] = (double)i;
    map["uptime"] = (double)getUptime();
    map["updatechannel"] = gwUpdateChannel;
    map["os"] = osPrettyName;
    map["runmode"] = gwRunMode;
    if (!piRevision.isEmpty())
    {
        map["pirev"] = piRevision;
    }

    QByteArray data = Json::serialize(map);
    inetDiscoveryManager->put(QNetworkRequest(QUrl(gwAnnounceUrl)), data);
}

/*! Callback for finished HTTP requests.

    \param reply the reply to a HTTP request
 */
void DeRestPluginPrivate::internetDiscoveryFinishedRequest(QNetworkReply *reply)
{
    DBG_Assert(reply != 0);

    if (!reply)
    {
        return;
    }

    if (reply->error() == QNetworkReply::NoError)
    {
        if (gwAnnounceVital < 0)
        {
            gwAnnounceVital = 0;
        }
        gwAnnounceVital++;
        DBG_Printf(DBG_INFO, "Announced to internet %s\n", qPrintable(gwAnnounceUrl));
        internetDiscoveryExtractGeo(reply);
        internetDiscoveryExtractVersionInfo(reply);
    }
    else
    {
        DBG_Printf(DBG_INFO, "discovery network reply error: %s\n", qPrintable(reply->errorString()));
        if (gwAnnounceVital > 0)
        {
            gwAnnounceVital = 0;
        }
        gwAnnounceVital--;

        if (gwProxyAddress != QLatin1String("none") && gwProxyPort > 0)
        {
            if (inetDiscoveryManager->proxy().type() != QNetworkProxy::HttpProxy)
            {
                //first fail, speed up retry
                QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired()));
            }

            QNetworkProxy proxy(QNetworkProxy::HttpProxy, gwProxyAddress, gwProxyPort);
            inetDiscoveryManager->setProxy(proxy);
        }

        if (gwAnnounceVital < -10) // try alternative path
        {
            gwAnnounceUrl = QLatin1String("https://phoscon.de/discover");
        }
    }

    reply->deleteLater();
}

/*! Fills major.minor.patch versions as int in the array \p ls.
    \returns true if \p version is a valid version string and \p ls could be filled.
 */
bool versionToIntList(const QString &version, std::array<int, 3> &ls)
{
    bool result = false;
    const auto versionList = version.split('.');

    if (versionList.size() >= 3)
    {
        for (size_t i = 0; i < ls.size(); i++)
        {
            ls[i] = versionList[i].toInt(&result);
            if (!result)
            {
                break;
            }
        }
    }

    return result;
}

/*! Returns true if the \p remote version is newer than \p current version.
 */
bool remoteVersionIsNewer(const std::array<int, 3> &current, const std::array<int, 3> &remote)
{
    return current[0] <  remote[0] ||
           (current[0] == remote[0] && current[1] <  remote[1]) ||
           (current[0] == remote[0] && current[1] == remote[1] && current[2] < remote[2]);
}

/*! Extracts the update channels version info about the deCONZ/WebApp.

    \param reply which holds the version info in JSON format
 */
void DeRestPluginPrivate::internetDiscoveryExtractVersionInfo(QNetworkReply *reply)
{
    bool ok;
    QByteArray content = reply->readAll();
    QVariant var = Json::parse(content, ok);
    QVariantMap map = var.toMap();

    if (!ok || map.isEmpty())
    {
        DBG_Printf(DBG_ERROR, "discovery couldn't extract version info from reply\n");
    }

#ifdef ARCH_ARM
    if (reply->hasRawHeader("date") || reply->hasRawHeader("Date"))
    {
        // if NTP is not working (UDP blocked, proxies, etc)
        // try to extract time from discover server http header if local time is too off
        QString date = reply->rawHeader("date");
        if (date.isEmpty())
        {
            date = reply->rawHeader("Date");
        }
        DBG_Printf(DBG_INFO, "discovery server date: %s\n", qPrintable(date));

        QStringList ls = date.split(' ');
        if (ls.size() == 6) // RFC 1123: ddd, dd MMM yyyy HH:mm:ss GTM
        {
            int day = ls[1].toInt();
            int month = 0;
            int year = ls[3].toInt();

            const char *months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
            for (int i = 0; i < 12; i++)
            {
                if (ls[2].startsWith(months[i]))
                {
                    month = i + 1;
                    break;
                }
            }
            QDateTime dt;
            dt.setTimeSpec(Qt::UTC);
            dt.setDate(QDate(year, month, day));
            dt.setTime(QTime::fromString(ls[4]));

            QDateTime now = QDateTime::currentDateTimeUtc();
            int diff = qAbs(now.secsTo(dt));

            if (diff < 60)
            {
                DBG_Printf(DBG_INFO, "\t local time seems to be ok\n");
            }
            else if (getUptime() > 600 &&
                     gwConfig["ntp"].toString() != QLatin1String("synced"))
            {
                DBG_Printf(DBG_INFO, "\t = %s, diff %d\n", qPrintable(dt.toString()), diff);
                // lazy adjustment of process time
                //time_t t = dt.toSecsSinceEpoch(); // Qt 5.8
                time_t t = dt.toTime_t();
                struct tm tbrokenDown;
                if (localtime_r(&t, &tbrokenDown))
                {
                    struct timeval tv;
                    tv.tv_sec = mktime(&tbrokenDown);
                    tv.tv_usec = 0;
                    if (settimeofday(&tv, NULL) < 0)
                    {
                        DBG_Printf(DBG_ERROR, "settimeofday(): errno %d\n", errno);
                    }
                }
            }
        }
    }
#endif // ARCH_ARM

#ifdef ARCH_ARM
    if (map.contains("versions") && (map["versions"].type() == QVariant::Map))
    {
        const auto versions = map["versions"].toMap();

        if (versions.contains(gwUpdateChannel) && (versions[gwUpdateChannel].type() == QVariant::String))
        {
            const auto version = versions[gwUpdateChannel].toString();

            if (!version.isEmpty())
            {
                std::array<int, 3> current = { };
                std::array<int, 3> remote = { };

                if (versionToIntList(gwUpdateVersion, current) &&
                    versionToIntList(version, remote) &&
                    remoteVersionIsNewer(current, remote))
                {
                    DBG_Printf(DBG_INFO, "discovery found version %s for update channel %s\n", qPrintable(version), qPrintable(gwUpdateChannel));
                    gwUpdateVersion = version;
                    gwSwUpdateState = swUpdateState.readyToInstall;
                }
                else
                {
                    gwSwUpdateState = swUpdateState.noUpdate;
                }
                updateEtag(gwConfigEtag);
            }
            else
            {
                DBG_Printf(DBG_ERROR, "discovery reply doesn't contain valid version info for update channel %s\n", qPrintable(gwUpdateChannel));
            }
        }
        else
        {
            DBG_Printf(DBG_ERROR, "discovery reply doesn't contain version info for update channel %s\n", qPrintable(gwUpdateChannel));
        }
    }
    else
    {
        DBG_Printf(DBG_ERROR, "discovery reply doesn't contain valid version info\n");
    }
#endif // ARCH_ARM

    if (map.contains("interval") && (map["interval"].type() == QVariant::Double))
    {
        const int interval = map["interval"].toInt(&ok);
        if (ok && interval >= 0 && interval != gwAnnounceInterval)
        {
            setInternetDiscoveryInterval(interval);
        }
    }
}

/*! Extracts the geo information.

    \param reply from discovery server
 */
void DeRestPluginPrivate::internetDiscoveryExtractGeo(QNetworkReply *reply)
{
//    for (const QByteArray &hdr : reply->rawHeaderList())
//    {
//        DBG_Printf(DBG_INFO, "hdr: %s: %s\n", qPrintable(hdr), qPrintable(reply->rawHeader(hdr)));
//    }

    if (reply->hasRawHeader("X-AppEngine-CityLatLong"))
    {
        QList<QByteArray> ll = reply->rawHeader("X-AppEngine-CityLatLong").split(',');
        if (ll.size() != 2)
        {
            // no geo information available
            return;
        }

        Sensor *sensor = getSensorNodeForId(daylightSensorId);
        DBG_Assert(sensor != 0);
        if (!sensor)
        {
            return;
        }

        ResourceItem *configured = sensor->item(RConfigConfigured);
        ResourceItem *lat = sensor->item(RConfigLat);
        ResourceItem *lon = sensor->item(RConfigLong);

        DBG_Assert(configured && lat && lon);
        if (!configured || !lat || !lon)
        {
            return;
        }

        if (!configured->toBool() || !configured->lastSet().isValid())
        {
            configured->setValue(true);
            lat->setValue(QString(ll[0]));
            lon->setValue(QString(ll[1]));
            sensor->setNeedSaveDatabase(true);
            queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY);
        }
    }
}

/*! Finished Lookup of http proxy IP address.

    \param host holds the proxy host info
 */
void DeRestPluginPrivate::inetProxyHostLookupDone(const QHostInfo &host)
{
    if (host.error() != QHostInfo::NoError)
    {
        DBG_Printf(DBG_ERROR, "Proxy host lookup failed: %s\n", qPrintable(host.errorString()));
        return;
    }

    foreach (const QHostAddress &address, host.addresses())
    {
        QString addr = address.toString();
        if (address.protocol() == QAbstractSocket::IPv4Protocol &&
            !addr.isEmpty() && gwProxyAddress != address.toString())
        {
            DBG_Printf(DBG_INFO, "Found proxy IP address: %s\n", qPrintable(address.toString()));
            gwProxyAddress = address.toString();
            DBG_Assert(gwProxyPort != 0);
            queSaveDb(DB_CONFIG, DB_SHORT_SAVE_DELAY);
            updateEtag(gwConfigEtag);
            return;
        }
    }
}

/*! Check if a received via field contains a usable proxy.

    \param via holds the proxy host info received by http request header
 */
void DeRestPluginPrivate::inetProxyCheckHttpVia(const QString &via)
{
    if (via.isEmpty())
    {
        return;
    }

    if (gwProxyPort != 0 && !gwProxyAddress.isEmpty() && gwProxyAddress != QLatin1String("none"))
    {
        return; // already configured?
    }

    // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.45
    // 1.1 proxy.some-domain.com:3128 (squid/2.7.STABLE9)
    DBG_Printf(DBG_INFO, "Test proxy: \t%s\n", qPrintable(via));

    for (QString &entry : via.split(',')) // there might be multiple proxied in the chain
    {
        QStringList ls = entry.split(' ');
        if (ls.size() < 2)
        {
            continue;
        }

        if (!ls[0].contains(QLatin1String("1.1")))
        {
            continue;
        }

        QStringList recvBy = ls[1].split(':');
        if (ls.size() < 1) // at least host must be specified
        {
            continue;
        }

        quint16 port = 8080;
        if (recvBy.size() == 2) // optional
        {
            port = recvBy[1].toUInt();
        }

        DBG_Printf(DBG_INFO, "\t --> %s:%u\n", qPrintable(recvBy[0]), port);

        if (gwProxyPort != 0)
        {
            continue;
        }

        if (gwAnnounceVital >= 0)
        {
            continue;
        }

        gwProxyAddress = recvBy[0];
        gwProxyPort = port;

        if (gwProxyAddress.contains('.'))
        {
            recvBy = gwProxyAddress.split('.');
            gwProxyAddress = recvBy[0]; // strip domain // todo might be too restrictive
        }

        QNetworkProxy proxy(QNetworkProxy::HttpProxy, gwProxyAddress, gwProxyPort);
        inetDiscoveryManager->setProxy(proxy);
        QHostInfo::lookupHost(proxy.hostName(),
                              this, SLOT(inetProxyHostLookupDone(QHostInfo)));
        updateEtag(gwConfigEtag);

        if (gwAnnounceInterval > 0)
        {
            QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired()));
        }
    }
}


text:
"""Contains all callable environments in Flow."""
from flow.envs.base import Env
from flow.envs.bay_bridge import BayBridgeEnv
from flow.envs.bottleneck import BottleneckAccelEnv, BottleneckEnv, \
    BottleneckDesiredVelocityEnv
from flow.envs.traffic_light_grid import TrafficLightGridEnv, \
    TrafficLightGridPOEnv, TrafficLightGridTestEnv, TrafficLightGridBenchmarkEnv
from flow.envs.ring.lane_change_accel import LaneChangeAccelEnv, \
    LaneChangeAccelPOEnv
from flow.envs.ring.accel import AccelEnv
from flow.envs.ring.wave_attenuation import WaveAttenuationEnv, \
    WaveAttenuationPOEnv
from flow.envs.merge import MergePOEnv
from flow.envs.test import TestEnv

# deprecated classes whose names have changed
from flow.envs.bottleneck_env import BottleNeckAccelEnv
from flow.envs.bottleneck_env import DesiredVelocityEnv
from flow.envs.green_wave_env import PO_TrafficLightGridEnv
from flow.envs.green_wave_env import GreenWaveTestEnv

# implemented for Presslight single agent
# from flow.envs.centralized_single_agent_presslight import MyGridEnv
from flow.envs.centralized_env import CentralizedGridEnv
__all__ = [
    'Env',
    'AccelEnv',
    'LaneChangeAccelEnv',
    'LaneChangeAccelPOEnv',
    'TrafficLightGridTestEnv',
    'MergePOEnv',
    'BottleneckEnv',
    'BottleneckAccelEnv',
    'WaveAttenuationEnv',
    'WaveAttenuationPOEnv',
    'TrafficLightGridEnv',
    'TrafficLightGridPOEnv',
    'TrafficLightGridBenchmarkEnv',
    'BottleneckDesiredVelocityEnv',
    'TestEnv',
    'BayBridgeEnv',
    "CentralizedGridEnv",
    # deprecated classes
    'BottleNeckAccelEnv',
    'DesiredVelocityEnv',
    'PO_TrafficLightGridEnv',
    'GreenWaveTestEnv',
]