<commit_before>import React from "react"

const knownOptions = {
  createOnly: {
    clientId: `string`,
    sampleRate: `number`,
    siteSpeedSampleRate: `number`,
    alwaysSendReferrer: `boolean`,
    allowAnchor: `boolean`,
    cookieName: `string`,
    cookieExpires: `number`,
    storeGac: `boolean`,
    legacyCookieDomain: `string`,
    legacyHistoryImport: `boolean`,
    allowLinker: `boolean`,
  },
  general: {
    allowAdFeatures: `boolean`,
    dataSource: `string`,
    queueTime: `number`,
    forceSSL: `boolean`,
    transport: `string`,
  },
}

export const onRenderBody = (
  { setHeadComponents, setPostBodyComponents },
  pluginOptions
) => {
  if (process.env.NODE_ENV !== `production` || !pluginOptions.trackingId) {
    return null
  }

  // Lighthouse recommends pre-connecting to google analytics
  setHeadComponents([
    <link
      rel="preconnect dns-prefetch"
      key="preconnect-google-analytics"
      href="https://www.google-analytics.com"
    />,
  ])

  const excludeGAPaths = []
  if (typeof pluginOptions.exclude !== `undefined`) {
    const Minimatch = require(`minimatch`).Minimatch
    pluginOptions.exclude.map(exclude => {
      const mm = new Minimatch(exclude)
      excludeGAPaths.push(mm.makeRe())
    })
  }

  const gaCreateOptions = {}
  for (const option in knownOptions.createOnly) {
    if (typeof pluginOptions[option] === knownOptions.createOnly[option]) {
      gaCreateOptions[option] = pluginOptions[option]
    }
  }

  const setComponents = pluginOptions.head
    ? setHeadComponents
    : setPostBodyComponents
  return setComponents([
    <script
      key={`gatsby-plugin-google-analytics`}
      dangerouslySetInnerHTML={{
        __html: `
  ${
    excludeGAPaths.length
      ? `window.excludeGAPaths=[${excludeGAPaths.join(`,`)}];`
      : ``
  }
  ${
    typeof pluginOptions.anonymize !== `undefined` &&
    pluginOptions.anonymize === true
      ? `function gaOptout(){document.cookie=disableStr+'=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/',window[disableStr]=!0}var gaProperty='${pluginOptions.trackingId}',disableStr='ga-disable-'+gaProperty;document.cookie.indexOf(disableStr+'=true')>-1&&(window[disableStr]=!0);`
      : ``
  }
  if(${
    typeof pluginOptions.respectDNT !== `undefined` &&
    pluginOptions.respectDNT == true
      ? `!(parseInt(navigator.doNotTrack) === 1 || parseInt(window.doNotTrack) === 1 || parseInt(navigator.msDoNotTrack) === 1 || navigator.doNotTrack === "yes")`
      : `true`
  }) {
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];${
      pluginOptions.defer ? `a.defer=1;` : `a.async=1;`
    }a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  }
  if (typeof ga === "function") {
    ga('create', '${pluginOptions.trackingId}', '${
          typeof pluginOptions.cookieDomain === `string`
            ? pluginOptions.cookieDomain
            : `auto`
        }', ${
          typeof pluginOptions.name === `string`
            ? `'${pluginOptions.name}', `
            : ``
        }${JSON.stringify(gaCreateOptions)});
      ${
        typeof pluginOptions.anonymize !== `undefined` &&
        pluginOptions.anonymize === true
          ? `ga('set', 'anonymizeIp', true);`
          : ``
      }
      ${
        typeof pluginOptions.optimizeId !== `undefined`
          ? `ga('require', '${pluginOptions.optimizeId}');`
          : ``
      }
      ${
        typeof pluginOptions.experimentId !== `undefined`
          ? `ga('set', 'expId', '${pluginOptions.experimentId}');`
          : ``
      }
      ${
        typeof pluginOptions.variationId !== `undefined`
          ? `ga('set', 'expVar', '${pluginOptions.variationId}');`
          : ``
      }
      ${Object.keys(knownOptions.general).reduce((gaSetCommands, option) => {
        if (typeof pluginOptions[option] === knownOptions.general[option]) {
          gaSetCommands += `ga('set', '${option}', '${pluginOptions[option]}');\n`
        }
        return gaSetCommands
      }, ``)}
      }`,
      }}
    />,
  ])
}
<commit_msg>fix(gatsby-plugin-google-analytics): Separate preconnect and dns-prefetch (#25279)<commit_after>import React from "react"

const knownOptions = {
  createOnly: {
    clientId: `string`,
    sampleRate: `number`,
    siteSpeedSampleRate: `number`,
    alwaysSendReferrer: `boolean`,
    allowAnchor: `boolean`,
    cookieName: `string`,
    cookieExpires: `number`,
    storeGac: `boolean`,
    legacyCookieDomain: `string`,
    legacyHistoryImport: `boolean`,
    allowLinker: `boolean`,
  },
  general: {
    allowAdFeatures: `boolean`,
    dataSource: `string`,
    queueTime: `number`,
    forceSSL: `boolean`,
    transport: `string`,
  },
}

export const onRenderBody = (
  { setHeadComponents, setPostBodyComponents },
  pluginOptions
) => {
  if (process.env.NODE_ENV !== `production` || !pluginOptions.trackingId) {
    return null
  }

  // Lighthouse recommends pre-connecting to google analytics
  setHeadComponents([
    <link
      rel="preconnect"
      key="preconnect-google-analytics"
      href="https://www.google-analytics.com"
    />,
    <link
      rel="dns-prefetch"
      key="dns-prefetch-google-analytics"
      href="https://www.google-analytics.com"
    />,
  ])

  const excludeGAPaths = []
  if (typeof pluginOptions.exclude !== `undefined`) {
    const Minimatch = require(`minimatch`).Minimatch
    pluginOptions.exclude.map(exclude => {
      const mm = new Minimatch(exclude)
      excludeGAPaths.push(mm.makeRe())
    })
  }

  const gaCreateOptions = {}
  for (const option in knownOptions.createOnly) {
    if (typeof pluginOptions[option] === knownOptions.createOnly[option]) {
      gaCreateOptions[option] = pluginOptions[option]
    }
  }

  const setComponents = pluginOptions.head
    ? setHeadComponents
    : setPostBodyComponents
  return setComponents([
    <script
      key={`gatsby-plugin-google-analytics`}
      dangerouslySetInnerHTML={{
        __html: `
  ${
    excludeGAPaths.length
      ? `window.excludeGAPaths=[${excludeGAPaths.join(`,`)}];`
      : ``
  }
  ${
    typeof pluginOptions.anonymize !== `undefined` &&
    pluginOptions.anonymize === true
      ? `function gaOptout(){document.cookie=disableStr+'=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/',window[disableStr]=!0}var gaProperty='${pluginOptions.trackingId}',disableStr='ga-disable-'+gaProperty;document.cookie.indexOf(disableStr+'=true')>-1&&(window[disableStr]=!0);`
      : ``
  }
  if(${
    typeof pluginOptions.respectDNT !== `undefined` &&
    pluginOptions.respectDNT == true
      ? `!(parseInt(navigator.doNotTrack) === 1 || parseInt(window.doNotTrack) === 1 || parseInt(navigator.msDoNotTrack) === 1 || navigator.doNotTrack === "yes")`
      : `true`
  }) {
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];${
      pluginOptions.defer ? `a.defer=1;` : `a.async=1;`
    }a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  }
  if (typeof ga === "function") {
    ga('create', '${pluginOptions.trackingId}', '${
          typeof pluginOptions.cookieDomain === `string`
            ? pluginOptions.cookieDomain
            : `auto`
        }', ${
          typeof pluginOptions.name === `string`
            ? `'${pluginOptions.name}', `
            : ``
        }${JSON.stringify(gaCreateOptions)});
      ${
        typeof pluginOptions.anonymize !== `undefined` &&
        pluginOptions.anonymize === true
          ? `ga('set', 'anonymizeIp', true);`
          : ``
      }
      ${
        typeof pluginOptions.optimizeId !== `undefined`
          ? `ga('require', '${pluginOptions.optimizeId}');`
          : ``
      }
      ${
        typeof pluginOptions.experimentId !== `undefined`
          ? `ga('set', 'expId', '${pluginOptions.experimentId}');`
          : ``
      }
      ${
        typeof pluginOptions.variationId !== `undefined`
          ? `ga('set', 'expVar', '${pluginOptions.variationId}');`
          : ``
      }
      ${Object.keys(knownOptions.general).reduce((gaSetCommands, option) => {
        if (typeof pluginOptions[option] === knownOptions.general[option]) {
          gaSetCommands += `ga('set', '${option}', '${pluginOptions[option]}');\n`
        }
        return gaSetCommands
      }, ``)}
      }`,
      }}
    />,
  ])
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {Fiber} from './ReactInternalTypes';
import type {Container, SuspenseInstance} from './ReactFiberHostConfig';
import type {SuspenseState} from './ReactFiberSuspenseComponent.old';

import invariant from 'shared/invariant';

import {get as getInstance} from 'shared/ReactInstanceMap';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import getComponentName from 'shared/getComponentName';
import {
  ClassComponent,
  HostComponent,
  HostRoot,
  HostPortal,
  HostText,
  FundamentalComponent,
  SuspenseComponent,
} from './ReactWorkTags';
import {NoFlags, Placement, Hydrating} from './ReactFiberFlags';
import {enableFundamentalAPI} from 'shared/ReactFeatureFlags';

const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;

export function getNearestMountedFiber(fiber: Fiber): null | Fiber {
  let node = fiber;
  let nearestMounted = fiber;
  if (!fiber.alternate) {
    // If there is no alternate, this might be a new tree that isn't inserted
    // yet. If it is, then it will have a pending insertion effect on it.
    let nextNode = node;
    do {
      node = nextNode;
      if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
        // This is an insertion or in-progress hydration. The nearest possible
        // mounted fiber is the parent but we need to continue to figure out
        // if that one is still mounted.
        nearestMounted = node.return;
      }
      nextNode = node.return;
    } while (nextNode);
  } else {
    while (node.return) {
      node = node.return;
    }
  }
  if (node.tag === HostRoot) {
    // TODO: Check if this was a nested HostRoot when used with
    // renderContainerIntoSubtree.
    return nearestMounted;
  }
  // If we didn't hit the root, that means that we're in an disconnected tree
  // that has been unmounted.
  return null;
}

export function getSuspenseInstanceFromFiber(
  fiber: Fiber,
): null | SuspenseInstance {
  if (fiber.tag === SuspenseComponent) {
    let suspenseState: SuspenseState | null = fiber.memoizedState;
    if (suspenseState === null) {
      const current = fiber.alternate;
      if (current !== null) {
        suspenseState = current.memoizedState;
      }
    }
    if (suspenseState !== null) {
      return suspenseState.dehydrated;
    }
  }
  return null;
}

export function getContainerFromFiber(fiber: Fiber): null | Container {
  return fiber.tag === HostRoot
    ? (fiber.stateNode.containerInfo: Container)
    : null;
}

export function isFiberMounted(fiber: Fiber): boolean {
  return getNearestMountedFiber(fiber) === fiber;
}

export function isMounted(component: React$Component<any, any>): boolean {
  if (__DEV__) {
    const owner = (ReactCurrentOwner.current: any);
    if (owner !== null && owner.tag === ClassComponent) {
      const ownerFiber: Fiber = owner;
      const instance = ownerFiber.stateNode;
      if (!instance._warnedAboutRefsInRender) {
        console.error(
          '%s is accessing isMounted inside its render() function. ' +
            'render() should be a pure function of props and state. It should ' +
            'never access something that requires stale data from the previous ' +
            'render, such as refs. Move this logic to componentDidMount and ' +
            'componentDidUpdate instead.',
          getComponentName(ownerFiber.type) || 'A component',
        );
      }
      instance._warnedAboutRefsInRender = true;
    }
  }

  const fiber: ?Fiber = getInstance(component);
  if (!fiber) {
    return false;
  }
  return getNearestMountedFiber(fiber) === fiber;
}

function assertIsMounted(fiber) {
  invariant(
    getNearestMountedFiber(fiber) === fiber,
    'Unable to find node on an unmounted component.',
  );
}

export function findCurrentFiberUsingSlowPath(fiber: Fiber): Fiber | null {
  const alternate = fiber.alternate;
  if (!alternate) {
    // If there is no alternate, then we only need to check if it is mounted.
    const nearestMounted = getNearestMountedFiber(fiber);
    invariant(
      nearestMounted !== null,
      'Unable to find node on an unmounted component.',
    );
    if (nearestMounted !== fiber) {
      return null;
    }
    return fiber;
  }
  // If we have two possible branches, we'll walk backwards up to the root
  // to see what path the root points to. On the way we may hit one of the
  // special cases and we'll deal with them.
  let a: Fiber = fiber;
  let b: Fiber = alternate;
  while (true) {
    const parentA = a.return;
    if (parentA === null) {
      // We're at the root.
      break;
    }
    const parentB = parentA.alternate;
    if (parentB === null) {
      // There is no alternate. This is an unusual case. Currently, it only
      // happens when a Suspense component is hidden. An extra fragment fiber
      // is inserted in between the Suspense fiber and its children. Skip
      // over this extra fragment fiber and proceed to the next parent.
      const nextParent = parentA.return;
      if (nextParent !== null) {
        a = b = nextParent;
        continue;
      }
      // If there's no parent, we're at the root.
      break;
    }

    // If both copies of the parent fiber point to the same child, we can
    // assume that the child is current. This happens when we bailout on low
    // priority: the bailed out fiber's child reuses the current child.
    if (parentA.child === parentB.child) {
      let child = parentA.child;
      while (child) {
        if (child === a) {
          // We've determined that A is the current branch.
          assertIsMounted(parentA);
          return fiber;
        }
        if (child === b) {
          // We've determined that B is the current branch.
          assertIsMounted(parentA);
          return alternate;
        }
        child = child.sibling;
      }
      // We should never have an alternate for any mounting node. So the only
      // way this could possibly happen is if this was unmounted, if at all.
      invariant(false, 'Unable to find node on an unmounted component.');
    }

    if (a.return !== b.return) {
      // The return pointer of A and the return pointer of B point to different
      // fibers. We assume that return pointers never criss-cross, so A must
      // belong to the child set of A.return, and B must belong to the child
      // set of B.return.
      a = parentA;
      b = parentB;
    } else {
      // The return pointers point to the same fiber. We'll have to use the
      // default, slow path: scan the child sets of each parent alternate to see
      // which child belongs to which set.
      //
      // Search parent A's child set
      let didFindChild = false;
      let child = parentA.child;
      while (child) {
        if (child === a) {
          didFindChild = true;
          a = parentA;
          b = parentB;
          break;
        }
        if (child === b) {
          didFindChild = true;
          b = parentA;
          a = parentB;
          break;
        }
        child = child.sibling;
      }
      if (!didFindChild) {
        // Search parent B's child set
        child = parentB.child;
        while (child) {
          if (child === a) {
            didFindChild = true;
            a = parentB;
            b = parentA;
            break;
          }
          if (child === b) {
            didFindChild = true;
            b = parentB;
            a = parentA;
            break;
          }
          child = child.sibling;
        }
        invariant(
          didFindChild,
          'Child was not found in either parent set. This indicates a bug ' +
            'in React related to the return pointer. Please file an issue.',
        );
      }
    }

    invariant(
      a.alternate === b,
      "Return fibers should always be each others' alternates. " +
        'This error is likely caused by a bug in React. Please file an issue.',
    );
  }
  // If the root is not a host container, we're in a disconnected tree. I.e.
  // unmounted.
  invariant(
    a.tag === HostRoot,
    'Unable to find node on an unmounted component.',
  );
  if (a.stateNode.current === a) {
    // We've determined that A is the current branch.
    return fiber;
  }
  // Otherwise B has to be current branch.
  return alternate;
}

export function findCurrentHostFiber(parent: Fiber): Fiber | null {
  const currentParent = findCurrentFiberUsingSlowPath(parent);
  if (!currentParent) {
    return null;
  }

  // Next we'll drill down this component to find the first HostComponent/Text.
  let node: Fiber = currentParent;
  while (true) {
    if (node.tag === HostComponent || node.tag === HostText) {
      return node;
    } else if (node.child) {
      node.child.return = node;
      node = node.child;
      continue;
    }
    if (node === currentParent) {
      return null;
    }
    while (!node.sibling) {
      if (!node.return || node.return === currentParent) {
        return null;
      }
      node = node.return;
    }
    node.sibling.return = node.return;
    node = node.sibling;
  }
  // Flow needs the return null here, but ESLint complains about it.
  // eslint-disable-next-line no-unreachable
  return null;
}

export function findCurrentHostFiberWithNoPortals(parent: Fiber): Fiber | null {
  const currentParent = findCurrentFiberUsingSlowPath(parent);
  if (!currentParent) {
    return null;
  }

  // Next we'll drill down this component to find the first HostComponent/Text.
  let node: Fiber = currentParent;
  while (true) {
    if (
      node.tag === HostComponent ||
      node.tag === HostText ||
      (enableFundamentalAPI && node.tag === FundamentalComponent)
    ) {
      return node;
    } else if (node.child && node.tag !== HostPortal) {
      node.child.return = node;
      node = node.child;
      continue;
    }
    if (node === currentParent) {
      return null;
    }
    while (!node.sibling) {
      if (!node.return || node.return === currentParent) {
        return null;
      }
      node = node.return;
    }
    node.sibling.return = node.return;
    node = node.sibling;
  }
  // Flow needs the return null here, but ESLint complains about it.
  // eslint-disable-next-line no-unreachable
  return null;
}

export function isFiberSuspenseAndTimedOut(fiber: Fiber): boolean {
  const memoizedState = fiber.memoizedState;
  return (
    fiber.tag === SuspenseComponent &&
    memoizedState !== null &&
    memoizedState.dehydrated === null
  );
}

export function doesFiberContain(
  parentFiber: Fiber,
  childFiber: Fiber,
): boolean {
  let node = childFiber;
  const parentFiberAlternate = parentFiber.alternate;
  while (node !== null) {
    if (node === parentFiber || node === parentFiberAlternate) {
      return true;
    }
    node = node.return;
  }
  return false;
}
<commit_msg>findDOMNode: Remove return pointer mutation (#20272)<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */

import type {Fiber} from './ReactInternalTypes';
import type {Container, SuspenseInstance} from './ReactFiberHostConfig';
import type {SuspenseState} from './ReactFiberSuspenseComponent.old';

import invariant from 'shared/invariant';

import {get as getInstance} from 'shared/ReactInstanceMap';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import getComponentName from 'shared/getComponentName';
import {
  ClassComponent,
  HostComponent,
  HostRoot,
  HostPortal,
  HostText,
  FundamentalComponent,
  SuspenseComponent,
} from './ReactWorkTags';
import {NoFlags, Placement, Hydrating} from './ReactFiberFlags';
import {enableFundamentalAPI} from 'shared/ReactFeatureFlags';

const ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;

export function getNearestMountedFiber(fiber: Fiber): null | Fiber {
  let node = fiber;
  let nearestMounted = fiber;
  if (!fiber.alternate) {
    // If there is no alternate, this might be a new tree that isn't inserted
    // yet. If it is, then it will have a pending insertion effect on it.
    let nextNode = node;
    do {
      node = nextNode;
      if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
        // This is an insertion or in-progress hydration. The nearest possible
        // mounted fiber is the parent but we need to continue to figure out
        // if that one is still mounted.
        nearestMounted = node.return;
      }
      nextNode = node.return;
    } while (nextNode);
  } else {
    while (node.return) {
      node = node.return;
    }
  }
  if (node.tag === HostRoot) {
    // TODO: Check if this was a nested HostRoot when used with
    // renderContainerIntoSubtree.
    return nearestMounted;
  }
  // If we didn't hit the root, that means that we're in an disconnected tree
  // that has been unmounted.
  return null;
}

export function getSuspenseInstanceFromFiber(
  fiber: Fiber,
): null | SuspenseInstance {
  if (fiber.tag === SuspenseComponent) {
    let suspenseState: SuspenseState | null = fiber.memoizedState;
    if (suspenseState === null) {
      const current = fiber.alternate;
      if (current !== null) {
        suspenseState = current.memoizedState;
      }
    }
    if (suspenseState !== null) {
      return suspenseState.dehydrated;
    }
  }
  return null;
}

export function getContainerFromFiber(fiber: Fiber): null | Container {
  return fiber.tag === HostRoot
    ? (fiber.stateNode.containerInfo: Container)
    : null;
}

export function isFiberMounted(fiber: Fiber): boolean {
  return getNearestMountedFiber(fiber) === fiber;
}

export function isMounted(component: React$Component<any, any>): boolean {
  if (__DEV__) {
    const owner = (ReactCurrentOwner.current: any);
    if (owner !== null && owner.tag === ClassComponent) {
      const ownerFiber: Fiber = owner;
      const instance = ownerFiber.stateNode;
      if (!instance._warnedAboutRefsInRender) {
        console.error(
          '%s is accessing isMounted inside its render() function. ' +
            'render() should be a pure function of props and state. It should ' +
            'never access something that requires stale data from the previous ' +
            'render, such as refs. Move this logic to componentDidMount and ' +
            'componentDidUpdate instead.',
          getComponentName(ownerFiber.type) || 'A component',
        );
      }
      instance._warnedAboutRefsInRender = true;
    }
  }

  const fiber: ?Fiber = getInstance(component);
  if (!fiber) {
    return false;
  }
  return getNearestMountedFiber(fiber) === fiber;
}

function assertIsMounted(fiber) {
  invariant(
    getNearestMountedFiber(fiber) === fiber,
    'Unable to find node on an unmounted component.',
  );
}

export function findCurrentFiberUsingSlowPath(fiber: Fiber): Fiber | null {
  const alternate = fiber.alternate;
  if (!alternate) {
    // If there is no alternate, then we only need to check if it is mounted.
    const nearestMounted = getNearestMountedFiber(fiber);
    invariant(
      nearestMounted !== null,
      'Unable to find node on an unmounted component.',
    );
    if (nearestMounted !== fiber) {
      return null;
    }
    return fiber;
  }
  // If we have two possible branches, we'll walk backwards up to the root
  // to see what path the root points to. On the way we may hit one of the
  // special cases and we'll deal with them.
  let a: Fiber = fiber;
  let b: Fiber = alternate;
  while (true) {
    const parentA = a.return;
    if (parentA === null) {
      // We're at the root.
      break;
    }
    const parentB = parentA.alternate;
    if (parentB === null) {
      // There is no alternate. This is an unusual case. Currently, it only
      // happens when a Suspense component is hidden. An extra fragment fiber
      // is inserted in between the Suspense fiber and its children. Skip
      // over this extra fragment fiber and proceed to the next parent.
      const nextParent = parentA.return;
      if (nextParent !== null) {
        a = b = nextParent;
        continue;
      }
      // If there's no parent, we're at the root.
      break;
    }

    // If both copies of the parent fiber point to the same child, we can
    // assume that the child is current. This happens when we bailout on low
    // priority: the bailed out fiber's child reuses the current child.
    if (parentA.child === parentB.child) {
      let child = parentA.child;
      while (child) {
        if (child === a) {
          // We've determined that A is the current branch.
          assertIsMounted(parentA);
          return fiber;
        }
        if (child === b) {
          // We've determined that B is the current branch.
          assertIsMounted(parentA);
          return alternate;
        }
        child = child.sibling;
      }
      // We should never have an alternate for any mounting node. So the only
      // way this could possibly happen is if this was unmounted, if at all.
      invariant(false, 'Unable to find node on an unmounted component.');
    }

    if (a.return !== b.return) {
      // The return pointer of A and the return pointer of B point to different
      // fibers. We assume that return pointers never criss-cross, so A must
      // belong to the child set of A.return, and B must belong to the child
      // set of B.return.
      a = parentA;
      b = parentB;
    } else {
      // The return pointers point to the same fiber. We'll have to use the
      // default, slow path: scan the child sets of each parent alternate to see
      // which child belongs to which set.
      //
      // Search parent A's child set
      let didFindChild = false;
      let child = parentA.child;
      while (child) {
        if (child === a) {
          didFindChild = true;
          a = parentA;
          b = parentB;
          break;
        }
        if (child === b) {
          didFindChild = true;
          b = parentA;
          a = parentB;
          break;
        }
        child = child.sibling;
      }
      if (!didFindChild) {
        // Search parent B's child set
        child = parentB.child;
        while (child) {
          if (child === a) {
            didFindChild = true;
            a = parentB;
            b = parentA;
            break;
          }
          if (child === b) {
            didFindChild = true;
            b = parentB;
            a = parentA;
            break;
          }
          child = child.sibling;
        }
        invariant(
          didFindChild,
          'Child was not found in either parent set. This indicates a bug ' +
            'in React related to the return pointer. Please file an issue.',
        );
      }
    }

    invariant(
      a.alternate === b,
      "Return fibers should always be each others' alternates. " +
        'This error is likely caused by a bug in React. Please file an issue.',
    );
  }
  // If the root is not a host container, we're in a disconnected tree. I.e.
  // unmounted.
  invariant(
    a.tag === HostRoot,
    'Unable to find node on an unmounted component.',
  );
  if (a.stateNode.current === a) {
    // We've determined that A is the current branch.
    return fiber;
  }
  // Otherwise B has to be current branch.
  return alternate;
}

export function findCurrentHostFiber(parent: Fiber): Fiber | null {
  const currentParent = findCurrentFiberUsingSlowPath(parent);
  return currentParent !== null
    ? findCurrentHostFiberImpl(currentParent)
    : null;
}

function findCurrentHostFiberImpl(node: Fiber) {
  // Next we'll drill down this component to find the first HostComponent/Text.
  if (node.tag === HostComponent || node.tag === HostText) {
    return node;
  }

  let child = node.child;
  while (child !== null) {
    const match = findCurrentHostFiberImpl(child);
    if (match !== null) {
      return match;
    }
    child = child.sibling;
  }

  return null;
}

export function findCurrentHostFiberWithNoPortals(parent: Fiber): Fiber | null {
  const currentParent = findCurrentFiberUsingSlowPath(parent);
  return currentParent !== null
    ? findCurrentHostFiberWithNoPortalsImpl(currentParent)
    : null;
}

function findCurrentHostFiberWithNoPortalsImpl(node: Fiber) {
  // Next we'll drill down this component to find the first HostComponent/Text.
  if (
    node.tag === HostComponent ||
    node.tag === HostText ||
    (enableFundamentalAPI && node.tag === FundamentalComponent)
  ) {
    return node;
  }

  let child = node.child;
  while (child !== null) {
    if (child.tag !== HostPortal) {
      const match = findCurrentHostFiberWithNoPortalsImpl(child);
      if (match !== null) {
        return match;
      }
    }
    child = child.sibling;
  }

  return null;
}

export function isFiberSuspenseAndTimedOut(fiber: Fiber): boolean {
  const memoizedState = fiber.memoizedState;
  return (
    fiber.tag === SuspenseComponent &&
    memoizedState !== null &&
    memoizedState.dehydrated === null
  );
}

export function doesFiberContain(
  parentFiber: Fiber,
  childFiber: Fiber,
): boolean {
  let node = childFiber;
  const parentFiberAlternate = parentFiber.alternate;
  while (node !== null) {
    if (node === parentFiber || node === parentFiberAlternate) {
      return true;
    }
    node = node.return;
  }
  return false;
}
<|endoftext|>


<commit_before>$(function() {

  var timerId = 0;

  // update job table with current values
  var updateJobs = function() {
     $.getJSON(
      '/update.jobs',
      {},
      function(json) {
        var finished = true;
        $.each(json, function(index, job) {
          // update only if necessary
          var currentStatus = $("#status-"+job.job_id).text();
          if (currentStatus in ['ProcessSucceeded', 'ProcessFailed', 'Exception']) {
            continue;
          }

          var status_class = 'label'
          if (job.status == 'ProcessSucceeded') {
            status_class += ' label-success';
          }
          else if (job.status == 'ProcessFailed') {
            status_class += ' label-warning';
          }
          else if (job.status == 'Exception') {
            status_class += ' label-important';
          }
          else {
            status_class += ' label-info';
            finished = false;
          }

          $("#status-"+job.job_id).attr('class', status_class);
          $("#status-"+job.job_id).text(job.status);
          $("#message-"+job.job_id).text(job.message);
          $("#progress-"+job.job_id).attr('style', "width: "+job.progress+"%");
          $("#progress-"+job.job_id).text(job.progress);
        });

        if (finished) {
          clearInterval(timerId);
        }
      }
    );
  };

  // refresh job list each sec ...
  timerId = setInterval(function() {
    updateJobs();
  }, 1000);

  // Refresh job list ...
  $("a.job-refresh").click(function(e) {
    e.preventDefault();
    updateJobs();
  });

  // Delete all jobs
  $("a.job-delete-all").click(function(e) {
    e.preventDefault();
    $.getJSON(
      '/deleteall.job',
      {},
      function(json) {
        location.reload()
      }
    );
  });

  // delete job
  $(".delete").button({
    text: false,
  }).click(function( event ) {
    var job_id = $(this).attr('data-value');
    var row = $(this).closest('tr');
    $.getJSON(
      '/delete.job',
      {'job_id': job_id},
      function(json) {
        row.remove();
      }
    );
  });

  // show details
  $(".show").button({
    text: false,
  }).click(function( event ) {
    var job_id = $(this).attr('data-value');
    window.location.href = "/output_details?job_id=" + job_id;
  });

});
<commit_msg>fixed update condition in job.js<commit_after>$(function() {

  var timerId = 0;

  // update job table with current values
  var updateJobs = function() {
     $.getJSON(
      '/update.jobs',
      {},
      function(json) {
        var finished = true;
        $.each(json, function(index, job) {
          // update only if necessary
          var currentStatus = $("#status-"+job.job_id).text();
          if (! (currentStatus in ['ProcessSucceeded', 'ProcessFailed', 'Exception']) ) {
            var status_class = 'label'
            if (job.status == 'ProcessSucceeded') {
              status_class += ' label-success';
            }
            else if (job.status == 'ProcessFailed') {
              status_class += ' label-warning';
            }
            else if (job.status == 'Exception') {
              status_class += ' label-important';
            }
            else {
              status_class += ' label-info';
              finished = false;
            }

            $("#status-"+job.job_id).attr('class', status_class);
            $("#status-"+job.job_id).text(job.status);
            $("#message-"+job.job_id).text(job.message);
            $("#progress-"+job.job_id).attr('style', "width: "+job.progress+"%");
            $("#progress-"+job.job_id).text(job.progress);
          }
        });

        if (finished == true) {
          clearInterval(timerId);
        }
      }
    );
  };

  // refresh job list each sec ...
  timerId = setInterval(function() {
    updateJobs();
  }, 1000);

  // Refresh job list ...
  $("a.job-refresh").click(function(e) {
    e.preventDefault();
    updateJobs();
  });

  // Delete all jobs
  $("a.job-delete-all").click(function(e) {
    e.preventDefault();
    $.getJSON(
      '/deleteall.job',
      {},
      function(json) {
        location.reload()
      }
    );
  });

  // delete job
  $(".delete").button({
    text: false,
  }).click(function( event ) {
    var job_id = $(this).attr('data-value');
    var row = $(this).closest('tr');
    $.getJSON(
      '/delete.job',
      {'job_id': job_id},
      function(json) {
        row.remove();
      }
    );
  });

  // show details
  $(".show").button({
    text: false,
  }).click(function( event ) {
    var job_id = $(this).attr('data-value');
    window.location.href = "/output_details?job_id=" + job_id;
  });

});
<|endoftext|>


<commit_before>import { storiesOf } from '@storybook/polymer';
import { action } from '@storybook/addon-actions';
import { withNotes } from '@storybook/addon-notes';
import {
  withKnobs,
  text,
  button,
  number,
  select,
  date,
  color,
  array,
  boolean,
} from '@storybook/addon-knobs/polymer';
import { document } from 'global';
import '../polymer-playground-app.html';
import '../playground-button.html';
import '../separated-button/separated-button.html';
import './storybook-welcome-to-polymer.html';

storiesOf('Advanced/Decorator', module)
  .addDecorator(story => {
    const el = story();
    el.setAttribute('title', `${el.getAttribute('title')} - decorated`);
    return el;
  })
  .add('example decoration', () => {
    const el = document.createElement('playground-button');
    el.setAttribute('title', 'An example title');
    return el;
  });

storiesOf('Advanced/Addon Actions', module)
  .add('Action only', () => {
    const el = document.createElement('playground-button');
    el.addEventListener('click', action('log1'));
    return el;
  })
  .add('Action and method', () => {
    const el = document.createElement('playground-button');
    el.addEventListener('click', e => action('log2')(e.target));
    return el;
  });

storiesOf('Advanced/Addon Notes', module)
  .add(
    'Simple note',
    withNotes({ text: 'My notes on some bold text' })(
      () =>
        '
Etiam vulputate elit eu venenatis eleifend. Duis nec lectus augue. Morbi egestas diam sed vulputate mollis. Fusce egestas pretium vehicula. Integer sed neque diam. Donec consectetur velit vitae enim varius, ut placerat arcu imperdiet. Praesent sed faucibus arcu. Nullam sit amet nibh a enim eleifend rhoncus. Donec pretium elementum leo at fermentum. Nulla sollicitudin, mauris quis semper tempus, sem metus tristique diam, efficitur pulvinar mi urna id urna.
'
    )
  )
  .add(
    'Note with HTML',
    withNotes({
      text: `

My notes on emojies

      It's not all that important to be honest, but..

      Emojis are great, I love emojis, in fact I like using them in my Component notes too! 😇
    `,
    })(() => '
🤔😳😯😮
😄😩😓😱
🤓😑😶😊
')
  );

storiesOf('Advanced/Addon Knobs', module)
  .addDecorator(withKnobs)
  .add('simple', () => {
    const title = text('Button title', 'Hello');
    const el = document.createElement('playground-button');
    el.setAttribute('title', title);
    button('callback', () => el.setAttribute('title', 'testing'));
    return el;
  })
  .add('complex', () => {
    const name = text('Name', 'Jane');
    const stock = number('Stock', 20, { range: true, min: 0, max: 30, step: 5 });
    const fruits = { apples: 'Apple', bananas: 'Banana', cherries: 'Cherry' };
    const fruit = select('Fruit', fruits, 'apple');
    const price = number('Price', 2.25);
    const colour = color('Border', 'deeppink');
    const today = date('Today', new Date('Jan 20 2017'));
    const items = array('Items', ['Laptop', 'Book', 'Whiskey']);
    const nice = boolean('Nice', true);

    const stockMessage = stock
      ? `I have a stock of ${stock} ${fruit}, costing $${price} each.`
      : `I'm out of ${fruit}${nice ? ', Sorry!' : '.'}`;

    button('Arbitrary action', action('You clicked it!'));

    return `

My name is ${name},

today is ${new Date(today).toLocaleDateString()}

${stockMessage}

Also, I have:

              ${items.map(item => `<li>${item}</li>`).join('')}

${nice ? 'Nice to meet you!' : 'Leave me alone!'}

        `;
  });
<commit_msg>Fix TZ + locale in polymer knobs stories<commit_after>import { storiesOf } from '@storybook/polymer';
import { action } from '@storybook/addon-actions';
import { withNotes } from '@storybook/addon-notes';
import {
  withKnobs,
  text,
  button,
  number,
  select,
  date,
  color,
  array,
  boolean,
} from '@storybook/addon-knobs/polymer';
import { document } from 'global';
import '../polymer-playground-app.html';
import '../playground-button.html';
import '../separated-button/separated-button.html';
import './storybook-welcome-to-polymer.html';

storiesOf('Advanced/Decorator', module)
  .addDecorator(story => {
    const el = story();
    el.setAttribute('title', `${el.getAttribute('title')} - decorated`);
    return el;
  })
  .add('example decoration', () => {
    const el = document.createElement('playground-button');
    el.setAttribute('title', 'An example title');
    return el;
  });

storiesOf('Advanced/Addon Actions', module)
  .add('Action only', () => {
    const el = document.createElement('playground-button');
    el.addEventListener('click', action('log1'));
    return el;
  })
  .add('Action and method', () => {
    const el = document.createElement('playground-button');
    el.addEventListener('click', e => action('log2')(e.target));
    return el;
  });

storiesOf('Advanced/Addon Notes', module)
  .add(
    'Simple note',
    withNotes({ text: 'My notes on some bold text' })(
      () =>
        '
Etiam vulputate elit eu venenatis eleifend. Duis nec lectus augue. Morbi egestas diam sed vulputate mollis. Fusce egestas pretium vehicula. Integer sed neque diam. Donec consectetur velit vitae enim varius, ut placerat arcu imperdiet. Praesent sed faucibus arcu. Nullam sit amet nibh a enim eleifend rhoncus. Donec pretium elementum leo at fermentum. Nulla sollicitudin, mauris quis semper tempus, sem metus tristique diam, efficitur pulvinar mi urna id urna.
'
    )
  )
  .add(
    'Note with HTML',
    withNotes({
      text: `

My notes on emojies

      It's not all that important to be honest, but..

      Emojis are great, I love emojis, in fact I like using them in my Component notes too! 😇
    `,
    })(() => '
🤔😳😯😮
😄😩😓😱
🤓😑😶😊
')
  );

storiesOf('Advanced/Addon Knobs', module)
  .addDecorator(withKnobs)
  .add('simple', () => {
    const title = text('Button title', 'Hello');
    const el = document.createElement('playground-button');
    el.setAttribute('title', title);
    button('callback', () => el.setAttribute('title', 'testing'));
    return el;
  })
  .add('complex', () => {
    const name = text('Name', 'Jane');
    const stock = number('Stock', 20, { range: true, min: 0, max: 30, step: 5 });
    const fruits = { apples: 'Apple', bananas: 'Banana', cherries: 'Cherry' };
    const fruit = select('Fruit', fruits, 'apple');
    const price = number('Price', 2.25);
    const colour = color('Border', 'deeppink');
    const today = date('Today', new Date('Jan 20 2017 GMT+0'));
    const items = array('Items', ['Laptop', 'Book', 'Whiskey']);
    const nice = boolean('Nice', true);

    const stockMessage = stock
      ? `I have a stock of ${stock} ${fruit}, costing $${price} each.`
      : `I'm out of ${fruit}${nice ? ', Sorry!' : '.'}`;
    const dateOptions = { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' };

    button('Arbitrary action', action('You clicked it!'));

    return `

My name is ${name},

today is ${new Date(today).toLocaleDateString('en-US', dateOptions)}

${stockMessage}

Also, I have:

              ${items.map(item => `<li>${item}</li>`).join('')}

${nice ? 'Nice to meet you!' : 'Leave me alone!'}

        `;
  });
<|endoftext|>


<commit_before>// Find conversion rate between viewing the teacher sign up form and creating a class

// Rough algorithm
// 1. Find all users that saw teacher form between 7 and 30 days ago
// 2. Find subset of those users that also created a class in last 30 days

// NOTE: update the endDay variable below to control the date range

if (process.argv.length !== 3) {
  log("Usage: node <script> <mongo connection Url analytics>");
  log("Include ?readPreference=secondary in connection URLs");
  process.exit();
}

'use strict';
const scriptStartTime = new Date();
const co = require('co');
const MongoClient = require('mongodb').MongoClient;
const mongoose = require('mongoose');
const mongoConnUrlAnalytics = process.argv[2];
const debugOutput = true;
const endDay = "2017-01-06";
let startDay = new Date(`${endDay}T00:00:00.000Z`);
startDay.setUTCDate(startDay.getUTCDate() - 30);
startDay = startDay.toISOString().substring(0, 10);
const daysToCreateClass = 7;

const teacherFormEvents = ['Teachers Request Demo Loaded', 'Teachers Create Account Loaded', 'Teachers Convert Account Loaded'];
const classCreatedEvent = 'Teachers Classes Create New Class Finished';

co(function*() {
  const analyticsDb = yield MongoClient.connect(mongoConnUrlAnalytics, {connectTimeoutMS: 1000 * 60 * 60, socketTimeoutMS: 1000 * 60 * 60});
  const startObjectId = objectIdWithTimestamp(new Date(`${startDay}T00:00:00.000Z`));
  const formEndDate = new Date(`${endDay}T00:00:00.000Z`);
  formEndDate.setUTCDate(formEndDate.getUTCDate() - daysToCreateClass);
  let endObjectId = objectIdWithTimestamp(formEndDate);
  debug(`Finding events..`);

  let query = {$and: [{_id: {$gte: startObjectId}}, {_id: {$lt: endObjectId}}, {event: {$in: teacherFormEvents}}]};
  const formEvents = yield analyticsDb.collection('log').find(query, {user: 1}).toArray();
  debug(`Teacher form events found ${formEvents.length}`);
  const userFormMap = {};
  for (const event of formEvents) {
    userFormMap[event.user] = true;
  }
  const userIds = Object.keys(userFormMap);
  debug(`Unique users ${userIds.length}`);

  endObjectId = objectIdWithTimestamp(new Date(`${endDay}T00:00:00.000Z`));
  query = {$and: [{_id: {$gte: startObjectId}}, {_id: {$lt: endObjectId}}, {event: classCreatedEvent}, {user: {$in: userIds}}]};
  const classEvents = yield analyticsDb.collection('log').find(query, {user: 1}).toArray();
  debug(`Class created events found ${classEvents.length}`);
  const userClassMap = {};
  for (const event of classEvents) {
    userClassMap[event.user] = true;
  }

  const usersSawTeacherForm = userIds.length;
  let teachersCreatedClass = 0;
  for (const userId in userFormMap) {
    if (userClassMap[userId]) {
      teachersCreatedClass++;
    }
  }
  console.log(`Looking at data from ${startDay} to ${endDay}:`);
  console.log(`Saw teacher signup form=${usersSawTeacherForm} Created class=${teachersCreatedClass} Conversion=%${(teachersCreatedClass / usersSawTeacherForm * 100).toFixed(2)}`);

  analyticsDb.close();
  debug(`Script runtime: ${new Date() - scriptStartTime}`);
})

// * Helper functions

function debug(msg) {
  if (debugOutput) console.log(`${new Date().toISOString()} ${msg}`);
}

function objectIdWithTimestamp(timestamp) {
  // Convert string date to Date object (otherwise assume timestamp is a date)
  if (typeof(timestamp) == 'string') timestamp = new Date(timestamp);
  // Convert date object to hex seconds since Unix epoch
  var hexSeconds = Math.floor(timestamp/1000).toString(16);
  // Create an ObjectId with that hex timestamp
  var constructedObjectId = mongoose.Types.ObjectId(hexSeconds + "0000000000000000");
  return constructedObjectId;
}
<commit_msg>Update teacher form => create class conversion script ranges<commit_after>// Find conversion rate between viewing the teacher sign up form and creating a class

// Rough algorithm
// 1. Find all users that saw teacher form between 7 and 30 days ago
// 2. Find subset of those users that also created a class in last 30 days

// NOTE: update the endDay variable below to control the date range

if (process.argv.length !== 3) {
  log("Usage: node <script> <mongo connection Url analytics>");
  log("Include ?readPreference=secondary in connection URLs");
  process.exit();
}

'use strict';
const scriptStartTime = new Date();
const co = require('co');
const MongoClient = require('mongodb').MongoClient;
const mongoose = require('mongoose');
const mongoConnUrlAnalytics = process.argv[2];
const debugOutput = true;
const daysToViewForm = 7
const daysToCreateClass = 4;
const endDay = "2017-01-13";
let startDay = new Date(`${endDay}T00:00:00.000Z`);
startDay.setUTCDate(startDay.getUTCDate() - daysToViewForm - daysToCreateClass);
startDay = startDay.toISOString().substring(0, 10);
debug(`Measuring days ${startDay} to ${endDay}`);

const teacherFormEvents = ['Teachers Request Demo Loaded', 'Teachers Create Account Loaded', 'Teachers Convert Account Loaded'];
const classCreatedEvent = 'Teachers Classes Create New Class Finished';

co(function*() {
  const analyticsDb = yield MongoClient.connect(mongoConnUrlAnalytics, {connectTimeoutMS: 1000 * 60 * 60, socketTimeoutMS: 1000 * 60 * 60});

  const startObjectId = objectIdWithTimestamp(new Date(`${startDay}T00:00:00.000Z`));
  const formEndDate = new Date(`${endDay}T00:00:00.000Z`);
  formEndDate.setUTCDate(formEndDate.getUTCDate() - daysToCreateClass);
  let endObjectId = objectIdWithTimestamp(formEndDate);
  debug(`Finding view teacher form events between ${startDay} and ${formEndDate.toISOString().substring(0, 10)}..`);

  let query = {$and: [{_id: {$gte: startObjectId}}, {_id: {$lt: endObjectId}}, {event: {$in: teacherFormEvents}}]};
  const formEvents = yield analyticsDb.collection('log').find(query, {user: 1}).toArray();
  debug(`Teacher form events found ${formEvents.length}`);
  const userFormMap = {};
  for (const event of formEvents) {
    userFormMap[event.user] = true;
  }
  const userIds = Object.keys(userFormMap);
  debug(`Unique users ${userIds.length}`);

  debug(`Finding created class events between ${startDay} and ${endDay}..`);
  endObjectId = objectIdWithTimestamp(new Date(`${endDay}T00:00:00.000Z`));
  query = {$and: [{_id: {$gte: startObjectId}}, {_id: {$lt: endObjectId}}, {event: classCreatedEvent}, {user: {$in: userIds}}]};
  const classEvents = yield analyticsDb.collection('log').find(query, {user: 1}).toArray();
  debug(`Class created events found ${classEvents.length}`);
  const userClassMap = {};
  for (const event of classEvents) {
    userClassMap[event.user] = true;
  }

  const usersSawTeacherForm = userIds.length;
  let teachersCreatedClass = 0;
  for (const userId in userFormMap) {
    if (userClassMap[userId]) {
      teachersCreatedClass++;
    }
  }
  console.log(`Looking at data from ${startDay} to ${endDay}:`);
  console.log(`Saw teacher signup form= ${usersSawTeacherForm} Created class= ${teachersCreatedClass} Conversion= ${(teachersCreatedClass / usersSawTeacherForm).toFixed(4)}`);

  analyticsDb.close();
  debug(`Script runtime: ${new Date() - scriptStartTime}`);
})

// * Helper functions

function debug(msg) {
  if (debugOutput) console.log(`${new Date().toISOString()} ${msg}`);
}

function objectIdWithTimestamp(timestamp) {
  // Convert string date to Date object (otherwise assume timestamp is a date)
  if (typeof(timestamp) == 'string') timestamp = new Date(timestamp);
  // Convert date object to hex seconds since Unix epoch
  var hexSeconds = Math.floor(timestamp/1000).toString(16);
  // Create an ObjectId with that hex timestamp
  var constructedObjectId = mongoose.Types.ObjectId(hexSeconds + "0000000000000000");
  return constructedObjectId;
}
<|endoftext|>


<commit_before>import expect from 'unexpected'

export const boolString = (v) => expect(v, 'to be a string').and('to be one of', ['0', '1']);

export const timeStampString = (v) => expect(v, 'to be a string').and('to match', /^\d+$/);

export const UUID = (v) => expect(v, 'to match', /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-(8|9|a|b)[a-f0-9]{3}-[a-f0-9]{12}$/);

export const user = {
  id:                      expect.it('to satisfy', UUID),
  username:                expect.it('to be a string'),
  screenName:              expect.it('to be a string'),
  isPrivate:               expect.it('to satisfy', boolString),
  isProtected:             expect.it('to satisfy', boolString),
  isVisibleToAnonymous:    expect.it('to satisfy', boolString),
  createdAt:               expect.it('to satisfy', timeStampString),
  updatedAt:               expect.it('to satisfy', timeStampString),
  type:                    expect.it('to equal', 'user'),
  description:             expect.it('to be a string'),
  profilePictureLargeUrl:  expect.it('to be a string'),
  profilePictureMediumUrl: expect.it('to be a string'),
  statistics:              expect.it('to be an object'),
};

export const group = {
  ...user,
  isRestricted:   expect.it('to satisfy', boolString),
  type:           expect.it('to equal', 'group'),
  administrators: expect.it('to be an array').and('to have items satisfying', UUID),
};

export const userOrGroup = (obj) => {
  const isGroup = obj && typeof obj === 'object' && obj.type === 'group';
  return expect(obj, 'to exhaustively satisfy', isGroup ? group : user);
};

const postBasic = {
  id:               expect.it('to satisfy', UUID),
  body:             expect.it('to be a string'),
  commentsDisabled: expect.it('to satisfy', boolString),
  createdAt:        expect.it('to satisfy', timeStampString),
  updatedAt:        expect.it('to satisfy', timeStampString),
  createdBy:        expect.it('to satisfy', UUID),
  postedTo:         expect.it('to be an array').and('to be empty').or('to have items satisfying', UUID),
  attachments:      expect.it('to be an array').and('to be empty').or('to have items satisfying', UUID),
  comments:         expect.it('to be an array').and('to be empty').or('to have items satisfying', UUID),
  likes:            expect.it('to be an array').and('to be empty').or('to have items satisfying', UUID),
  omittedComments:  expect.it('to be a number'),
  omittedLikes:     expect.it('to be a number'),
};

export const post = (obj) => {
  const isHidden = obj && typeof obj === 'object' && obj.isHidden;
  if (!isHidden) {
    return expect(obj, 'to exhaustively satisfy', postBasic);
  }
  return expect(obj, 'to exhaustively satisfy', {
    ...postBasic,
    isHidden: expect.it('to be', true),
  });
};

export const comment = {
  id:        expect.it('to satisfy', UUID),
  body:      expect.it('to be a string'),
  createdAt: expect.it('to satisfy', timeStampString),
  updatedAt: expect.it('to satisfy', timeStampString),
  createdBy: expect.it('to satisfy', UUID),
};

const attachmentCommons = {
  id:           expect.it('to satisfy', UUID),
  createdAt:    expect.it('to satisfy', timeStampString),
  updatedAt:    expect.it('to satisfy', timeStampString),
  createdBy:    expect.it('to satisfy', UUID),
  mediaType:    expect.it('to be one of', ['image', 'audio', 'general']),
  fileName:     expect.it('to be a string'),
  fileSize:     expect.it('to be a string').and('to match', /^\d+$/),
  imageSizes:   expect.it('to be an object'),
  thumbnailUrl: expect.it('to be a string'),
  url:          expect.it('to be a string'),
};

export const attachmentImage = {
  ...attachmentCommons,
  mediaType:  expect.it('to equal', 'image'),
  imageSizes: expect.it('to have keys satisfying', 'to be one of', ['o', 't', 't2'])
    .and('to have values exhaustively satisfying', {
      w:   expect.it('to be a number'),
      h:   expect.it('to be a number'),
      url: expect.it('to be a string'),
    }),
};

export const attachmentAudio = {
  ...attachmentCommons,
  mediaType:  expect.it('to equal', 'audio'),
  artist:     expect.it('to be a string'),
  title:      expect.it('to be a string'),
  imageSizes: expect.it('to be empty'),
};

export const attachmentGeneral = {
  ...attachmentCommons,
  mediaType:  expect.it('to equal', 'general'),
  imageSizes: expect.it('to be empty'),
};

export const attachment = (obj) =>
  expect(obj, 'to be an object')
  .and('to satisfy', attachmentCommons)
  .and('to satisfy', (obj) => {
    switch (obj.mediaType) {
      case 'image':   return expect(obj, 'to exhaustively satisfy', attachmentImage);
      case 'audio':   return expect(obj, 'to exhaustively satisfy', attachmentAudio);
      case 'general': return expect(obj, 'to exhaustively satisfy', attachmentGeneral);
    }
    return null;
  });
<commit_msg>Add comment likes fields to post and comment schema expectation.<commit_after>import expect from 'unexpected'

export const boolString = (v) => expect(v, 'to be a string').and('to be one of', ['0', '1']);

export const timeStampString = (v) => expect(v, 'to be a string').and('to match', /^\d+$/);

export const UUID = (v) => expect(v, 'to match', /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-(8|9|a|b)[a-f0-9]{3}-[a-f0-9]{12}$/);

export const user = {
  id:                      expect.it('to satisfy', UUID),
  username:                expect.it('to be a string'),
  screenName:              expect.it('to be a string'),
  isPrivate:               expect.it('to satisfy', boolString),
  isProtected:             expect.it('to satisfy', boolString),
  isVisibleToAnonymous:    expect.it('to satisfy', boolString),
  createdAt:               expect.it('to satisfy', timeStampString),
  updatedAt:               expect.it('to satisfy', timeStampString),
  type:                    expect.it('to equal', 'user'),
  description:             expect.it('to be a string'),
  profilePictureLargeUrl:  expect.it('to be a string'),
  profilePictureMediumUrl: expect.it('to be a string'),
  statistics:              expect.it('to be an object'),
};

export const group = {
  ...user,
  isRestricted:   expect.it('to satisfy', boolString),
  type:           expect.it('to equal', 'group'),
  administrators: expect.it('to be an array').and('to have items satisfying', UUID),
};

export const userOrGroup = (obj) => {
  const isGroup = obj && typeof obj === 'object' && obj.type === 'group';
  return expect(obj, 'to exhaustively satisfy', isGroup ? group : user);
};

const postBasic = {
  id:                     expect.it('to satisfy', UUID),
  body:                   expect.it('to be a string'),
  commentsDisabled:       expect.it('to satisfy', boolString),
  createdAt:              expect.it('to satisfy', timeStampString),
  updatedAt:              expect.it('to satisfy', timeStampString),
  createdBy:              expect.it('to satisfy', UUID),
  postedTo:               expect.it('to be an array').and('to be empty').or('to have items satisfying', UUID),
  attachments:            expect.it('to be an array').and('to be empty').or('to have items satisfying', UUID),
  comments:               expect.it('to be an array').and('to be empty').or('to have items satisfying', UUID),
  likes:                  expect.it('to be an array').and('to be empty').or('to have items satisfying', UUID),
  omittedComments:        expect.it('to be a number'),
  omittedLikes:           expect.it('to be a number'),
  commentLikes:           expect.it('to be a number'),
  ownCommentLikes:        expect.it('to be a number'),
  omittedCommentLikes:    expect.it('to be a number'),
  omittedOwnCommentLikes: expect.it('to be a number'),
};

export const post = (obj) => {
  const isHidden = obj && typeof obj === 'object' && obj.isHidden;
  if (!isHidden) {
    return expect(obj, 'to exhaustively satisfy', postBasic);
  }
  return expect(obj, 'to exhaustively satisfy', {
    ...postBasic,
    isHidden: expect.it('to be', true),
  });
};

export const comment = {
  id:         expect.it('to satisfy', UUID),
  body:       expect.it('to be a string'),
  createdAt:  expect.it('to satisfy', timeStampString),
  updatedAt:  expect.it('to satisfy', timeStampString),
  createdBy:  expect.it('to satisfy', UUID),
  likes:      expect.it('to be a number'),
  hasOwnLike: expect.it('to be a boolean'),
};

const attachmentCommons = {
  id:           expect.it('to satisfy', UUID),
  createdAt:    expect.it('to satisfy', timeStampString),
  updatedAt:    expect.it('to satisfy', timeStampString),
  createdBy:    expect.it('to satisfy', UUID),
  mediaType:    expect.it('to be one of', ['image', 'audio', 'general']),
  fileName:     expect.it('to be a string'),
  fileSize:     expect.it('to be a string').and('to match', /^\d+$/),
  imageSizes:   expect.it('to be an object'),
  thumbnailUrl: expect.it('to be a string'),
  url:          expect.it('to be a string'),
};

export const attachmentImage = {
  ...attachmentCommons,
  mediaType:  expect.it('to equal', 'image'),
  imageSizes: expect.it('to have keys satisfying', 'to be one of', ['o', 't', 't2'])
    .and('to have values exhaustively satisfying', {
      w:   expect.it('to be a number'),
      h:   expect.it('to be a number'),
      url: expect.it('to be a string'),
    }),
};

export const attachmentAudio = {
  ...attachmentCommons,
  mediaType:  expect.it('to equal', 'audio'),
  artist:     expect.it('to be a string'),
  title:      expect.it('to be a string'),
  imageSizes: expect.it('to be empty'),
};

export const attachmentGeneral = {
  ...attachmentCommons,
  mediaType:  expect.it('to equal', 'general'),
  imageSizes: expect.it('to be empty'),
};

export const attachment = (obj) =>
  expect(obj, 'to be an object')
  .and('to satisfy', attachmentCommons)
  .and('to satisfy', (obj) => {
    switch (obj.mediaType) {
      case 'image':   return expect(obj, 'to exhaustively satisfy', attachmentImage);
      case 'audio':   return expect(obj, 'to exhaustively satisfy', attachmentAudio);
      case 'general': return expect(obj, 'to exhaustively satisfy', attachmentGeneral);
    }
    return null;
  });
<|endoftext|>


<commit_before>//Created by Madushanka on 24/02/2015.

angular.module('admin').factory('RestService', function ($resource)
{
    this.ResuestData = function (restPath)
    {
        return $resource(restPath);
    };
})<commit_msg>methord name change<commit_after>//Created by Madushanka on 24/02/2015.

angular.module('admin').factory('RestService', function ($resource)
{
    this.requestData = function (restPath)
    {
        return $resource(restPath);
    };
})<|endoftext|>


<commit_before>var expect = require('chai').expect;
var xml2js = require('xml2js');
var httpUtils = require('../utils/http');
var serverUtils = require('../utils/server');

describe('A request to /index.xml', function () {
  serverUtils.run();
  httpUtils.save({
    url: serverUtils.getUrl('/index.xml'),
    expectedStatusCode: 200,
    parseHTML: false
  });
  before(function parseXml(done) {
    var that = this;
    var parser = new xml2js.Parser();
    parser.parseString(this.body, function (err, xml) {
      that.xml = xml;
      done(err);
    });
  });

  it('returns a list of articles', function () {
    expect(this.xml.feed.title).to.deep.equal(['Todd Wolfson - Software Engineer']);
    expect(this.xml.feed.id).to.deep.equal(['http://twolfson.com/']);
    expect(this.xml.feed.author).to.be.deep.equal([{name: ['Todd Wolfson']}]);
    expect(this.xml.feed.entry.length).to.be.greaterThan(0);
  });
});
<commit_msg>Fixed broken Travis CI test<commit_after>var expect = require('chai').expect;
var xml2js = require('xml2js');
var httpUtils = require('../utils/http');
var serverUtils = require('../utils/server');

describe('A request to /index.xml', function () {
  serverUtils.run();
  httpUtils.save({
    url: serverUtils.getUrl('/index.xml'),
    expectedStatusCode: 200,
    parseHTML: false
  });
  before(function parseXml(done) {
    var that = this;
    var parser = new xml2js.Parser();
    parser.parseString(this.body, function (err, xml) {
      that.xml = xml;
      done(err);
    });
  });

  it('returns a list of articles', function () {
    expect(this.xml.feed.title).to.deep.equal(['Todd Wolfson - Software Engineer']);
    expect(this.xml.feed.id).to.deep.equal(['https://twolfson.com/']);
    expect(this.xml.feed.author).to.be.deep.equal([{name: ['Todd Wolfson']}]);
    expect(this.xml.feed.entry.length).to.be.greaterThan(0);
  });
});
<|endoftext|>


<commit_before>import should from 'should/as-function';
import Promise from 'bluebird';
import _ from 'lodash';
import Syncano from '../../src/syncano';
import {ValidationError} from '../../src/errors';
import {suffix, credentials, hex} from './utils';

describe('APNSConfig', function() {
  this.timeout(15000);

  let connection = null;
  let Instance = null;
  let Model = null;
  const instanceName = suffix.get('APNSConfig');
  const data = {instanceName};

  before(function() {
    connection = Syncano(credentials.getCredentials());
    Instance = connection.Instance;
    Model = connection.APNSConfig;

    return Instance.please().create({name: instanceName});
  });

  after(function() {
    return Instance.please().delete({name: instanceName});
  });

  it('should be validated', function() {
    should(Model().save()).be.rejectedWith(ValidationError);
  });

  it('should require "instanceName"', function() {
    should(Model().save()).be.rejectedWith(/instanceName/);
  });

  describe('#please()', function() {

    it('should be able to get a Model', function() {
      return Model.please().get(data)
        .then((object) => {
          should(object).be.a.Object();
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('links').which.is.Object();
          should(object).have.property('production_certificate').which.is.false();
          should(object).have.property('production_expiration_date').which.is.null();
          should(object).have.property('production_bundle_identifier').which.is.null();
          should(object).have.property('production_certificate_name').which.is.null();
          should(object).have.property('development_certificate').which.is.false();
          should(object).have.property('development_expiration_date').which.is.null();
          should(object).have.property('development_bundle_identifier').which.is.null();
          should(object).have.property('development_certificate_name').which.is.null();
        });
    });

    it('should be able to update a Model', function() {
      return Model.please()
        .update(data, {
          production_certificate_name: instanceName,
          development_certificate: Syncano.file(__dirname + '/certificates/ApplePushDevelopment.p12'),
          development_bundle_identifier: 'com.syncano.testAPNS'
        })
        .then((object) => {
          should(object).be.a.Object();
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('links').which.is.Object();
          should(object).have.property('production_certificate_name').which.is.String().equal(instanceName);
          should(object).have.property('development_certificate').which.is.true();
          should(object).have.property('development_bundle_identifier').which.is.String().equal('com.syncano.testAPNS');
        });
    });

  });

});
<commit_msg>[LIB-694] lint<commit_after>import should from 'should/as-function';
import Syncano from '../../src/syncano';
import {ValidationError} from '../../src/errors';
import {suffix, credentials} from './utils';

describe('APNSConfig', function() {
  this.timeout(15000);

  let connection = null;
  let Instance = null;
  let Model = null;
  const instanceName = suffix.get('APNSConfig');
  const data = {instanceName};

  before(function() {
    connection = Syncano(credentials.getCredentials());
    Instance = connection.Instance;
    Model = connection.APNSConfig;

    return Instance.please().create({name: instanceName});
  });

  after(function() {
    return Instance.please().delete({name: instanceName});
  });

  it('should be validated', function() {
    should(Model().save()).be.rejectedWith(ValidationError);
  });

  it('should require "instanceName"', function() {
    should(Model().save()).be.rejectedWith(/instanceName/);
  });

  describe('#please()', function() {

    it('should be able to get a Model', function() {
      return Model.please().get(data)
        .then((object) => {
          should(object).be.a.Object();
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('links').which.is.Object();
          should(object).have.property('production_certificate').which.is.false();
          should(object).have.property('production_expiration_date').which.is.null();
          should(object).have.property('production_bundle_identifier').which.is.null();
          should(object).have.property('production_certificate_name').which.is.null();
          should(object).have.property('development_certificate').which.is.false();
          should(object).have.property('development_expiration_date').which.is.null();
          should(object).have.property('development_bundle_identifier').which.is.null();
          should(object).have.property('development_certificate_name').which.is.null();
        });
    });

    it('should be able to update a Model', function() {
      return Model.please()
        .update(data, {
          production_certificate_name: instanceName,
          development_certificate: Syncano.file(__dirname + '/certificates/ApplePushDevelopment.p12'),
          development_bundle_identifier: 'com.syncano.testAPNS'
        })
        .then((object) => {
          should(object).be.a.Object();
          should(object).have.property('instanceName').which.is.String().equal(instanceName);
          should(object).have.property('links').which.is.Object();
          should(object).have.property('production_certificate_name').which.is.String().equal(instanceName);
          should(object).have.property('development_certificate').which.is.true();
          should(object).have.property('development_bundle_identifier').which.is.String().equal('com.syncano.testAPNS');
        });
    });

  });

});
<|endoftext|>


<commit_before>/**
 * This class handles listeners for brightcove
 *
 * Warning: This is a "smart" event manager in that it will look to see if your
 * event has fired before you registered an event listener. If your event already
 * fired, we trigger it again.
 */
var RcmBrightCoveEventManager = new function () {
    var self = this;
    var listeners = {};
    var triggeredEvents = {};

    /**
     * Registers an event listener
     *
     * @param event
     * @param listener
     */
    self.on = function (event, listener) {

        self.log('added listener for ' + event);

        if (!listeners[event]) {
            listeners[event] = [];
        }

        listeners[event].push(listener);

        if (triggeredEvents[event]) {
            self.log(event + ' was previously fired, calling its just-added handler now');
            listener(triggeredEvents[event]);
        }
    };

    /**
     * Triggers an event
     *
     * @param event
     * @param args
     */
    self.trigger = function (event, args) {

        self.log('triggering ' + event);

        triggeredEvents[event] = args;

        if (listeners[event]) {
            jQuery.each(
                listeners[event],
                function (index, value) {
                    value(args);
                }
            );
        }
    };

    /**
     * This is a great place to toss a console dot log
     *
     * @param message
     */
    self.log = function (message) {
        console.log(message);
    }
}();<commit_msg>fix brightcove event madness<commit_after>/**
 * This class handles listeners for brightcove
 *
 * Warning: This is a "smart" event manager in that it will look to see if your
 * event has fired before you registered an event listener. If your event already
 * fired, we trigger it again.
 */
var RcmBrightCoveEventManager = new function () {
    var self = this;
    var listeners = {};
    var triggeredEvents = {};

    /**
     * Registers an event listener
     *
     * @param event
     * @param listener
     */
    self.on = function (event, listener) {

        self.log('added listener for ' + event);

        if (!listeners[event]) {
            listeners[event] = [];
        }

        listeners[event].push(listener);

        if (triggeredEvents[event]) {
            self.log(event + ' was previously fired, calling its just-added handler now');
            listener(triggeredEvents[event]);
        }
    };

    /**
     * Triggers an event
     *
     * @param event
     * @param args
     */
    self.trigger = function (event, args) {

        self.log('triggering ' + event);

        triggeredEvents[event] = args;

        if (listeners[event]) {
            jQuery.each(
                listeners[event],
                function (index, value) {
                    value(args);
                }
            );
        }
    };

    /**
     * This is a great place to toss a console dot log
     *
     * @param message
     */
    self.log = function (message) {
    }
}();<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: './src/iframeScript.js',
  output: {
    path: path.join(__dirname, './lib'),
    filename: 'iframe-bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, './src'),
          path.dirname(
            require.resolve('chalk', {
              paths: [path.dirname(require.resolve('@babel/code-frame'))],
            })
          ),
          path.dirname(
            require.resolve('ansi-styles', {
              paths: [
                path.dirname(
                  require.resolve('chalk', {
                    paths: [path.dirname(require.resolve('@babel/code-frame'))],
                  })
                ),
              ],
            })
          ),
        ],
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['react-app'],
          },
        },
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      // We set process.env.NODE_ENV to 'production' so that React is built
      // in production mode.
      'process.env': { NODE_ENV: '"production"' },
      // This prevents our bundled React from accidentally hijacking devtools.
      __REACT_DEVTOOLS_GLOBAL_HOOK__: '({})',
    }),
    // This code is embedded as a string, so it would never be optimized
    // elsewhere.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        comparisons: false,
      },
      output: {
        comments: false,
        ascii_only: false,
      },
    }),
  ],
};
<commit_msg>Fix the build<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: './src/iframeScript.js',
  output: {
    path: path.join(__dirname, './lib'),
    filename: 'iframe-bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, './src'),
          /\/node_modules\/(ansi-styles|chalk)\//,
        ],
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['react-app'],
          },
        },
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      // We set process.env.NODE_ENV to 'production' so that React is built
      // in production mode.
      'process.env': { NODE_ENV: '"production"' },
      // This prevents our bundled React from accidentally hijacking devtools.
      __REACT_DEVTOOLS_GLOBAL_HOOK__: '({})',
    }),
    // This code is embedded as a string, so it would never be optimized
    // elsewhere.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        comparisons: false,
      },
      output: {
        comments: false,
        ascii_only: false,
      },
    }),
  ],
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDom from 'react-dom';
import Switch from 'react-toggle-switch';
import 'styles/main.scss';

