text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<title>Fils de syndication

					 - Plugiciels

				 - Documentation

 - Boîte à outils de l'expérience Web
</title>
		<meta content="width=device-width, initial-scale=1" name="viewport" />

		<meta name="description" content="Affiche les articles d'un ou plus fils de syndication." />

<link href="../../../assets/favicon.ico" rel="icon" type="image/x-icon" />
<link rel="stylesheet" href="../../../css/wet-boew.css" />

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

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

		Passer au contenu principal

		Passer à « À propos de ce site »

Sélection de la langue

Français (actuel)

English

Recherche et menus

Recherche et menus

	<object type="image/svg+xml" tabindex="-1" data="../../../assets/logo.svg"></object>
	Boîte à outils de l'expérience Web, Projet à source ouverte collaboratif dirigé par le Gouvernement du Canada

Recherche

					<form action="https://google.ca/search" method="get" role="search" class="form-inline">

		Recherchez le site Web
		<input id="wb-srch-q" class="form-control" name="q" type="search" value="" size="27" maxlength="150" />
		<input type="hidden" name="q" value="site:wet-boew.github.io OR site:github.com/wet-boew/" />

	<button type="submit" id="wb-srch-sub" class="btn btn-default">Recherche</button>

</form>

Menu des sujets

Projet de la BOEW

Mise en œuvre de la BOEW

Contribuer à la BOEW

Vous êtes ici :

				Accueil

						Documentation

						Plugiciels

Fils de syndication

Fils de syndication

Vous cherchez la BOEW v3.1?

À partir du 23 septembre 2014, la version 3.1 de la Boîte à outils de l'expérience Web n'est plus supportée. Le code source et la documentation ont été déplacés vers le dépôt wet-boew-legacy.

	Questions ou commentaires?

But

Cette composante est un gadget logiciel permettant de regrouper et d'afficher des données d'un ou plusieurs fils de syndication. Les formats soutenus sont Atom, RSS et Media RSS.

Utiliser lors

de la promotion et le partage d'information de fils de syndication sur une page Web

Exemples

Exemple anglais

Exemple français

Comment implémenter

Pour chaque zone qui affiche des fils de syndication, créer un élément section avec class="wb-feeds".

<section class="wb-feeds"></section>

Dans l'élément section, ajouter une entête (h1 - h6).

Ajouter une liste non-ordonnée (ul) après l'entête avec la classe feeds-cont.

Fils de syndication Facebook :

Ajouter la classe media-list à la liste non-ordonnée.

Ajouter <div class="clearfix"></div> après la liste non-ordonnée.

Fils de syndication Flickr et YouTube :

Ajouter la classe list-inline à la liste non-ordonnée.

Ajouter <div class="clearfix"></div> après la liste non-ordonnée.

Pour chaque source de fil de syndication à afficher, ajouter un élément de liste contenant un lien vers le fil.

Fils de syndication ordinaires :

<li>
	<a href="http://canada.ca/sample.atom">Exemple de flux Atom</a>
</li>

Fils de syndication Facebook :

Ajouter la classe media à l'élément liste.

Ajouter la classe pull-left au lien.

Ajouter une image de profile avec la classe media-object au lien.

Ajouter une élément section avec la classe media-body après le lien.

À l'intérieur de l'élément section, ajouter une entête (h1 - h6) avec la classe media-heading. Ajouter le nom du compte Facebook dans cette entête (e.g., "Parcs Canada - Facebook").

Ajouter un élément p contenant la description du compte Facebook après l'entête.

<li class="media">
	<a class="pull-left" href="https://www.facebook.com/feeds/page.php?id=134615279898518&amp;format=atom10">
		<img class="media-object" src="http://graph.facebook.com/134615279898518/picture?type=large" alt="Logo Parcs Canada" width="64" />
	</a>
	<section class="media-body">
		<h4 class="media-heading"><a href="https://www.facebook.com/feeds/page.php?id=134615279898518&amp;format=atom10" rel="external">Parcs Canada - Facebook</a></h4>
		<p>Les parcs nationaux, aires marines nationales de conservation et lieux historiques nationaux du Canada.</p>
	</section>
</li>

Fils de syndication Flickr :

L'attribut href du lien doit contenir l'URL du fil-photo du compte Flickr.

Ajouter l'attribut data-ajax au lien contenant l'URL du fil JSON du compte Flickr (en anglais seulement).

<li>
	<a href="https://www.flickr.com/photos/environmentcan" rel="external" data-ajax="https://api.flickr.com/services/feeds/photos_public.gne?id=47721741@N05&format=json">Flickr d'Environnement Canada</a>
</li>

Fils de syndication YouTube :

L'attribut href du lien doit contenir l'URL du compte YouTube.

Ajouter l'attribut data-ajax au lien contenant l'URL du fil JSON du compte YouTube.

<li>
	<a href="https://www.youtube.com/user/ParksCanadaAgency" rel="external" data-ajax="https://gdata.youtube.com/feeds/api/users/UCr23fllByMomgNGeShe-73g/uploads?v=2&alt=json">YouTube de Parcs Canada</a>
</li>

Facultatif : Regrouper plusieurs types de fils de syndication dans une interface à onglets. L'avantage de cette approche est qu'elle ne charge que les fils qui sont actuellement visibles (ce qui améliore considérablement la performance lorsqu'il y a beaucoup d'éléments).

Créer un élément div avec la classe class="wb-tabs".

Ajouter un élément divavec class="tabpanels" à l'intérieur de l'élément div précédent.

Pour chaque groupe de flux (regrouper les fils par type), ajouter un élément details. Ajouter l'attribut open="open" au groupe de fils qui doit être affiché par défaut.

Ajouter un élément summary au début de chaque élément details avec le nom du groupe de fils (e.g., <summary>Facebook</summary>).

Ajouter les zonnes pour afficher les flux Web après chaque élément summary tel que décrit aux étapes 1 à 4, mais avec l'exception d'ajouter la classe wb-inv à l'entête de chaque zone.

<section>
	<h3>Les comptes des médias sociaux à onglets</h3>
	<div class="wb-tabs col-md-5 wb-eqht">
		<div class="tabpanels">
			<details id="details-facebook" open="open">
				<summary>Facebook</summary>
				<section class="wb-feeds limit-5">
					<h4 class="wb-inv">Facebook</h4>
					<ul class="feeds-cont media-list">
						...
					</ul>
					<div class="clearfix"></div>
				</section>
			</details>

			<details id="details-flickr">
				<summary>Flickr</summary>
				<section class="wb-feeds limit-10">
					<h4 class="wb-inv">Flickr</h4>
					<ul class="feeds-cont list-inline">
						...
					</ul>
					<div class="clearfix"></div>
				</section>
			</details>

			<details id="details-youtube">
				<summary>YouTube</summary>
				<section class="wb-feeds limit-10">
					<h4 class="wb-inv">YouTube</h4>
					<ul class="feeds-cont list-inline">
						...
					</ul>
					<div class="clearfix"></div>
				</section>
			</details>
		</div>
	</div>
	<div class="clearfix"></div>
</section>

Exemples de code

Fils de syndication ordinaires

<section class="wb-feeds limit-5">
	<h3>Communiqués de presse et rappels de la sécurité routière</h3>
	<ul class="feeds-cont">
		<li>
			<a href="http://www.tc.gc.ca/medias/rss/routier.xml" rel="external">Communiqués de presse routière (Tous)</a>
		</li>
		<li>
			<a href="http://wwwapps.tc.gc.ca/Saf-Sec-Sur/7/VRDB-BDRV/search-recherche/rss.aspx?lang=fra" rel="external">Rappels de la Sécurité Routière</a>
		</li>
	</ul>
</section>

Fils de syndication Facebook

<section class="wb-feeds limit-5">
	<ul class="feeds-cont media-list">
		<li class="media">
			<a class="pull-left" href="https://www.facebook.com/feeds/page.php?id=460123390028&format=atom10">
				<img class="media-object" src="http://graph.facebook.com/460123390028/picture?type=large" alt="Logo Environnement Canada" width="64" />
			</a>
			<section class="media-body">
				<h4 class="media-heading"><a href="https://www.facebook.com/feeds/page.php?id=460123390028&format=atom10" rel="external">Environnement Canada - Facebook</a></h4>
				<p>EC est une organisation diversifiée offrant des programmes et des services efficaces et regroupant des gens dynamiques qui font une différence sur le plan environnemental et dans différents aspects de la vie des Canadiennes et Canadiens..</p>
			</section>
		</li>
		<li class="media">
			<a class="pull-left" href="https://www.facebook.com/feeds/page.php?id=134615279898518&format=atom10">
				<img class="media-object" src="http://graph.facebook.com/134615279898518/picture?type=large" alt="Logo Parcs Canada" width="64" />
			</a>
			<section class="media-body">
				<h4 class="media-heading"><a href="https://www.facebook.com/feeds/page.php?id=134615279898518&format=atom10" rel="external">Parcs Canada- Facebook</a></h4>
				<p>Les parcs nationaux, aires marines nationales de conservation et lieux historiques nationaux du Canada.</p>
			</section>
		</li>
	</ul>
	<div class="clearfix"></div>
</section>

Fils de syndication Flickr

<section class="wb-feeds limit-15">
	<ul class="feeds-cont list-inline">
		<li>
			<a href="https://www.flickr.com/photos/environnementcan" rel="external" data-ajax="https://api.flickr.com/services/feeds/photos_public.gne?id=47721741@N05&format=json">Flickr d'Environnement Canada</a>
		</li>
	</ul>
	<div class="clearfix"></div>
</section>

Fils de syndication YouTube

<section class="wb-feeds limit-15">
	<ul class="feeds-cont list-inline">
		<li>
			<a href="https://www.youtube.com/user/ParksCanadaAgency" rel="external" data-ajax="https://gdata.youtube.com/feeds/api/users/UCr23fllByMomgNGeShe-73g/uploads?v=2&alt=json">YouTube de Parcs Canada</a>
		</li>
		<li>
			<a href="https://www.youtube.com/user/fisheriescanada?feature=results_main" rel="external" data-ajax="https://gdata.youtube.com/feeds/api/users/UCf1JLCB96nHLjidhSJtHDFA/uploads?v=2&alt=json">YouTube de Pêches et Océans Canada</a>
		</li>
	</ul>
	<div class="clearfix"></div>
