text:
import '../amp-pan-zoom';
import {Services} from '../../../../src/services';
import {createPointerEvent} from '../../../../testing/test-helper';
import {htmlFor} from '../../../../src/static-template';
import {listenOncePromise} from '../../../../src/event-helper';
import {setStyles} from '../../../../src/style';

describes.realWin(
  'amp-pan-zoom',
  {
    amp: {
      extensions: ['amp-pan-zoom'],
    },
  },
  (env) => {
    let win;
    let doc;
    let el;
    let impl;
    let svg;

    const measureMutateElementStub = (measure, mutate) => {
      return Promise.resolve().then(measure).then(mutate);
    };

    /**
     * This function takes an object of attributes and constructs and builds
     * an amp-pan-zoom element and attaches it to the page. Assumes the contents
     * to be an SVG of width and height 300x300.
     * @param {Object} opt_attributes
     */
    function getPanZoom(opt_attributes) {
      el = htmlFor(doc)`
      <amp-pan-zoom layout="fixed" width ="300" height="400">
      </amp-pan-zoom>
    `;

      for (const key in opt_attributes) {
        el.setAttribute(key, opt_attributes[key]);
      }

      svg = htmlFor(doc)`
      <svg width="100" height="100">
        <rect width="100" height="100" fill="#95B3D7"></rect>
      </svg>
    `;

      el.appendChild(svg);
      doc.body.appendChild(el);
      return el.build().then(() => {
        impl = el.implementation_;
        env.sandbox
          .stub(impl, 'measureMutateElement')
          .callsFake(measureMutateElementStub);
        env.sandbox
          .stub(impl, 'mutateElement')
          .callsFake((mutate) => measureMutateElementStub(undefined, mutate));
      });
    }

    beforeEach(() => {
      win = env.win;
      doc = win.document;
      env.iframe.height = 500;
      env.iframe.width = 400;
    });

    it('should schedule layout of own children', () => {
      let scheduleLayoutSpy;
      return getPanZoom()
        .then(() => {
          scheduleLayoutSpy = env.sandbox.spy(
            Services.ownersForDoc(impl.element),
            'scheduleLayout'
          );
          el.layoutCallback();
        })
        .then(() => {
          expect(scheduleLayoutSpy).to.be.calledOnceWith(impl.element, svg);
        });
    });

    it('should size contents correctly', () => {
      return getPanZoom()
        .then(() => el.layoutCallback())
        .then(() => {
          expect(svg.clientWidth).to.equal(300);
          expect(svg.clientHeight).to.equal(300);
          expect(svg.getAttribute('class')).to.match(
            /i-amphtml-pan-zoom-child/
          );
          expect(el.className).to.match(/i-amphtml-pan-zoom/);
        });
    });

    it('should position and scale correctly based on initial values', () => {
      return getPanZoom({
        'initial-scale': '2',
        'initial-x': '10',
        'initial-y': '50',
      })
        .then(() => el.layoutCallback())
        .then(() => {
          expect(impl.startX_).to.equal(10);
          expect(impl.posX_).to.equal(10);
          expect(impl.startY_).to.equal(50);
          expect(impl.posY_).to.equal(50);
          expect(svg.style.transform).to.equal(
            'translate(10px, 50px) scale(2)'
          );
        });
    });

    it('should initialize all measured variables correctly', () => {
      return getPanZoom()
        .then(() => el.layoutCallback())
        .then(() => {
          expect(impl.startScale_).to.equal(1);
          expect(impl.startX_).to.equal(0);
          expect(impl.startY_).to.equal(0);
          expect(impl.sourceWidth_).to.equal(100);
          expect(impl.sourceHeight_).to.equal(100);
        });
    });

    it('should update pan and zoom bounds correctly', () => {
      return getPanZoom()
        .then(() => {
          el.getBoundingClientRect = () => {
            return {
              'top': 0,
              'left': 0,
              'height': 400,
              'width': 300,
            };
          };
          return el.layoutCallback();
        })
        .then(() => {
          expect(impl.elementBox_.height).to.equal(400);
          expect(impl.elementBox_.width).to.equal(300);
          expect(impl.contentBox_.height).to.equal(300);
          expect(impl.contentBox_.width).to.equal(300);

          expect(impl.minX_).to.equal(0);
          expect(impl.maxX_).to.equal(0);
          expect(impl.minY_).to.equal(0);
          expect(impl.maxY_).to.equal(0);

          impl.updatePanZoomBounds_(2);
          // (600 - 300) / 2
          expect(impl.minX_).to.equal(-150);
          expect(impl.maxX_).to.equal(150);
          // (600 - 400) / 2
          expect(impl.minY_).to.equal(-100);
          expect(impl.maxY_).to.equal(100);

          impl.updatePanZoomBounds_(3);
          // (900 - 300) / 2
          expect(impl.minX_).to.equal(-300);
          expect(impl.maxX_).to.equal(300);
          // (900 - 400) / 2
          expect(impl.minY_).to.equal(-250);
          expect(impl.maxY_).to.equal(250);
        });
    });

    it('should correctly update bounds with top-aligned content', () => {
      return getPanZoom({
        'style': 'display: initial',
      })
        .then(() => {
          el.getBoundingClientRect = () => {
            return {
              'top': 0,
              'left': 0,
              'height': 400,
              'width': 300,
            };
          };
          return el.layoutCallback();
        })
        .then(() => {
          expect(impl.minY_).to.equal(0);
          expect(impl.maxY_).to.equal(0);

          impl.updatePanZoomBounds_(2);
          expect(impl.minY_).to.equal(-50);
          expect(impl.maxY_).to.equal(150);

          impl.updatePanZoomBounds_(3);
          expect(impl.minY_).to.equal(-200);
          expect(impl.maxY_).to.equal(300);
        });
    });

    it('should correctly update bounds with left-aligned content', () => {
      return getPanZoom({
        'height': '300',
        'width': '400',
        'style': 'justify-content: start',
      })
        .then(() => {
          el.getBoundingClientRect = () => {
            return {
              'top': 0,
              'left': 0,
              'height': 300,
              'width': 400,
            };
          };
          return el.layoutCallback();
        })
        .then(() => {
          expect(impl.minY_).to.equal(0);
          expect(impl.maxY_).to.equal(0);

          impl.updatePanZoomBounds_(2);
          expect(impl.minX_).to.equal(-50);
          expect(impl.maxX_).to.equal(150);

          impl.updatePanZoomBounds_(3);
          expect(impl.minX_).to.equal(-200);
          expect(impl.maxX_).to.equal(300);
        });
    });

    it('should correctly update bounds with bottom-aligned content', () => {
      return getPanZoom({
        'style': 'justify-content: start; flex-direction: column-reverse',
      })
        .then(() => {
          el.getBoundingClientRect = () => {
            return {
              'top': 0,
              'left': 0,
              'height': 400,
              'width': 300,
            };
          };
          return el.layoutCallback();
        })
        .then(() => {
          expect(impl.minY_).to.equal(0);
          expect(impl.maxY_).to.equal(0);

          impl.updatePanZoomBounds_(2);

          expect(impl.minY_).to.equal(-150);
          expect(impl.maxY_).to.equal(50);

          impl.updatePanZoomBounds_(3);
          expect(impl.minY_).to.equal(-300);
          expect(impl.maxY_).to.equal(200);
        });
    });

    it('should correctly update css after calling transform', () => {
      return getPanZoom()
        .then(() => el.layoutCallback())
        .then(() => impl.transform(10, 20, 2))
        .then(() => {
          expect(impl.posX_).to.equal(10);
          expect(impl.posY_).to.equal(20);
          expect(impl.scale_).to.equal(2);
          expect(svg.style.transform).to.equal(
            'translate(10px, 20px) scale(2)'
          );
        });
    });

    describe('reset-on-resize', () => {
      it('should clear inline width/height before measuring', async function () {
        await getPanZoom();
        await el.layoutCallback();
        expect(svg.style.width).to.equal('300px');
        expect(svg.style.height).to.equal('300px');
        setStyles(svg, {
          'width': '50px',
          'height': '400px',
        });
        expect(svg.style.width).to.equal('50px');
        expect(svg.style.height).to.equal('400px');
        await impl.resetContentDimensions_();
        expect(svg.style.width).to.equal('300px');
        expect(svg.style.height).to.equal('300px');
      });
    });

    describe('gestures', () => {
      it('should pan correctly via mouse when zoomed', async function () {
        await getPanZoom();
        await el.layoutCallback();
        await impl.transform(0, 0, 2);
        expect(svg.style.transform).to.equal('translate(0px, 0px) scale(2)');
        const mouseDown = createPointerEvent('mousedown', 10, 10);
        const mouseMove = createPointerEvent('mousemove', 20, 20);
        const mouseUp = createPointerEvent('mouseup', 20, 20);
        const transformEndPromise = listenOncePromise(el, 'transformEnd');
        el.dispatchEvent(mouseDown);
        el.dispatchEvent(mouseMove);
        el.dispatchEvent(mouseUp);
        await transformEndPromise;
        expect(svg.style.transform).to.equal('translate(10px, 10px) scale(2)');
      });
    });

    describe('transformEnd', () => {
      it('should trigger only once after double tap zoom', async function () {
        await getPanZoom();
        await el.layoutCallback();
        const transformEndPromise = listenOncePromise(el, 'transformEnd');
        const actionTriggerSpy = env.sandbox.spy(impl.action_, 'trigger');
        impl.handleDoubleTap({clientX: 10, clientY: 10});
        await transformEndPromise;
        expect(actionTriggerSpy).to.be.calledOnce;
      });

      it('should not trigger while pinch zooming', async function () {
        await getPanZoom();
        await el.layoutCallback();
        const actionTriggerSpy = env.sandbox.spy(impl.action_, 'trigger');
        await impl.handlePinch({
          centerClientX: 10,
          centerClientY: 10,
          deltaX: 10,
          deltaY: 10,
          dir: 1,
          last: false,
        });
        expect(actionTriggerSpy).not.to.be.called;
      });

      it('should trigger exactly once after pinch zoom ends', async function () {
        await getPanZoom();
        await el.layoutCallback();
        const transformEndPromise = listenOncePromise(el, 'transformEnd');
        const actionTriggerSpy = env.sandbox.spy(impl.action_, 'trigger');
        impl.handlePinch({
          centerClientX: 10,
          centerClientY: 10,
          deltaX: 10,
          deltaY: 10,
          dir: 1,
          last: true, // This indicates zoom ended
        });
        await transformEndPromise;
        expect(actionTriggerSpy).to.be.calledOnce;
      });

      it('should not trigger while panning', async function () {
        await getPanZoom();
        await el.layoutCallback();
        const actionTriggerSpy = env.sandbox.spy(impl.action_, 'trigger');
        await impl.handleSwipe({
          deltaX: 10,
          deltaY: 10,
          last: false,
          velocityX: 10,
          velocityY: 10,
        });
        expect(actionTriggerSpy).not.to.be.called;
      });

      it('should trigger exactly once after panning ends', async function () {
        await getPanZoom();
        await el.layoutCallback();
        const transformEndPromise = listenOncePromise(el, 'transformEnd');
        const actionTriggerSpy = env.sandbox.spy(impl.action_, 'trigger');
        impl.handleSwipe({
          deltaX: 10,
          deltaY: 10,
          last: true, // This indicates panning ended.
          velocityX: 10,
          velocityY: 10,
        });
        await transformEndPromise;
        expect(actionTriggerSpy).to.be.calledOnce;
      });
    });
  }
);