class Usage1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {on: false};
  }

  render() {
    return (

Basic usage

Switch state: {this.state.on ? 'On' : 'Off'}

        <Switch onClick={() => this.setState({on: !this.state.on})} on={this.state.on}/>

    );
  }
}

class Usage2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {on: false};
  }

  render() {
    return (

Toggle directly or indirectly

Switch state: {this.state.on ? 'On' : 'Off'}

        <Switch onClick={() => this.setState({on: !this.state.on})} on={this.state.on}/>

This button demonstrates how to toggle the switch indirectly by simply updating the "on" prop.

        <button onClick={() => this.setState({on: !this.state.on})}>{this.state.on ? 'Switch Off' : 'Switch On'}</button>

    );
  }
}

class Usage3 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {on: false};
  }

  render() {
    return (

Disabled Switch

Off and disabled

        <Switch enabled={false}/>

On and disabled

        <Switch enabled={false} on={true}/>

    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      on: false
    };
  }

  render() {
    return (

React Toggle Switch

        <Usage1/>
        <Usage2/>
        <Usage3/>

    );
  }
}

ReactDom.render(<App/>, document.getElementById('app'));<commit_msg>Extract Component directly from react import<commit_after>import React, {Component} from 'react';
import ReactDom from 'react-dom';
import Switch from 'react-toggle-switch';
import 'styles/main.scss';