</section>

Les comptes des médias sociaux à onglets

<section>
	<h3>Les comptes des médias sociaux à onglets</h3>
	<div class="wb-tabs col-md-5 wb-eqht">
		<div class="tabpanels">
			<details id="details-facebook" open="open">
				<summary>Facebook</summary>
				<section class="wb-feeds limit-5">
					<h4 class="wb-inv">Facebook</h4>
					<ul class="feeds-cont media-list">
						<li class="media">
							<a class="pull-left" href="https://www.facebook.com/feeds/page.php?id=460123390028&format=atom10">
								<img class="media-object" src="http://graph.facebook.com/460123390028/picture?type=large" alt="Logo Environnement Canada" width="64" />
							</a>
							<section class="media-body">
								<h4 class="media-heading"><a href="https://www.facebook.com/feeds/page.php?id=460123390028&format=atom10" rel="external">Environnement Canada - Facebook</a></h4>
								<p>EC est une organisation diversifiée offrant des programmes et des services efficaces et regroupant des gens dynamiques qui font une différence sur le plan environnemental et dans différents aspects de la vie des Canadiennes et Canadiens.</p>
							</section>
						</li>
						<li class="media">
							<a class="pull-left" href="https://www.facebook.com/feeds/page.php?id=134615279898518&format=atom10">
								<img class="media-object" src="http://graph.facebook.com/134615279898518/picture?type=large" alt="Logo Parcs Canada" width="64" />
							</a>
							<section class="media-body">
								<h4 class="media-heading"><a href="https://www.facebook.com/feeds/page.php?id=134615279898518&format=atom10" rel="external">Parcs Canada- Facebook</a></h4>
								<p>Les parcs nationaux, aires marines nationales de conservation et lieux historiques nationaux du Canada.</p>
							</section>
						</li>
					</ul>
					<div class="clearfix"></div>
				</section>
			</details>

			<details id="details-flickr">
				<summary>Flickr</summary>
				<section class="wb-feeds limit-10">
					<h4 class="wb-inv">Flickr</h4>
					<ul class="feeds-cont list-inline">
						<li>
							<a href="https://www.flickr.com/photos/environnementcan" rel="external" data-ajax="https://api.flickr.com/services/feeds/photos_public.gne?id=47721741@N05&format=json">Flickr d'Environnement Canada</a>
						</li>
					</ul>
					<div class="clearfix"></div>
				</section>
			</details>

			<details id="details-youtube">
				<summary>YouTube</summary>
				<section class="wb-feeds limit-10">
					<h4 class="wb-inv">YouTube</h4>
					<ul class="feeds-cont list-inline">
						<li>
							<a href="https://www.youtube.com/user/ParksCanadaAgency" rel="external" data-ajax="https://gdata.youtube.com/feeds/api/users/UCr23fllByMomgNGeShe-73g/uploads?v=2&alt=json">YouTube de Parcs Canada</a>
						</li>
						<li>
							<a href="https://www.youtube.com/user/fisheriescanada?feature=results_main" rel="external" data-ajax="https://gdata.youtube.com/feeds/api/users/UCf1JLCB96nHLjidhSJtHDFA/uploads?v=2&alt=json">YouTube de Pêches et Océans Canada</a>
						</li>
					</ul>
					<div class="clearfix"></div>
				</section>
			</details>
		</div>
	</div>
	<div class="clearfix"></div>
</section>

Options de configuration

Documente les options de configuration publiques qui peuvent être utilisées par les intégrateurs ou les développeurs.

				Option
				Description
				Comment configurer
				Valeurs

				limit-x
				Contrôle le nombre d'items du fil de syndication que le widget affichera.
				Ajouter la classe limit-x après la classe wb-feeds et remplacer x avec nombre entier.

limit-4 (défaut):

Limite l'affichage à quatre items.

Événements

Documente les événements publics qui peuvent être utilisés par les intégrateurs ou les développeurs .

				Événement
				Déclencheur
				Ce qu'il fait

				wb-init.wb-feeds
				Déclenché manuellement (e.g., $( ".wb-feeds" ).trigger( "wb-init.wb-feeds" );).
				Utilisé pour initialiser manuellement le widget de fils de syndication. Note: Le widget de fils de syndication sera initialisé automatiquement à moins qu'il soit ajouté après le chargement initial de la page.

				wb-ready.wb-feeds (v4.0.5+)
				Déclenché automatiquement après que le plugiciel de fils de syndication ait été initialisé.
				Utilisé pour identifier où le plugiciel a fini d'être initialisé (cible de l'événement).

$( document ).on( "wb-ready.wb-feeds", ".wb-feeds", function( event ) {
});

$( ".wb-feeds" ).on( "wb-ready.wb-feeds", function( event ) {
});

				wb-feed-ready.wb-feeds (v4.0.5+)
				Déclenché automatiquement après que le fil de syndication soit devenu visible.
				Utilisé pour identifier quel fil est devenu visible (cible de l'événement).

$( document ).on( "wb-feed-ready.wb-feeds", ".wb-feeds .feeds-cont", function( event ) {
});

$( ".wb-feeds .feeds-cont" ).on( "wb-feed-ready.wb-feeds", function( event ) {
});

				wb-ready.wb (v4.0.5+)
				Déclenché automatiquement lorsque BOEW a terminé son chargement et son exécution.
				Utilisé pour identifier quand tous les plugiciels BOEW et les correctifs ont terminé leur chargement et leur exécution.

$( document ).on( "wb-ready.wb", function( event ) {
});

Code source

Code source du widget de fils de syndications sur GitHub

Date de modification :

<time property="dateModified">2015-03-19</time>

À propos de ce site

Contactez-nous

Questions ou commentaires?

À propos

À propos de la Boîte à outils de l'expérience Web

À propos des normes Web

Nouvelles

Activité du projet récente

Statistiques du projet

Restez branchés

Twitter


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.AccessControl;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Creates a new directory with the attributes of a specified template directory (if one is specified).
      ///   If the underlying file system supports security on files and directories, the function applies the specified security descriptor to the new directory.
      ///   The new directory retains the other attributes of the specified template directory.
      /// </summary>
      /// <returns>
      ///   <para>Returns an object that represents the directory at the specified path.</para>
      ///   <para>This object is returned regardless of whether a directory at the specified path already exists.</para>
      /// </returns>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryNotFoundException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="returnNull">When <c>true</c> returns <c>null</c> instead of a <see cref="DirectoryInfo"/> instance.</param>
      /// <param name="transaction">The transaction.</param>
      /// <param name="path">The directory to create.</param>
      /// <param name="templatePath">The path of the directory to use as a template when creating the new directory. May be <c>null</c> to indicate that no template should be used.</param>
      /// <param name="directorySecurity">The <see cref="DirectorySecurity"/> access control to apply to the directory, may be null.</param>
      /// <param name="compress">When <c>true</c> compresses the directory using NTFS compression.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static DirectoryInfo CreateDirectoryCore(bool returnNull, KernelTransaction transaction, string path, string templatePath, ObjectSecurity directorySecurity, bool compress, PathFormat pathFormat)
      {
         var longPath = path;

         if (pathFormat != PathFormat.LongFullPath)
         {
            if (null == path)
               throw new ArgumentNullException("path");

            Path.CheckSupportedPathFormat(path, true, true);
            Path.CheckSupportedPathFormat(templatePath, true, true);

            longPath = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);

            pathFormat = PathFormat.LongFullPath;
         }

         if (!char.IsWhiteSpace(longPath[longPath.Length - 1]))
         {
            // Return DirectoryInfo instance if the directory specified by path already exists.

            if (File.ExistsCore(transaction, true, longPath, PathFormat.LongFullPath))

               // We are not always interested in a new DirectoryInfo instance.
               return returnNull ? null : new DirectoryInfo(transaction, longPath, PathFormat.LongFullPath);
         }

         // MSDN: .NET 3.5+: IOException: The directory specified by path is a file or the network name was not found.
         if (File.ExistsCore(transaction, false, longPath, PathFormat.LongFullPath))
            NativeError.ThrowException(Win32Errors.ERROR_ALREADY_EXISTS, longPath);

         var templatePathLp = Utils.IsNullOrWhiteSpace(templatePath)
            ? null
            : Path.GetExtendedLengthPathCore(transaction, templatePath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator);

         var list = ConstructFullPath(transaction, longPath);

         // Directory security.
         using (var securityAttributes = new Security.NativeMethods.SecurityAttributes(directorySecurity))
         {
            // Create the directory paths.
            while (list.Count > 0)
            {
               var folderLp = list.Pop();

               // CreateDirectory() / CreateDirectoryEx()
               // 2013-01-13: MSDN confirms LongPath usage.

               if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista

                  ? (templatePathLp == null

                     ? NativeMethods.CreateDirectory(folderLp, securityAttributes)

                     : NativeMethods.CreateDirectoryEx(templatePathLp, folderLp, securityAttributes))

                  : NativeMethods.CreateDirectoryTransacted(templatePathLp, folderLp, securityAttributes, transaction.SafeHandle)))
               {
                  var lastError = Marshal.GetLastWin32Error();

                  switch ((uint) lastError)
                  {
                     // MSDN: .NET 3.5+: If the directory already exists, this method does nothing.
                     // MSDN: .NET 3.5+: IOException: The directory specified by path is a file.
                     case Win32Errors.ERROR_ALREADY_EXISTS:
                        if (File.ExistsCore(transaction, false, longPath, PathFormat.LongFullPath))
                           NativeError.ThrowException(lastError, longPath);

                        if (File.ExistsCore(transaction, false, folderLp, PathFormat.LongFullPath))
                           NativeError.ThrowException(Win32Errors.ERROR_PATH_NOT_FOUND, null, folderLp);
                        break;

                     case Win32Errors.ERROR_BAD_NET_NAME:
                        NativeError.ThrowException(Win32Errors.ERROR_BAD_NET_NAME, longPath);
                        break;

                     case Win32Errors.ERROR_DIRECTORY:
                        // MSDN: .NET 3.5+: NotSupportedException: path contains a colon character (:) that is not part of a drive label ("C:\").
                        throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Resources.Unsupported_Path_Format, longPath));

                     case Win32Errors.ERROR_ACCESS_DENIED:
                        // Report the parent folder, the inaccessible folder.
                        var parent = GetParent(folderLp);

                        NativeError.ThrowException(lastError, null != parent ? parent.FullName : folderLp);
                        break;

                     default:
                        NativeError.ThrowException(lastError, true, folderLp);
                        break;
                  }
               }

               else if (compress)
                  Device.ToggleCompressionCore(transaction, true, folderLp, true, PathFormat.LongFullPath);
            }

            // We are not always interested in a new DirectoryInfo instance.

            return returnNull ? null : new DirectoryInfo(transaction, longPath, PathFormat.LongFullPath);
         }
      }

      private static Stack<string> ConstructFullPath(KernelTransaction transaction, string path)
      {
         var longPathPrefix = Path.IsUncPathCore(path, false, false) ? Path.LongPathUncPrefix : Path.LongPathPrefix;
         path = Path.GetRegularPathCore(path, GetFullPathOptions.None, false);

         var length = path.Length;
         if (length >= 2 && Path.IsDVsc(path[length - 1], false))
            --length;

         var rootLength = Path.GetRootLength(path, false);
         if (length == 2 && Path.IsDVsc(path[1], false))
            throw new ArgumentException(Resources.Cannot_Create_Directory, "path");

         // Check if directories are missing.
         var list = new Stack<string>(100);

         if (length > rootLength)
         {
            for (var index = length - 1; index >= rootLength; --index)
            {
               var path1 = path.Substring(0, index + 1);
               var path2 = longPathPrefix + path1.TrimStart('\\');

               if (!File.ExistsCore(transaction, true, path2, PathFormat.LongFullPath))
                  list.Push(path2);

               while (index > rootLength && !Path.IsDVsc(path[index], false))
                  --index;
            }
         }

         return list;
      }
   }
}

