text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace DediLib.Collections
{
    /// <summary>
    /// Dictionary with multiple values per key (not thread-safe)
    /// </summary>
    /// <typeparam name="TKey">key type</typeparam>
    /// <typeparam name="TValue">value type</typeparam>
    public class ListDictionary<TKey, TValue> : IDictionary<TKey, TValue>
    {
        readonly Dictionary<TKey, TValue> _singleItems;
        readonly Dictionary<TKey, List<TValue>> _multiItems;

        int _valuesCount;
        readonly List<TKey> _allKeys;
        readonly List<TValue> _allValues;
        bool _updateKeysList = true;
        bool _updateValuesList = true;

        /// <summary>
        /// Dictionary is not read-only
        /// </summary>
        public bool IsReadOnly => false;

        /// <summary>
        /// Constructor
        /// </summary>
        public ListDictionary()
            : this(100)
        {
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="capacity">initial capacity</param>
        public ListDictionary(int capacity)
        {
            _singleItems = new Dictionary<TKey, TValue>(capacity);
            _multiItems = new Dictionary<TKey, List<TValue>>(capacity);

            _allKeys = new List<TKey>(capacity);
            _allValues = new List<TValue>(capacity);
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="keyComparer">key comparer</param>
        public ListDictionary(IEqualityComparer<TKey> keyComparer)
        {
            if (keyComparer == null) throw new ArgumentNullException(nameof(keyComparer));

            _singleItems = new Dictionary<TKey, TValue>(keyComparer);
            _multiItems = new Dictionary<TKey, List<TValue>>(keyComparer);

            _allKeys = new List<TKey>();
            _allValues = new List<TValue>();
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="capacity">initial capacity</param>
        /// <param name="keyComparer">key comparer</param>
        public ListDictionary(int capacity, IEqualityComparer<TKey> keyComparer)
        {
            if (keyComparer == null) throw new ArgumentNullException(nameof(keyComparer));

            _singleItems = new Dictionary<TKey, TValue>(capacity, keyComparer);
            _multiItems = new Dictionary<TKey, List<TValue>>(capacity, keyComparer);

            _allKeys = new List<TKey>(capacity);
            _allValues = new List<TValue>(capacity);
        }

        /// <summary>
        /// Add key/value pair to IndexDictionary
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        public void Add(TKey key, TValue value)
        {
            TValue existingItem;
            List<TValue> existingList;

            if (_singleItems.TryGetValue(key, out existingItem))
            {
                // convert single item to list
                existingList = new List<TValue>();
                _multiItems.Add(key, existingList);
                _singleItems.Remove(key);
                existingList.Add(existingItem);
                existingList.Add(value);
                if (!_updateValuesList) _allValues.Add(value);
                if (_valuesCount >= 0) _valuesCount++;
                return;
            }

            if (_multiItems.TryGetValue(key, out existingList))
            {
                existingList.Add(value);
                if (!_updateValuesList) _allValues.Add(value);
                if (_valuesCount >= 0) _valuesCount++;
                return;
            }

            // add new single item
            _singleItems.Add(key, value);
            if (_valuesCount >= 0) _valuesCount++;
            if (!_updateKeysList) _allKeys.Add(key);
            if (!_updateValuesList) _allValues.Add(value);
        }

        /// <summary>
        /// Add multiple key/value pairs to IndexDictionary
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="values">values</param>
        public void AddMany(TKey key, ICollection<TValue> values)
        {
            if (values == null) throw new ArgumentNullException(nameof(values));

            var count = values.Count;
            if (count == 0) return;
            if (count == 1)
            {
                Add(key, values.First());
                return;
            }

            TValue existingItem;
            List<TValue> existingList;

            if (_singleItems.TryGetValue(key, out existingItem))
            {
                // convert single item to list
                existingList = new List<TValue>();
                _multiItems.Add(key, existingList);
                _singleItems.Remove(key);
                existingList.Add(existingItem);
                existingList.AddRange(values);
                if (!_updateValuesList) _allValues.AddRange(values);
                if (_valuesCount >= 0) _valuesCount += count;
                return;
            }

            if (!_multiItems.TryGetValue(key, out existingList))
            {
                existingList = new List<TValue>();
                _multiItems[key] = existingList;
            }

            // add items to existing list
            existingList.AddRange(values);
            if (!_updateValuesList) _allValues.AddRange(values);
            if (_valuesCount >= 0) _valuesCount += count;
        }

        /// <summary>
        /// Add key/value pair to IndexDictionary
        /// </summary>
        /// <param name="item">key/value pair</param>
        public void Add(KeyValuePair<TKey, TValue> item)
        {
            Add(item.Key, item.Value);
        }

        /// <summary>
        /// Adds multiple key/value pair values at once
        /// </summary>
        /// <param name="range">collection of values to add</param>
        public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> range)
        {
            foreach (var item in range)
                Add(item.Key, item.Value);
        }

        /// <summary>
        /// Remove all values for a specific key
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>true, if values have been removed</returns>
        public bool Remove(TKey key)
        {
            var removed = _singleItems.Remove(key);
            if (!removed)
            {
                removed = _multiItems.Remove(key);
                if (!removed) return false;

                _valuesCount = -1; // to be updated if needed
                _updateKeysList = true;
                _updateValuesList = true;
            }
            else
            {
                if (_valuesCount >= 0) _valuesCount--;
                _updateKeysList = true;
                _updateValuesList = true;
            }
            return true;
        }

        /// <summary>
        /// Remove a key and value
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <returns>true, if key/value pair has been removed</returns>
        public bool Remove(TKey key, TValue value)
        {
            TValue existingItem;
            bool removed;

            if (!_singleItems.TryGetValue(key, out existingItem))
            {
                List<TValue> existingList;
                if (!_multiItems.TryGetValue(key, out existingList)) return false; // item not found

                removed = existingList.Remove(value);
                if (!removed) return false;

                if (_valuesCount >= 0) _valuesCount--;
                if (existingList.Count != 1) return true;

                // convert multi item to single item
                _singleItems[key] = existingList.First();
                _multiItems.Remove(key);
                _updateValuesList = true; // values list is to be updated
                return true;
            }

            // check if single value matches the value to be removed)
            if (!Equals(existingItem, value)) return false;

            removed = _singleItems.Remove(key);
            if (removed && _valuesCount >= 0) _valuesCount--;
            return removed;
        }

        /// <summary>
        /// Remove a key/value pair
        /// </summary>
        /// <param name="item">key/value pair</param>
        /// <returns>true, if key/value pair has been removed</returns>
        public bool Remove(KeyValuePair<TKey, TValue> item)
        {
            return Remove(item.Key, item.Value);
        }

        /// <summary>
        /// Check if dictionary contains a key
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>true, if dictionary contains the specific key</returns>
        public bool ContainsKey(TKey key)
        {
            return _singleItems.ContainsKey(key) || _multiItems.ContainsKey(key);
        }

        /// <summary>
        /// Check if dictionary contains a key/value pair
        /// </summary>
        /// <param name="item">key</param>
        /// <returns>true, if dictionary contains the specific key</returns>
        public bool Contains(KeyValuePair<TKey, TValue> item)
        {
            TValue existingItem;

            if (_singleItems.TryGetValue(item.Key, out existingItem))
                return _singleItems.Contains(item);

            List<TValue> existingList;
            return _multiItems.TryGetValue(item.Key, out existingList) && existingList.Contains(item.Value);
        }

        /// <summary>
        /// Gets a list of keys
        /// </summary>
        public ICollection<TKey> Keys
        {
            get
            {
                if (_updateKeysList) UpdateAllKeys();
                return new ReadOnlyCollection<TKey>(_allKeys);
            }
        }

        /// <summary>
        /// Try to get the first single value of a specific key
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        /// <returns></returns>
        public bool TryGetValue(TKey key, out TValue value)
        {
            TValue existingItem;
            List<TValue> existingList;

            // check if there is a single item
            if (_singleItems.TryGetValue(key, out existingItem))
            {
                value = existingItem;
                return true;
            }

            // check if there are multiple items
            if (!_multiItems.TryGetValue(key, out existingList))
            {
                // item not found
                value = default(TValue);
                return false;
            }

            value = existingList.First();
            return true;
        }

        /// <summary>
        /// Gets a list of all values
        /// </summary>
        public ICollection<TValue> Values
        {
            get
            {
                if (_updateValuesList) UpdateAllValues();
                return new ReadOnlyCollection<TValue>(_allValues);
            }
        }

        /// <summary>
        /// Indexer
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>value</returns>
        /// <exception cref="KeyNotFoundException">The given key was not present in the dictionary.</exception>
        public TValue this[TKey key]
        {
            get
            {
                TValue itemValue;
                if (TryGetValue(key, out itemValue)) return itemValue;
                throw new KeyNotFoundException("The given key was not present in the dictionary.");
            }
            set
            {
                TValue existingItem;
                List<TValue> existingList;

                // check if there is a single item
                if (_singleItems.TryGetValue(key, out existingItem))
                {
                    _singleItems[key] = value;
                    _updateValuesList = true; // to be updated if needed
                    return;
                }

                // check if there are multiple items
                if (_multiItems.TryGetValue(key, out existingList))
                {
                    // overwrite multiple items with single item
                    if (_valuesCount >= 0) _valuesCount -= existingList.Count - 1;
                    _multiItems.Remove(key);
                    _singleItems[key] = value;
                    _updateValuesList = true; // to be updated if needed
                    return;
                }

                // add single item
                _singleItems.Add(key, value);
                if (!_updateKeysList) _allKeys.Add(key);
                if (!_updateValuesList) _allValues.Add(value);
                if (_valuesCount >= 0) _valuesCount++;
            }
        }

        /// <summary>
        /// Clear collection
        /// </summary>
        public void Clear()
        {
            _multiItems.Clear();
            _singleItems.Clear();
            _allKeys.Clear();
            _allValues.Clear();
            _valuesCount = 0;
        }

        /// <summary>
        /// Copy key/pair values to
        /// </summary>
        /// <param name="array">array to copy to</param>
        /// <param name="arrayIndex">array index to start with</param>
        public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
        {
            int index = arrayIndex;
            foreach (var pair in this)
                array[index++] = pair;
        }

        /// <summary>
        /// Gets the number of values in dictionary
        /// </summary>
        public int Count
        {
            get
            {
                if (_valuesCount < 0) _valuesCount = GetValuesCount();
                return _valuesCount;
            }
        }

        /// <summary>
        /// Get all values for specific key
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>collection of values</returns>
        public IEnumerable<TValue> GetValues(TKey key)
        {
            TValue existingItem;
            List<TValue> existingList;

            if (_singleItems.TryGetValue(key, out existingItem))
            {
                yield return existingItem;
                yield break;
            }

            if (!_multiItems.TryGetValue(key, out existingList))
            {
                // no items found for key
                yield break;
            }

            foreach (var value in existingList)
                yield return value;
        }

        /// <summary>
        /// Update values count
        /// </summary>
        /// <returns>number of values in dictionary</returns>
        private int GetValuesCount()
        {
            var count = _singleItems.Count;
            foreach (var list in _multiItems.Values)
                count += list.Count;
            return count;
        }

        /// <summary>
        /// Update internal list of all keys
        /// </summary>
        private void UpdateAllKeys()
        {
            _allKeys.Clear();
            _allKeys.AddRange(_singleItems.Keys);
            _allKeys.AddRange(_multiItems.Keys);
        }

        /// <summary>
        /// Update internal list of all values
        /// </summary>
        private void UpdateAllValues()
        {
            _allValues.Clear();
            _allValues.AddRange(_singleItems.Values);

            foreach (var list in _multiItems)
                foreach (var item in list.Value)
                    _allValues.Add(item);
        }

        /// <summary>
        /// Get generic enumerator for all KeyValuePairs of dictionary
        /// </summary>
        /// <returns>Generic enumerator for all KeyValuePairs of dictionary</returns>
        public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
        {
            foreach (var item in _singleItems)
                yield return item;

            foreach (var item in _multiItems)
                foreach (var value in item.Value)
                    yield return new KeyValuePair<TKey, TValue>(item.Key, value);
        }

        /// <summary>
        /// Get enumerator interface for all KeyValuePairs of dictionary
        /// </summary>
        /// <returns>Enumerator interface for all KeyValuePairs of dictionary</returns>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


text:
package com.diaodu.service;

import java.sql.SQLException;

import com.diaodu.dao.ETLDao;
import com.diaodu.dao.impl.ETLDaoImpl;
import com.diaodu.db.JDBCUtils;
import com.diaodu.domain.ETL;

public class ETLService {

	public int updateETL(ETL etl){
		int elts = 0;
		JDBCUtils.startTransaction();
		try {
			ETLDao etldao = new ETLDaoImpl();
			elts = etldao.updateETL(etl);
		} catch (SQLException e) {
			e.printStackTrace();
			JDBCUtils.rollback();
		}finally {
			JDBCUtils.close();
		}
		return elts;
	}

	public int updateSchedulingByID(int etl_id,int is_scheduling){
		int elts = 0;
		JDBCUtils.startTransaction();
		try {
			ETLDao etldao = new ETLDaoImpl();
			elts = etldao.updateSchedulingByID(etl_id,is_scheduling);
		} catch (SQLException e) {
			JDBCUtils.rollback();
			e.printStackTrace();
		}finally {
			JDBCUtils.close();
		}
		return elts;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Giosh94mhz\GeonamesBundle\Import\StepBuilder;

use Giosh94mhz\GeonamesBundle\Entity\Admin1;
use Giosh94mhz\GeonamesBundle\Model\Toponym;
use Doctrine\Common\Persistence\ObjectManager;

/**
 *
 * @author Premi Giorgio <giosh94mz@gmail.com>
 *
 */
class Admin1ImportStepBuilder extends AbstractAdminImportStepBuilder
{
    /**
     * @var \Doctrine\Common\Persistence\ObjectRepository
     */
    protected $repository;

    public function __construct(ObjectManager $om)
    {
        parent::__construct($om);
        $this->repository = $this->om->getRepository('Giosh94mhzGeonamesBundle:Admin1');
    }

    public function getClass()
    {
        return 'Admin1';
    }

    public function getUrl()
    {
        return self::GEONAME_DUMP_URL . 'admin1CodesASCII.txt';
    }

    protected function buildAdminEntity($value, Toponym $toponym)
    {
        /* @var $admin \Giosh94mhz\GeonamesBundle\Entity\Admin1 */
        $admin = $this->repository->find($toponym) ?: new Admin1($toponym);

        $admin
            ->setCode($value[5])
            ->setCountryCode($value[4])
            ->setName($value[1])
            ->setAsciiName($value[2])
        ;

        return $admin;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.2"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Hardware Abstraction Layer (HAL)</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Hardware Abstraction Layer (HAL)

I2S (Inter-IC Sound)
CAT1 (PSoC™ 6) Implementation Specific

The CAT1 (PSoC™ 6) I2S Supports the following values for word lengths:

8 bits

10 bits (CAT1B only)

12 bits (CAT1B only)

14 bits (CAT1B only)

16 bits

18 bits

20 bits

24 bits

32 bits

The channel length must be greater than or equal to the word length. On CAT1A devices, the set of supported channel lengths is the same as the set of supported word lengths. On CAT1B devices, the channel length may be any value between 8 and 32 bits.

The sclk signal is formed by integer division of the input clock source (either internally provided or from the mclk pin). The CAT1A I2S supports sclk divider values from 1 to 64. On CAT1B devices, the I2S supports sclk divider values from 2 to 256.

On CAT1A devices, if both RX and TX are used, the same GPIO must be specified for mclk in both directions. See the device datasheet for more details on valid pin selections.

The following events are not supported on CAT1B:

CYHAL_I2S_TX_EMPTY

CYHAL_I2S_TX_NOT_FULL

CYHAL_I2S_RX_FULL

CYHAL_I2S_RX_NOT_EMPTY

Note

If the I2S hardware is initialized with a configurator-generated configuration via the cyhal_i2s_init_cfg function, the CYHAL_I2S_TX_HALF_EMPTY and CYHAL_I2S_RX_HALF_FULL events will be raised at the configurator defined TX and RX FIFO trigger levels, respectively, instead of their usual trigger level of half the FIFO depth.


text: SimplGUI is simple GUI library for SFML. It provides simple widgets that can be used independently.


text:
// ***********************************************************************
// Copyright (c) 2017 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using System;
using System.Collections.Generic;
using NUnit.Framework.Interfaces;

namespace NUnit.Framework.Internal.Commands
{
    /// <summary>
    /// OneTimeTearDownCommand performs any teardown actions
    /// specified for a suite and calls Dispose on the user
    /// test object, if any.
    /// </summary>
    public class DisposeFixtureCommand : AfterTestCommand
    {
        /// <summary>
        /// Construct a OneTimeTearDownCommand
        /// </summary>
        /// <param name="innerCommand">The command wrapped by this command</param>
        public DisposeFixtureCommand(TestCommand innerCommand)
            : base(innerCommand)
        {
            Guard.OperationValid(Test is IDisposableFixture, "DisposeFixtureCommand does not apply to a " + Test.GetType().Name);

            AfterTest = (context) =>
            {
                try
                {
                    IDisposable disposable = context.TestObject as IDisposable;
                    if (disposable != null)
                        disposable.Dispose();
                }
                catch (Exception ex)
                {
                    context.CurrentResult.RecordTearDownException(ex);
                }
            };
        }
    }
}


text:
<!DOCTYPE html>

		<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
		<meta name="author" content="www.frebsite.nl" />
		<meta name="viewport" content="width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=yes" />
		<meta name="robots" content="noindex, nofollow" />

		<title>jQuery.mmenu » Color themes</title>

		<link type="text/css" rel="stylesheet" href="../docs.css" />
		<link type="text/css" rel="stylesheet" href="../../mmenu.css" />
		<link type="text/css" rel="stylesheet" href="../../mmenu-theme-light.css" />

				Color themes

The menu on this page uses a light gray (#DDD) theme.

This is a demo page.

					Click the menu-button in the header to open the menu.

Default theme

Default light theme

Shades of gray

Dark gray

Light Gray

Colors

Bordeau

Army

Navy


text:
<TITLE>Review for Almost Heroes (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Almost Heroes (1998)

reviewed by
Matt Williams

ALMOST HEROES
A film review by Matt Williams

RATING: [zero stars] out of * * * *

It's sad...Chris Farley's last film is also his worst.  It's a bad
epitaph, and a worse movie.

Matthew Perry stars as Leslie Edwards, an explorer whose goal is to beat
Lewis and Clark to the Pacific Ocean.  To achieve this goal, he hires
the second best tracker in early America, Bartholomew Hunt (Chris
Farley), a drunken buffoon who has blundered his way into his
reputation.

And that's about all there is which passes for plot in this film. Their
party contains some purportedly colorful characters such as jealous
Frenchman Guy Fontenot (Eugene Levy), and encounters some purportedly
colorful characters, such as the vain Spaniard Hidalgo (Kevin Dunn), but
someone, somewhere forgot the humor.

There are only two sequences in the entire film which are barely
chuckle-worthy (Farley's eagle trials, and the group of elderly
warriors). But they in no way can justify anyone in their right mind
suffering through the rest of this atrocious film.

Die-hard fans of Farley will undoubtedly visit this travesty even though
they would be better served by reviewing his best work: his skits on
SNL. Farley was never able to locate a worthy movie for his talents.
(Tommy Boy was the closest, but a messy and cluttered attempt that was
more miss than hit.)  Perhaps the problem was his reliance on the
"fat-guy-falls-down" brand of humor that worked well in sketch comedy,
but seemed labored when stretched out to fill a full movie. He never was
able to either transcend the juvenile level of humor, or to make a movie
filled with juvenile humor actually entertaining.

But, if Farley did a bad job here, at least he had company. Matthew
Perry does a horrifically bad job.  He actually manages to outshine
Farley in the overacting category - an impressive feat, mind you, but
not one conducive to a pleasant viewing experience.  The rest of the
cast are for the most part forgettable (a fact which I'm sure many of
them will appreciate).

Director Christopher Guest takes a major wrong turn after his appealing
Waiting for Guffman. Almost Heroes wallows in stupidity...not
stupid-funny...just plain stupid. I got the feeling that some of the
material might have played better had the movie allowed itself to stray
from the rigidity of its plot.  For example, the subplot involving an
injury prone explorer could have actually been humorous if the movie
allowed its tone to resemble that of say, Monty Python and the Holy
Grail, or even South Park.  But, no, the movie never strays far from
reality, and as a result, the humor stays grounded.

Why were Edwards and Hunt left out of the history books? Anyone who sees
this movie will have a good idea: it's definitely not something you want
to remember.

Copyright 1998 Matt Williams

- Matt Williams (matt@cinematter.com)
Reviewer for Cinematter: http://www.cinematter.com
Home of over 500 reviews, and information on over 600 upcoming releases

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
LabJack-process_manager handling multiple processes example
=======================

To get started, execute "npm install"

To run, execute "node main.js"


text:
'use strict';

// TODO (bvaughn) Enable Fiber experiement via ReactNativeFeatureFlags
module.exports = require('ReactNativeStack');


text:
<?php
abstract class DatabaseQuery {
  protected $group_by = array();
  protected $order_by = array();
  protected $where = array();
  protected $where_raw = '';
  protected $limit = array();
  protected $tables = array();

  protected $current_table = false;
  protected $primary_key = false;
  protected $model = false;

  public function __construct($table, $primary_key, $model) {
    $this->model = $model;

    $this->setTable($table);

    $this->primary_key = array();

    if ($primary_key) {
      $primary_key = is_array($primary_key) ? $primary_key : array($primary_key);

      foreach ($primary_key as $key) {
        if (!preg_match('#^[a-zA-Z0-9_-]++$#', $key)) {
          trigger_error('Primary key is not correct: '. $key);
          exit;
        }

        $this->primary_key[] = $key;
      }
    }
  }

  public function setTable() {
    $args = func_get_args();
    $tables = array();

    foreach ($args as $arg) {
      if (!$arg) {
        continue;
      }

      if (!is_array($arg)) {
        $tables[] = $arg;
        continue;
      }

      foreach ($arg as $_arg) {
        if (is_array($_arg)) {
          continue;
        }

        $tables[] = $_arg;
      }
    }

    $this->tables = array();
    $this->current_table = false;

    if (!count($tables)) {
      return $this;
    }

    foreach ($tables as $t) {
      if (!preg_match('#^([a-zA-Z0-9_-]+)(?:\s++[a-zA-Z0-9_-]++)?$#', $t, $data)) {
        trigger_error('incorrect table name: ' . $t);
        exit;
      }

      $this->current_table = $data[0];
      $this->tables[] = $t;
    }

    if (count($tables) > 1) {
      $this->current_table = false;
    }

    return $this;
  }

  public function from() {
    return call_user_func_array(
      array($this, 'setTable'),
      func_get_args()
    );
  }

  public function find() {
    $args = func_get_args();
    $ids = array();

    foreach ($args as $arg) {
      if (!is_array($arg)) {
        $ids[] = $arg;
        continue;
      }

      foreach ($arg as $_a) {
        if (is_array($_a)) {
          // omg
          continue;
        }

        $ids[] = $_a;
      }
    }

    if (!count($this->primary_key)) {
      return false;
    }

    if (count($this->primary_key) != count($ids)) {
      trigger_error('all the primary keys need to be specified');
      exit;
    }

    for ($i = 0, $end = count($this->primary_key); $i < $end; ++$i) {
      $this->whereAnd($this->primary_key[$i], '=', $ids[$i]);
    }

    if (!$this->current_table) {
      trigger_error('table must be specified');
      exit;
    }

    $query = 'SELECT * FROM ' . $this->escapeTable($this->current_table) . ' ' . $this->makeQuery();
    $rows = $this->query($query);

    if (!is_array($rows)) {
      return false;
    }

    if (count($rows) != 1) {
      return false;
    }

    if ($this->model) {
      $model = new $this->model;
    }
    else {
      $model = new Database($this->current_table);
    }

    if (!$model->initRow($rows[0])) {
      trigger_error('model initialization error');
      exit;
    }

    return $model;
  }

  public function get() {
    if (!($from = $this->makeFromQuery())) {
      return false;
    }

    $query = 'SELECT * FROM ' . $from . ' ' . $this->makeQuery();
    $rows = $this->query($query);

    if (!is_array($rows)) {
      return false;
    }

    $ret = array();

    foreach ($rows as $row) {
      if ($this->model) {
        $model = new $this->model;
      }
      else {
        $model = new Database($this->current_table);
      }

      if (!$model->initRow($row)) {
        trigger_error('model initialization error');
        exit;
      }

      $ret[] = $model;
    }

    return $ret;
  }

  public function all() {
    return $this->get();
  }

  public function count() {
    if (!($from = $this->makeFromQuery())) {
      return false;
    }

    $query = 'SELECT COUNT(*) as count FROM ' . $from . ' ' . $this->makeQuery();
    $rows = $this->query($query);

    if (!is_array($rows)) {
      return false;
    }

    if (!isset($rows[0]['count'])) {
      return false;
    }

    return (int)($rows[0]['count']);
  }

  public function update($attributes) {
    if (!is_array($attributes) || !count($attributes)) {
      return false;
    }

    if (!$this->current_table) {
      trigger_error('table must be specified');
      exit;
    }

    $query = '';

    foreach ($attributes as $key => $value) {
      if ($query) {
        $query .= ', ';
      }

      $query .= $this->escapeFieldName($key);
      $query .= ' = ' . $this->escapeFieldValue($value);
    }

    $query = 'UPDATE ' . $this->escapeTable($this->current_table) . ' SET ' . $query . ' ' . $this->makeQuery();

    return !!$this->query($query);
  }

  public function insert($attributes) {
    if (!is_array($attributes) || !count($attributes)) {
      return false;
    }

    if (!$this->current_table) {
      trigger_error('table must be specified');
      exit;
    }

    $query = '';

    foreach ($attributes as $key => $value) {
      if ($query) {
        $query .= ', ';
      }

      $query .= $this->escapeFieldName($key);
      $query .= ' = ' . $this->escapeFieldValue($value);
    }

    $query = 'INSERT INTO ' . $this->escapeTable($this->current_table) . ' SET ' . $query;

    return !!$this->query($query);
  }

  public function delete() {
    if (!$this->current_table) {
      trigger_error('table must be specified');
      exit;
    }

    $query = 'DELETE FROM ' . $this->escapeTable($this->current_table) . ' ' . $this->makeQuery();
    return !!$this->query($query);
  }

  public function where($field, $comparison_operator, $arg, $logical_operator = 'AND', $arg_type = 'variable') {
    $this->where_raw = '';

    if (!in_array($comparison_operator, array('<', '<=', '=', '>=', '>', '<>', '!=', 'LIKE', 'IN'))) {
      trigger_error('incorrect operator: ' . $comparison_operator);
      exit;
    }

    $this->where[] = array(
      'field' => $field,
      'comparison_operator' => $comparison_operator,
      'logical_operator' => $logical_operator,
      'arg' => $arg,
      'arg_type' => $arg_type == 'variable' ? 'variable' : 'field',
    );

    return $this;
  }

  public function whereOr($field, $operator, $arg, $arg_type = 'variable') {
    return $this->where($field, $operator, $arg, 'OR', $arg_type);
  }

  public function whereAnd($field, $operator, $arg, $arg_type = 'variable') {
    return $this->where($field, $operator, $arg, 'AND', $arg_type);
  }

  public function whereRaw($query, $args = array()) {
    $this->where = array();

    $args_count = count($args);
    $ph_count = 0;

    for ($i = 0, $len = strlen($query); $i < $len; ++$i) {
      if ($query[$i] == '?') {
        ++$ph_count;
      }
    }

    if ($args_count != $ph_count) {
      trigger_error('placeholders amount must mutch arguments amount');
      exit;
    }

    if ($ph_count == 0) {
      $this->where_raw = $query;
      return $this;
    }

    $sprintf_args = array(
      str_replace(
        array('%', '?'),
        array('%%', '%s'),
        $query
      )
    );

    foreach ($args as $arg) {
      $sprintf_args[] = $this->escapeFieldValue($value);
    }

    $this->where_raw = call_user_func_array(
      'sprintf',
      $sprintf_args
    );

    return $this;
  }

  public function orderBy($order_field, $order_type = 'asc') {
    $order_type = strtolower($order_type);

    if (!in_array($order_type, array('asc', 'desc'))) {
      trigger_error('incorrect order type: ' . $order_type);
      exit;
    }

    $this->order_by[] = array(
      'field' => $order_field,
      'type' => $order_type,
    );

    return $this;
  }

  public function groupBy($group_field) {
    $this->group_by[] = $group_field;

    return $this;
  }

  public function limit($count, $start = 0) {
    $count = (int)$count;
    $start = (int)$start;

    $this->limit = array(
      'count' => $count,
      'start' => $start,
    );

    return $this;
  }

  protected function makeQuery() {
    $query  = '';
    $query .= ' ' . $this->makeWhere() . ' ';
    $query .= ' ' . $this->makeGroupBy() . ' ';
    $query .= ' ' . $this->makeOrderBy() . ' ';
    $query .= ' ' . $this->makeLimit() . ' ';

    return $query;
  }

  protected function makeFromQuery() {
    if (!count($this->tables)) {
      return false;
    }

    $query = '';

    foreach($this->tables as $table) {
      if ($query) {
        $query .= ', ';
      }

      $query .= $this->escapeTable($table);
    }

    return $query;
  }

  protected function makeWhere() {
    if ($this->where_raw) {
      return 'WHERE ' . $this->where_raw;
    }

    if (!count($this->where)) {
      return '';
    }

    $query = '';

    foreach ($this->where as $where) {
      if ($query) {
        $query .= ' ' . ($where['logical_operator'] == 'OR' ? 'OR' : 'AND') . ' ';
      }

      $query .= $this->escapeFieldName($where['field']);
      $query .= ' ' . $where['comparison_operator'] . ' ';

      if ($where['comparison_operator'] == 'IN') {
        $_in   = array();
        $_args = is_array($where['arg']) ? $where['arg'] : array($where['arg']);

        foreach ($_args as $arg) {
          $_in[] = $this->escapeFieldValue($arg);
        }

        $query .= '(' . implode(',', $_in) . ')';

        $_args = null;
        $_in   = null;
      }
      else {
        if ($where['arg_type'] == 'variable') {
          $query .= $this->escapeFieldValue($where['arg']);
        }
        else {
          $query .= $this->escapeFieldName($where['arg']);
        }
      }
    }

    return 'WHERE ' . $query;
  }

  protected function makeGroupBy() {
    if (!count($this->group_by)) {
      return '';
    }

    $query = '';

    foreach ($this->group_by as $group_by) {
      if ($query) {
        $query .= ', ';
      }

      $query .= $this->escapeFieldName($group_by);
    }

    return 'GROUP BY ' . $query;
  }

  protected function makeOrderBy() {
    if (!count($this->order_by)) {
      return '';
    }

    $query = '';

    foreach ($this->order_by as $order_by) {
      if ($query) {
        $query .= ', ';
      }

      $query .= $this->escapeFieldName($order_by['field']) . ' ' . $order_by['type'];
    }

    return 'ORDER BY ' . $query;
  }

  protected function makeLimit() {
    if (!isset($this->limit['start']) || !isset($this->limit['count'])) {
      return '';
    }

    return 'LIMIT ' . $this->limit['start'] . ', ' . $this->limit['count'];
  }

  public abstract function tableExists();
  public abstract function query($query);
  public abstract function escape($data);
  public abstract function getAutoIncrementField();
  public abstract function getLastAutoIncrementValue();
  public abstract function escapeFieldName($name);
  public abstract function escapeFieldValue($value);
  public abstract function escapeTable($table);
}
?>


text:
import re

import numpy as np
import pytest

import pandas as pd

class TestSetitemValidation:
    def _check_setitem_invalid(self, arr, invalid):
        msg = f"Invalid value '{str(invalid)}' for dtype {arr.dtype}"
        msg = re.escape(msg)
        with pytest.raises(TypeError, match=msg):
            arr[0] = invalid

        with pytest.raises(TypeError, match=msg):
            arr[:] = invalid

        with pytest.raises(TypeError, match=msg):
            arr[[0]] = invalid

        # FIXME: don't leave commented-out
        # with pytest.raises(TypeError):
        #    arr[[0]] = [invalid]

        # with pytest.raises(TypeError):
        #    arr[[0]] = np.array([invalid], dtype=object)

        # Series non-coercion, behavior subject to change
        ser = pd.Series(arr)
        with pytest.raises(TypeError, match=msg):
            ser[0] = invalid
            # TODO: so, so many other variants of this...

    _invalid_scalars = [
        1 + 2j,
        "True",
        "1",
        "1.0",
        pd.NaT,
        np.datetime64("NaT"),
        np.timedelta64("NaT"),
    ]

    @pytest.mark.parametrize(
        "invalid", _invalid_scalars + [1, 1.0, np.int64(1), np.float64(1)]
    )
    def test_setitem_validation_scalar_bool(self, invalid):
        arr = pd.array([True, False, None], dtype="boolean")
        self._check_setitem_invalid(arr, invalid)

    @pytest.mark.parametrize("invalid", _invalid_scalars + [True, 1.5, np.float64(1.5)])
    def test_setitem_validation_scalar_int(self, invalid, any_int_ea_dtype):
        arr = pd.array([1, 2, None], dtype=any_int_ea_dtype)
        self._check_setitem_invalid(arr, invalid)

    @pytest.mark.parametrize("invalid", _invalid_scalars + [True])
    def test_setitem_validation_scalar_float(self, invalid, float_ea_dtype):
        arr = pd.array([1, 2, None], dtype=float_ea_dtype)
        self._check_setitem_invalid(arr, invalid)