class Usage1 extends Component {
  constructor(props) {
    super(props);
    this.state = {on: false};
  }

  render() {
    return (

Basic usage

Switch state: {this.state.on ? 'On' : 'Off'}

        <Switch onClick={() => this.setState({on: !this.state.on})} on={this.state.on}/>

    );
  }
}

class Usage2 extends Component {
  constructor(props) {
    super(props);
    this.state = {on: false};
  }

  render() {
    return (

Toggle directly or indirectly

Switch state: {this.state.on ? 'On' : 'Off'}

        <Switch onClick={() => this.setState({on: !this.state.on})} on={this.state.on}/>

This button demonstrates how to toggle the switch indirectly by simply updating the "on" prop.

        <button onClick={() => this.setState({on: !this.state.on})}>{this.state.on ? 'Switch Off' : 'Switch On'}</button>

    );
  }
}

class Usage3 extends Component {
  constructor(props) {
    super(props);
    this.state = {on: false};
  }

  render() {
    return (

Disabled Switch

Off and disabled

        <Switch enabled={false}/>

On and disabled

        <Switch enabled={false} on={true}/>

    );
  }
}

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      on: false
    };
  }

  render() {
    return (

React Toggle Switch

        <Usage1/>
        <Usage2/>
        <Usage3/>

    );
  }
}