redpajama_set_name: RedPajamaGithub


text:
@interface RCDCSTagView ()
@property (nonatomic, strong) UILabel *tagTitle;
@property (nonatomic, strong) NSMutableDictionary *selectedTags;
@end
@implementation RCDCSTagView
- (instancetype)init {
    self = [super init];
    if (self) {
        self.selectedTags = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)settagTitle {
    self.tagTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 20)];
    self.tagTitle.textColor = RCDDYCOLOR(0x3c4d65, 0x9f9f9f);
    self.tagTitle.text = RCDLocalizedString(@"cs_evaluate_problem_title");
    self.tagTitle.font = [UIFont systemFontOfSize:16];
    self.tagTitle.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.tagTitle];
}

- (void)setTags:(NSArray *)tags {
    if (!self.tagTitle) {
        [self settagTitle];
    }
    for (UIView *view in self.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    for (int i = 0; i < tags.count; i++) {
        CGFloat posX = (self.frame.size.width - horizental_space - button_width * 2) / 2;
        CGFloat posY = CGRectGetMaxY(self.tagTitle.frame) + 13;
        if (i % 2 != 0) {
            posX += (i % 2) * button_width + horizental_space;
        }
        posY += (i / 2) * (button_height + vertical_space);
        RCDCSButton *button = [[RCDCSButton alloc] initWithFrame:CGRectMake(posX, posY, button_width, button_height)];
        [button setTitle:tags[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(didSelectTag:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i;
        [self addSubview:button];
    }
    _tags = tags;
}

- (void)didSelectTag:(UIButton *)sender {
    sender.selected = !sender.selected;
    NSString *key = [NSString stringWithFormat:@"%ld", (long)sender.tag];
    if (sender.selected) {
        [self.selectedTags setObject:self.tags[sender.tag] forKey:key];
    } else {
        [self.selectedTags removeObjectForKey:key];
    }
    self.isSelectedTags(self.selectedTags);
}

- (void)isMustSelect:(BOOL)isMustSelect {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (isMustSelect) {
            self.tagTitle.text = RCDLocalizedString(@"cs_evaluate_problem_must_title");
        } else {
            self.tagTitle.text = RCDLocalizedString(@"cs_evaluate_problem_title");
        }
    });
}
@end


text:
int main(int argc, char *argv[])
{
	@autoreleasepool {
		NimMain();
		return UIApplicationMain(argc, argv, nil,
			NSStringFromClass([AppDelegate class]));
	}
}


text:
void init_converter(converter conv, unsigned char should_this_be_freed) {
	conv->should_this_be_freed = should_this_be_freed;
	conv_tree tree = malloc(sizeof(struct convert_tree_node));
	init_conv_tree(tree, 1);
	conv->location = tree;
	conv->root = tree;
}

void free_converter(converter conv) {
	free_conv_tree(conv->root);
	if (conv->should_this_be_freed)
		free(conv);
}

// 1 = feeded character advanced converter
// 2 = more options
unsigned char feed_converter(converter conv, char c) {
	conv_tree next = find_subnode(conv->location, c);
	if (next) {
		conv->location = next;
		if (conv->location->subnodes_len) {
			return 3;
		} else {
			return 1;
		}
	}
	if (conv->location->subnodes_len) {
		return 2;
	} else {
		return 0;
	}
}
unsigned char is_converter_reset(converter conv) {
	return conv->location == conv->root;
}

char *get_current_conversion(converter conv) {
	return conv->location->value;
}


text:
(function () {
    'use strict';

    angular
        .module('app')
        .controller('WorkingHoursModalController', WorkingHoursModalController);

    WorkingHoursModalController.$inject = ['$rootScope', 'schedule', 'config', '$uibModalStack', '$stateParams'];

    function WorkingHoursModalController($rootScope, schedule, config, $uibModalStack, $stateParams) {
        var vm = this;

        vm.schedule = schedule;
        vm.config = config;

        vm.close = close;

        activate();

        function activate() {
            if (vm.schedule) {
                vm.config.schedules.on('schedule-deleted', function() {
                    $uibModalStack.dismissAll();
                });
                vm.schedule.on('schedule-updated', function() {
                    $uibModalStack.dismissAll();
                });
            }
        }

        function close() {
            $uibModalStack.dismissAll();

            if (vm.schedule.id) {
                vm.schedule.getRemote();
            }
        }
    }

})();


text:
var http = require('http');
var Static = require('node-static');
var juice = http.createServer(handler);
var path = require('path');
var logger = require('morgan');
var io = require('socket.io').listen(juice);
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var express = require('express');

var juice = express();

juice.set('port', process.env.PORT || 1234);
juice.use(logger('dev'));
juice.use(bodyParser.json());
juice.use(bodyParser.urlencoded());
juice.use(cookieParser());
juice.use(express.static(path.join(__dirname, 'wireframe-tools')));

function handler (request,response){
    request.on('end',function(){
      files.serve(request,response);
    }).resume();
}

io.set('log level' , 1);

io.sockets.on('connection',function(socket){

  socket.on('send:coords', function(data){
    socket.broadcast.emit('load:coords' , data);
  });
});

// start the juice on specified port
// console.log('bbdo-geolocation server on ' + port);

juice.listen(juice.get('port'), function() {
    console.log('juice is listening on port 1234');
});


text:
package com.iappsam;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;

@Indexed
@Entity
@Table(name = "Item_Status")
public class ItemStatus implements Serializable, Validatable {

	private static final long serialVersionUID = 2409352590535823393L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "Id")
	private int id;

	@Field(name = "name")
	@Column(name = "name")
	private String name;

	public ItemStatus() {
		super();
	}

	public ItemStatus(String name) {
		setName(name);
	}

	public String getName() {
		return name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setName(String name) {
		if (name != null)
			this.name = name.trim();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ItemStatus other = (ItemStatus) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return name;
	}

	@Override
	public boolean validate() {
		return name != null && !name.equals("");
	}
}


text:
//MIT, 2015-present, EngineKit

using System;
using System.Net.Sockets;
using SharpConnect.Internal;

namespace SharpConnect.WebServers
{
    sealed class PlainWebSocketConn : WebSocketConnectionBase, ISendIO
    {

        readonly SocketAsyncEventArgs _sockAsyncSender;
        readonly SocketAsyncEventArgs _sockAsyncListener;

        Socket _clientSocket;
        const int RECV_BUFF_SIZE = 1024;
        RecvIO _recvIO;
        SendIO _sendIO;

        public PlainWebSocketConn(bool asClient) : base(asClient)
        {

            //-------------------
            //send,resp
            _sockAsyncSender = new SocketAsyncEventArgs();
            _sockAsyncSender.SetBuffer(new byte[RECV_BUFF_SIZE], 0, RECV_BUFF_SIZE);
            _sendIO = new SendIO(_sockAsyncSender, 0, RECV_BUFF_SIZE, HandleSendCompleted);
            _sockAsyncSender.Completed += new EventHandler<SocketAsyncEventArgs>((s, e) =>
            {
                switch (e.LastOperation)
                {
                    default:
                        {
                        }
                        break;
                    case SocketAsyncOperation.Send:
                        {
                            _sendIO.ProcessWaitingData();
                        }
                        break;
                    case SocketAsyncOperation.Receive:
                        {
                        }
                        break;
                }
            });
            _webSocketResp = new WebSocketResponse(_connectionId, asClient, this);

            //------------------------------------------------------------------------------------
            //recv,req ,new socket
            _sockAsyncListener = new SocketAsyncEventArgs();
            _sockAsyncListener.SetBuffer(new byte[RECV_BUFF_SIZE], 0, RECV_BUFF_SIZE);
            _recvIO = new RecvIO(_sockAsyncListener, 0, RECV_BUFF_SIZE, HandleReceivedData);

            RecvIOBufferStream recvIOStream = new RecvIOBufferStream();
            _webSocketReqParser = new WebSocketProtocolParser(this, recvIOStream);
            _webSocketReqParser.SetNewParseResultHandler(req =>
            {
                WebSocketReqInputQueue.Enqueue(new WebSocketReqQueueItem(this, req));
            });
            _sockAsyncListener.Completed += new EventHandler<SocketAsyncEventArgs>((s, e) =>
            {
                switch (e.LastOperation)
                {
                    default:
                        {
                        }
                        break;
                    case SocketAsyncOperation.Send:
                        {
                        }
                        break;
                    case SocketAsyncOperation.Receive:
                        {
                            //copy data and write to recvIO stream

                            int recvByteCount = e.BytesTransferred;
                            if (recvByteCount > 0)
                            {
                                //TODO
                                byte[] tmp1 = new byte[recvByteCount];
                                Buffer.BlockCopy(e.Buffer, 0, tmp1, 0, recvByteCount);
                                recvIOStream.WriteData(tmp1, recvByteCount);
                                _recvIO.ProcessReceivedData();
                            }

                        }
                        break;
                }
            });
            //------------------------------------------------------------------------------------

        }
        public override WebSocketContentCompression Compression
        {
            get => base.Compression;
            set
            {
                base.Compression = value;
                _webSocketResp.Compression = value;
            }
        }
        public void Bind(Socket clientSocket, byte[] connReplMsg)
        {
            _clientSocket = clientSocket;
            //sender
            _sockAsyncSender.AcceptSocket = clientSocket;
            //------------------------------------------------------
            //listener
            _sockAsyncListener.AcceptSocket = clientSocket;
            //sockAsyncListener.SetBuffer(new byte[RECV_BUFF_SIZE], 0, RECV_BUFF_SIZE);
            //------------------------------------------------------
            //when bind we start listening

            clientSocket.ReceiveAsync(_sockAsyncListener);
            //------------------------------------------------------

            //send websocket reply
            _sendIO.EnqueueOutputData(connReplMsg, connReplMsg.Length);
            _sendIO.StartSendAsync();
            //--------
        }
        void ISendIO.EnqueueSendingData(byte[] buffer, int len) => _sendIO.EnqueueOutputData(buffer, len);
        void ISendIO.SendIOStartSend() => _sendIO.StartSendAsync();

        bool _beginWebSocketMode;
        void HandleReceivedData(RecvEventCode recvCode)
        {
            switch (recvCode)
            {
                case RecvEventCode.HasSomeData:
                    {
                        if (_asClientContext && !_beginWebSocketMode)
                        {

                            int recvByteCount = _recvIO.BytesTransferred;
                            byte[] tmp1 = new byte[2048];
                            _recvIO.CopyTo(0, tmp1, recvByteCount);
                            //_clientStream.ReadBuffer(0, recvByteCount, tmp1, 0);
                            string text = System.Text.Encoding.UTF8.GetString(tmp1, 0, recvByteCount);

                            if (text.StartsWith("HTTP/1.1 101 Switching Protocols\r\nUpgrade"))
                            {
                                //clear prev buffer

                                _webSocketReqParser.ClearMemBuffer();
                                _beginWebSocketMode = true;
                                _recvIO.StartReceive();

                                ////*** clear prev buffer before new recv
                                //_clientStream.ClearReceiveBuffer();
                                //_clientStream.BeginWebsocketMode = true; //***
                                //_clientStream.StartReceive();//***
                                return;
                            }
                            else if (text.StartsWith("HTTP/1.1"))
                            {
                                _recvIO.StartReceive();
                                return;
                            }
                            //--
                        }

                        //parse recv msg
                        switch (_webSocketReqParser.ParseRecvData())
                        {
                            //in this version all data is copy into WebSocketRequest
                            //so we can reuse recv buffer
                            //TODO: review this, if we need to copy?,

                            case ProcessReceiveBufferResult.Complete:

                                //you can choose ...
                                //invoke webSocketReqHandler in this thread or another thread
                                _recvIO.StartReceive();
                                //***no code after StartReceive***
                                return;
                            case ProcessReceiveBufferResult.NeedMore:
                                _recvIO.StartReceive();
                                //***no code after StartReceive***
                                return;
                            case ProcessReceiveBufferResult.Error:
                            default:
                                throw new NotSupportedException();
                        }
                    }
                case RecvEventCode.NoMoreReceiveData:
                    {
                    }
                    break;
                case RecvEventCode.SocketError:
                    {
                    }
                    break;
            }
        }
        void HandleSendCompleted(SendIOEventCode eventCode)
        {

        }
        public override void Close() => _clientSocket.Close();

    }

}


text:
import random, pyperclip

myMessage = """When I use a word, it means just what I choose it to mean -- neither more nor less."""
myKey = '302'
mode = 'encrypt' # set to 'encrypt' or 'decrypt'

def main():
    if mode == 'encrypt':
        translated = encryptMessage(myKey, myMessage)
    elif mode == 'decrypt':
        translated = decryptMessage(myKey, myMessage)

    print('%sed message: ' % (mode.title()) + translated)
    print('The message has been copied to the clipboard.')
    pyperclip.copy(translated)

def encryptMessage(key, message):
    # The expression int(key[keyIndex]) will be used to decide how many
    # nulls should be inserted. For example, if key is the value '570'
    # and keyIndex is 0, then 5 null characters will be inserted into
    # the ciphertext.
    keyIndex = 0

    ciphertext = '' # will contain the encrypted string
    for symbol in list(message) + [None]:
        for dummy in range(int(key[keyIndex])):
            # Add a null.
            ciphertext += random.choice(myMessage)

        if symbol == None:
            break # the None value marks the end

        # Increment keyIndex so that on the next iteration, we use a
        # number of nulls specified by the next character in key.
        keyIndex += 1
        if keyIndex == len(key):
            # keyIndex is past the end, so reset it back to 0.
            keyIndex = 0

        # Add the real symbol after adding the nulls.
        ciphertext += symbol
    return ciphertext

def decryptMessage(key, message):
    # The value inside messageIndex will refer to the index we are
    # currently looking at in message.
    messageIndex = 0
    keyIndex = 0

    plaintext = '' # will contain the decrypted string

    while True:
        # The expression int(key[keyIndex]) will give us the int value of
        # how many nulls to skip over. We will increment the value in
        # messageIndex by this amount.
        messageIndex += int(key[keyIndex])

        if messageIndex >= len(message):
            # When messageIndex is past the last index, we are done.
            break

        # Increment keyIndex so that on the next iteration, we
        # use a number of nulls specified by the next character in key.
        keyIndex += 1
        if keyIndex == len(key):
            keyIndex = 0

        # Append the symbol at messageIndex to the plaintext variable.
        plaintext += message[messageIndex]
        messageIndex += 1

    return plaintext

if __name__ == '__main__':
    main()


text:
using System;
using System.Diagnostics;
using Arc;
using Arc.Values;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Unit_Tests
{
    [TestClass]
    public class Types
    {
        [TestMethod]
        public void Number_IsDecimal()
        {
            {
                double x = 0.1;
                double sum = 0.0;
                for (int i = 0; i != 10; ++i)
                    sum += x;
                Trace.WriteLine("Floating-point result: " + sum.ToString("R"));
            }
            {
                var x = NumberValue.Create(0.1M);
                var sum = NumberValue.Zero;
                for (int i = 0; i != 10; ++i)
                    sum = NumberValue.Create(sum.Value + x.Value);
                Trace.WriteLine("Number result: " + sum.Value);
                Assert.AreEqual(1, sum.Value);
            }
        }

        // todo: string precision.
    }
}


text:
import { connect } from 'react-redux'
import values from 'lodash/values'
import sortBy from 'lodash/sortBy'
import map from 'lodash/map'

import { loadColors } from '../../actions/colors'

import ColorPalettePicker from './ColorPalettePicker'

function mapStateToProps (state, ownProps) {
  const allColors = sortBy(values(state.color), 'values')

  return {
    normalColors: map(allColors, 'normal'),
    deuteranopiaColors: map(allColors, 'deuteranopia'),
    protanopiaColors: map(allColors, 'protanopia'),
    tritanopiaColors: map(allColors, 'tritanopia')
  }
}

function mapDispatchToProps (dispatch, ownProps) {
  dispatch(loadColors())

  return {}
}

export default connect(mapStateToProps, mapDispatchToProps)(ColorPalettePicker)


text:
#ifndef V8DOMConfiguration_h
#define V8DOMConfiguration_h

#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8DOMWrapper.h"
#include <v8.h>

namespace blink {

class V8DOMConfiguration {
public:
    // The following Configuration structs and install methods are used for
    // setting multiple properties on an ObjectTemplate, used from the
    // generated bindings initialization (ConfigureXXXTemplate). This greatly
    // reduces the binary size by moving from code driven setup to data table
    // driven setup.

    enum ExposeConfiguration {
        ExposedToAllScripts,
        OnlyExposedToPrivateScript,
    };

    enum InstanceOrPrototypeConfiguration {
        OnInstance,
        OnPrototype,
    };

    // AttributeConfiguration translates into calls to SetAccessor() on either
    // the instance or the prototype ObjectTemplate, based on |instanceOrPrototypeConfiguration|.
    struct AttributeConfiguration {
        const char* const name;
        v8::AccessorGetterCallback getter;
        v8::AccessorSetterCallback setter;
        v8::AccessorGetterCallback getterForMainWorld;
        v8::AccessorSetterCallback setterForMainWorld;
        const WrapperTypeInfo* data;
        v8::AccessControl settings;
        v8::PropertyAttribute attribute;
        ExposeConfiguration exposeConfiguration;
        InstanceOrPrototypeConfiguration instanceOrPrototypeConfiguration;
    };

    // AccessorConfiguration translates into calls to SetAccessorProperty()
    // on prototype ObjectTemplate.
    struct AccessorConfiguration {
        const char* const name;
        v8::FunctionCallback getter;
        v8::FunctionCallback setter;
        v8::FunctionCallback getterForMainWorld;
        v8::FunctionCallback setterForMainWorld;
        const WrapperTypeInfo* data;
        v8::AccessControl settings;
        v8::PropertyAttribute attribute;
        ExposeConfiguration exposeConfiguration;
    };

    static void installAttributes(v8::Isolate*, v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::ObjectTemplate>, const AttributeConfiguration*, size_t attributeCount);

    template<class ObjectOrTemplate>
    static inline void installAttribute(v8::Handle<ObjectOrTemplate> instanceTemplate, v8::Handle<ObjectOrTemplate> prototype, const AttributeConfiguration& attribute, v8::Isolate* isolate)
    {
        DOMWrapperWorld& world = DOMWrapperWorld::current(isolate);
        if (attribute.exposeConfiguration == OnlyExposedToPrivateScript && !world.isPrivateScriptIsolatedWorld())
            return;

        v8::AccessorGetterCallback getter = attribute.getter;
        v8::AccessorSetterCallback setter = attribute.setter;
        if (world.isMainWorld()) {
            if (attribute.getterForMainWorld)
                getter = attribute.getterForMainWorld;
            if (attribute.setterForMainWorld)
                setter = attribute.setterForMainWorld;
        }
        (attribute.instanceOrPrototypeConfiguration == OnPrototype ? prototype : instanceTemplate)->SetAccessor(v8AtomicString(isolate, attribute.name),
            getter,
            setter,
            v8::External::New(isolate, const_cast<WrapperTypeInfo*>(attribute.data)),
            attribute.settings,
            attribute.attribute);
    }

    enum ConstantType {
        ConstantTypeShort,
        ConstantTypeLong,
        ConstantTypeUnsignedShort,
        ConstantTypeUnsignedLong,
        ConstantTypeFloat,
        ConstantTypeDouble,
        ConstantTypeString
    };

    // ConstantConfiguration translates into calls to Set() for setting up an
    // object's constants. It sets the constant on both the FunctionTemplate and
    // the ObjectTemplate. PropertyAttributes is always ReadOnly.
    struct ConstantConfiguration {
        const char* const name;
        int ivalue;
        double dvalue;
        const char* const svalue;
        ConstantType type;
    };

    static void installConstants(v8::Isolate*, v8::Handle<v8::FunctionTemplate>, v8::Handle<v8::ObjectTemplate>, const ConstantConfiguration*, size_t constantCount);
    static void installConstant(v8::Isolate*, v8::Handle<v8::FunctionTemplate>, v8::Handle<v8::ObjectTemplate>, const char* name, v8::AccessorGetterCallback);

    // MethodConfiguration translates into calls to Set() for setting up an
    // object's callbacks. It sets the method on both the FunctionTemplate or
    // the ObjectTemplate.
    struct MethodConfiguration {
        v8::Local<v8::Name> methodName(v8::Isolate* isolate) const { return v8AtomicString(isolate, name); }
        v8::FunctionCallback callbackForWorld(const DOMWrapperWorld& world) const
        {
            return world.isMainWorld() && callbackForMainWorld ? callbackForMainWorld : callback;
        }

        const char* const name;
        v8::FunctionCallback callback;
        v8::FunctionCallback callbackForMainWorld;
        int length;
        ExposeConfiguration exposeConfiguration;
    };

    struct SymbolKeyedMethodConfiguration {
        v8::Local<v8::Name> methodName(v8::Isolate* isolate) const { return getSymbol(isolate); }
        v8::FunctionCallback callbackForWorld(const DOMWrapperWorld&) const
        {
            return callback;
        }

        v8::Local<v8::Symbol> (*getSymbol)(v8::Isolate*);
        v8::FunctionCallback callback;
        // SymbolKeyedMethodConfiguration doesn't support per-world bindings.
        int length;
        ExposeConfiguration exposeConfiguration;
    };

    static void installMethods(v8::Isolate*, v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::Signature>, v8::PropertyAttribute, const MethodConfiguration*, size_t callbackCount);

    template <class ObjectOrTemplate, class Configuration>
    static void installMethod(v8::Handle<ObjectOrTemplate> objectOrTemplate, v8::Handle<v8::Signature> signature, v8::PropertyAttribute attribute, const Configuration& callback, v8::Isolate* isolate)
    {
        DOMWrapperWorld& world = DOMWrapperWorld::current(isolate);
        if (callback.exposeConfiguration == OnlyExposedToPrivateScript && !world.isPrivateScriptIsolatedWorld())
            return;

        v8::Local<v8::FunctionTemplate> functionTemplate = functionTemplateForCallback(isolate, signature, callback.callbackForWorld(world), callback.length);
        setMethod(objectOrTemplate, callback.methodName(isolate), functionTemplate, attribute);
    }

    static void installAccessors(v8::Isolate*, v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::Signature>, const AccessorConfiguration*, size_t accessorCount);

    static v8::Local<v8::Signature> installDOMClassTemplate(v8::Isolate*, v8::Local<v8::FunctionTemplate>, const char* interfaceName, v8::Handle<v8::FunctionTemplate> parentClass, size_t fieldCount,
        const AttributeConfiguration*, size_t attributeCount,
        const AccessorConfiguration*, size_t accessorCount,
        const MethodConfiguration*, size_t callbackCount);

    static v8::Handle<v8::FunctionTemplate> domClassTemplate(v8::Isolate*, WrapperTypeInfo*, void (*)(v8::Local<v8::FunctionTemplate>, v8::Isolate*));

private:
    static void setMethod(v8::Handle<v8::Object> target, v8::Handle<v8::Name> name, v8::Handle<v8::FunctionTemplate> functionTemplate, v8::PropertyAttribute attribute)
    {
        target->Set(name, functionTemplate->GetFunction());
    }
    static void setMethod(v8::Handle<v8::FunctionTemplate> target, v8::Handle<v8::Name> name, v8::Handle<v8::FunctionTemplate> functionTemplate, v8::PropertyAttribute attribute)
    {
        target->Set(name, functionTemplate, attribute);
    }
    static void setMethod(v8::Handle<v8::ObjectTemplate> target, v8::Handle<v8::Name> name, v8::Handle<v8::FunctionTemplate> functionTemplate, v8::PropertyAttribute attribute)
    {
        target->Set(name, functionTemplate, attribute);
    }

    static v8::Handle<v8::FunctionTemplate> functionTemplateForCallback(v8::Isolate*, v8::Handle<v8::Signature>, v8::FunctionCallback, int length);
};

} // namespace blink

#endif // V8DOMConfiguration_h


text:
import PIL
from PIL import Image

im = Image.open("l16/mozart.gif")
print im.size, im.mode

g = im.convert("RGB")
l = list(g.getdata())

## almost-whites
poss = [(x,x,x) for x in range(240, 255)] ## don't include 255 !!

things = []

globidx = 0

while globidx < len(l):
    foundstuff = []
    for item in poss:
        try:
            ## try to find a "white"
            idx = l.index(item, globidx)
            ## found one
            foundstuff.append(idx) ## remember we found THIS one
        except ValueError:
            pass
    if foundstuff == []:
        break ## none of the poss found, so we're done
    ## we're only interested in the minimum index ("first" one found)
    it = min(foundstuff)

    print "found : at pos", it, ":", l[it:it+7]
    ## append this thingie, including position
    things.append((l[it:it+7], it))
    globidx = it + 7

print "*** total found :", len(things)

f = open("l16/blocks.txt", "w")
f.writelines("\n".join(map(str, things)))
f.close()


text:
from django.contrib.auth.models import User
from django.core.management import call_command
from django.shortcuts import reverse
from django.test import Client, TestCase

from dataschema_manager.models import DataSchema
from experiments_manager.models import Experiment
from git_manager.models import GitRepository
from user_manager.models import WorkbenchUser

class UserManagerTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('test', 'test@test.nl', 'test')
        self.workbench_user = WorkbenchUser.objects.get(user=self.user)

        self.git_repo = GitRepository.objects.create(name='Experiment',
                                                     owner=self.workbench_user,
                                                     github_url='https://github')
        schema = DataSchema(name='main')
        schema.save()
        self.experiment = Experiment.objects.create(title='Experiment', description='test',
                                                    owner=self.workbench_user,
                                                    git_repo=self.git_repo,
                                                    language_id=1,
                                                    template_id=2,
                                                    schema=schema)

        self.client = Client()
        self.client.login(username='test', password='test')

        call_command('loaddata', 'fixtures/steps.json', verbosity=0)
        call_command('loaddata', 'fixtures/measures.json', verbosity=0)
        call_command('loaddata', 'fixtures/package_categories_languages.json', verbosity=0)

    def test_index(self):
        response = self.client.get(reverse('index'))
        self.assertEqual(response.status_code, 200)

    def test_detail_profile_view(self):
        response = self.client.get(reverse('view_my_profile'))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['workbench_user'], self.workbench_user)

    def test_sign_out(self):
        response = self.client.get(reverse('logout'), follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(str(response.context['user']), 'AnonymousUser')

    def test_sign_out_without_signed_in(self):
        c = Client()
        response = c.get(reverse('logout'), follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(str(response.context['user']), 'AnonymousUser')

    def test_sign_in_get(self):
        response = self.client.get(reverse('login'))
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])

    def test_sign_in_post(self):
        c = Client()
        data = {'username': 'test', 'password': 'test'}
        response = c.post(reverse('login'), data=data, follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'], self.user)

    def test_sign_in_post_incorrect_username(self):
        c = Client()
        data = {'username': 'NON_EXISTENT_USER', 'password': 'test'}
        response = c.post(reverse('login'), data=data)
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])
        self.assertEqual(str(response.context['user']), 'AnonymousUser')

    def test_sign_in_post_incorrect_password(self):
        c = Client()
        data = {'username': 'test', 'password': 'INCORRECT_PASSWORD'}
        response = c.post(reverse('login'), data=data)
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])
        self.assertEqual(str(response.context['user']), 'AnonymousUser')

    def test_sign_in_post_missing_password(self):
        c = Client()
        data = {'username': 'test'}
        response = c.post(reverse('login'), data=data)
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])
        self.assertEqual(str(response.context['user']), 'AnonymousUser')

    def test_sign_in_post_missing_username(self):
        c = Client()
        data = {'password': 'RANDOM_PASSWORD'}
        response = c.post(reverse('login'), data=data)
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])
        self.assertEqual(str(response.context['user']), 'AnonymousUser')

    def test_edit_profile_view_get(self):
        response = self.client.get(reverse('edit_profile'))
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])

    def test_edit_profile_view_post(self):
        data = {'netid': '123456789'}
        response = self.client.post(reverse('edit_profile'), data=data)
        self.assertEqual(response.status_code, 302)
        self.workbench_user.refresh_from_db()
        self.assertEqual(self.workbench_user.netid, '123456789')

    def test_edit_profile_view_post_none(self):
        data = {}
        response = self.client.post(reverse('edit_profile'), data=data)
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])

    def test_register_view_get(self):
        c = Client()
        response = c.get(reverse('register'))
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])

    def test_register_view_post(self):
        c = Client()
        data = {'username': 'test3',
                'email': 'test2@test2.nl',
                'password': 'test',
                'password_again': 'test',
                'netid': '123456789'}
        response = c.post(reverse('register'), data=data)
        self.assertEqual(response.status_code, 302)
        new_user = User.objects.filter(email=data['email'])
        self.assertTrue(new_user)

    def test_register_view_post_missing_data(self):
        c = Client()
        data = {'username': 'test3',
                'email': 'test2@test2.nl',
                'password': 'test',
                'password_again': 'test',}
        response = c.post(reverse('register'), data=data)
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])

    def test_register_view_post_same_username(self):
        c = Client()
        data = {'username': 'test',
                'email': 'test2@test2.nl',
                'password': 'DIFFERENT_PASSWORD',
                'password_again': 'DIFFERENT_PASSWORD',
                'netid': '123456789'}
        response = c.post(reverse('register'), data=data)
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])
        self.user.refresh_from_db()
        self.assertNotEqual(self.user.email, data['email'])

    def test_register_view_post_same_email(self):
        c = Client()
        data = {'username': 'test2',
                'email': self.user.email,
                'password': 'DIFFERENT_PASSWORD',
                'password_again': 'DIFFERENT_PASSWORD',
                'netid': '123456789'}
        response = c.post(reverse('register'), data=data)
        self.assertEqual(response.status_code, 200)
        self.assertIsNotNone(response.context['form'])
        new_user = User.objects.filter(username=data['username'])
        self.assertFalse(new_user)


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