text:
layout: page
title: "PHIL 3190: War and Morality Statistics"
comments: true
description: "blanks"
keywords: "PHIL,3190,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 3.4%

**Percent incomplete**: 1.62%

**Average grade** (4.0 scale): 2.9

**Standard deviation in grades** (4.0 scale): 0.2

**Average workload** (raw): 2.35

**Standard deviation in workload** (raw): 0.19

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 4.9

**Standard deviation in course rating** (6 point scale): 0.51

**Average instructor rating** (6 point scale): 5.21

**Standard deviation in instructor rating** (6 point scale): 0.53

**Instructors**: Martin Robert Eyestone, Diane Mayer, Thomas Nelson Metcalf, Ryan Mott, Daniel Sturgis, Katharyn Waidler, David Youkey

#### GENERAL CLASS INFORMATION

**Years provided**: Spring 2007, Fall 2007, Spring 2010, Spring 2011, Fall 2011, Spring 2012, Fall 2012, Spring 2013, Fall 2013, Spring 2014, Fall 2014, Fall 2015, Fall 2016

**Credits**: 3

**RAP/Honors class?** Neither

**Number of Sections**: 13

**Department**: PHIL

**College**: College of Arts and Sciences

**A&S Division**: Arts and Humanities

**Level**: Upper

**Activity**: LEC - Lecture

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;

using System.Management.Automation.Internal;
using Dbg = System.Management.Automation.Diagnostics;

namespace System.Management.Automation
{
    /// <summary>
    /// Defines generic utilities and helper methods for PowerShell
    /// </summary>
    internal static class PathUtils
    {
        /// <summary>
        /// THE method for opening a file for writing.
        /// Should be used by all cmdlets that write to a file.
        /// </summary>
        /// <param name="cmdlet">cmdlet that is opening the file (used mainly for error reporting)</param>
        /// <param name="filePath">path to the file (as specified on the command line - this method will resolve the path)</param>
        /// <param name="encoding">encoding (this method will convert the command line strin to an Encoding instance)</param>
        /// <param name="defaultEncoding">if <c>true</c>, then we will use default .NET encoding instead of the encoding specified in <paramref name="encoding"/> parameter</param>
        /// <param name="Append"></param>
        /// <param name="Force"></param>
        /// <param name="NoClobber"></param>
        /// <param name="fileStream">Result1: <see cref="FileStream"/> opened for writing</param>
        /// <param name="streamWriter">Result2: <see cref="StreamWriter"/> (inherits from <see cref="TextWriter"/>) opened for writing</param>
        /// <param name="readOnlyFileInfo">Result3: file info that should be used to restore file attributes after done with the file (<c>null</c> is this is not needed)</param>
        /// <param name="isLiteralPath">True if wildcard expansion should be bypassed.</param>
        internal static void MasterStreamOpen(
            PSCmdlet cmdlet,
            string filePath,
            string encoding,
            bool defaultEncoding,
            bool Append,
            bool Force,
            bool NoClobber,
            out FileStream fileStream,
            out StreamWriter streamWriter,
            out FileInfo readOnlyFileInfo,
            bool isLiteralPath
            )
        {
            Encoding resolvedEncoding = EncodingConversion.Convert(cmdlet, encoding);

            MasterStreamOpen(cmdlet, filePath, resolvedEncoding, defaultEncoding, Append, Force, NoClobber, out fileStream, out streamWriter, out readOnlyFileInfo, isLiteralPath);
        }