ReactDom.render(<App/>, document.getElementById('app'));
<|endoftext|>


<commit_before>var Busboy = require('busboy'),
    path = require('path'),
    fs = require('fs'),
    gm = require('gm'),
    uuid = require('node-uuid'),
    config = require('../../../config/config');

module.exports = function (data) {
    return {
        getAll: function (req, res) {
            data.products.getAll()
                .then(function (products) {
                    res.send(products);
                }, function (error) {
                    res.render('error', {
                        error: error,
                        message: 'Cannot get all products!'
                    });
                });
        },
        getById: function (req, res) {
            var id = req.params.id;

            data.products.getById(id)
                .then(function (product) {
                    res.send(product);
                }, function (error) {
                    res.render('error', {
                        error: error,
                        message: 'Cannot get product by id!'
                    });
                });
        },
        create: function (req, res) {
            //Data validation
            //Price is mandatory

            var busboy = new Busboy({ headers: req.headers }),
                productData = {
                    assets : []
                };

            busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {

                var uuidFilename = uuid() + filename;
                var saveToPath = path.join(path.normalize(config.storageDir  + '/products/images/'), path.basename(uuidFilename));

                var productImageData = {
                    title: filename,
                    src: config.storageDir + '/products/images/' + uuidFilename,
                    thumbSrc: config.storageDir + '/products/images/thumb_' + uuidFilename
                    // TODO: get width and height and assign them here
                };

                var fileStream = fs.createWriteStream(saveToPath);

                productData.assets.push(productImageData);

                file.pipe(fileStream);

                file.on('end', function() {
                    var pathToNewImage = path.join(path.normalize(config.storageDir  + '/products/images/'), 'thumb_' + path.basename(uuidFilename));
                    gm(saveToPath)
                        .options({imageMagick: true})
                        // TODO: Choose the correct image
                        .resize(50, 50, '%')
                        .write(pathToNewImage, function(error){
                            if (error) {
                                return console.log('Image thumb cannot be created! ', arguments);
                            }
                        }
                    )
                });

            });

            busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
                if(fieldname == 'description' || fieldname == 'attributes') {
                    var value = JSON.parse(val);
                }else{
                    var value = val;
                }

                productData[fieldname] = value;
            });

            busboy.on('finish', function() {
                data.products.create(productData)
                    .then(function (createdProduct) {
                        res.json({
                            message: 'New product saved successfully!',
                            product: createdProduct
                        });
                    }, function (error) {
                        res.render('error', {
                            message: 'Cannot create product!',
                            error: error
                        });
                    });
            });

            req.pipe(busboy);
        },
        updateById: function (req, res) {
            var busboy = new Busboy({ headers: req.headers }),
                productData = {
                    assets : []
                };
            busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {

                var uuidFilename = uuid() + filename;
                var saveToPath = path.join(path.normalize(__dirname  + '/../../../public/storage/products/images/'), path.basename(uuidFilename));

                var productImageData = {
                    title: filename,
                    src: 'storage/products/images/' + uuidFilename
                };
                productData.assets.push(productImageData);
                file.pipe(fs.createWriteStream(saveToPath));
            });

            busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
                if(fieldname == 'description' || fieldname == 'attributes') {
                    var value = JSON.parse(val);
                }else{
                    var value = val;
                }

                productData[fieldname] = value;
            });

            busboy.on('finish', function() {
                data.products.updateProductById({id:req.params.id, updatesObject:productData})
                    .then(function (updatedProduct) {
                        res.json({
                            message: 'Product updated successfully!',
                            product: updatedProduct
                        });
                    },function (error) {
                        res.render('error', {
                            message: 'Cannot update product!',
                            error: error
                        });
                    });
            });

            req.pipe(busboy);
        },
        remove: function (req, res) {

        }
    }
};<commit_msg>ImageMagick removed for test<commit_after>var Busboy = require('busboy'),
    path = require('path'),
    fs = require('fs'),
    //gm = require('gm'),
    uuid = require('node-uuid'),
    config = require('../../../config/config');