<title>I2cDeviceImpl</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.qualcomm.robotcore.hardware

Class I2cDeviceImpl

java.lang.Object

com.qualcomm.robotcore.hardware.I2cControllerPortDeviceImpl

com.qualcomm.robotcore.hardware.I2cDeviceImpl

All Implemented Interfaces:

HardwareDevice, I2cController.I2cPortReadyCallback, I2cControllerPortDevice, I2cDevice

public class I2cDeviceImpl
extends I2cControllerPortDeviceImpl
implements I2cDevice, HardwareDevice, I2cController.I2cPortReadyCallback

Control a single I2C Device

Nested Class Summary

Nested classes/interfaces inherited from interface com.qualcomm.robotcore.hardware.HardwareDevice

HardwareDevice.Manufacturer

Field Summary

Fields

Modifier and Type
Field and Description

protected I2cController.I2cPortReadyCallback
callback

protected java.util.concurrent.atomic.AtomicInteger
callbackCount

Fields inherited from class com.qualcomm.robotcore.hardware.I2cControllerPortDeviceImpl

controller, physicalPort

Constructor Summary

Constructors

Constructor and Description

I2cDeviceImpl(I2cController controller,
             int port)

Constructor

Method Summary

All Methods Instance Methods Concrete Methods Deprecated Methods