        /// <summary>
        /// THE method for opening a file for writing.
        /// Should be used by all cmdlets that write to a file.
        /// </summary>
        /// <param name="cmdlet">cmdlet that is opening the file (used mainly for error reporting)</param>
        /// <param name="filePath">path to the file (as specified on the command line - this method will resolve the path)</param>
        /// <param name="resolvedEncoding">encoding (this method will convert the command line strin to an Encoding instance)</param>
        /// <param name="defaultEncoding">if <c>true</c>, then we will use default .NET encoding instead of the encoding specified in <paramref name="encoding"/> parameter</param>
        /// <param name="Append"></param>
        /// <param name="Force"></param>
        /// <param name="NoClobber"></param>
        /// <param name="fileStream">Result1: <see cref="FileStream"/> opened for writing</param>
        /// <param name="streamWriter">Result2: <see cref="StreamWriter"/> (inherits from <see cref="TextWriter"/>) opened for writing</param>
        /// <param name="readOnlyFileInfo">Result3: file info that should be used to restore file attributes after done with the file (<c>null</c> is this is not needed)</param>
        /// <param name="isLiteralPath">True if wildcard expansion should be bypassed.</param>
        internal static void MasterStreamOpen(
            PSCmdlet cmdlet,
            string filePath,
            Encoding resolvedEncoding,
            bool defaultEncoding,
            bool Append,
            bool Force,
            bool NoClobber,
            out FileStream fileStream,
            out StreamWriter streamWriter,
            out FileInfo readOnlyFileInfo,
            bool isLiteralPath)
        {
            fileStream = null;
            streamWriter = null;
            readOnlyFileInfo = null;

            // resolve the path and the encoding
            string resolvedPath = ResolveFilePath(filePath, cmdlet, isLiteralPath);

            try
            {
                // variable to track file open mode
                // this is controlled by append/force parameters
                FileMode mode = FileMode.Create;
                if (Append)
                {
                    mode = FileMode.Append;
                }
                else if (NoClobber)
                {
                    // throw IOException if file exists
                    mode = FileMode.CreateNew;
                }

                if (Force && (Append || !NoClobber))
                {
                    if (File.Exists(resolvedPath))
                    {
                        FileInfo fInfo = new FileInfo(resolvedPath);
                        if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                        {
                            // remember to reset the read-only attribute later
                            readOnlyFileInfo = fInfo;
                            // Clear the read-only attribute
                            fInfo.Attributes &= ~(FileAttributes.ReadOnly);
                        }
                    }
                }

                // if the user knows what he/she is doing and uses "-Force" switch,
                // then we let more than 1 process write to the same file at the same time
                FileShare fileShare = Force ? FileShare.ReadWrite : FileShare.Read;

                // mode is controlled by force and ShouldContinue()
                fileStream = new FileStream(resolvedPath, mode, FileAccess.Write, fileShare);

                // create stream writer
                // NTRAID#Windows Out Of Band Releases-931008-2006/03/27
                // For some reason, calling this without specifying
                // the encoding is different from passing Encoding.Default.
                if (defaultEncoding)
                    streamWriter = new StreamWriter(fileStream);
                else
                    streamWriter = new StreamWriter(fileStream, resolvedEncoding);
            }
            // These are the known exceptions for File.Load and StreamWriter.ctor
            catch (ArgumentException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (IOException e)
            {
                if (NoClobber && File.Exists(resolvedPath))
                {
                    // This probably happened because the file already exists
                    ErrorRecord errorRecord = new ErrorRecord(
                        e, "NoClobber", ErrorCategory.ResourceExists, resolvedPath);
                    errorRecord.ErrorDetails = new ErrorDetails(
                        cmdlet,
                        "PathUtilsStrings",
                        "UtilityFileExistsNoClobber",
                        filePath,
                        "NoClobber"); // prevents localization

                    // NOTE: this call will throw
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (UnauthorizedAccessException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (NotSupportedException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
            catch (System.Security.SecurityException e)
            {
                // NOTE: this call will throw
                ReportFileOpenFailure(cmdlet, resolvedPath, e);
            }
        } // void MasterStreamOpen

        internal static void ReportFileOpenFailure(Cmdlet cmdlet, string filePath, Exception e)
        {
            ErrorRecord errorRecord = new ErrorRecord(
                e,
                "FileOpenFailure",
                ErrorCategory.OpenError,
                null);

            cmdlet.ThrowTerminatingError(errorRecord);
        }

        internal static StreamReader OpenStreamReader(PSCmdlet command, string filePath, string encoding, bool isLiteralPath)
        {
            FileStream fileStream = OpenFileStream(filePath, command, isLiteralPath);
            if (encoding == null)
            {
                return new StreamReader(fileStream);
            }
            else
            {
                return new StreamReader(fileStream, EncodingConversion.Convert(command, encoding));
            }
        }

        internal static FileStream OpenFileStream(string filePath, PSCmdlet command, bool isLiteralPath)
        {
            string resolvedPath = PathUtils.ResolveFilePath(filePath, command, isLiteralPath);

            try
            {
                return new FileStream(resolvedPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            }
            // These are the known exceptions for FileStream.ctor
            catch (ArgumentException e)
            {
                PathUtils.ReportFileOpenFailure(command, filePath, e);
                return null; // the line above will throw - silencing the compiler
            }
            catch (IOException e)
            {
                PathUtils.ReportFileOpenFailure(command, filePath, e);
                return null; // the line above will throw - silencing the compiler
            }
            catch (UnauthorizedAccessException e)
            {
                PathUtils.ReportFileOpenFailure(command, filePath, e);
                return null; // the line above will throw - silencing the compiler
            }
            catch (NotSupportedException e)
            {
                PathUtils.ReportFileOpenFailure(command, filePath, e);
                return null; // the line above will throw - silencing the compiler
            }
            catch (System.Management.Automation.DriveNotFoundException e)
            {
                PathUtils.ReportFileOpenFailure(command, filePath, e);
                return null; // the line above will throw - silencing the compiler
            }
        }

        /// <summary>
        /// resolve a user provided file name or path (including globbing characters)
        /// to a fully qualified file path, using the file system provider
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="command"></param>
        /// <returns></returns>
        internal static string ResolveFilePath(string filePath, PSCmdlet command)
        {
            return ResolveFilePath(filePath, command, false);
        }

        /// <summary>
        /// resolve a user provided file name or path (including globbing characters)
        /// to a fully qualified file path, using the file system provider
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="command"></param>
        /// <param name="isLiteralPath"></param>
        /// <returns></returns>
        internal static string ResolveFilePath(string filePath, PSCmdlet command, bool isLiteralPath)
        {
            string path = null;

            try
            {
                ProviderInfo provider = null;
                PSDriveInfo drive = null;
                List<string> filePaths = new List<string>();

                if (isLiteralPath)
                {
                    filePaths.Add(command.SessionState.Path.GetUnresolvedProviderPathFromPSPath(filePath, out provider, out drive));
                }
                else
                {
                    filePaths.AddRange(command.SessionState.Path.GetResolvedProviderPathFromPSPath(filePath, out provider));
                }

                if (!provider.NameEquals(command.Context.ProviderNames.FileSystem))
                {
                    ReportWrongProviderType(command, provider.FullName);
                }

                if (filePaths.Count > 1)
                {
                    ReportMultipleFilesNotSupported(command);
                }
                if (filePaths.Count == 0)
                {
                    ReportWildcardingFailure(command, filePath);
                }

                path = filePaths[0];
            }
            catch (ItemNotFoundException)
            {
                path = null;
            }
            if (string.IsNullOrEmpty(path))
            {
                CmdletProviderContext cmdletProviderContext = new CmdletProviderContext(command);
                ProviderInfo provider = null;
                PSDriveInfo drive = null;
                path =
                    command.SessionState.Path.GetUnresolvedProviderPathFromPSPath(
                        filePath, cmdletProviderContext, out provider, out drive);
                cmdletProviderContext.ThrowFirstErrorOrDoNothing();
                if (!provider.NameEquals(command.Context.ProviderNames.FileSystem))
                {
                    ReportWrongProviderType(command, provider.FullName);
                }
            }
            return path;
        }

        internal static void ReportWrongProviderType(Cmdlet cmdlet, string providerId)
        {
            string msg = StringUtil.Format(PathUtilsStrings.OutFile_ReadWriteFileNotFileSystemProvider, providerId);

            ErrorRecord errorRecord = new ErrorRecord(
                PSTraceSource.NewInvalidOperationException(),
                "ReadWriteFileNotFileSystemProvider",
                ErrorCategory.InvalidArgument,
                null);

            errorRecord.ErrorDetails = new ErrorDetails(msg);
            cmdlet.ThrowTerminatingError(errorRecord);
        }

        internal static void ReportMultipleFilesNotSupported(Cmdlet cmdlet)
        {
            string msg = StringUtil.Format(PathUtilsStrings.OutFile_MultipleFilesNotSupported);

            ErrorRecord errorRecord = new ErrorRecord(
                PSTraceSource.NewInvalidOperationException(),
                "ReadWriteMultipleFilesNotSupported",
                ErrorCategory.InvalidArgument,
                null);

            errorRecord.ErrorDetails = new ErrorDetails(msg);
            cmdlet.ThrowTerminatingError(errorRecord);
        }

        internal static void ReportWildcardingFailure(Cmdlet cmdlet, string filePath)
        {
            string msg = StringUtil.Format(PathUtilsStrings.OutFile_DidNotResolveFile, filePath);

            ErrorRecord errorRecord = new ErrorRecord(
                new FileNotFoundException(),
                "FileOpenFailure",
                ErrorCategory.OpenError,
                filePath);

            errorRecord.ErrorDetails = new ErrorDetails(msg);
            cmdlet.ThrowTerminatingError(errorRecord);
        }

        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;
            try
            {
                string rootedPath = Microsoft.PowerShell.Commands.ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith(".", StringComparison.OrdinalIgnoreCase))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }
                if (string.IsNullOrEmpty(rootedPath))
                {
                    string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                    rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details = new ErrorDetails(errorMessage);
                        ErrorRecord errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);

                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details = new ErrorDetails(errorMessage);
                ErrorRecord errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return directoryInfo;
        }

        internal static DirectoryInfo CreateTemporaryDirectory()
        {
            DirectoryInfo temporaryDirectory = new DirectoryInfo(Path.GetTempPath());
            DirectoryInfo moduleDirectory;
            do
            {
                moduleDirectory = new DirectoryInfo(
                    Path.Combine(
                        temporaryDirectory.FullName,
                        string.Format(
                            null,
                            "tmp_{0}",
                            Path.GetRandomFileName())));
            } while (moduleDirectory.Exists);

            Directory.CreateDirectory(moduleDirectory.FullName);
            return new DirectoryInfo(moduleDirectory.FullName);
        }
    }

    internal static class EncodingConversion
    {
        internal const string Unknown = "unknown";
        internal const string String = "string";
        internal const string Unicode = "unicode";
        internal const string BigEndianUnicode = "bigendianunicode";
        internal const string Ascii = "ascii";
        internal const string Utf8 = "utf8";
        internal const string Utf7 = "utf7";
        internal const string Utf32 = "utf32";
        internal const string Default = "default";
        internal const string OEM = "oem";

        /// <summary>
        /// retrieve the encoding paramater from the command line
        /// it throws if the encoding does not match the known ones
        /// </summary>
        /// <returns>a System.Text.Encoding object (null if no encoding specified)</returns>
        internal static Encoding Convert(Cmdlet cmdlet, string encoding)
        {
            if (string.IsNullOrEmpty(encoding))
            {
                // no parameter passed, default to Unicode (OS preferred)
                return System.Text.Encoding.Unicode;
            }

            // Default to unicode (this matches Get-Content)
            if (string.Equals(encoding, Unknown, StringComparison.OrdinalIgnoreCase))
                return System.Text.Encoding.Unicode;

            if (string.Equals(encoding, String, StringComparison.OrdinalIgnoreCase))
                return System.Text.Encoding.Unicode;

            // these are the encodings the CLR supports
            if (string.Equals(encoding, Unicode, StringComparison.OrdinalIgnoreCase))
                return System.Text.Encoding.Unicode;

            if (string.Equals(encoding, BigEndianUnicode, StringComparison.OrdinalIgnoreCase))
                return System.Text.Encoding.BigEndianUnicode;

            if (string.Equals(encoding, Utf8, StringComparison.OrdinalIgnoreCase))
                return System.Text.Encoding.UTF8;

            if (string.Equals(encoding, Ascii, StringComparison.OrdinalIgnoreCase))
                return System.Text.Encoding.ASCII;

            if (string.Equals(encoding, Utf7, StringComparison.OrdinalIgnoreCase))
                return System.Text.Encoding.UTF7;

            if (string.Equals(encoding, Utf32, StringComparison.OrdinalIgnoreCase))
                return System.Text.Encoding.UTF32;

            if (string.Equals(encoding, Default, StringComparison.OrdinalIgnoreCase))
                return ClrFacade.GetDefaultEncoding();

            if (string.Equals(encoding, OEM, StringComparison.OrdinalIgnoreCase))
            {
                return ClrFacade.GetOEMEncoding();
            }

            // error condition: unknown encoding value
            string validEncodingValues = string.Join(
                ", ",
                new string[] { Unknown, String, Unicode, BigEndianUnicode, Ascii, Utf8, Utf7, Utf32, Default, OEM });
            string msg = StringUtil.Format(PathUtilsStrings.OutFile_WriteToFileEncodingUnknown,
                encoding, validEncodingValues);

            ErrorRecord errorRecord = new ErrorRecord(
                PSTraceSource.NewArgumentException("Encoding"),
                "WriteToFileEncodingUnknown",
                ErrorCategory.InvalidArgument,
                null);

            errorRecord.ErrorDetails = new ErrorDetails(msg);
            cmdlet.ThrowTerminatingError(errorRecord);

            return null;
        }
    }
}


text:
package edu.usc.cct.rapport.web_games.client.trading_area.agent_behaviour.decision_making;

import com.google.gwt.core.client.Duration;

import edu.usc.cct.rapport.web_games.client.support.tuple.Pair;
import edu.usc.cct.rapport.web_games.client.trading_area.AgentEnum;
import edu.usc.cct.rapport.web_games.client.trading_area.NegotiationSession;
import edu.usc.cct.rapport.web_games.client.trading_area.Proposal;
import edu.usc.cct.rapport.web_games.client.trading_area.TradingAction;
import edu.usc.cct.rapport.web_games.client.trading_area.TradingActionEnum;

public class RationalProposalDecisionMakingStrategy implements ProposalDecisionMakingStrategy {

	final private ProposalDecisionMakingTactic tactic;

	public RationalProposalDecisionMakingStrategy(final ProposalDecisionMakingTactic tactic) {
		this.tactic = tactic;
	};

	@Override
	public TradingAction determineAction(final int counterpartBestAlternativeToNegotiatedActionValue, final NegotiationSession negotiationSession) {

		final Pair<TradingActionEnum, Proposal> action;

		final int plyRemaining = negotiationSession.getPlyRemaining();
		if (1 == plyRemaining) {
			if (negotiationSession.isEmpty()) {
				action = acceptOrClaimBATNAValue(null, counterpartBestAlternativeToNegotiatedActionValue);
			} else {
				final Proposal mostRecentlyReceivedProposal = negotiationSession.get(negotiationSession.size()-1).getProposal();
				action = acceptOrClaimBATNAValue(mostRecentlyReceivedProposal, counterpartBestAlternativeToNegotiatedActionValue);
			};
		} else {
			action = tactic.acceptProposalOrOfferCounterproposal(negotiationSession, counterpartBestAlternativeToNegotiatedActionValue);
		};

		final double timestamp = Duration.currentTimeMillis();
		final TradingAction result = new TradingAction(AgentEnum.counterpart, timestamp, action.getFirst(), action.getSecond());
		return result;
	};

	private Pair<TradingActionEnum, Proposal> acceptOrClaimBATNAValue(final Proposal proposalToAcceptOrReject, final int counterpartBestAlternativeToNegotiatedActionValue) {

		final int valueOfMostRecentlyReceivedProposal;
		if (proposalToAcceptOrReject == null) {
			valueOfMostRecentlyReceivedProposal = Integer.MIN_VALUE;
		} else {
			valueOfMostRecentlyReceivedProposal = proposalToAcceptOrReject.getProposalValueFromAgentPerspective(AgentEnum.counterpart);
		};

		final Pair<TradingActionEnum, Proposal> result;
		if (valueOfMostRecentlyReceivedProposal >= counterpartBestAlternativeToNegotiatedActionValue) {
			result = new Pair<TradingActionEnum, Proposal>(TradingActionEnum.acceptProposal, null);
		} else {
			result = new Pair<TradingActionEnum, Proposal>(TradingActionEnum.claimBATNAValue, null);
		};

		return result;
	};

};


text:
package org.kuali.rice.krms.api.repository.agenda;

import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.CoreConstants;
import org.kuali.rice.core.api.mo.AbstractDataTransferObject;
import org.kuali.rice.core.api.mo.ModelBuilder;
import org.kuali.rice.core.api.util.jaxb.MapStringStringAdapter;
import org.kuali.rice.krms.api.KrmsConstants;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Concrete model object implementation of KRMS Repository Agenda
 * immutable.
 * Instances of Agenda can be (un)marshalled to and from XML.
 *
 * @see AgendaDefinitionContract
 */
@XmlRootElement(name = AgendaDefinition.Constants.ROOT_ELEMENT_NAME)
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = AgendaDefinition.Constants.TYPE_NAME, propOrder = {
		AgendaDefinition.Elements.AGENDA_ID,
		AgendaDefinition.Elements.NAME,
		AgendaDefinition.Elements.TYPE_ID,
		AgendaDefinition.Elements.CONTEXT_ID,
        AgendaDefinition.Elements.ACTIVE,
		AgendaDefinition.Elements.FIRST_ITEM_ID,
		AgendaDefinition.Elements.ATTRIBUTES,
        CoreConstants.CommonElements.VERSION_NUMBER,
		CoreConstants.CommonElements.FUTURE_ELEMENTS
})
public final class AgendaDefinition extends AbstractDataTransferObject implements AgendaDefinitionContract {
	private static final long serialVersionUID = 2783959459503209577L;

	@XmlElement(name = Elements.AGENDA_ID, required = false)
	private final String id;

	@XmlElement(name = Elements.NAME, required = true)
	private final String name;

	@XmlElement(name = Elements.TYPE_ID, required = false)
	private final String typeId;

	@XmlElement(name = Elements.CONTEXT_ID, required = true)
	private final String contextId;

    @XmlElement(name = Elements.ACTIVE, required = false)
    private final boolean active;

	@XmlElement(name = Elements.FIRST_ITEM_ID, required = false)
	private final String firstItemId;

	@XmlElement(name = Elements.ATTRIBUTES, required = false)
	@XmlJavaTypeAdapter(value = MapStringStringAdapter.class)
	private final Map<String, String> attributes;

    @XmlElement(name = CoreConstants.CommonElements.VERSION_NUMBER, required = false)
    private final Long versionNumber;

    @SuppressWarnings("unused")
    @XmlAnyElement
    private final Collection<org.w3c.dom.Element> _futureElements = null;

	/**
     * This constructor should never be called.
     * It is only present for use during JAXB unmarshalling.
     */
    private AgendaDefinition() {
    	this.id = null;
    	this.name = null;
    	this.typeId = null;
    	this.contextId = null;
        this.active = true;
    	this.firstItemId = null;
    	this.attributes = null;
        this.versionNumber = null;
    }

    /**
	 * Constructs a KRMS Repository Agenda object from the given builder.
	 * This constructor is private and should only ever be invoked from the builder.
	 *
	 * @param builder the Builder from which to construct the Agenda
	 */
    private AgendaDefinition(Builder builder) {
        this.id = builder.getId();
        this.name = builder.getName();
        this.typeId = builder.getTypeId();
        this.contextId = builder.getContextId();
        this.active = builder.isActive();
        this.firstItemId = builder.getFirstItemId();
        if (builder.getAttributes() != null){
        	this.attributes = Collections.unmodifiableMap(new HashMap<String, String>(builder.getAttributes()));
        } else {
        	this.attributes = null;
        }
        this.versionNumber = builder.getVersionNumber();
    }

	@Override
	public String getId() {
		return this.id;
	}

	@Override
	public String getName() {
		return this.name;
	}

	@Override
	public String getTypeId() {
		return this.typeId;
	}

	@Override
	public String getContextId(){
		return this.contextId;
	}

    @Override
    public boolean isActive() {
        return this.active;
    }

	@Override
	public String getFirstItemId(){
		return this.firstItemId;
	}

    /**
     * Returns the internal list of custom/remote attributes associated with the
     * agenda.
     *
     * @return the internal list of custom/remote attribute of the agenda.
     */
	public Map<String, String> getAttributes() {
		return this.attributes;
	}

    @Override
    public Long getVersionNumber() {
        return versionNumber;
    }

 	/**
     * This builder is used to construct instances of KRMS Repository Agenda.  It enforces the constraints of the {@link AgendaDefinitionContract}.
     */
    public static class Builder implements AgendaDefinitionContract, ModelBuilder, Serializable {

        private static final long serialVersionUID = -8862851720709537839L;

		private String id;
        private String name;
        private String typeId;
        private String contextId;
        private boolean active;
        private String firstItemId;
        private Map<String, String> attributes;
        private Long versionNumber;

		/**
		 * Private constructor for creating a builder with all of it's required attributes.
		 */
        private Builder(String id, String name, String typeId, String contextId) {
        	setId(id);
            setName(name);
            setTypeId(typeId);
            setContextId(contextId);
            setActive(true);
            setAttributes(new HashMap<String, String>());
        }

         /**
          * Create a builder with the given parameters.
          *
          * @param id
          * @param name
          * @param typeId
          * @param contextId
          * @return Builder
          */
        public static Builder create(String id, String name, String typeId, String contextId){
        	return new Builder(id, name, typeId, contextId);
        }

        /**
         * Creates a builder by populating it with data from the given {@link AgendaDefinitionContract}.
         *
         * @param contract the contract from which to populate this builder
         * @return an instance of the builder populated with data from the contract
         * @throws IllegalArgumentException if the contract is null
         */
        public static Builder create(AgendaDefinitionContract contract) {
        	if (contract == null) {
                throw new IllegalArgumentException("contract is null");
            }
            Builder builder =  new Builder(contract.getId(), contract.getName(), contract.getTypeId(), contract.getContextId());
            builder.setActive(contract.isActive());
            builder.setFirstItemId( contract.getFirstItemId() );
            if (contract.getAttributes() != null) {
                builder.setAttributes(new HashMap<String, String>(contract.getAttributes()));
            }
            builder.setVersionNumber(contract.getVersionNumber());
            return builder;
        }

		/**
		 * Sets the value of the id on this builder to the given value.
		 *
		 * @param agendaId the agenda id value to set, may be null, must not be blank
         *
The agenda id is generated by the system.  For new agendas (not yet persisted) this field is null.
         *    For existing agendas this field is the generated id.

		 * @throws IllegalArgumentException if the id is blank
		 */
        public void setId(String agendaId) {
            if (agendaId != null && StringUtils.isBlank(agendaId)) {
                throw new IllegalArgumentException("agenda ID must be null or non-blank");
            }
			this.id = agendaId;
		}

        /**
         * Set the value of the name on this builder to the given value.
         *
         * @param name the name of the agenda to set, must not be null or blank
         * @throws IllegalArgumentException if the name is null or blank
         */
        public void setName(String name) {
            if (StringUtils.isBlank(name)) {
                throw new IllegalArgumentException("name is blank");
            }
			this.name = name;
		}

         /**
          * Set the value of the type id on this builder to the given value.
          * @param typeId the type id of the agenda to set
          */
		public void setTypeId(String typeId) {
			this.typeId = typeId;
		}

        /**
         * Set the value of the context id on this builder to the given value.
         *
         * @param contextId the context id of the agenda to set, must not be null or blank
         * @throws IllegalArgumentException if the name is null or blank
         */
		public void setContextId(String contextId) {
			if (StringUtils.isBlank(contextId)) {
                throw new IllegalArgumentException("context id is blank");
		}
			this.contextId = contextId;
		}

         /**
          * Set the value of the active indicator on this builder to the given value.
          *
          * @param active the active indicator of the agenda to set
          */
        public void setActive(boolean active) {
            this.active = active;
        }

         /**
          * Set the value of the first agenda item id on this builder to the given value.
          *
          * @param firstItemId the first agenda item of the agenda tree to set
          */
		public void setFirstItemId(String firstItemId) {
			this.firstItemId = firstItemId;
		}

         /**
          * Set the value of the remote/custom attributes on this builder to the given value.
          *
          * @param attributes the remote/custom attributes of the agenda to set
          */
		public void setAttributes(Map<String, String> attributes){
			if (attributes == null){
				this.attributes = Collections.emptyMap();
			} else {
                this.attributes = Collections.unmodifiableMap(attributes);
            }
		}

		/**
         * Sets the version number on this builder to the given value.
         *
         * @param versionNumber the version number to set
         */
        public void setVersionNumber(Long versionNumber){
            this.versionNumber = versionNumber;
        }

		@Override
		public String getId() {
			return id;
		}

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

		@Override
		public String getTypeId() {
			return typeId;
		}

		@Override
		public String getContextId() {
			return contextId;
		}

        @Override
        public boolean isActive() {
            return active;
        }

		@Override
		public String getFirstItemId() {
			return firstItemId;
		}

		@Override
		public Map<String, String> getAttributes() {
			return attributes;
		}

        @Override
        public Long getVersionNumber() {
            return versionNumber;
        }

		/**
		 * Builds an instance of a Agenda based on the current state of the builder.
		 *
		 * @return the fully-constructed Agenda
		 */
        @Override
        public AgendaDefinition build() {
            return new AgendaDefinition(this);
        }

    }

	/**
	 * Defines some constants used on this class.
	 */
	public static class Constants {
		final static String ROOT_ELEMENT_NAME = "agenda";
		final static String TYPE_NAME = "AgendaType";
		final static String[] HASH_CODE_EQUALS_EXCLUDE = { "_futureElements" };
        public final static String EVENT = "Event";   // key for event attribute
	}

	/**
	 * A private class which exposes constants which define the XML element names to use
	 * when this object is marshalled to XML.
	 */
	public static class Elements {
		public final static String AGENDA_ID = "id";
		final static String NAME = "name";
		final static String TYPE_ID = "typeId";
		final static String CONTEXT_ID = "contextId";
        final static String ACTIVE = "active";
		final static String FIRST_ITEM_ID = "firstItemId";
		final static String ATTRIBUTES = "attributes";
		final static String ATTRIBUTE = "attribute";
	}

    public static class Cache {
        public static final String NAME = KrmsConstants.Namespaces.KRMS_NAMESPACE_2_0 + "/" + AgendaDefinition.Constants.TYPE_NAME;
    }
}


text:
package model

import (
	"time"
)

type Comment struct {
	ID        uint      `gorm:"column:comment_id;primary_key"`
	TorrentID uint      `gorm:"column:torrent_id"`
	UserID    uint      `gorm:"column:user_id"`
	Content   string    `gorm:"column:content"`
	CreatedAt time.Time `gorm:"column:created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at"`
	DeletedAt *time.Time

	Torrent *Torrent `gorm:"AssociationForeignKey:TorrentID;ForeignKey:torrent_id"`
	User    *User    `gorm:"AssociationForeignKey:UserID;ForeignKey:user_id"`
}

// Returns the total size of memory recursively allocated for this struct
func (c Comment) Size() int {
	return (3 + 3*3 + 2 + 2 + len(c.Content)) * 8
}

type OldComment struct {
	TorrentID uint      `gorm:"column:torrent_id"`
	Username  string    `gorm:"column:username"`
	Content   string    `gorm:"column:content"`
	Date      time.Time `gorm:"column:date"`

	Torrent *Torrent `gorm:"ForeignKey:torrent_id"`
}

// Returns the total size of memory recursively allocated for this struct
func (c OldComment) Size() int {
	return (1 + 2*2 + len(c.Username) + len(c.Content) + 3 + 1) * 8
}

func (c OldComment) TableName() string {
	// cba to rename this in the db
	// TODO: Update database schema to fix this hack
	//       I find this odd considering how often the schema changes already
	return "comments_old"
}


text:
#include "libioP.h"
#include <wchar.h>
#include <sys/param.h>

wchar_t *
__fgetws_unlocked_chk (wchar_t *buf, size_t size, int n, _IO_FILE *fp)
{
  _IO_size_t count;
  wchar_t *result;
  int old_error;
  CHECK_FILE (fp, NULL);
  if (n <= 0)
    return NULL;
  /* This is very tricky since a file descriptor may be in the
     non-blocking mode. The error flag doesn't mean much in this
     case. We return an error only when there is a new error. */
  old_error = fp->_IO_file_flags & _IO_ERR_SEEN;
  fp->_IO_file_flags &= ~_IO_ERR_SEEN;
  count = _IO_getwline (fp, buf, MIN ((size_t) n - 1, size), L'\n', 1);
  /* If we read in some bytes and errno is EAGAIN, that error will
     be reported for next read. */
  if (count == 0 || ((fp->_IO_file_flags & _IO_ERR_SEEN)
  		     && errno != EAGAIN))
    result = NULL;
  else if (count >= size)
    __chk_fail ();
  else
    {
      buf[count] = '\0';
      result = buf;
    }
  fp->_IO_file_flags |= old_error;
  return result;
}


text:
"""
Edge of a graph.

@package bridgecut
@author Aaron Zampaglione <azampagl@my.fit.edu>
@copyright 2011 Aaron Zampaglione
@license MIT
"""
from bridgecut.lib.util import combinations

class Edge(object):

    def __init__(self, node1, node2):
        """
        Init.

        Key arguments:
        node1 -- node 1
        node2 -- node 2
        """
        self.node1 = node1
        self.node2 = node2

        # Append this edge to the vertices.
        node1.edges.append(self)
        node2.edges.append(self)

    def __str__(self):
        """
        String representation of the edge.
        """
        return str(self.node1) + ' <-> ' + str(self.node2)

    def bridge_coeff(self, d=1):
        """
        Finds the bridging coefficient of this edge.

        Key arguments:
        d -- the depth [optional]
        """
        num = self.node1.deg(d) * self.node1.bridge_coeff(d) + \
              self.node2.deg(d) * self.node2.bridge_coeff(d)

        den = (self.node1.deg(d) + self.node2.deg(d)) * \
              (len(self.node1.nbrs(self.node2, d)) + 1)

        # Possibility that the nodes have 0 neighbors at depth d.
        if den == 0:
            return 0.0

        return num / float(den)

    def btwns(self, paths):
        """
        Find the betweenness centrality for this edge.

        Key arguments:
        paths -- a dictionary of all the shortest paths.
        """
        ret = 0.0

        for node1, node2 in combinations(paths.keys(), 2):
            # There theoretically can be no shortests paths if we deleted
            #  a bridge, but the density of the new clusters didn't meet the threshold.
            if paths[node1][node2] != None:
                # A direct path from one to another still counts as a shortest path.
                if len(paths[node1][node2]) == 0:
                    ret += 1.0
                else:
                    ret += sum([1 for path in paths[node1][node2] if self.node1 in path and self.node2 in path]) / float(len(paths[node1][node2]))

        return ret

    def destroy(self):
        """
        Destroy's this edge and returns the two nodes that were part of it.
        """
        node1 = self.node1
        node2 = self.node2

        node1.edges.remove(self)
        node2.edges.remove(self)

        return [node1, node2]

    def node(self, node):
        """
        Returns the other node in this pair.

        Key arguments:
        node -- the node that we are NOT looking for.
        """
        if node == self.node1:
            return self.node2
        if node == self.node2:
            return self.node1

        return None


text:
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Begin the Import Process</title>

          chipKIT Sketch Help

      Import Sketch : Import the Sketch : Begin the Import Process

Begin the Import Process

The installed plug-in adds new functionality in MPLAB X IDE to import the project. Select <dfn style="font-style: italic; font-variant: normal; text-decoration: underline; text-transform: none; vertical-align: baseline;">File>Import>chipKIT Project</dfn> (Figure: Import Project) to start the process of importing the sketch.

Figure: Import Project

          Microchip Support

            Help Updated: 2017-04-13 14:25:13Z

Help Page: 16


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

namespace HrdLib
{
    public class HrdElement
    {
        protected readonly List<HrdElement> _elements = new List<HrdElement>();

        private readonly string _name;
        public string Name
        {
            get { return _name; }
        }

        protected HrdElement(string name)
        {
            _name = name;
        }

        public virtual void AddElement(HrdElement elementBase)
        {
            if (elementBase == null)
                throw new ArgumentNullException("elementBase");

            if (ReferenceEquals(elementBase, this))
                throw new Exception("Element can't conatains itself.");

            if (elementBase.Name != null && _elements.Any(el => string.Equals(el.Name, elementBase.Name, StringComparison.Ordinal)))
                throw new Exception(string.Format("Element with name '{0}' is already added.", elementBase.Name));

            _elements.Add(elementBase);
        }

        public void AddElements(params HrdElement[] elements)
        {
            AddElements((IEnumerable<HrdElement>) elements);
        }

        public void AddElements(IEnumerable<HrdElement> elements)
        {
            foreach(var el in elements)
                AddElement(el);
        }

        public TElement GetElement<TElement>(string name)
            where TElement:HrdElement
        {
            if (name == null)
                throw new ArgumentNullException("name");

            return
                _elements.OfType<TElement>().FirstOrDefault(el => string.Equals(el.Name, name, StringComparison.Ordinal));
        }

        public IEnumerable<TElement> GetUnnamedElements<TElement>()
            where TElement:HrdElement
        {
            return _elements.OfType<TElement>().Where(el => el.Name == null);
        }

        public IEnumerable<HrdElement> GetElements()
        {
            return _elements.AsEnumerable();
        }

        public IEnumerable<HrdElement> GetUnnamedElemetns()
        {
            return _elements.Where(el => el.Name == null);
        }

        public IEnumerable<TElement> GetElements<TElement>()
            where TElement:HrdElement
        {
            return _elements.OfType<TElement>();
        }
    }
}


text:
import Immutable from 'immutable';
import * as Actions from '../actions/GameActions';
import uuid from 'uuid';

const newGame = () => Immutable.fromJS({
  id: uuid.v4(),
  startDate: new Date(),
  endDate: null,
  events: []
});

const initialState = newGame();

export default function (state = initialState, action) {
  switch (action.type) {
    case Actions.NEW_GAME:
      return newGame();
    case Actions.SET_END_DATE:
      return state.set('endDate', action.endDate);
    case Actions.ADD_EVENT:
      return state.update('events', events => events.push(action.event));
    case Actions.UNDO:
      return state.update('events', events => events.pop()).set('endDate', null);
    default:
      return state;
  }
}


text:
/**
 * Curvytron Controller
 *
 * @param {Object} $scope
 * @param {Object} $window
 * @param {SocketClient} client
 * @param {PhotoBooth} photoBooth
 */
function CurvytronController($scope, $window, client, photoBooth)
{
    this.$scope     = $scope;
    this.$window    = $window;
    this.client     = client;
    this.photoBooth = photoBooth;

    // Bind
    this.onConnect    = this.onConnect.bind(this);
    this.onDisconnect = this.onDisconnect.bind(this);
    this.reload       = this.reload.bind(this);

    // Hydrate scope
    this.$scope.curvytron = {bodyClass: ''};
    this.$scope.status    = 'connecting';
    this.$scope.reload    = this.reload;

    this.client.on('connected', this.onConnect);
    this.client.on('disconnected', this.onDisconnect);

    this.photoBooth.stop();
}

/**
 * On connect
 *
 * @param {Event} e
 */
CurvytronController.prototype.onConnect = function(e)
{
    this.$scope.status = 'online';
    this.applyScope();
};

/**
 * On disconnect
 *
 * @param {Event} e
 */
CurvytronController.prototype.onDisconnect = function(e)
{
    this.$scope.status    = 'disconnected';
    this.$scope.curvytron = { bodyClass: '' };
    this.applyScope();
};

/**
 * Reload
 */
CurvytronController.prototype.reload = function()
{
    this.$window.location.href = '/';
};

/**
 * Apply scope
 */
CurvytronController.prototype.applyScope = function()
{
    var phase = this.$scope && this.$scope.$root ? this.$scope.$root.$$phase : null;

    if (phase !== '$apply' && phase !== '$digest') {
        this.$scope.$apply();
    }
};


text:
<?php

namespace LaMaltiere\SiteWebMaltiereBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class VideosController extends Controller
{
	public function chargerVideosAction($id)
	{
                return $this->chargerVideos(true, $id);
	}

        public function chargerVideosAdminAction()
	{
		return $this->chargerVideos(false, 0);
	}

        private function chargerVideos($accueil,$id){
            if($accueil){
                $videos = $this->getDoctrine()->getRepository('LaMaltiereSiteWebMaltiereBundle:TypeVideo')->find($id);
                if($id == 1){
                    return $this->render('LaMaltiereSiteWebMaltiereBundle:Corps:videoslamaltiere.html.twig', array(
                        'typeVideos' => $videos
                    ));
                }else{
                    return $this->render('LaMaltiereSiteWebMaltiereBundle:Corps:videosclients.html.twig', array(
                        'typeVideos' => $videos
                    ));
                }
            }else{
                $videos = $this->getDoctrine()->getRepository('LaMaltiereSiteWebMaltiereBundle:TypeVideo')->findAll();

                return $this->render('LaMaltiereSiteWebMaltiereBundle:Admin:adminVideos.html.twig', array(
                    'typeVideos' => $videos
                ));
            }
        }

        public function enregistrerVideoAction(Request $request)
	{
            if ($request->isMethod('POST')) {
                if($request->request->get('id') == ""){
                    $this->creerVideo($request);
                }else {
                    $this->modifierVideo($request);
                }
            }

            return $this->chargerVideos(false, 0);
	}

        private function creerVideo(Request $request){
            $em = $this->getDoctrine()->getManager();
            $video = new \LaMaltiere\SiteWebMaltiereBundle\Entity\Video();
            $video->setUrl($request->request->get('url'));
            $type = $em->getRepository('LaMaltiereSiteWebMaltiereBundle:TypeVideo')->find($request->request->get('lstTypeVideosAdmin'));
            $video->setType($type);

            $em->persist($video);
            $em->flush();
        }

        private function modifierVideo(Request $request){
            $em = $this->getDoctrine()->getManager();
            $video = $em->getRepository('LaMaltiereSiteWebMaltiereBundle:Video')->find($request->request->get('id'));

            if (!$video){
                throw $this->createNotFoundException(
                    'Aucun article trouvé pour cet id : '.$request->request->get('id')
                );
            }

            $video->setUrl($request->request->get('url'));
            $type = $em->getRepository('LaMaltiereSiteWebMaltiereBundle:TypeVideo')->find($request->request->get('lstTypesVideoAdmin'));
            $video->setType($type);
            $em->flush();
        }

        public function supprimerVideoAction($url)
	{
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('LaMaltiereSiteWebMaltiereBundle:Video')->find($url);

            $em->remove($entity);
            $em->flush();

            return $this->chargerVideos(false,0);
	}
}


text:
<?php
	session_start();

	require_once('../php/api_settings.php');
	require_once('../php/api_auth.php');

	require_once('../php/get_albums.php');

	$album_page = (isset($_GET["album_page"])? $_GET["album_page"] : 1);
	$_SESSION["last_album_page"] = $album_page;

?>

<!doctype html>

	<title>TagIt | Bulk Flickr Tag Editor</title>

	<?php include("../includes/assets.php") ?>

			<?php include('../includes/header.php'); ?>

Albums

		<?php
			if (count($albums["albums"]) == 0) {
				?>

							<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
							Sorry! Tagga currently only supports editing albums. Sort your gallery into a few albums and try again.

				<?php
			}
			else {
				?>

							<?php

								foreach($albums["albums"] as $a) {
									?>

											<div class="custom-thumb album-thumb" data-album-id="<?php echo $a["id"] ?>" style="background-image: url('<?php echo $a["thumb_url"] ?>')">

													<?php echo $a["title"]["_content"] ?>

									<?php
								}
							?>

										<a id="pagination-prev" class="btn btn-info <?php echo ($album_page == 1?"disabled":"") ?>" href="/app/albums/<?php echo $album_page-1?>">

Page <?php echo $album_page ?> of <?php echo $albums["pages"] ?>

										<a id="pagination-next" class="btn btn-info <?php echo ($album_page == $albums["pages"]?"disabled":"") ?>" href="/app/albums/<?php echo $album_page+1?>">

								<form id="album-jump">

										Jump to Album

											<input type="text" placeholder="Album ID" class="form-control" value="">

												<button type="submit" class="btn btn-success">Go</button>

								</form>

								App going slow?

									Click here to run the setup process again. This may need to be done periodically.

				<?php
			}

		?>

				<?php include('../includes/footer.php'); ?>


text:
The `firmware` package contains updated firmware files required by any
driver compiled as a module. Based on the modules included in a recent
LinuxKit kernel, copy the required firmware binaries as reported by
'modinfo'. We deliberately do *not* pick the latest version here to
prevent it being updated on kernel updates. Firmware revisions do not
change very often and we expect older and newer kernels to work with a
range of firmware binaries.

Note: The current mechanism only handles firmware blobs required by
modules and ignores firmware blobs required by drivers compiled into
the kernel. However, with the LinuxKit kernels we typically compile
all hardware drivers as modules.


text:
require 'mechanize'
require 'w3c_mobile_ok/best_practice'
require 'w3c_mobile_ok/failure'
require 'w3c_mobile_ok/non_existent_resource_error'
require 'w3c_mobile_ok/parser'
require 'w3c_mobile_ok/resource'
require 'w3c_mobile_ok/result'
require 'w3c_mobile_ok/version'

module W3CMobileOk
  def self.parse(url)
    Parser.new(url).parse!
  end
end


text:
const static unsigned int g_dwPlayerSessionBuffLen = 64 * 1024;
static char g_pPlayerSessionBuf[g_dwPlayerSessionBuffLen];

class RedisGetServerId : public IRedisQuery
{
public:
	RedisGetServerId(unsigned long long qwPlayerId) : m_qwPlayerId(qwPlayerId), m_dwServerId(0), m_pReader(NULL) {}
	~RedisGetServerId() {}

	virtual int					GetDBId(void) { return 0; }
	virtual void				OnQuery(IRedisConnection *poDBConnection)
	{
		char szQuery[64] = { 0 };
		sprintf(szQuery, "ZSCORE %s %llu", RedisConstant::szOnLinePlayer, m_qwPlayerId);
		poDBConnection->Query(szQuery, &m_pReader);
	}
	virtual void OnResult(void) { std::string szServerId; m_pReader->GetValue(szServerId); m_dwServerId = atoi(szServerId.c_str()); }
	virtual void Release(void) { m_pReader->Release(); }

	int GetServerId() { return m_dwServerId; }

private:
	IRedisDataReader* m_pReader;
	int m_dwServerId;
	unsigned long long m_qwPlayerId;
};

CPlayerSession::CPlayerSession()
	:m_oProtoDispatch(*this)
{
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLoginServerId::descriptor(), &CPlayerSession::OnPlayerRequestLoginServerId);
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLogin::descriptor(), &CPlayerSession::OnPlayerRequestLogin);
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLoginMakeTeam::descriptor(), &CPlayerSession::OnPlayerRequestLoginMakeTeam);
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLoginInviteTeam::descriptor(), &CPlayerSession::OnPlayerRequestLoginInviteTeam);
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLoginChangeSlot::descriptor(), &CPlayerSession::OnPlayerRequestLoginChangeSlot);
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLoginGameStart::descriptor(), &CPlayerSession::OnPlayerRequestLoginGameStart);
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLoginOnLinePlayer::descriptor(), &CPlayerSession::OnPlayerRequestLoginOnLinePlayer);
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLoginEnterTeam::descriptor(), &CPlayerSession::OnPlayerRequestLoginEnterTeam);
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLoginRefuseEnterTeam::descriptor(), &CPlayerSession::OnPlayerRequestLoginRefuseEnterTeam);
	m_oProtoDispatch.RegistFunction(GameProto::PlayerRequestLoginLeaveTeam::descriptor(), &CPlayerSession::OnPlayerRequestLoginLeaveTeam);
}