module.exports = function (data) {
    return {
        getAll: function (req, res) {
            data.products.getAll()
                .then(function (products) {
                    res.send(products);
                }, function (error) {
                    res.render('error', {
                        error: error,
                        message: 'Cannot get all products!'
                    });
                });
        },
        getById: function (req, res) {
            var id = req.params.id;

            data.products.getById(id)
                .then(function (product) {
                    res.send(product);
                }, function (error) {
                    res.render('error', {
                        error: error,
                        message: 'Cannot get product by id!'
                    });
                });
        },
        create: function (req, res) {
            //Data validation
            //Price is mandatory

            var busboy = new Busboy({ headers: req.headers }),
                productData = {
                    assets : []
                };

            busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {

                var uuidFilename = uuid() + filename;
                var saveToPath = path.join(path.normalize(config.storageDir  + '/products/images/'), path.basename(uuidFilename));

                var productImageData = {
                    title: filename,
                    src: config.storageDir + '/products/images/' + uuidFilename,
                    thumbSrc: config.storageDir + '/products/images/thumb_' + uuidFilename
                    // TODO: get width and height and assign them here
                };

                var fileStream = fs.createWriteStream(saveToPath);

                productData.assets.push(productImageData);

                file.pipe(fileStream);

                //file.on('end', function() {
                //    var pathToNewImage = path.join(path.normalize(config.storageDir  + '/products/images/'), 'thumb_' + path.basename(uuidFilename));
                //    gm(saveToPath)
                //        .options({imageMagick: true})
                //        // TODO: Choose the correct image
                //        .resize(50, 50, '%')
                //        .write(pathToNewImage, function(error){
                //            if (error) {
                //                return console.log('Image thumb cannot be created! ', arguments);
                //            }
                //        })
                //});

            });

            busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
                if(fieldname == 'description' || fieldname == 'attributes') {
                    var value = JSON.parse(val);
                }else{
                    var value = val;
                }

                productData[fieldname] = value;
            });

            busboy.on('finish', function() {
                data.products.create(productData)
                    .then(function (createdProduct) {
                        res.json({
                            message: 'New product saved successfully!',
                            product: createdProduct
                        });
                    }, function (error) {
                        res.render('error', {
                            message: 'Cannot create product!',
                            error: error
                        });
                    });
            });

            req.pipe(busboy);
        },
        updateById: function (req, res) {
            var busboy = new Busboy({ headers: req.headers }),
                productData = {
                    assets : []
                };
            busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {

                var uuidFilename = uuid() + filename;
                var saveToPath = path.join(path.normalize(__dirname  + '/../../../public/storage/products/images/'), path.basename(uuidFilename));

                var productImageData = {
                    title: filename,
                    src: 'storage/products/images/' + uuidFilename
                };
                productData.assets.push(productImageData);
                file.pipe(fs.createWriteStream(saveToPath));
            });

            busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
                if(fieldname == 'description' || fieldname == 'attributes') {
                    var value = JSON.parse(val);
                }else{
                    var value = val;
                }

                productData[fieldname] = value;
            });

            busboy.on('finish', function() {
                data.products.updateProductById({id:req.params.id, updatesObject:productData})
                    .then(function (updatedProduct) {
                        res.json({
                            message: 'Product updated successfully!',
                            product: updatedProduct
                        });
                    },function (error) {
                        res.render('error', {
                            message: 'Cannot update product!',
                            error: error
                        });
                    });
            });

            req.pipe(busboy);
        },
        remove: function (req, res) {

        }
    }
};<|endoftext|>