Modifier and Type
Method and Description

void
clearI2cPortActionFlag()

Clears the flag that I2cDevice.setI2cPortActionFlag() sets

void
close()

Closes this device

protected void
controllerNowArmedOrPretending()

intended as a subclass hook

void
copyBufferIntoWriteBuffer(byte[] buffer)

Copy a byte array into the buffer that is set to be written out to the device

void
deregisterForPortReadyBeginEndCallback()

deregister for port-ready begin and cessation notifications

void
deregisterForPortReadyCallback()

Unregister for a port-ready callback

void
enableI2cReadMode(I2cAddr i2cAddr,
                 int memAddress,
                 int length)

Deprecated.

void
enableI2cWriteMode(I2cAddr i2cAddr,
                  int memAddress,
                  int length)

Deprecated.

int
getCallbackCount()

Returns the number of callbacks ever experienced by this I2cDevice instance, whether or not
 they were ever seen by a registered callback.

java.lang.String
getConnectionInfo()

Get connection information about this device in a human readable format

I2cController
getController()

returns the I2cController on which this device is found

byte[]
getCopyOfReadBuffer()

Get a copy of the most recent data read in from the device

byte[]
getCopyOfWriteBuffer()

Get a copy of the data that is set to be written out to the device

java.lang.String
getDeviceName()