CPlayerSession::~CPlayerSession()
{
}

void CPlayerSession::OnConnect(void)
{
}

void CPlayerSession::OnClose(void)
{
	Player* pPlayer = GameServer::Instance()->GetPlayerManager().GetPlayer(m_qwPlayerId);
	if (pPlayer)
	{
		pPlayer->OnClose();
	}
	else
	{
		LogExe(LogLv_Critical, "can't find player %llu", m_qwPlayerId);
		Close();
	}
}

void CPlayerSession::OnError(unsigned int dwErrorNo)
{
	LogExe(LogLv_Debug, "ip : %s, port : %d, connect addr : %p, error no : %d", GetRemoteIPStr(), GetRemotePort(), (GetConnection()), dwErrorNo);
}

void CPlayerSession::OnRecv(const char* pBuf, unsigned int dwLen)
{
	CNetStream oStream(pBuf, dwLen);
	std::string szProtocolName;
	oStream.ReadString(szProtocolName);
	LogExe(LogLv_Debug, "player : %llu, protocol name : %s", m_qwPlayerId, szProtocolName.c_str());
	unsigned int dwProtoLen = oStream.GetDataLength();
	char* pData = oStream.ReadData(dwProtoLen);
	if (!m_oProtoDispatch.Dispatch(szProtocolName.c_str(),
		(const unsigned char*)pData, dwProtoLen, this, *this))
	{
		LogExe(LogLv_Debug, "%s proccess error", szProtocolName.c_str());
	}
}