<commit_before>$(document).ready(function() {
  var source = {
    id: 2,
    name: "Blue lamp",
    description: null,
    ui: undefined,
    price: 10,
    purchasePrice: 6,
    purchaseDate: new Date(2014, 10, 1),
    isInUse: true,
    getProfit: function() {
      return this.price - this.purchasePrice;
    }
  };

  var storableProperties = propertyExtractor.extractStorableProperties(source);

  $("#output").html("
Object properties:");

  _.each(storableProperties, function(value, key, list){
    var existingContent = $("#output").html();
    var newContent = "Property: " + key + " of type: " + typeof value + " has value: " + value;
    $("#output").html(existingContent + "
" + newContent);
  }, source );
});
<commit_msg>removed redundant parameters<commit_after>$(document).ready(function() {
  var source = {
    id: 2,
    name: "Blue lamp",
    description: null,
    ui: undefined,
    price: 10,
    purchasePrice: 6,
    purchaseDate: new Date(2014, 10, 1),
    isInUse: true,
    getProfit: function() {
      return this.price - this.purchasePrice;
    }
  };

  var storableProperties = propertyExtractor.extractStorableProperties(source);

  $("#output").html("
Object properties:");

  _.each(storableProperties, function(value, key, list){
    var existingContent = $("#output").html();
    var newContent = "Property: " + key + " of type: " + typeof value + " has value: " + value;
    $("#output").html(existingContent + "
" + newContent);
  });
});
<|endoftext|>


<commit_before>function ping(data) {
    data.msg.channel.send(":ship: Heartbeat: `" + data.bot.ping + "ms` | :trumpet: Latency: `*Getting latency*`").then(msg => {
        msg.edit(msg.content.replace("*Getting latency*", Math.floor(new Date(msg.createdTimestamp).valueOf() - new Date(data.msg.createdTimestamp).valueOf()) + "ms"))
            .catch(data.err).then(data.complete)
    }).catch(data.err)
}

module.exports = {
    commands: [
        {
            trigger: ["ping"],
            call: ping,
            description: ":100: Bestest command for test",
            category: "pongy",
            usage: "ping",
            permissions: 0
        }
    ]
}<commit_msg>updated desc on ping<commit_after>function ping(data) {
    data.msg.channel.send(":ship: Heartbeat: `" + data.bot.ping + "ms` | :trumpet: Latency: `*Getting latency*`").then(msg => {
        msg.edit(msg.content.replace("*Getting latency*", Math.floor(new Date(msg.createdTimestamp).valueOf() - new Date(data.msg.createdTimestamp).valueOf()) + "ms"))
            .catch(data.err).then(data.complete)
    }).catch(data.err)
}

module.exports = {
    commands: [
        {
            trigger: ["ping"],
            call: ping,
            description: "Check the bot's heatbeat and latency.",
            category: "pongy",
            usage: "ping",
            permissions: 0
        }
    ]
}<|endoftext|>