Returns a string suitable for display to the user as to the type of device.

I2cController.I2cPortReadyCallback
getI2cPortReadyCallback()

returns the currently registered port-ready callback for this device

byte[]
getI2cReadCache()

Get direct access to the read cache used by this I2C device

java.util.concurrent.locks.Lock
getI2cReadCacheLock()

Get access to the read cache lock.

TimeWindow
getI2cReadCacheTimeWindow()

Returns the time window object into which time stamps are written when the read cache is updated

byte[]
getI2cWriteCache()

Get direct access to the write cache used by this I2C device

java.util.concurrent.locks.Lock
getI2cWriteCacheLock()

Get access to the write cache lock.

HardwareDevice.Manufacturer
getManufacturer()

Returns an indication of the manufacturer of this device.

int
getMaxI2cWriteLatency()

Returns the maximum interval, in milliseconds, from when the controller receives an I2c write
 transmission over USB to when that write is actually issued to the I2c device.

int
getPort()

returns the port number on the controller on which this device is found

I2cController.I2cPortReadyBeginEndNotifications
getPortReadyBeginEndCallback()

returns the currently registered callback that will receive begin and cessation notifications

int
getVersion()

Version

boolean
isArmed()

Returns whether, as of this instant, this I2cDevice is alive and operational in
 its normally expected mode; that is, whether it is currently in communication
 with its underlying hardware or whether it is in some other state

boolean
isI2cPortActionFlagSet()

Check whether or not the action flag is set for this I2C port

boolean
isI2cPortInReadMode()

Query whether or not the port is in Read mode

boolean
isI2cPortInWriteMode()

Query whether or not this port is in write mode

boolean
isI2cPortReady()

Query whether or not this I2c port is ready

void
portIsReady(int port)

void
readI2cCacheFromController()

Trigger a read of the I2C cache

void
readI2cCacheFromModule()

Deprecated.

void
registerForI2cPortReadyCallback(I2cController.I2cPortReadyCallback callback)

The method used to register for a port-ready callback

void
registerForPortReadyBeginEndCallback(I2cController.I2cPortReadyBeginEndNotifications callback)

registers for notifications as to when port-ready callbacks begin or cease

void
resetDeviceConfigurationForOpMode()

Resets the device's configuration to that which is expected at the beginning of an OpMode.

void
setI2cPortActionFlag()

Set the port action flag; this flag tells the controller to send the
 current data in its buffer to the I2C device

void
writeI2cCacheToController()

Trigger a write of the I2C cache

void
writeI2cCacheToModule()

Deprecated.

void
writeI2cPortFlagOnlyToController()

Write only the action flag

void
writeI2cPortFlagOnlyToModule()

Deprecated.

Methods inherited from class com.qualcomm.robotcore.hardware.I2cControllerPortDeviceImpl

controllerNowDisarmed, finishConstruction, getI2cController, onModuleStateChange

Methods inherited from class java.lang.Object

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

Methods inherited from interface com.qualcomm.robotcore.hardware.I2cControllerPortDevice

getI2cController

Field Detail

callback

protected I2cController.I2cPortReadyCallback callback

callbackCount

protected java.util.concurrent.atomic.AtomicInteger callbackCount

Constructor Detail

I2cDeviceImpl

public I2cDeviceImpl(I2cController controller,
                     int port)

Constructor

Parameters:

controller - I2C controller this channel is attached to

port - port on the I2C controller

Method Detail

controllerNowArmedOrPretending

protected void controllerNowArmedOrPretending()

Description copied from class: I2cControllerPortDeviceImpl

intended as a subclass hook

Overrides:

controllerNowArmedOrPretending in class I2cControllerPortDeviceImpl

getController

public I2cController getController()

returns the I2cController on which this device is found

Specified by:

getController in interface I2cDevice

Returns:

the I2cController on which this device is found

getPort

public int getPort()

returns the port number on the controller on which this device is found

Specified by:

getPort in interface I2cControllerPortDevice

Overrides:

getPort in class I2cControllerPortDeviceImpl

Returns:

the port number on the controller on which this device is found

enableI2cReadMode

@Deprecated
public void enableI2cReadMode(I2cAddr i2cAddr,
                                          int memAddress,
                                          int length)

Deprecated.

Enable read mode for this I2C device

Specified by:

enableI2cReadMode in interface I2cDevice

Parameters:

memAddress - mem address at which to start reading

length - number of bytes to read

i2cAddr - the address of the device on the I2c bus which should be read

See Also:

I2cDevice.writeI2cCacheToController()

enableI2cWriteMode

@Deprecated
public void enableI2cWriteMode(I2cAddr i2cAddr,
                                           int memAddress,
                                           int length)

Deprecated.

Enable write mode for this I2C device

Specified by:

enableI2cWriteMode in interface I2cDevice

Parameters:

memAddress - mem address at which to start writing

length - number of bytes to write

i2cAddr - the address of the device on the I2c bus which should be written

See Also:

I2cDevice.writeI2cCacheToController()

getCopyOfReadBuffer

public byte[] getCopyOfReadBuffer()

Get a copy of the most recent data read in from the device