void CPlayerSession::Init()
{
	m_qwPlayerId = 0;
}

bool CPlayerSession::OnPlayerRequestLoginServerId(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLoginServerId* pMsg = dynamic_cast<GameProto::PlayerRequestLoginServerId*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}
	GameProto::LoginAckPlayerServerId oResult;
	oResult.set_dw_result(0);
	oResult.set_dw_server_id(GameServer::Instance()->GetServerId());

	char* pBuf = NULL;
	unsigned int dwBufLen = 0;
	ProtoUtility::MakeProtoSendBuffer(oResult, pBuf, dwBufLen);
	Send(pBuf, dwBufLen);
	return true;
}

bool CPlayerSession::OnPlayerRequestLogin(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLogin* pMsg = dynamic_cast<GameProto::PlayerRequestLogin*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}

	RedisGetServerId oServerId(pMsg->qw_player_id());
	FxRedisGetModule()->QueryDirect(&oServerId);
	unsigned int dwServerId = oServerId.GetServerId();

	GameServer::Instance()->GetPlayerManager().OnPlayerLogin(this, *pMsg);
	m_qwPlayerId = pMsg->qw_player_id();

	CLoginSession* pLoginSession = GameServer::Instance()->GetLoginSessionManager().GetLoginSession(dwServerId);
	if (pLoginSession)
	{
		GameProto::LoginNotifyLoginPlayerKick oKick;
		oKick.set_qw_player_id(pMsg->qw_player_id());
	}

	GameProto::LoginAckPlayerLoginResult oResult;
	oResult.set_dw_result(0);

	char* pBuf = NULL;
	unsigned int dwBufLen = 0;
	ProtoUtility::MakeProtoSendBuffer(oResult, pBuf, dwBufLen);
	Send(pBuf, dwBufLen);
	return true;
}

bool CPlayerSession::OnPlayerRequestLoginMakeTeam(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLoginMakeTeam* pMsg = dynamic_cast<GameProto::PlayerRequestLoginMakeTeam*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}
	Player* pPlayer =  GameServer::Instance()->GetPlayerManager().GetPlayer(m_qwPlayerId);
	if (pPlayer)
	{
		pPlayer->OnPlayerRequestLoginMakeTeam(*this, *pMsg);
	}
	else
	{
		LogExe(LogLv_Critical, "can't find player %llu", m_qwPlayerId);
		Close();
	}
	return true;
}

bool CPlayerSession::OnPlayerRequestLoginInviteTeam(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLoginInviteTeam* pMsg = dynamic_cast<GameProto::PlayerRequestLoginInviteTeam*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}
	Player* pPlayer = GameServer::Instance()->GetPlayerManager().GetPlayer(m_qwPlayerId);
	if (pPlayer)
	{
		return pPlayer->OnPlayerRequestLoginInviteTeam(*this, *pMsg);
	}
	else
	{
		LogExe(LogLv_Critical, "can't find player %llu", m_qwPlayerId);
	}
	return true;
}

bool CPlayerSession::OnPlayerRequestLoginChangeSlot(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLoginChangeSlot* pMsg = dynamic_cast<GameProto::PlayerRequestLoginChangeSlot*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}
	Player* pPlayer = GameServer::Instance()->GetPlayerManager().GetPlayer(m_qwPlayerId);
	if (pPlayer)
	{
		return pPlayer->OnPlayerRequestLoginChangeSlot(*this, *pMsg);
	}
	else
	{
		LogExe(LogLv_Critical, "can't find player %llu", m_qwPlayerId);
	}
	return true;
}