Specified by:

getCopyOfReadBuffer in interface I2cDevice

Returns:

a copy of the most recent data read in from the device

See Also:

I2cDevice.getI2cReadCache()

getCopyOfWriteBuffer

public byte[] getCopyOfWriteBuffer()

Get a copy of the data that is set to be written out to the device

Specified by:

getCopyOfWriteBuffer in interface I2cDevice

Returns:

a copy of the data set to be written out to the device

See Also:

I2cDevice.getI2cWriteCache()

copyBufferIntoWriteBuffer

public void copyBufferIntoWriteBuffer(byte[] buffer)

Copy a byte array into the buffer that is set to be written out to the device

Specified by:

copyBufferIntoWriteBuffer in interface I2cDevice

Parameters:

buffer - buffer to copy

See Also:

I2cDevice.getI2cWriteCache()

setI2cPortActionFlag

public void setI2cPortActionFlag()

Set the port action flag; this flag tells the controller to send the
 current data in its buffer to the I2C device

Specified by:

setI2cPortActionFlag in interface I2cDevice

See Also:

I2cDevice.clearI2cPortActionFlag()

clearI2cPortActionFlag

public void clearI2cPortActionFlag()

Description copied from interface: I2cDevice

Clears the flag that I2cDevice.setI2cPortActionFlag() sets

Specified by:

clearI2cPortActionFlag in interface I2cDevice

See Also:

I2cDevice.setI2cPortActionFlag()

isI2cPortActionFlagSet

public boolean isI2cPortActionFlagSet()

Check whether or not the action flag is set for this I2C port

Specified by:

isI2cPortActionFlagSet in interface I2cDevice

Returns:

a boolean indicating whether or not the flag is set

readI2cCacheFromController

public void readI2cCacheFromController()

Trigger a read of the I2C cache

Specified by:

readI2cCacheFromController in interface I2cDevice

writeI2cCacheToController

public void writeI2cCacheToController()

Trigger a write of the I2C cache

Specified by:

writeI2cCacheToController in interface I2cDevice

writeI2cPortFlagOnlyToController

public void writeI2cPortFlagOnlyToController()

Write only the action flag

Specified by:

writeI2cPortFlagOnlyToController in interface I2cDevice

isI2cPortInReadMode

public boolean isI2cPortInReadMode()

Query whether or not the port is in Read mode

Specified by:

isI2cPortInReadMode in interface I2cDevice

Returns:

whether or not this port is in read mode

isI2cPortInWriteMode

public boolean isI2cPortInWriteMode()

Query whether or not this port is in write mode

Specified by:

isI2cPortInWriteMode in interface I2cDevice

Returns:

whether or not this port is in write mode

isI2cPortReady

public boolean isI2cPortReady()

Query whether or not this I2c port is ready

Specified by:

isI2cPortReady in interface I2cDevice

Returns:

boolean indicating I2c port readiness

See Also:

I2cDeviceSynch,
I2cDevice.registerForI2cPortReadyCallback(I2cController.I2cPortReadyCallback)

getI2cReadCacheLock

public java.util.concurrent.locks.Lock getI2cReadCacheLock()

Get access to the read cache lock.

 This is needed if you are accessing the read cache directly. The read
 cache lock needs to be acquired before attempting to interact with the read cache

Specified by:

getI2cReadCacheLock in interface I2cDevice

Returns:

the read cache lock

getI2cWriteCacheLock

public java.util.concurrent.locks.Lock getI2cWriteCacheLock()

Get access to the write cache lock.

 This is needed if you ace accessing the write cache directly. The write
 cache lock needs to be acquired before attempting to interact with the
 write cache

Specified by:

getI2cWriteCacheLock in interface I2cDevice

Returns:

write cache lock

getI2cReadCache

public byte[] getI2cReadCache()

Get direct access to the read cache used by this I2C device

 Please lock the cache before accessing it.

Specified by:

getI2cReadCache in interface I2cDevice

Returns:

the read cache

See Also:

I2cDevice.getI2cReadCacheLock(),
I2cDevice.getCopyOfReadBuffer()

getI2cReadCacheTimeWindow

public TimeWindow getI2cReadCacheTimeWindow()

Description copied from interface: I2cDevice

Returns the time window object into which time stamps are written when the read cache is updated

Specified by:

getI2cReadCacheTimeWindow in interface I2cDevice

Returns:

the time window object into which time stamps are written when the read cache is updated

See Also:

I2cDevice.getI2cReadCache()

getI2cWriteCache

public byte[] getI2cWriteCache()

Get direct access to the write cache used by this I2C device

 Please lock the cache before accessing it.

Specified by:

getI2cWriteCache in interface I2cDevice

Returns:

the write cache

See Also:

I2cDevice.getI2cWriteCacheLock(),
I2cDevice.getCopyOfWriteBuffer()

portIsReady

public void portIsReady(int port)

Specified by:

portIsReady in interface I2cController.I2cPortReadyCallback

getMaxI2cWriteLatency

public int getMaxI2cWriteLatency()

Description copied from interface: I2cDevice

Returns the maximum interval, in milliseconds, from when the controller receives an I2c write
 transmission over USB to when that write is actually issued to the I2c device.

Specified by:

getMaxI2cWriteLatency in interface I2cDevice

Returns:

the maximum interval, in milliseconds, from when the controller receives an I2c write
 transmission over USB to when that write is actually issued to the I2c device.

registerForI2cPortReadyCallback

public void registerForI2cPortReadyCallback(I2cController.I2cPortReadyCallback callback)

The method used to register for a port-ready callback

Specified by:

registerForI2cPortReadyCallback in interface I2cDevice

Parameters:

callback - pass in the I2C callback that will be called when the device is ready

See Also:

I2cDevice.getI2cPortReadyCallback(),
I2cDevice.deregisterForPortReadyCallback()

getI2cPortReadyCallback

public I2cController.I2cPortReadyCallback getI2cPortReadyCallback()

returns the currently registered port-ready callback for this device

Specified by:

getI2cPortReadyCallback in interface I2cDevice

Returns:

the currently registered port-ready callback for this device

deregisterForPortReadyCallback

public void deregisterForPortReadyCallback()

Unregister for a port-ready callback

Specified by:

deregisterForPortReadyCallback in interface I2cDevice

See Also:

I2cDevice.registerForI2cPortReadyCallback(I2cController.I2cPortReadyCallback)

getCallbackCount

public int getCallbackCount()

Description copied from interface: I2cDevice

Returns the number of callbacks ever experienced by this I2cDevice instance, whether or not
 they were ever seen by a registered callback. This method is mostly useful for debugging and
 gathering of statistics.

Specified by:

getCallbackCount in interface I2cDevice

Returns:

the number of port-is-ready callbacks ever experienced by this I2cDevice instance

registerForPortReadyBeginEndCallback

public void registerForPortReadyBeginEndCallback(I2cController.I2cPortReadyBeginEndNotifications callback)

registers for notifications as to when port-ready callbacks begin or cease

Specified by:

registerForPortReadyBeginEndCallback in interface I2cDevice

Parameters:

callback - the callback which will receive such notifications

See Also:

I2cDevice.getPortReadyBeginEndCallback(),
I2cDevice.deregisterForPortReadyBeginEndCallback()

getPortReadyBeginEndCallback

public I2cController.I2cPortReadyBeginEndNotifications getPortReadyBeginEndCallback()

returns the currently registered callback that will receive begin and cessation notifications

Specified by:

getPortReadyBeginEndCallback in interface I2cDevice

Returns:

the currently registered callback that will receive begin and cessation notifications

See Also:

I2cDevice.registerForPortReadyBeginEndCallback(I2cController.I2cPortReadyBeginEndNotifications)

deregisterForPortReadyBeginEndCallback

public void deregisterForPortReadyBeginEndCallback()

deregister for port-ready begin and cessation notifications

Specified by:

deregisterForPortReadyBeginEndCallback in interface I2cDevice

See Also:

I2cDevice.registerForPortReadyBeginEndCallback(I2cController.I2cPortReadyBeginEndNotifications)

isArmed

public boolean isArmed()

Description copied from interface: I2cDevice

Returns whether, as of this instant, this I2cDevice is alive and operational in
 its normally expected mode; that is, whether it is currently in communication
 with its underlying hardware or whether it is in some other state

Specified by:

isArmed in interface I2cDevice

Returns:

the arming status of this I2cDevice

getManufacturer

public HardwareDevice.Manufacturer getManufacturer()

Description copied from interface: HardwareDevice

Returns an indication of the manufacturer of this device.

Specified by:

getManufacturer in interface HardwareDevice

Returns:

the device's manufacturer

getDeviceName

public java.lang.String getDeviceName()

Description copied from interface: HardwareDevice

Returns a string suitable for display to the user as to the type of device.
 Note that this is a device-type-specific name; it has nothing to do with the
 name by which a user might have configured the device in a robot configuration.

Specified by:

getDeviceName in interface HardwareDevice

Returns:

device manufacturer and name

getConnectionInfo

public java.lang.String getConnectionInfo()

Description copied from interface: HardwareDevice

Get connection information about this device in a human readable format

Specified by:

getConnectionInfo in interface HardwareDevice

Returns:

connection info

getVersion

public int getVersion()

Description copied from interface: HardwareDevice

Version

Specified by:

getVersion in interface HardwareDevice

Returns:

get the version of this device

resetDeviceConfigurationForOpMode

public void resetDeviceConfigurationForOpMode()

Description copied from interface: HardwareDevice

Resets the device's configuration to that which is expected at the beginning of an OpMode.
 For example, motors will reset the their direction to 'forward'.

Specified by:

resetDeviceConfigurationForOpMode in interface HardwareDevice

close

public void close()

Description copied from interface: HardwareDevice

Closes this device

Specified by:

close in interface HardwareDevice

readI2cCacheFromModule

@Deprecated
public void readI2cCacheFromModule()

Deprecated.

Deprecated, use readI2cCacheFromController()

Specified by:

readI2cCacheFromModule in interface I2cDevice

writeI2cCacheToModule