bool CPlayerSession::OnPlayerRequestLoginGameStart(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLoginGameStart* pMsg = dynamic_cast<GameProto::PlayerRequestLoginGameStart*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}
	Player* pPlayer = GameServer::Instance()->GetPlayerManager().GetPlayer(m_qwPlayerId);
	if (pPlayer)
	{
		return pPlayer->OnPlayerRequestLoginGameStart(*this, *pMsg);
	}
	else
	{
		LogExe(LogLv_Critical, "can't find player %llu", m_qwPlayerId);
	}
	return true;
}

bool CPlayerSession::OnPlayerRequestLoginOnLinePlayer(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLoginOnLinePlayer* pMsg = dynamic_cast<GameProto::PlayerRequestLoginOnLinePlayer*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}

	class RedisPlayerIds : public IRedisQuery
	{
	public:
		RedisPlayerIds() : m_pReader(NULL) {}
		~RedisPlayerIds() {}

		virtual int					GetDBId(void) { return 0; }
		virtual void				OnQuery(IRedisConnection *poDBConnection)
		{
			char szQuery[64] = { 0 };
			sprintf(szQuery, "ZRANGE %s 0 -1", RedisConstant::szOnLinePlayer);
			poDBConnection->Query(szQuery, &m_pReader);
		}
		virtual void OnResult(void)
		{
			std::vector<std::string> vecIds;
			m_pReader->GetValue(vecIds);
			for (std::vector<std::string>::iterator it = vecIds.begin(); it != vecIds.end(); ++it)
			{
				m_vecPlayers.push_back(atoll(it->c_str()));
			}
		}
		virtual void Release(void) { m_pReader->Release(); }

		std::vector<unsigned long long>& GetPlayers() { return m_vecPlayers; }

	private:
		IRedisDataReader* m_pReader;
		std::vector<unsigned long long> m_vecPlayers;
	};

	RedisPlayerIds oServerPlayerIds;
	FxRedisGetModule()->QueryDirect(&oServerPlayerIds);

	GameProto::LoginAckPlayerOnLinePlayer oResult;
	std::vector<unsigned long long>& ref_vecPlayers = oServerPlayerIds.GetPlayers();
	for (std::vector<unsigned long long>::iterator it = ref_vecPlayers.begin(); it != ref_vecPlayers.end(); ++it)
	{
		oResult.add_qw_player_id(*it);
	}
	char* pBuf = NULL;
	unsigned int dwBufLen = 0;
	ProtoUtility::MakeProtoSendBuffer(oResult, pBuf, dwBufLen);
	Send(pBuf, dwBufLen);
	return true;
}

bool CPlayerSession::OnPlayerRequestLoginEnterTeam(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLoginEnterTeam* pMsg = dynamic_cast<GameProto::PlayerRequestLoginEnterTeam*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}

	Player* pPlayer = GameServer::Instance()->GetPlayerManager().GetPlayer(m_qwPlayerId);
	if (pPlayer == NULL)
	{
		LogExe(LogLv_Critical, "cann't find player : %llu", m_qwPlayerId);
		return true;
	}

	CBinaryTeamSession* pTeamSession = GameServer::Instance()->GetTeamSessionManager().GetTeamSession(pMsg->dw_team_server_id());
	if (pTeamSession == NULL)
	{
		LogExe(LogLv_Critical, "no team server player : %llu, team server id : %d", m_qwPlayerId, pMsg->dw_team_server_id());
		GameProto::LoginAckPlayerEnterTeam oResult;
		oResult.set_dw_result(GameProto::EC_NoTeamServer);
		char* pBuf = NULL;
		unsigned int dwBufLen = 0;
		ProtoUtility::MakeProtoSendBuffer(oResult, pBuf, dwBufLen);
		Send(pBuf, dwBufLen);
		return true;
	}

	GameProto::LoginRequestTeamEnterTeam oRequest;
	oRequest.set_qw_team_id(pMsg->qw_team_id());
	GameProto::RoleData* pRoleData = oRequest.mutable_role_data();
	pRoleData->set_qw_player_id(pPlayer->GetPlayerId());
	pRoleData->set_dw_sex(pPlayer->GetSex());
	pRoleData->set_sz_avatar(pPlayer->GetAvatar());
	pRoleData->set_sz_nick_name(pPlayer->GetNickName());

	char* pBuf = NULL;
	unsigned int dwBufLen = 0;
	ProtoUtility::MakeProtoSendBuffer(oRequest, pBuf, dwBufLen);
	pTeamSession->Send(pBuf, dwBufLen);

	return true;
}

bool CPlayerSession::OnPlayerRequestLoginRefuseEnterTeam(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLoginRefuseEnterTeam* pMsg = dynamic_cast<GameProto::PlayerRequestLoginRefuseEnterTeam*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}

	Player* pPlayer = GameServer::Instance()->GetPlayerManager().GetPlayer(m_qwPlayerId);
	if (pPlayer == NULL)
	{
		LogExe(LogLv_Critical, "cann't find player : %llu", m_qwPlayerId);
		Close();
		return true;
	}

	Player* pInvitePlay = GameServer::Instance()->GetPlayerManager().GetPlayer(pMsg->qw_player_id());
	if (pInvitePlay)
	{
		GameProto::LoginNotifyPlayerRefuseEnterTeam oNotify;
		oNotify.set_qw_player_id(m_qwPlayerId);
		oNotify.set_sz_reason(pMsg->sz_reason());

		char* pBuf = NULL;
		unsigned int dwBufLen = 0;
		ProtoUtility::MakeProtoSendBuffer(oNotify, pBuf, dwBufLen);
		pInvitePlay->GetSession()->Send(pBuf, dwBufLen);
		return true;
	}

	RedisGetServerId oServerId(pMsg->qw_player_id());
	FxRedisGetModule()->QueryDirect(&oServerId);
	unsigned int dwServerId = oServerId.GetServerId();

	CLoginSession* pLoginSession = GameServer::Instance()->GetLoginSessionManager().GetLoginSession(dwServerId);
	if (pLoginSession)
	{
		GameProto::LoginNotifyLoginPlayerRefuseEnterTeam oNotify;
		oNotify.set_qw_invite_id(pMsg->qw_player_id());
		oNotify.set_qw_invitee_id(m_qwPlayerId);
		oNotify.set_sz_reason(pMsg->sz_reason());

		char* pBuf = NULL;
		unsigned int dwBufLen = 0;
		ProtoUtility::MakeProtoSendBuffer(oNotify, pBuf, dwBufLen);
		pInvitePlay->GetSession()->Send(pBuf, dwBufLen);
		return true;
	}
	return true;
}

bool CPlayerSession::OnPlayerRequestLoginLeaveTeam(CPlayerSession& refSession, google::protobuf::Message& refMsg)
{
	GameProto::PlayerRequestLoginLeaveTeam* pMsg = dynamic_cast<GameProto::PlayerRequestLoginLeaveTeam*>(&refMsg);
	if (pMsg == NULL)
	{
		return false;
	}

	Player* pPlayer = GameServer::Instance()->GetPlayerManager().GetPlayer(m_qwPlayerId);
	if (pPlayer == NULL)
	{
		LogExe(LogLv_Critical, "cann't find player : %llu", m_qwPlayerId);
		Close();
		return true;
	}

	CBinaryTeamSession* pSession = GameServer::Instance()->GetTeamSessionManager().GetTeamSession(pPlayer->GetTeamServerId());
	if (!pSession)
	{
		LogExe(LogLv_Critical, "cann't find team session : %d", pPlayer->GetTeamServerId());
		return true;
	}
	GameProto::LoginRequestTeamPlayerLeave oKickPlayer;
	oKickPlayer.set_qw_player_id(pPlayer->GetPlayerId());
	oKickPlayer.set_qw_team_id(pPlayer->GetTeamId());
	char* pBuf = NULL;
	unsigned int dwBufLen = 0;
	ProtoUtility::MakeProtoSendBuffer(oKickPlayer, pBuf, dwBufLen);
	pSession->Send(pBuf, dwBufLen);
	return true;
}

//////////////////////////////////////////////////////////////////////////
void CWebSocketPlayerSession::Release(void)
{
	LogExe(LogLv_Debug, "ip : %s, port : %d, connect addr : %p", GetRemoteIPStr(), GetRemotePort(), GetConnection());

	GameServer::Instance()->GetPlayerManager().OnSessionClose(m_qwPlayerId);
	OnDestroy();

	GameServer::Instance()->GetPlayerSessionManager().Release(this);
}

//////////////////////////////////////////////////////////////////////////
CWebSocketPlayerSession * WebSocketPlayerSessionManager::CreateSession()
{
	CWebSocketPlayerSession* pSession = m_poolSessions.FetchObj();
	return pSession;
}

bool WebSocketPlayerSessionManager::Init()
{
	return m_poolSessions.Init(64, 64);
}

void WebSocketPlayerSessionManager::Release(FxSession * pSession)
{
	Assert(0);
}

void WebSocketPlayerSessionManager::Release(CWebSocketPlayerSession* pSession)
{
	m_poolSessions.ReleaseObj(pSession);
}


text:
WHAT IS TINYGRAPHS

Tinygraphs is an avatar generator web service. Use it to generate avatars for your web app.

     TRY IT OUT


text:
'use strict';
// deps
var path = require('path'),
	grunt = require('grunt'),
	log = grunt.log,
	fail = grunt.fail,
	util = grunt.util,
	_ = util._;

function dasherizeStamp(date) {
	return [date.getFullYear(), date.getMonth()+1, date.getDate()].join('-');
}

module.exports = function(grunt) {
	grunt.registerMultiTask('jekylls', "testing multi", function (title) {
		if (!title) {
			var target = log.wordlist([this.name, this.target], {separator: ':', color: 'cyan'});
			log.errorlns('Title required');
			return false;
		}

		var date = new Date(),
			dasherizedStamp = dasherizeStamp(date),
			fname = [dasherizedStamp,title].join('-'),
			_title = title.replace(/[-_]/g, ' ');

		var defaults = {
			expand: true,
			cwd: '.',
			extDot: 'first',
			flatten: true,
			rename: function (dest, src) {
				fname = path.join(dest, fname + path.extname(src));
				if (grunt.file.exists(fname)) {
					fail.warn(fname + ' already exists');
				}
				return fname;
			}
		};

		var locals = this.data.locals||{};

		// extend options with defaults and data options
		var options = _.extend({
				dest: '_' + this.target,
				ext: '.markdown'
			}, this.options(this.data.options));

		_.extend(options, defaults);

		grunt.loadNpmTasks('grunt-contrib-copy');
		grunt.config('copy.' + this.target, { files: [options] });

		grunt.registerTask('processTemplate', function () {
			log.writeln('Processing:', log.wordlist([fname], {color: 'cyan'}));
			var template = grunt.file.read(fname);
			var data = _.extend(locals, {
				title: _title,
				date: dasherizedStamp
			});
			grunt.file.write(fname, _.template(template)(data));
		});

		log.writeln('Generating jekyll ' + this.target);
		grunt.task.run('copy:' + this.target, 'processTemplate');

	});
};


text:
package org.biopax.paxtools.pattern.constraint;

import org.biopax.paxtools.model.BioPAXElement;
import org.biopax.paxtools.model.level3.*;
import org.biopax.paxtools.pattern.Match;
import org.biopax.paxtools.pattern.util.Blacklist;
import org.biopax.paxtools.pattern.util.RelType;

import java.util.*;

/**
 * This constraint is useful when we want traverse Control-Conversion-PE (input or output). Control
 * and Conversion are prerequisites, PE is generated.
 *
 * Var0 - Control
 * Var1 - Conversion
 * Var2 - input or output PhysicalEntity
 *
 * @deprecated
 * @see Participant
 *
 * @author Ozgun Babur
 */
public class ParticipatingPE extends ConstraintAdapter
{
	/**
	 * Desired direction after the Conversion.
	 */
	RelType type;

	/**
	 * Constructor with parameters.
	 * @param type direction from the Conversion
	 */
	public ParticipatingPE(RelType type, Blacklist blacklist)
	{
		super(3, blacklist);
		this.type = type;
	}

	/**
	 * Constructor with parameters.
	 * @param type direction from the Conversion
	 */
	public ParticipatingPE(RelType type)
	{
		this(type, null);
	}

	/**
	 * This is a generative constraint.
	 * @return true if the constraint can generate candidates
	 */
	@Override
	public boolean canGenerate()
	{
		return true;
	}

	/**
	 * First evaluates the direction that the Control is affecting the Conversion, then gets the
	 * related participants.
	 * @param match current pattern match
	 * @param ind mapped indices
	 * @return related participants
	 */
	@Override
	public Collection<BioPAXElement> generate(Match match, int... ind)
	{
		Control cont = (Control) match.get(ind[0]);
		Conversion conv = (Conversion) match.get(ind[1]);

		// This is the direction for our use only.
		ConversionDirectionType dir = getDirection(conv, cont);

		Set<Set<PhysicalEntity>> sides = new HashSet<Set<PhysicalEntity>>();

		if (dir == ConversionDirectionType.LEFT_TO_RIGHT)
		{
			sides.add(type == RelType.INPUT ? conv.getLeft() : conv.getRight());
		}
		else if (dir == ConversionDirectionType.RIGHT_TO_LEFT)
		{
			sides.add(type == RelType.OUTPUT ? conv.getLeft() : conv.getRight());
		}
		else // dir is reversible and we will go both sides
		{
			sides.add(conv.getLeft());
			sides.add(conv.getRight());
		}

		Set<BioPAXElement> result = new HashSet<BioPAXElement>();

		if (blacklist == null)
		{
			for (Set<PhysicalEntity> side : sides)
			{
				result.addAll(side);
			}
		}
		else
		{
			for (Set<PhysicalEntity> side : sides)
			{
				// if the control is in fact reversible then don't mind the context
				result.addAll(blacklist.getNonUbiques(side,
					dir == ConversionDirectionType.REVERSIBLE ? null : type));
			}
		}

		return result;
	}
}


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

<title>gov.ornl.keva.core</title>
<meta name="date" content="2013-05-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package gov.ornl.keva.core

Class Summary

Class
Description

BloomFilter

A bloom filter is a space efficient datastructure used to test membership
 against some set of data.

EmptyIterator<E>

Used when we need an iterator, but there no items to iterate.

MergeSortedIterator<E>

Merge multiple, sorted iterators into a single iterator.

MerkleTree

A merkle tree is a hierarchical way to store a checksum.

MinimumIterator<E>

Selects a single item from a set of choices.

OpenOptions

Open options.

OptionsSerializer

Serialize open options.

PruneOptions

Pruning options that are used to determine which data to
 delete.

ReadOptions

Read options.

SingletonIterator<E>

Used when we need an iterator, but there is only a single item.

StreamIterator<E>

Iterators that contain some extra options.

StreamIterator.ReverseIterator<E>

Use a reverse iterator.

StreamIterator.SimpleIterator<E>

Wrap this iterator and add stream-specific
 capabilities

TreeUnionIterator<E>

Merge multiple, sorted iterators into a single iterator.

UnionIterator<E>

Merge multiple, sorted iterators into a single iterator.

VectorClock

A vector clock is a logical time mechanism that consists of a set of
 two-tuples <ID, Time>.

WriteOptions

Write options.

Exception Summary

Exception
Description

KevaDBException

Capture and report errors associated with various database operations.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
import functools
import os
import threading
from concurrent.futures import ThreadPoolExecutor

import youtube_dl

from src.cache import Cache

out_folder = os.path.join(os.getcwd(), 'cache', 'audio', '%(extractor)s-%(id)s-%(title)s.%(ext)s')
opts = {
    'format': 'bestaudio/best',
    'extractaudio': True,
    'audioformat': 'mp3',
    'outtmpl': out_folder,
    'restrictfilenames': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0',
    'external_downloader': 'ffmpeg',
    'external_downloader_args': ['-loglevel', 'error'],
    'prefer_ffmpeg': True,
    'nooverwrites': True}

youtube_dl.utils.bug_reports_message = lambda: ''

class DownloaderPool:
    def __init__(self, max_workers=3):
        self.executor = ThreadPoolExecutor(max_workers=max_workers)
        self._success = threading.Event()
        self._not_downloading = threading.Event()
        self._not_downloading.set()
        self.ytdl = youtube_dl.YoutubeDL(opts)
        self.extract_flat = youtube_dl.YoutubeDL(opts)
        self.extract_flat.params['extract_flat'] = True

        cache = os.path.join(os.getcwd(), 'cache', 'audio')
        if not os.path.isdir(cache):
            os.mkdir(cache)
        self.cache = Cache(cache)

    def download(self, link, **kwargs):
        return self.executor.submit(self._get_song, link, **kwargs)

    def get_info(self, link, flat=False):
        return self.executor.submit(self._get_info, link, flat=flat)

    def _get_info(self, link, flat=False):
        try:
            if flat:
                yt = self.extract_flat
            else:
                yt = self.ytdl

            info = functools.partial(yt.extract_info, link, download=False)()
        except Exception as e:
            print('Exception while downloading file. %s' % e)
        else:
            return info

    def _get_song(self, link, flat=False, **kwargs):
        try:
            info = functools.partial(self.ytdl.extract_info, link, **kwargs)()
        except Exception as e:
            print('Exception while downloading file. %s' % e)
        else:
            fname = self.ytdl.prepare_filename(info)
            if os.path.exists(fname):
                self.cache.add_file(fname)
            else:
                fname = False

            return info, fname


text:
using System;
using System.Runtime.Serialization;

namespace Google.DataTable.Net.Wrapper
{
    public static class SerializationInfoExtensions
    {
        public static T TryGetValue<T>(this SerializationInfo info, string property, T defaultValue)// where T : class
        {
            try
            {
                var value = info.GetValue(property, typeof(T));
                if (value != null)
                    return (T)value;
                else
                    return defaultValue;
            }
            catch
            {
                return defaultValue;
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Atas Inst. Micol. Univ. Recife 5: 164 (1967)

#### Original name
Chaetothyrina vochysiae Bat. & Peres

### Remarks
null


text:
package ref.sdfe.gpslogsheet2;

/**
 * Created by B028406 on 9/14/2017.
 */

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A placeholder fragment containing a simple view.
 */
public class ExtrasFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "4";

    public ExtrasFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static ExtrasFragment newInstance(int sectionNumber) {
        ExtrasFragment fragment = new ExtrasFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_extras, container, false);
    }
}


text:
<?php

namespace BufeteBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;

class AsignacionclinicaType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->bufete = $options['bufete'];
        $builder->add('notaClinica')
        ->add('observacionesClinica')
        ->add('estadoAsignacionest')
        ->add('idEstudiante')
        ->add('idClinica', EntityType::class,array(
          "class" => "BufeteBundle:Clinicas",
          "label" => "Clinica: ",
          "query_builder" => function (EntityRepository $er){
            return $er->createQueryBuilder('c')
            ->innerJoin('BufeteBundle:Personas', 'p', Join::WITH, 'p.idPersona = c.idPersona')
            ->where('p.idBufete = :bufete')
            ->andWhere('c.estadoClinica = 1')
            ->setParameter('bufete', $this->bufete);
          },
          'placeholder' => 'Ninguno seleccionado',
          'required'   => false,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'BufeteBundle\Entity\Asignacionclinica',
            'bufete' => null,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'bufetebundle_asignacionclinica';
    }

}


text:
package com.demo.app.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Date;

public class Event {

    @JsonProperty(value = "_id")
    private String _id;
    @JsonProperty(value = "event_date")
    private String date;
    @JsonProperty(value = "event_type")
    private String type;
    @JsonProperty(value = "event_summary")
    private String summary;
    @JsonProperty(value = "event_size")
    private int size;
    @JsonProperty(value = "event_details")
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private String details;

    public String getDate() {
        return date;
    }

    public String getType() {
        return type;
    }

    public String getSummary() {
        return summary;
    }

    public int getSize() {
        return size;
    }

    public String getId(){
        return _id;
    }

    public String getDetails() {
        return details;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public void setSize(int size) {
        this.size = size;
    }

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

    public void setDetails(String details) {
        this.details = details;
    }
}


text:
'use strict'

const schools = require('./lib/data/schools.json')

module.exports = orgId => {
  if (!orgId) {
    throw new Error('Missing required input: organizationId')
  }
  var school = schools[orgId.toString()]

  if (!school) {
    throw new Error('School not found')
  } else {
    return school
  }
}


text:
#include "GrClipData.h"

#include "GrSurface.h"
#include "SkRect.h"

///////////////////////////////////////////////////////////////////////////////

/**
 * getConservativeBounds returns the conservative bounding box of the clip
 * in device (as opposed to canvas) coordinates. If the bounding box is
 * the result of purely intersections of rects (with an initial replace)
 * isIntersectionOfRects will be set to true.
 */
void GrClipData::getConservativeBounds(int width, int height,
                                       SkIRect* devResult,
                                       bool* isIntersectionOfRects) const {
    SkRect devBounds;

    fClipStack->getConservativeBounds(-fOrigin.fX,
                                      -fOrigin.fY,
                                      width,
                                      height,
                                      &devBounds,
                                      isIntersectionOfRects);

    devBounds.roundOut(devResult);
}