@Deprecated
public void writeI2cCacheToModule()

Deprecated.

Deprecated, use writeI2cCacheToController()

Specified by:

writeI2cCacheToModule in interface I2cDevice

writeI2cPortFlagOnlyToModule

@Deprecated
public void writeI2cPortFlagOnlyToModule()

Deprecated.

Deprecated, use writeI2cPortFlagOnlyToController()

Specified by:

writeI2cPortFlagOnlyToModule in interface I2cDevice

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
"""Platform for Mazda device tracker integration."""
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS
from homeassistant.components.device_tracker.config_entry import TrackerEntity

from . import MazdaEntity
from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the device tracker platform."""
    client = hass.data[DOMAIN][config_entry.entry_id][DATA_CLIENT]
    coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR]

    entities = []

    for index, _ in enumerate(coordinator.data):
        entities.append(MazdaDeviceTracker(client, coordinator, index))

    async_add_entities(entities)

class MazdaDeviceTracker(MazdaEntity, TrackerEntity):
    """Class for the device tracker."""

    @property
    def name(self):
        """Return the name of the entity."""
        vehicle_name = self.get_vehicle_name()
        return f"{vehicle_name} Device Tracker"

    @property
    def unique_id(self):
        """Return a unique identifier for this entity."""
        return self.vin

    @property
    def icon(self):
        """Return the icon to use in the frontend."""
        return "mdi:car"

    @property
    def source_type(self):
        """Return the source type, eg gps or router, of the device."""
        return SOURCE_TYPE_GPS

    @property
    def force_update(self):
        """All updates do not need to be written to the state machine."""
        return False

    @property
    def latitude(self):
        """Return latitude value of the device."""
        return self.data["status"]["latitude"]

    @property
    def longitude(self):
        """Return longitude value of the device."""
        return self.data["status"]["longitude"]


text:
package org.usfirst.frc2832.Robot2017.autonCommands;

import org.usfirst.frc2832.Robot2017.DriveEncoders;
import org.usfirst.frc2832.Robot2017.Robot;
import org.usfirst.frc2832.Robot2017.RobotMap;
//import org.usfirst.frc2832.Robot2017.subsystems.DriveTrain;

import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/**
 *
 * Created 4/4/2017 with Pat from Lightning.  Make direction adjustment smoother
 */
public class VisionAimGear extends Command {
	private double initEncoderVal =0;
	private double distance;
	private byte[] buffer;
	private double startTime;
	private double endTime;
	private byte[] sendBuffer = "draco".getBytes();
	int dispCount = 0;
	    public VisionAimGear() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
     	requires (Robot.driveTrain);
     	endTime = 5; //changed from seven to five at chs

    }

    public VisionAimGear(double distance, int timeout) {
        // Use requires() here to declare subsystem dependencies

    	this();
    	setDistance(distance);
    	endTime = timeout;

    	}

    // Called just before this Command runs the first time
    protected void initialize() {
    	setInitEncoderVal(DriveEncoders.getAbsoluteValue());
    	buffer = new byte[1];
    	startTime = Timer.getFPGATimestamp();
		Robot.pixyValue = (byte) 255;
		dispCount = 0;

    }

	public void setDistance(double straightDistance) {
		this.distance = straightDistance;
	}

	public double getDistance() {
			return distance;
	}

	public double getInitEncoderVal() {
		return initEncoderVal;
	}

	public void setInitEncoderVal(double initEncoderVal) {
		this.initEncoderVal = initEncoderVal;
	}

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	//figure out how close is "close enough" because it's unlikely we'll ever get to 2.5 on the dot.  Figure this out through testing
    	double power = 0.5;

    /*	if (Robot.pixyCamera.transaction(sendBuffer, sendBuffer.length, buffer, 1))
    	{
    		pixyValue = buffer[0]  & 0xFF;
    	} */

    	SmartDashboard.putNumber("pixyXVisionAimGear", Robot.pixyValue);

    		final double turnP = 0.2; // 0.15; ***Changed by Calvin after match 43: 4/14/2017
    		double turn = (127.0 - ((double)Robot.pixyValue)) / 127;
    		//USE ONE OF THESE TWO
    		//Robot.driveTrain.setTankDriveCommand(power - (turn * turnP), power + (turn * turnP)); // was + - changed after match 43: 4/14/17
    		//MUST LOAD NEW ARDUINO CODE BEFORE THIS CAN BE USED
    		Robot.driveTrain.setTankDriveCommand(power + (turn * turnP), power - (turn * turnP));

    		//if (turn > 0)  // COMMENTED OUT
    			//System.out.println("VISION turning left");
    		//else if (turn < 0)
    			//System.out.println("VISION Turning Right");
    		//else
    			//System.out.println("VISION going straight");

    		if (dispCount > 10) {
    			System.out.println("Pixy: " + Robot.pixyValue + " turn factor: " + turn + " Motor Values: "  + (power - (turn * turnP)) + "  " + (power + (turn * turnP)));
    			dispCount = 0;
    		}
    		else {
    			dispCount++;

    		}

    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        double wheelSpeedR;
        double wheelSpeedL;
        double elapsedTime;
        wheelSpeedL = RobotMap.driveTrainLeftFront.getSpeed();
        wheelSpeedR = RobotMap.driveTrainRightFront.getSpeed();
        elapsedTime = Timer.getFPGATimestamp() - startTime;
        if (elapsedTime > 1 && (wheelSpeedL <= .001 && wheelSpeedR <= .001))
        {
        	//System.out.println("VISION stop by Speed");
        	return true;
        }
        else if  (elapsedTime > endTime)
        {
        	//System.out.println("VISION Stop by timeout");
        	return true;
        }
        return false;
    	//return (elapsedTime > 1 && (wheelSpeedL <= .001 && wheelSpeedR <= .001)) || (elapsedTime > endTime); //|| (NavX.ahrs.getWorldLinearAccelY() < -1); //-0.8);

    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.driveTrain.setTankDriveCommand(0, 0);

    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
using Assets.Scripts.Constants;
using Assets.Scripts.GameScripts.GameLogic.AILogic;
using Assets.Scripts.Utility;
using StateMachine;
using StateMachine.Action;
using UnityEngine;

namespace Assets.Scripts.AIStateMachine.StateMachineActions{
	[Info (category = "Custom",
	description = "Random Patrol around",
	url = "")]
    public class Patrol : StateAction
	{
        [FieldInfo(tooltip = "Maxium time allowed of a patrol path before renewing a new path")]
        public FloatParameter MaxiumSinglePathTime;
        [FieldInfo(tooltip = "Maximum Radius within which the patrol point is allowed to chose from")]
        public FloatParameter MaximumPatrolPointSelectionRadius;
        [FieldInfo(tooltip = "Minimum Radius within which the patrol point is allowed to chose from")]
        public FloatParameter MinimumPatrolPointSelectionRadius;

	    private PathFinding _pathFinding;
	    private float _currentPathPatroltime;
	    private GameObject _patrolPoint;

		public override void OnEnter()
		{
		    _currentPathPatroltime = 0f;
            if (_patrolPoint == null)
		    {
		        _patrolPoint = new GameObject();
		        _patrolPoint.transform.parent = stateMachine.owner.transform;
		    }
            if (_pathFinding == null)
            {
                _pathFinding = stateMachine.owner.GetComponent<PathFinding>();
            }
		}

	    public override void OnUpdate()
		{
		}

	    public override void OnFixedUpdate()
	    {
            _currentPathPatroltime += Time.fixedDeltaTime;

            if (stateMachine.owner.HitPointAtZero() || stateMachine.owner.IsInterrupted())
            {
                return;
            }

            if (_currentPathPatroltime >= MaxiumSinglePathTime || !_pathFinding.CurrentPathReachable || (Vector2.Distance(_patrolPoint.transform.position, stateMachine.owner.transform.position) <= 0.5f))
            {
                Vector3 newPatrolPointPosition = new Vector3(stateMachine.owner.transform.position.x + Random.Range(MinimumPatrolPointSelectionRadius, MaximumPatrolPointSelectionRadius) * (UtilityFunctions.RollChance(0.5f) ? 1 : -1),
                                                             stateMachine.owner.transform.position.y + Random.Range(MinimumPatrolPointSelectionRadius, MaximumPatrolPointSelectionRadius) * (UtilityFunctions.RollChance(0.5f) ? 1 : -1),
                                                             stateMachine.owner.transform.position.z);
                _patrolPoint.transform.position = newPatrolPointPosition;
                _pathFinding.UpdateTarget(_patrolPoint);
                _currentPathPatroltime = 0f;
            }

            _pathFinding.TrySearchPath();

            Vector2 moveDirection = _pathFinding.GetMoveDirection();

            if ((moveDirection == Vector2.zero) || !_pathFinding.CurrentPathReachable)
            {
                return;
            }

            stateMachine.owner.TriggerGameScriptEvent(GameScriptEvent.CharacterNonRigidMove, moveDirection);
	    }
	}
}


text:
import os

# Configurations
from config import BASE_DIR

# Import JSON
import json

# Import the models
from ..settings.models import VAT

def to_int(num):
	"""Convert decimal to integer for storage in DB"""
	return int(num * 100)

def to_dec(num):
	"""Convert to decimal after being retrieved from DB"""
	return float(num) / 100

def to_dec_string(num):
	"""Convert to decimal after being retrieved from DB"""
	return "%.2f" % (float(num) / 100)

def add_vat(price, vat):
	"""Add VAT to selling price before taxes"""
	vat_amount = VAT.query.get_or_404(vat)
	vat_coeff = (float(vat_amount.amount) / 10000) + 1
	return price * vat_coeff

def calc_margin(buying_price, selling_price):
	"""Compute gross margin for products"""
	selling_price = float(selling_price)
	buying_price = float(buying_price)
	margin = ((selling_price - buying_price) / buying_price) * 100
	return "%.2f" % margin

def read_setting(setting):
	with open(os.path.join(BASE_DIR, 'app/settings/config.json')) as json_data_file:
		config_data = json.load(json_data_file)
	return config_data[setting]