text:
using base::ScopedCFTypeRef;

namespace net {

namespace {

int NetErrorFromOSStatus(OSStatus status) {
  switch (status) {
    case noErr:
      return OK;
    case errSecNotAvailable:
      return ERR_NOT_IMPLEMENTED;
    case errSecAuthFailed:
      return ERR_ACCESS_DENIED;
    default:
      return ERR_FAILED;
  }
}

// Creates a series of SecPolicyRefs to be added to a SecTrustRef used to
// validate a certificate for an SSL server. |hostname| contains the name of
// the SSL server that the certificate should be verified against. If
// successful, returns noErr, and stores the resultant array of SecPolicyRefs
// in |policies|.
OSStatus CreateTrustPolicies(ScopedCFTypeRef<CFArrayRef>* policies) {
  ScopedCFTypeRef<CFMutableArrayRef> local_policies(
      CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
  if (!local_policies)
    return errSecAllocate;

  SecPolicyRef ssl_policy = SecPolicyCreateBasicX509();
  CFArrayAppendValue(local_policies, ssl_policy);
  CFRelease(ssl_policy);
  ssl_policy = SecPolicyCreateSSL(true, nullptr);
  CFArrayAppendValue(local_policies, ssl_policy);
  CFRelease(ssl_policy);

  policies->reset(local_policies.release());
  return noErr;
}

// Builds and evaluates a SecTrustRef for the certificate chain contained
// in |cert_array|, using the verification policies in |trust_policies|. On
// success, returns OK, and updates |trust_ref| and |trust_result|. On failure,
// no output parameters are modified.
//
// Note: An OK return does not mean that |cert_array| is trusted, merely that
// verification was performed successfully.
int BuildAndEvaluateSecTrustRef(CFArrayRef cert_array,
                                CFArrayRef trust_policies,
                                ScopedCFTypeRef<SecTrustRef>* trust_ref,
                                ScopedCFTypeRef<CFArrayRef>* verified_chain,
                                SecTrustResultType* trust_result) {
  SecTrustRef tmp_trust = nullptr;
  OSStatus status =
      SecTrustCreateWithCertificates(cert_array, trust_policies, &tmp_trust);
  if (status)
    return NetErrorFromOSStatus(status);
  ScopedCFTypeRef<SecTrustRef> scoped_tmp_trust(tmp_trust);

  if (TestRootCerts::HasInstance()) {
    status = TestRootCerts::GetInstance()->FixupSecTrustRef(tmp_trust);
    if (status)
      return NetErrorFromOSStatus(status);
  }

  SecTrustResultType tmp_trust_result;
  status = SecTrustEvaluate(tmp_trust, &tmp_trust_result);
  if (status)
    return NetErrorFromOSStatus(status);

  ScopedCFTypeRef<CFMutableArrayRef> tmp_verified_chain(
      CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks));
  const CFIndex chain_length = SecTrustGetCertificateCount(tmp_trust);
  for (CFIndex i = 0; i < chain_length; ++i) {
    SecCertificateRef chain_cert = SecTrustGetCertificateAtIndex(tmp_trust, i);
    CFArrayAppendValue(tmp_verified_chain, chain_cert);
  }

  trust_ref->swap(scoped_tmp_trust);
  *trust_result = tmp_trust_result;
  verified_chain->reset(tmp_verified_chain.release());
  return OK;
}

void GetCertChainInfo(CFArrayRef cert_chain, CertVerifyResult* verify_result) {
  DCHECK_LT(0, CFArrayGetCount(cert_chain));

  verify_result->has_md2 = false;
  verify_result->has_md4 = false;
  verify_result->has_md5 = false;
  verify_result->has_sha1 = false;
  verify_result->has_sha1_leaf = false;

  SecCertificateRef verified_cert = nullptr;
  std::vector<SecCertificateRef> verified_chain;
  for (CFIndex i = 0, count = CFArrayGetCount(cert_chain); i < count; ++i) {
    SecCertificateRef chain_cert = reinterpret_cast<SecCertificateRef>(
        const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, i)));
    if (i == 0) {
      verified_cert = chain_cert;
    } else {
      verified_chain.push_back(chain_cert);
    }

    std::string der_bytes;
    if (!X509Certificate::GetDEREncoded(chain_cert, &der_bytes))
      return;
    const uint8_t* bytes = reinterpret_cast<const uint8_t*>(der_bytes.data());
    ScopedX509 x509_cert(d2i_X509(NULL, &bytes, der_bytes.size()));

    base::StringPiece spki_bytes;
    if (!asn1::ExtractSPKIFromDERCert(der_bytes, &spki_bytes))
      continue;

    HashValue sha1(HASH_VALUE_SHA1);
    CC_SHA1(spki_bytes.data(), spki_bytes.size(), sha1.data());
    verify_result->public_key_hashes.push_back(sha1);

    HashValue sha256(HASH_VALUE_SHA256);
    CC_SHA256(spki_bytes.data(), spki_bytes.size(), sha256.data());
    verify_result->public_key_hashes.push_back(sha256);

    int sig_alg = OBJ_obj2nid(x509_cert->sig_alg->algorithm);
    if (sig_alg == NID_md2WithRSAEncryption) {
      verify_result->has_md2 = true;
    } else if (sig_alg == NID_md4WithRSAEncryption) {
      verify_result->has_md4 = true;
    } else if (sig_alg == NID_md5WithRSAEncryption ||
               sig_alg == NID_md5WithRSA) {
      verify_result->has_md5 = true;
    } else if (sig_alg == NID_sha1WithRSAEncryption ||
               sig_alg == NID_dsaWithSHA || sig_alg == NID_dsaWithSHA1 ||
               sig_alg == NID_dsaWithSHA1_2 || sig_alg == NID_sha1WithRSA ||
               sig_alg == NID_ecdsa_with_SHA1) {
      verify_result->has_sha1 = true;
      if (i == 0)
        verify_result->has_sha1_leaf = true;
    }
  }
  if (!verified_cert) {
    NOTREACHED();
    return;
  }

  verify_result->verified_cert =
      X509Certificate::CreateFromHandle(verified_cert, verified_chain);
}

}  // namespace

CertVerifyProcIOS::CertVerifyProcIOS() {}

CertVerifyProcIOS::~CertVerifyProcIOS() {}

bool CertVerifyProcIOS::SupportsAdditionalTrustAnchors() const {
  return false;
}

bool CertVerifyProcIOS::SupportsOCSPStapling() const {
  return false;
}

int CertVerifyProcIOS::VerifyInternal(
    X509Certificate* cert,
    const std::string& hostname,
    const std::string& ocsp_response,
    int flags,
    CRLSet* crl_set,
    const CertificateList& additional_trust_anchors,
    CertVerifyResult* verify_result) {
  ScopedCFTypeRef<CFArrayRef> trust_policies;
  OSStatus status = CreateTrustPolicies(&trust_policies);
  if (status)
    return NetErrorFromOSStatus(status);

  ScopedCFTypeRef<CFMutableArrayRef> cert_array(
      cert->CreateOSCertChainForCert());
  ScopedCFTypeRef<SecTrustRef> trust_ref;
  SecTrustResultType trust_result = kSecTrustResultDeny;
  ScopedCFTypeRef<CFArrayRef> final_chain;

  status = BuildAndEvaluateSecTrustRef(cert_array, trust_policies, &trust_ref,
                                       &final_chain, &trust_result);
  if (status)
    return NetErrorFromOSStatus(status);

  if (CFArrayGetCount(final_chain) == 0)
    return ERR_FAILED;

  GetCertChainInfo(final_chain, verify_result);

  // TODO(sleevi): Support CRLSet revocation.
  // TODO(svaldez): Add specific error codes for trust errors resulting from
  // expired/not-yet-valid certs.
  switch (trust_result) {
    case kSecTrustResultUnspecified:
    case kSecTrustResultProceed:
      break;
    case kSecTrustResultDeny:
      verify_result->cert_status |= CERT_STATUS_AUTHORITY_INVALID;
    default:
      verify_result->cert_status |= CERT_STATUS_INVALID;
  }

  // Perform hostname verification independent of SecTrustEvaluate.
  if (!verify_result->verified_cert->VerifyNameMatch(
          hostname, &verify_result->common_name_fallback_used)) {
    verify_result->cert_status |= CERT_STATUS_COMMON_NAME_INVALID;
  }

  verify_result->is_issued_by_known_root = false;

  if (IsCertStatusError(verify_result->cert_status))
    return MapCertStatusToNetError(verify_result->cert_status);

  return OK;
}

}  // namespace net


text:
/* Implentación de Agregar Formularios y remover formularios */
collectionDomicilioHolder = jQuery('.domicilio');
collectionDomicilioHolder.data('index', collectionDomicilioHolder.find(':input').length);
jQuery('.add-domicilio-form').click(function(e) {
    e.preventDefault();
    addFormulario(jQuery(this).parent().find('.domicilio'), jQuery(this).parent().find('.domicilio'));
});
jQuery('.domicilio').delegate('.delete-form','click', function(e) {
    e.preventDefault();
    deleteRow(this);
});

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * This file is part of the WebScale library. It is licenced under
 * MIT licence. For more information, see LICENSE file that
 * was distributed with this library.
 */
namespace WebScale\Driver;

use WebScale\Serializer\SerializerInterface;
use WebScale\Exception\InvalidArgumentException;
use Psr\Log\LogLevel;
use RegexIterator;
use RecursiveIteratorIterator;
use RecursiveDirectoryIterator;

/**
 * Cache driver for file system.
 */
class FileSystem extends AbstractDriver
{
    /**
     * @ignore
     */
    const EXTENSION = '.cache';

    /**
     * @ignore
     */
    protected $directory;

    /**
     * @ignore
     */
    protected $serializer;

    /**
     * @ignore
     */
    protected $serializer_hash;

    /**
     * Constructor
     *
     * @param string $directory
     * @param array $options
     * @param bool $autoclean
     */
    public function __construct($directory, SerializerInterface $serializer = null, $autocleaning = true)
    {
        if (!is_dir($directory) && !@mkdir($directory, 0755, true)) {
            throw new InvalidArgumentException(
                sprintf('The directory "%s" does not exist and could not be created.', $directory)
            );
        }
        if (!is_writable($directory)) {
            throw new InvalidArgumentException(
                sprintf('The directory "%s" is not writable.', $directory)
            );
        }
        if (!file_exists($index = $directory . DIRECTORY_SEPARATOR . 'index.php')) {
            touch($index);
        }

        // Everyone uses Apache :-) SRSLY, do not use web-accessible directory.
        if (!file_exists($htaccess = $directory . DIRECTORY_SEPARATOR . '.htaccess')) {
            $extension = $this::EXTENSION;
            $contents = <<<HTACCESS
<FilesMatch ".($extension)$">
    Order allow,deny
    Deny from all
</FilesMatch>
HTACCESS;
            file_put_contents($htaccess, $contents);
            chmod($htaccess, 0644);
        }

        $this->directory = realpath($directory);
        $this->serializer = $serializer ? $serializer : Factory::getSerializer(true, false);
        $this->serializer_class = get_class($this->serializer);

        // @codeCoverageIgnoreStart
        if ($autocleaning && rand(0, 99) == 0) {
            register_shutdown_function(array($this, 'clean'));
        }
        // @codeCoverageIgnoreEnd
    }

    /**
     * Clean unused items
     *
     * @param int $interval
     *     Do not perform cleaning if last clean operation was performed
     *     less than $interval seconds ago
     * @param int $min_unused
     *     Items that haven't been used in more than $min_unused
     *     seconds will be removed.
     * @return bool
     */
    public function clean($interval = 3600, $min_unused = 604800)
    {
        if (file_exists($cleanfile = $this->directory . DIRECTORY_SEPARATOR . 'lastclean')) {
            if (filemtime($cleanfile) >= time() - $interval) {
                return false;
            }
        }
        touch($cleanfile);
        $iterator = $this->getIterator();
        $iterator->rewind();
        while ($iterator->valid()) {
            $file = $iterator->key();
            if (fileatime($file) <= time() - $min_unused) {
                @unlink($file);
            }
            $iterator->next();
        }
        return true;
    }

    /********************************************************************************
     * \WebScale\Driver\AbstractDriver
     *******************************************************************************/

    /**
     * {@inheritdoc}
     */
    protected function doGet($key, &$found)
    {
        if (false === ($resource = @fopen($this->hashKey($key), 'r'))) {
            $found = false;
            return false;
        }

        $expires = (int) fgets($resource);

        // covered by doExists
        // @codeCoverageIgnoreStart
        if ($expires !== 0 && $expires < time()) {
            fclose($resource);
            $found = false;
            return null;
        }
        // @codeCoverageIgnoreEnd

        $data = '';
        while (false !== ($line = fgets($resource))) {
            $data .= $line;
        }
        fclose($resource);

        $found = true;
        return $this->serializer->unserialize($data);
    }

    /**
     * {@inheritdoc}
     */
    protected function doSet($key, $data, $ttl = null)
    {
        if (!is_dir($filepath = pathinfo($filename = $this->hashKey($key), PATHINFO_DIRNAME))) {
            if (true !== @mkdir($filepath, 0755, true)) {
            }
            touch($filepath . DIRECTORY_SEPARATOR . 'index.php');
            if (!file_exists($index = dirname($filepath) . DIRECTORY_SEPARATOR . 'index.php')) {
                touch($index);
            }
        }

        $expires = is_null($ttl) ? 0 : time() + $ttl;

        if (false !== file_put_contents(
            $tmpname = tempnam($filepath, basename($filename)),
            $expires . PHP_EOL . $this->serializer->serialize($data)
        )) {
            if (rename($tmpname, $filename)) {
                return true;
            }
        }
        return false;
    }

    /**
     * {@inheritdoc}
     */
    protected function doDelete($key)
    {
        @unlink($this->hashKey($key));
        return true;
    }

    /**
     * {@inheritdoc}
     */
    protected function doExists($key)
    {
        if (false === ($resource = @fopen($this->hashKey($key), 'r'))) {
            return false;
        }
        $expires = (int) fgets($resource);
        fclose($resource);
        if ($expires !== 0 && $expires < time()) {
            return false;
        }
        return true;
    }

    /********************************************************************************
     * \WebScale\Driver\DriverInterface
     *******************************************************************************/

    /**
     * {@inheritdoc}
     *
     * @codeCoverageIgnore
     */
    public static function isAvailable()
    {
        return true;
    }

    /********************************************************************************
     * Protected
     *******************************************************************************/

    protected function hashKey($key)
    {
        $key = hash('sha1', $key . $this->serializer_class);
        $path = substr($key, 0, 1) . DIRECTORY_SEPARATOR . substr($key, 1, 2) . DIRECTORY_SEPARATOR . substr($key, 3);
        return $this->directory . DIRECTORY_SEPARATOR . $path . $this::EXTENSION;
    }

    protected function getIterator()
    {
        $iterator = new RecursiveDirectoryIterator($this->directory);
        $iterator = new RecursiveIteratorIterator($iterator);
        return new RegexIterator($iterator, '/^.+\\' . $this::EXTENSION . '$/i');
    }
}


text:
package org.pantsbuild.contrib.findbugs;

public class NormalWarning {
  public static void main(String[] args) {
    String normal = null;
    System.out.printf("FindBugs Normal Warning NP_ALWAYS_NULL: %d", normal.length());
  }
}


text:
<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test.js"></script>
</head>
<body>
<script>
function makeOrphanShadow() {
    var host = document.createElement("div");
    var shadow = host.attachShadow({mode: 'open'});
    return shadow;
};

var shadow = makeOrphanShadow();
gc(true);

try { shadow.innerHTML = "Hello"; } catch(e) { }
shadow.appendChild(document.createElement("span"));

document.body.innerHTML = "PASS unless crash.";
</script>
</body>
</html>


text:
#ifndef _NTO_TDEP_H
#define _NTO_TDEP_H

#include "defs.h"
#include "solist.h"

/* Generic functions in nto-tdep.c.  */

extern void nto_init_solib_absolute_prefix (void);

char **nto_parse_redirection (char *start_argv[], char **in,
			      char **out, char **err);

int proc_iterate_over_mappings (int (*func) (int, CORE_ADDR));

void nto_relocate_section_addresses (struct so_list *, struct section_table *);

int nto_map_arch_to_cputype (const char *);

int nto_find_and_open_solib (char *, unsigned, char **);

/* Dummy function for initializing nto_target_ops on targets which do
   not define a particular regset.  */
void nto_dummy_supply_regset (char *regs);

/* Target operations defined for Neutrino targets (<target>-nto-tdep.c).  */

struct nto_target_ops
{
  int nto_internal_debugging;
  unsigned nto_cpuinfo_flags;
  int nto_cpuinfo_valid;

  int (*nto_regset_id) (int);
  void (*nto_supply_gregset) (char *);
  void (*nto_supply_fpregset) (char *);
  void (*nto_supply_altregset) (char *);
  void (*nto_supply_regset) (int, char *);
  int (*nto_register_area) (int, int, unsigned *);
  int (*nto_regset_fill) (int, char *);
  struct link_map_offsets *(*nto_fetch_link_map_offsets) (void);
};

extern struct nto_target_ops current_nto_target;

/* For 'maintenance debug nto-debug' command.  */
#define nto_internal_debugging \
	(current_nto_target.nto_internal_debugging)

/* The CPUINFO flags from the remote.  Currently used by
   i386 for fxsave but future proofing other hosts.
   This is initialized in procfs_attach or nto_start_remote
   depending on our host/target.  It would only be invalid
   if we were talking to an older pdebug which didn't support
   the cpuinfo message.  */
#define nto_cpuinfo_flags \
	(current_nto_target.nto_cpuinfo_flags)

/* True if successfully retrieved cpuinfo from remote.  */
#define nto_cpuinfo_valid \
	(current_nto_target.nto_cpuinfo_valid)

/* Given a register, return an id that represents the Neutrino
   regset it came from.  If reg == -1 update all regsets.  */
#define nto_regset_id(reg) \
	(*current_nto_target.nto_regset_id) (reg)

#define nto_supply_gregset(regs) \
	(*current_nto_target.nto_supply_gregset) (regs)

#define nto_supply_fpregset(regs) \
	(*current_nto_target.nto_supply_fpregset) (regs)

#define nto_supply_altregset(regs) \
	(*current_nto_target.nto_supply_altregset) (regs)

/* Given a regset, tell gdb about registers stored in data.  */
#define nto_supply_regset(regset, data) \
	(*current_nto_target.nto_supply_regset) (regset, data)

/* Given a register and regset, calculate the offset into the regset
   and stuff it into the last argument.  If regno is -1, calculate the
   size of the entire regset.  Returns length of data, -1 if unknown
   regset, 0 if unknown register.  */
#define nto_register_area(reg, regset, off) \
	(*current_nto_target.nto_register_area) (reg, regset, off)

/* Build the Neutrino register set info into the data buffer.
   Return -1 if unknown regset, 0 otherwise.  */
#define nto_regset_fill(regset, data) \
	(*current_nto_target.nto_regset_fill) (regset, data)

/* Gives the fetch_link_map_offsets function exposure outside of
   solib-svr4.c so that we can override relocate_section_addresses().  */
#define nto_fetch_link_map_offsets() \
	(*current_nto_target.nto_fetch_link_map_offsets) ()

/* Keep this consistant with neutrino syspage.h.  */
enum
{
  CPUTYPE_X86,
  CPUTYPE_PPC,
  CPUTYPE_MIPS,
  CPUTYPE_SPARE,
  CPUTYPE_ARM,
  CPUTYPE_SH,
  CPUTYPE_UNKNOWN
};

enum
{
  OSTYPE_QNX4,
  OSTYPE_NTO
};

/* These correspond to the DSMSG_* versions in dsmsgs.h. */
enum
{
  NTO_REG_GENERAL,
  NTO_REG_FLOAT,
  NTO_REG_SYSTEM,
  NTO_REG_ALT,
  NTO_REG_END
};

typedef char qnx_reg64[8];

typedef struct _debug_regs
{
  qnx_reg64 padding[1024];
} nto_regset_t;

#endif


text:
<ul id="__html_id__" class="bx-menu-main-submenu<bx_if:show_more_auto_class> bx-menu-more-auto</bx_if:show_more_auto_class> bx-menu-object-__object__ flex items-stretch">
    <bx_repeat:menu_items>

            __title____popup__

    </bx_repeat:menu_items>

__js_code__


text:
using System;
using System.Threading.Tasks;

namespace Pomelo.Net.Pomelium.Server.Client
{
    public interface IClient
    {
        bool IsLocal { get; }

        Guid SessionId { get; }

        Task<object> InvokeAsync(string method, object[] args);

        Task SendAsync(Packet packet);
    }
}


text:
(function() {
  module.exports.boothDeepAndShalow = function(strIn) {
    return "DEEP_TEST" + strIn;
  };

}).call(this);

//# sourceMappingURL=deepModule.js.map


text:
using std::unique_ptr;

namespace mozc {
namespace dictionary {
namespace {

const char kTextLines[] =
    "key_test1\t0\t0\t1\tvalue_test1\n"
    "foo\t1\t2\t3\tbar\n"
    "buz\t10\t20\t30\tfoobar\n";

const char kReadingCorrectionLines[] =
    "bar\tfoo\tfoo_correct\n"
    "foobar\tfoobar_error\tfoobar_correct\n";

}  // namespace

class TextDictionaryLoaderTest : public ::testing::Test {
 protected:
  // Explicitly define constructor to prevent Visual C++ from
  // considering this class as POD.
  TextDictionaryLoaderTest() {}

  virtual void SetUp() {
    pos_matcher_ = UserPosManager::GetUserPosManager()->GetPOSMatcher();
  }

  TextDictionaryLoader *CreateTextDictionaryLoader() {
    return new TextDictionaryLoader(*pos_matcher_);
  }

  const POSMatcher *pos_matcher_;
  scoped_data_manager_initializer_for_testing
      scoped_data_manager_initializer_for_testing_;
};

TEST_F(TextDictionaryLoaderTest, BasicTest) {
  {
    unique_ptr<TextDictionaryLoader> loader(CreateTextDictionaryLoader());
    vector<Token *> tokens;
    loader->CollectTokens(&tokens);
    EXPECT_TRUE(tokens.empty());
  }

  const string filename = FileUtil::JoinPath(FLAGS_test_tmpdir, "test.tsv");
  {
    OutputFileStream ofs(filename.c_str());
    ofs << kTextLines;
  }

  {
    unique_ptr<TextDictionaryLoader> loader(CreateTextDictionaryLoader());
    loader->Load(filename, "");
    const vector<Token *> &tokens = loader->tokens();

    EXPECT_EQ(3, tokens.size());

    EXPECT_EQ("key_test1", tokens[0]->key);
    EXPECT_EQ("value_test1", tokens[0]->value);
    EXPECT_EQ(0, tokens[0]->lid);
    EXPECT_EQ(0, tokens[0]->rid);
    EXPECT_EQ(1, tokens[0]->cost);

    EXPECT_EQ("foo", tokens[1]->key);
    EXPECT_EQ("bar", tokens[1]->value);
    EXPECT_EQ(1, tokens[1]->lid);
    EXPECT_EQ(2, tokens[1]->rid);
    EXPECT_EQ(3, tokens[1]->cost);

    EXPECT_EQ("buz", tokens[2]->key);
    EXPECT_EQ("foobar", tokens[2]->value);
    EXPECT_EQ(10, tokens[2]->lid);
    EXPECT_EQ(20, tokens[2]->rid);
    EXPECT_EQ(30, tokens[2]->cost);

    loader->Clear();
    EXPECT_TRUE(loader->tokens().empty());
  }

  {
    unique_ptr<TextDictionaryLoader> loader(CreateTextDictionaryLoader());
    loader->LoadWithLineLimit(filename, "", 2);
    const vector<Token *> &tokens = loader->tokens();

    EXPECT_EQ(2, tokens.size());

    EXPECT_EQ("key_test1", tokens[0]->key);
    EXPECT_EQ("value_test1", tokens[0]->value);
    EXPECT_EQ(0, tokens[0]->lid);
    EXPECT_EQ(0, tokens[0]->rid);
    EXPECT_EQ(1, tokens[0]->cost);

    EXPECT_EQ("foo", tokens[1]->key);
    EXPECT_EQ("bar", tokens[1]->value);
    EXPECT_EQ(1, tokens[1]->lid);
    EXPECT_EQ(2, tokens[1]->rid);
    EXPECT_EQ(3, tokens[1]->cost);

    loader->Clear();
    EXPECT_TRUE(loader->tokens().empty());
  }

  {
    unique_ptr<TextDictionaryLoader> loader(CreateTextDictionaryLoader());
    // open twice -- tokens are cleared everytime
    loader->Load(filename, "");
    loader->Load(filename, "");
    const vector<Token *> &tokens = loader->tokens();
    EXPECT_EQ(3, tokens.size());
  }

  FileUtil::Unlink(filename);
}

TEST_F(TextDictionaryLoaderTest, RewriteSpecialTokenTest) {
  unique_ptr<TextDictionaryLoader> loader(CreateTextDictionaryLoader());
  {
    Token token;
    token.lid = 100;
    token.rid = 200;
    EXPECT_TRUE(loader->RewriteSpecialToken(&token, ""));
    EXPECT_EQ(100, token.lid);
    EXPECT_EQ(200, token.rid);
    EXPECT_EQ(Token::NONE, token.attributes);
  }

  {
    Token token;
    token.lid = 100;
    token.rid = 200;
    EXPECT_TRUE(loader->RewriteSpecialToken(&token, "SPELLING_CORRECTION"));
    EXPECT_EQ(100, token.lid);
    EXPECT_EQ(200, token.rid);
    EXPECT_EQ(Token::SPELLING_CORRECTION, token.attributes);
  }

  {
    Token token;
    token.lid = 100;
    token.rid = 200;
    EXPECT_TRUE(loader->RewriteSpecialToken(&token, "ZIP_CODE"));
    EXPECT_EQ(pos_matcher_->GetZipcodeId(), token.lid);
    EXPECT_EQ(pos_matcher_->GetZipcodeId(), token.rid);
    EXPECT_EQ(Token::NONE, token.attributes);
  }

  {
    Token token;
    token.lid = 100;
    token.rid = 200;
    EXPECT_TRUE(loader->RewriteSpecialToken(&token, "ENGLISH:RATED"));
    EXPECT_EQ(pos_matcher_->GetIsolatedWordId(), token.lid);
    EXPECT_EQ(pos_matcher_->GetIsolatedWordId(), token.rid);
    EXPECT_EQ(Token::NONE, token.attributes);
  }

  {
    Token token;
    token.lid = 100;
    token.rid = 200;
    EXPECT_FALSE(loader->RewriteSpecialToken(&token, "foo"));
    EXPECT_EQ(100, token.lid);
    EXPECT_EQ(200, token.rid);
    EXPECT_EQ(Token::NONE, token.attributes);
  }
}

TEST_F(TextDictionaryLoaderTest, LoadMultipleFilesTest) {
  const string filename1 = FileUtil::JoinPath(FLAGS_test_tmpdir, "test1.tsv");
  const string filename2 = FileUtil::JoinPath(FLAGS_test_tmpdir, "test2.tsv");
  const string filename = filename1 + "," + filename2;

  {
    OutputFileStream ofs(filename1.c_str());
    ofs << kTextLines;
  }
  {
    OutputFileStream ofs(filename2.c_str());
    ofs << kTextLines;
  }

  {
    unique_ptr<TextDictionaryLoader> loader(CreateTextDictionaryLoader());
    loader->Load(filename, "");
    EXPECT_EQ(6, loader->tokens().size());
  }

  FileUtil::Unlink(filename1);
  FileUtil::Unlink(filename2);
}

TEST_F(TextDictionaryLoaderTest, ReadingCorrectionTest) {
  unique_ptr<TextDictionaryLoader> loader(CreateTextDictionaryLoader());

  const string dic_filename =
      FileUtil::JoinPath(FLAGS_test_tmpdir, "test.tsv");
  const string reading_correction_filename =
      FileUtil::JoinPath(FLAGS_test_tmpdir, "reading_correction.tsv");

  {
    OutputFileStream ofs(dic_filename.c_str());
    ofs << kTextLines;
  }
  {
    OutputFileStream ofs(reading_correction_filename.c_str());
    ofs << kReadingCorrectionLines;
  }

  loader->Load(dic_filename, reading_correction_filename);
  const vector<Token *> &tokens = loader->tokens();
  ASSERT_EQ(tokens.size(), 4);
  EXPECT_EQ("foobar_error", tokens[3]->key);
  EXPECT_EQ("foobar", tokens[3]->value);
  EXPECT_EQ(10, tokens[3]->lid);
  EXPECT_EQ(20, tokens[3]->rid);
  EXPECT_EQ(30 + 2302, tokens[3]->cost);
}

}  // namespace dictionary
}  // namespace mozc


text:
import { quote } from '../mappers';

export default function processName ( name ) {
	return name ? quote( name ) + ', ' : '';
}


text:
export * from './user'
export * from './list'
export * from './forms'
export * from './deletedBook'
//the export _ from 'PLACEHOLDER' syntax allows you to skip the import to here. leaving above import commented for self-education/reminder purposes. the _ could be a single exportable good from the PLACHOLDER file

export function receiveResults(results) {

  return {
    type: 'RECEIVE_RESULTS',
    results
  }
}


text:
title: 'Normal deep purple'
label: post-normal-deep-purple
categories: [style]
color:
  main:
    content: deep-purple
  drawer:
    background: deep-purple
---

# Elements

## Paragraphs

This is a short paragraph.

And this is a paragraph with way more words. I'll just type a few things. Well,
I don't know what to say. This is difficult. Almost finished with second line...
Yay! I did it! Let's see if I can get to the forth line. Almost here, I can feel
IT, yeah!!! I just drank some water. There is a reason why I took the first
chapters from Quixote to fill content. This is really hard. I've been writing
this for 6 minutes now. Maybe 3 more lines and I'll stop. I wonder if the
paragraph is long enough. It better be, I'm suffering with this situation. I'll
just finish talking about my commute. I take three trains to get to work and I
have to walk to the first. Normally it takes about an hour. Really weird people
in the morning train. When someone is really weird I usually talk about it on
Twitter.

## Notes

> This is a note, and I'll use it to link to my twitter:
[@ahaasler](https://twitter.com/ahaasler "Adrian Haasler on twitter").

Long note:

> Long note: Well, here we are again. This time I'll put less words. A few lines
will be enough. This time I'll talk about the commute back home. And yes, it is
three trains again. But it takes more times because they come less often.

## Tables

| A | B | C | D | E | F |
|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 |
| a | b | c | d | e | f |
| 6 | 5 | 4 | 3 | 2 | 1 |
| f | e | d | c | b | a |

## Headers

# Header 1
## Header 2
### Header 3
#### Header 4
##### Header 5
###### Header 6

## Lists

### Bullet list

- First
	- Inside the first
- Second
- Third

### Numeric list

1. First
	1. Little first
2. Second
3. Third

## Code blocks

```bash
echo "This is a code block"
# Yes it is
```

## Emphasis

This is how **bold text** looks. This would be *italic*. But don't be afraid to
***use both***.

## Horizontal line

---

It's above this text.


text:
#ifndef WINDOWLIBRARY_WINLIB_PLATFORM_WIN32GLCONTEXTIMPL_H
#define WINDOWLIBRARY_WINLIB_PLATFORM_WIN32GLCONTEXTIMPL_H

#include "windowlibrary/glcontext.h"

namespace WindowLibrary
{

struct GLContext::Impl
{
    GLContext      *_parent;
    GraphicsWindow *_window;
    ::HDC           _dc;
    ::HGLRC         _rc;

    Impl(
        GLContext *inParent,
        GraphicsWindow *inWindow);
    ~Impl();

    void
    createContext();

    void
    makeCurrent();

    void
    detachCurrent();

    void
    swapBuffers();

private:
    void
    destroyContext();

    void
    do_make_current(
        ::HGLRC inRenderContext);
};

} // namespace WindowLibrary

#endif // WINDOWLIBRARY_WINLIB_PLATFORM_WIN32GLCONTEXTIMPL_H


text:
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	// A fully qualified URL to the Intern proxy
	proxyUrl: 'http://localhost:9000/',

	// Default desired capabilities for all environments. Individual capabilities can be overridden by any of the
	// specified browser environments in the `environments` array below as well. See
	// https://code.google.com/p/selenium/wiki/DesiredCapabilities for standard Selenium capabilities and
	// https://saucelabs.com/docs/additional-config#desired-capabilities for Sauce Labs capabilities.
	// Note that the `build` capability will be filled in with the current commit ID from the Travis CI environment
	// automatically
	capabilities: {
		'selenium-version': '2.41.0'
	},

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 3,

	// Name of the tunnel class to use for WebDriver tests
	tunnel: 'SauceLabsTunnel',

	// The desired AMD loader to use when running unit tests (client.html/client.js). Omit to use the default Dojo
	// loader
	useLoader: {
		'host-node': 'dojo/dojo',
		'host-browser': 'node_modules/dojo/dojo.js'
	},

	// Non-functional test suite(s) to run in each browser
	suites: [
		'tests/server/wifi-tool'
	],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation: /^(?:tests|client\/src\/bower_components|node_modules)\//
});


text:
Topics are my oppionions about the past, present and future of
client-side JavaScript. And also a gentle introduction and overview to
[AngularJS](http://angularjs.org).

#License

Slides are based on [Reveal.js](http://lab.hakim.se/reveal-js/). Those
parts are on their own license. All my content is under a creative
commons like license. Do what you want with it, but I'd appreciate if
you attribute me where appropriate.


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
N. Amer. Polyp. (Oslo), Vol. 2 Megasporoporia - Wrightoporia 704 (1987)

#### Original name
Poria apacheriensis Gilb. & Canf., 1973

### Remarks
null


text:
package io.opensec.oval.core.xml.windows;

import io.opensec.oval.model.windows.AuditEnumeration;

import org.exolab.castor.mapping.GeneralizedFieldHandler;

/**
 *
 * @author Akihito Nakamura (nakamura5akihito@gmail.com)
 */
public class AuditEnumerationHandler
    extends GeneralizedFieldHandler
{

    public AuditEnumerationHandler()
    {
        super();
    }

    @Override
    public Object convertUponGet(
                    final Object value
                    )
    {
        if (value == null) {
            return null;
        }
        AuditEnumeration  e = AuditEnumeration.class.cast( value );
        return e.value();
    }

    @Override
    public Object convertUponSet(
                    final Object value
                    )
    {
        if (value == null) {
            return null;
        }
        return AuditEnumeration.fromValue( value.toString() );
    }

    @Override
    public Class<AuditEnumeration> getFieldType()
    {
        return AuditEnumeration.class;
    }

//    public Object newInstance(
//                    final Object parent
//                    )
//    throws IllegalStateException
//    {
//        //-- Since it's marked as a string...just return null,
//        //-- it's not needed.
//        return null;
//    }

}
// FileTypeEnumerationHandler


text:
@interface NBPhoneMetadataFR : NBPhoneMetaData
{
}

- (id)init;

@end


text:
package com.eeontheway.android.applocker.push;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 个推服务
 * @author lishutong
 * @version v1.0
 * @Time 2016-12-15
 */
public class GetTuiPush implements IPush {
    private static final String appId = "DIB5qDDshd8SnmEUcDGaU";
    private static final String appkey = "6a8QobLFBg75RSzDoAaBp3";
    private static final String MASTERSECRET = "GWUoVVG4Ub6EoFAxpiRTk1";

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void pushMsg(PushInfo info, String clientId) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("action", "pushmessage"); // pushmessage为接口名,注意全部小写
                /*---以下代码用于设定接口相应参数---*/
        param.put("appkey", appkey);
        param.put("appid", appId);
        // 注:透传内容后面需用来验证接口调用是否成功,假定填写为hello girl~
        param.put("data", info.toString());

        Date curDate = new Date(System.currentTimeMillis());
        param.put("time", formatter.format(curDate)); // 当前请求时间,可选
        param.put("clientid", clientId); // 您获取的ClientID
        param.put("expire", 3600); // 消息超时时间,单位为秒,可选

        // 生成Sign值,用于鉴权
        param.put("sign", GetuiSdkHttpPost.makeSign(MASTERSECRET, param));

        GetuiSdkHttpPost.httpPost(param);
    }
}


text:
"""Manages logging (to stdout) for our versioning system.
"""
import logging

log=logging.getLogger('migrate.versioning')
log.setLevel(logging.WARNING)
log.addHandler(logging.StreamHandler())

__all__=['log','logging']


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Nigeria In Nigeria it has been decided to both put the country in a complete lockdown including curfew during the night. This is despite the relatively low amount of new cases, but as it has been seen it other countries things can go wrong extremely fast.
Nigeria differs from Kenya as every state has their own responsibility for handling the outbreaks, which means that there is less national control as it is seen in the US."><meta property="og:title" content="Timeline Nigeria" />
<meta property="og:description" content="Nigeria In Nigeria it has been decided to both put the country in a complete lockdown including curfew during the night. This is despite the relatively low amount of new cases, but as it has been seen it other countries things can go wrong extremely fast.
Nigeria differs from Kenya as every state has their own responsibility for handling the outbreaks, which means that there is less national control as it is seen in the US." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://covid19.compute.dtu.dk/posts/timeline_nigeria/" />
<meta property="article:modified_time" content="2020-07-01T14:45:34+07:00" />
<title>Timeline Nigeria | COVID-19 mobility</title>
<link rel="icon" href="/favicon.png" type="image/x-icon">

<link rel="stylesheet" href="/book.min.8b34b0846c7c6544613b2301559d146e1ddebf7ee7068ccc53d2fd0e9b3701b9.css" integrity="sha256-izSwhGx8ZURhOyMBVZ0Ubh3ev37nBozMU9L9Dps3Abk=">

  <input type="checkbox" class="hidden" id="menu-control" />

  COVID-19 mobility

Main Page

Posts

Kenya
Timeline

Kenya:

Data quality

Kenya:

Where are people?

Kenya:

How people move

Nigeria
Timeline

Nigeria:

Data quality

Nigeria:

Where are people?

Nigeria:

How people move

Visualizations

Where people are

Going out

Change in population size

Population distribution

How people move

New Particle city movement

New Tile city movement

Staying home

Movements between municipalities

Data

Population Density Maps

Movement Maps

  Timeline Nigeria

Nigeria

In Nigeria it has been decided to both put the country in a complete lockdown including curfew during the night. This is despite the relatively low amount of new cases, but as it has been seen it other countries things can go wrong extremely fast.

Nigeria differs from Kenya as every state has their own responsibility for handling the outbreaks, which means that there is less national control as it is seen in the US. This means that there is no exact date, where the entire country closed down as in Kenya and Denmark, but in this timeline an estimate of the nationwide events is provided.


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

namespace LNF.Helpdesk
{
    public class TicketMessage
    {
        public int MsgID { get; set; }
        public string Created { get; set; }
        public string Message { get; set; }
        public string Source { get; set; }
        public string IPAddress { get; set; }
        public int Attachments { get; set; }
    }
}


text:
@implementation ZYVideoAdRegistry

+ (ZYVideoAdRegistry *)sharedRegistry {
    static ZYVideoAdRegistry *registry = nil;
    if (registry == nil) {
        registry = [[ZYVideoAdRegistry alloc] init];
    }
    return registry;
}

- (id)init
{
    self = [super init];
    if (self) {
        self.adapterDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)registerClass:(Class)adapterClass and:(ZYVideoType)type {
    // have to do all these to avoid compiler warnings...
    NSString *key = [NSString stringWithFormat:@"%d",type];
    ZYVideoClassWrapper *wapper = [[ZYVideoClassWrapper alloc] initWithClass:adapterClass];
    [self.adapterDict setObject:wapper forKey:key];
}

- (void)unregisterClassFor:(NSInteger)adNetworkType
{
    [self.adapterDict removeObjectForKey:[NSNumber numberWithInteger:adNetworkType]];
}

- (NSDictionary*)getClassesDict
{
    return self.adapterDict;
}

@end


text:
using System.Reflection;

namespace ReadSharp.Ports.NReadability
{
  public static class Consts
  {
    private static readonly string _nReadabilityFullName;

    #region Constructor(s)

    static Consts()
    {
      _nReadabilityFullName = string.Format("NReadability {0}", typeof(Consts).GetTypeInfo().Assembly.FullName);
    }

    #endregion

    #region Properties

    public static string NReadabilityFullName
    {
      get { return _nReadabilityFullName; }
    }

    #endregion

  }
}


text:
(This article has been posted in Sharetribe blog)

# Just enough Git for a non-developer

At Sharetribe almost everyone is somehow dealing with the code. That's the spirit of a small tech startup. We use Git and Github for source code management.

This article was meant to be an internal document for our non-developers who have to small code changes every now and then, namely our designer and analytics expert. However, as this stuff might interest others, I decided to make the article in a form of a blog post.

The best way to learn is by doing. That's why this tutorial contains also an interactive part. The tutorial can be found here https://github.com/sharetribe/just-enough-git. Feel free to make your own fork.

## Prerequisite

The article concentrates on branching. I expect that you already have the basic knowledge of Git, that is:

* You know how to access and use command-line
* You have git installed
* You have a Github account
* You know how to `git clone` a repository
* You know how to view current `git status`
* You know how to `git add` changes to next commit and how to `git commit` them
* You know how to `git push` the commits to Github
* You know how to `git pull` others' commits from Github
* You know what is a code branch, although you may not be familiar with them

That said, you already know quite a lot! However, to be efficient with Git, there are still a couple tricks you need to learn.

## The branching model

At Sharetribe, we use a simple and minimalistic branching model, which goes like this:

1. **Branch:** When you start working with a new feature/bug fix/document improvement/anything, you create a new branch.
1. **Pull Request:** As soon as possible, even before the feature is ready, push the branch to Github and create a Pull Request, so that others can see what you are up to.
1. **Rebase:** Make sure, that your branch is up to date. If not, rebase.
1. **Review:** When the feature is ready, ask a fellow teammate for a review. Fix the issues the reviewer found, if any
1. **Merge:** When the reviewer gives green light, merge the Pull Request to master.

![Branching model](diagrams/branchmodel.png)

A rule of thumb is that you should **never brake the master branch**. Master branch goes always to production.

## Learning goals

In order to follow that branching model, you need to learn a couple new Git skills:

* Your git is properly configured
* You know how to create a branch
* You know how to jump from branch to another
* You know how to push the branch to Github
* You know how to update (rebase) your branch to include newest changes by others
* You know how to resolve merge conflicts

## Git configurations

In order to work efficiently with the branching model, you need to have following git configurations set. Open command-line and type:

```
git config --global push.default current
git config --global branch.autosetuprebase always
```

Now you're ready to start.

# Let the tutorial begin

### 1. Copying the repository

We want a separate copy of the repository, as it is extremely rare to work with forks at Sharetribe. Therefore, we'll create a completely separate repository for the purposes of this tutorial.

Navigate to https://github.com/new in order to create a new repository.

Make sure it's your account selected as owner, enter just-enough-git as the repository name, leave the repository as public and leave the README initialization checkbox unchecked.

Now you can click `Create repository`.

Now, let's clone the original repository to your local machine, switch the remote to your version of the repository and push the contents there.

Usually, you don't need to deal with the remotes, but this makes the rest of the tutorial easier.

On command-line, type:

```
git clone git@github.com:sharetribe/just-enough-git.git
cd just-enough-git
git remote rm origin
git remote add origin git@github.com:<your-username>/just-enough-git.git
git push -u origin master
ls
```

You should now see the content of the repository. There are not that many files, but the one we are interested in is the `index.html` file. Open it in your browser to view the content.

### 2. Let's add description!

Now let's add a description to our website! Do you still remember the branching model? The first thing to do is **Branch**. So, let's create a new branch.

First, type:

```
git status
```

From the first line, you see that you are currently on `master` branch.

`git checkout` is a command to jumps from branch to another. If you give it an option -b, it will create a new branch. Let's try this. Type:

```
git checkout -b add-description
git status
```

Congrats! You created a branch. `git status` shows you that you are currently in the newly created `add-description` branch.

Let's make a change to `index.html`. You can see that there's an empty paragraph with class `description`. Add a description, so that the result is:

```
<p class="description">This is how you branch like a rockstar!</p>
```

Next, save the file and use `git add`, `git commit` and `git push` to save and push your changes.

```
git add index.html
git commit
git push
```

Now, go to the Github repository. You can see that Github is suggesting you to create a new Pull request.

Hit the **Compare and create a pull request**, add title and description to the Pull request and create it.

The repository currently looks like this:

![1](diagrams/1.png)

Now, go to Github to your pull request and click **Merge pull request**. Now you branch got merged to master. The repository looks like this:

![2](diagrams/2.png)

Your changes has now been merged to master, so you don't need your branch anymore. On the pull request page, click **Delete branch**.

Now back to command-line. Jump back to master branch.

```
git checkout master
```

If you now take a look at `index.html` you can see that your latest changes are not there yet. That's because locally your `add-description` branch and `master` are still separated. We only did the merge on Github. Thus, you need to pull the newest changes from Github.

```
git pull
```

Now you can see your changes in place.

Let's recap what we've learned so far:

* `git checkout -b [branchname]` creates a new branch
* `git checkout [branchname]` jumps to another branch
* In Github, you know how to create a pull request from your branch and how to merge it

From the five step branching model, you already master 3 steps: **Branch**, **Pull request** and **Merge**. Next we learn how to **Rebase**.

### Updating your branch

While you are working in your own branch, others might be pushing their changes to master branch. It's important to update your branch to include these changes. That way you avoid having a huge merge hell after working one week in isolation with your own branch.

Let's create two new branches, `edit-description` and `edit-title` from the master branch:

```
git checkout -b edit-description
```

Go and edit the `index.html` file, so that the description block looks like following:

```html
<p class="description">This is how you rebase like a rockstar!</p>
```

When your ready, save the file and push the changes to Github.

```
git add index.html
git commit
git push
```

Go to Github and make a new pull request, but do not merge it this time.

Now back to the command-line. At the moment you are in `edit-description` branch. Jump back to master:

```bash
git checkout master
```

Now create the other branch:

```bash
git checkout -b edit-title
```

Edit the `index.html` so that the title is now:

```html
<h1>Welcome to interactive Git and Github tutorial</h1>
```

Again, save and push the changes to Github.

```
git add index.html
git commit
git push
```

Go to Github and make a new Pull request, but do not merge it.

Let's recap what we just did: We created two branches, `edit-description` and `edit-title`. We did Pull request for both of them. The repository currently looks like this:

![3](diagrams/3.png)

Now go to Github and merge the `edit-title` pull request.

On command-line, go to master and pull the changes

```
git chechkout master
git pull
```

Now the repository looks like this:

![4](diagrams/4.png)

As you can see from the diagram, the `edit-description` branch is lagging behind. There are new changes in master that are not included in `edit-description` branch. It's time to rebase.

Rebasing means that we change the "base" of the branch. Let's try it in practice.

Go to the branch that you want to update:

```bash
git checkout edit-description
```

Rebase it on top of the master branch:

```bash
git rebase master
```

Now the repository looks like this:

![5](diagrams/5.png)

The `edit-description` has now a new base. It has been placed on top of the latest changes on the master branch. Open the `index.html` file. You can see that the title includes now `and Github`, the change that was made in the `edit-title` branch.

Push the updated branch to Github. This time we have to force push the branch, because its history has changed:

```
git push --force
```

**WARNING!** The main purpose of Git is to make sure you never lose any changed you've made. It's damn difficult to screw up things with Git so badly, that someone would lose his day's work. However, `--force` is the only command in Git which allows you to make catastrophical screw ups. So, be careful. Make sure you are in a correct branch when you force push. **NEVER force push on master branch.** **NEVER FORCE PUSH ON MASTER BRANCH**.

**WARNING #2!** You ONLY need to force push after rebase. **Never force push, unless you have just rebased**.

Let's recap:

* We have now learned how to `git rebase` your branch to include latest changes from master
* We learned how to `git push --force` changes after rebase
* We learned that with great `--force` comes a great responsibility.

### Resolving conflicts

Git is pretty good at merging branches together. However, if two people edit the same part of the same file at the same time, Git doesn't know how to handle it. In this case, you have to manually resolve the conflict.

Let's try this out.

Remember that you have now an unmerged branch `edit-description`, which changed the description paragraph in `index.html`. Create yet another branch in which we edit the description paragraph too.

```bash
git checkout -b resolve-like-rockstar
```

Edit the `index.html` file, so that the description is following:

```html
<p class="description">This is how you resolve conflicts like a rockstar!</p>
```

When your ready, push the changes to Github.

```
git add index.html
git commit
git push
```

Go to Github and make a new Pull request and merge it immediately.

Now go to master and pull changes.

```
git checkout master
git pull
```

Your repository looks now like this:

![5.5](diagrams/55.png)

Yet again, we see that there's one branch, `edit-description`, that is lagging behing. Let's rebase it:

```bash
git checkout edit-description
git rebase master
```

Whou! That did not go smoothly. Git is saying that there's a conflict in `index.html` file:

```
CONFLICT (content): Merge conflict in index.html
```

You can also see this with status command, type:

```bash
git status
```

Which prints:

```

...

Unmerged paths:
  (use "git reset HEAD <file>..." to unstage)
  (use "git add <file>..." to mark resolution)

    both modified:   index.html

no changes added to commit (use "git add" and/or "git commit -a")
```

Open the `index.html` file in your editor and you will see this:

```html
<<<<<<< HEAD
<p class="description">This is how you resolve conflicts like a rockstar!</p>
=======
<p class="description">This is how you rebase like a rockstar!</p>
>>>>>>> [your commit message]
```

Edit the file so that it include both changes and remove lines starting with `<<<<<<<`, `=======` and `>>>>>>>` so that the end result is:

```html
<p class="description">This is how you rebase and resolve conflicts like a rockstar!</p>
```

Save the file. Now that you've resolved the conflict, you have to mark the file as resolved. Do it with `git add`:

```bash
git add index.html
```

Do this for every file that has conflicts.

After you have resolved all the conflicts, `git status` should not show you any `Unmerged paths`:

```bash
git status
```

Now that we are done, we can continue:

```bash
git rebase --continue
```

Git moves to the next commit. You may have to resolve any additional conflicts.

If anything goes wrong during the rebase, you can always enter `git rebase --abort`. It will cancel the whole rebase process.

Now it's time to be extra careful again, and force push our changes.

```bash
git push --force
```

And that's it! You just resolved a merge conflict. `edit-description` is now ready to be merged to master. Your repository looks now like this:

![6](diagrams/6.png)

### Final recap

You have now learned all the necessary steps: Branch, Pull request, Rebase, Review (just ask someone to take a look at your code) and Merge.

Here's a list of commands you need when working with branches:

* `git checkout [branchname]`: Jump from a branch to another
* `git checkout -b [branchname]`: Create a new branch
* `git rebase master`: Rebase your branch on top of master branch
* `git add [filename]`: Mark conflicted file as resolved
* `git rebase --continue`: Continue rebasing after resolving conflicts
* `git rebase --abort`: Abort rebasing

With these commands, you should be able to work with the development team and git!


text:
require 'spec_helper'
require 'whois/record/parser/whois.tcinet.ru.rb'

describe Whois::Record::Parser::WhoisTcinetRu, "status_registered.expected" do

  subject do
    file = fixture("responses", "whois.tcinet.ru/su/status_registered.txt")
    part = Whois::Record::Part.new(body: File.read(file))
    described_class.new(part)
  end

  describe "#domain" do
    it do
      expect(subject.domain).to eq("google.su")
    end
  end
  describe "#domain_id" do
    it do
      expect { subject.domain_id }.to raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#status" do
    it do
      expect(subject.status).to eq(["REGISTERED", "DELEGATED", "UNVERIFIED"])
    end
  end
  describe "#available?" do
    it do
      expect(subject.available?).to eq(false)
    end
  end
  describe "#registered?" do
    it do
      expect(subject.registered?).to eq(true)
    end
  end
  describe "#created_on" do
    it do
      expect(subject.created_on).to be_a(Time)
      expect(subject.created_on).to eq(Time.parse("2005-10-16"))
    end
  end
  describe "#updated_on" do
    it do
      expect { subject.updated_on }.to raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#expires_on" do
    it do
      expect(subject.expires_on).to be_a(Time)
      expect(subject.expires_on).to eq(Time.parse("2010-10-16"))
    end
  end
  describe "#registrar" do
    it do
      expect(subject.registrar).to be_a(Whois::Record::Registrar)
      expect(subject.registrar.id).to eq("RUCENTER-REG-FID")
      expect(subject.registrar.name).to eq(nil)
      expect(subject.registrar.organization).to eq(nil)
    end
  end
  describe "#registrant_contacts" do
    it do
      expect { subject.registrant_contacts }.to raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#admin_contacts" do
    it do
      expect(subject.admin_contacts).to be_a(Array)
      expect(subject.admin_contacts).to have(1).items
      expect(subject.admin_contacts[0]).to be_a(Whois::Record::Contact)
      expect(subject.admin_contacts[0].type).to eq(Whois::Record::Contact::TYPE_ADMINISTRATIVE)
      expect(subject.admin_contacts[0].id).to eq(nil)
      expect(subject.admin_contacts[0].name).to eq("Private Person")
      expect(subject.admin_contacts[0].phone).to eq("+7 495 9681807")
      expect(subject.admin_contacts[0].fax).to eq("+7 495 9681807")
      expect(subject.admin_contacts[0].email).to eq("cis@cis.su")
    end
  end
  describe "#technical_contacts" do
    it do
      expect { subject.technical_contacts }.to raise_error(Whois::AttributeNotSupported)
    end
  end
  describe "#nameservers" do
    it do
      expect(subject.nameservers).to be_a(Array)
      expect(subject.nameservers).to have(2).items
      expect(subject.nameservers[0]).to be_a(Whois::Record::Nameserver)
      expect(subject.nameservers[0].name).to eq("ns1073.hostgator.com")
      expect(subject.nameservers[1]).to be_a(Whois::Record::Nameserver)
      expect(subject.nameservers[1].name).to eq("ns1074.hostgator.com")
    end
  end
end


text:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var app = express();
module.exports = app;

var index = require('./routes/index');
var api = require('./routes/api/api');

app.use(express.static(path.join(__dirname,'client/dist/')));
app.use(bodyParser.json());

app.get('/', index.get);
app.get('/api/list', api.list.getList);
app.post('/api/item', api.item.addItem);

function start(){
    var port = process.env.PORT || 8080;

    app.listen(port, function(){
        console.log('grocery_totes is running on port: ' + port);
    });
};

app.start = start;


text:
package gov.samhsa.consent2share.web.controller;

import gov.samhsa.consent2share.common.AuthenticatedUser;
import gov.samhsa.consent2share.common.UserContext;
import gov.samhsa.consent2share.service.dto.ValueSetCategoryDto;
import gov.samhsa.consent2share.service.dto.ValueSetDto;
import gov.samhsa.consent2share.service.dto.ValueSetVSCDto;
import gov.samhsa.consent2share.service.valueset.InvalidCSVException;
import gov.samhsa.consent2share.service.valueset.ValueSetCategoryNotFoundException;
import gov.samhsa.consent2share.service.valueset.ValueSetCategoryService;
import gov.samhsa.consent2share.service.valueset.ValueSetNotFoundException;
import gov.samhsa.consent2share.service.valueset.ValueSetService;
import gov.samhsa.consent2share.web.AjaxException;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * The Class ValueSetController.
 */
@Controller
@SessionAttributes("valueSet")
@RequestMapping("/sysadmin")
public class ValueSetController extends AbstractNodeController {

	/** The Constant LOGGER. */
	private static final Logger LOGGER = LoggerFactory
			.getLogger(ValueSetController.class);

	/** The Constant ERROR_MESSAGE_KEY_DELETED_VALUESET_WAS_NOT_FOUND. */
	protected static final String ERROR_MESSAGE_KEY_DELETED_VALUESET_WAS_NOT_FOUND = "Deleted valueSet was not found.";

	/** The Constant ERROR_MESSAGE_KEY_EDITED_VALUESET_WAS_NOT_FOUND. */
	protected static final String ERROR_MESSAGE_KEY_EDITED_VALUESET_WAS_NOT_FOUND = "Edited valueSet was not found.";

	/** The Constant ERROR_MESSAGE_VALUSETCATEGORIES_NOT_FOUND. */
	protected static final String ERROR_MESSAGE_VALUSETCATEGORIES_NOT_FOUND = "Value Set Categories not Found. To create and manage Value Sets, you need to add Value Set Categories.";

	protected static final String ERROR_MESSAGE_DUPLICATE_VALUESET = "Cannot insert duplicate value sets.";

	/** The Constant MODEL_ATTIRUTE_VALUESETDTO. */

	protected static final String MODEL_ATTIRUTE_VALUESETDTO = "valueSetDto";

	/** The Constant MODEL_ATTIRUTE_VALUESETVCSDTO. */
	protected static final String MODEL_ATTIRUTE_VALUESETVCSDTO = "valueSetVCSDto";

	/** The Constant MODEL_ATTRIBUTE_VALUESETDTOS. */
	protected static final String MODEL_ATTRIBUTE_VALUESETDTOS = "valueSetDtos";

	/** The Constant MODEL_ATTRIBUTE_VALUESETCATEGORYDTOS. */
	protected static final String MODEL_ATTRIBUTE_VALUESETCATEGORYDTOS = "valueSetCategoryDtos";

	/** The Constant VALUESET_ADD_FORM_VIEW. */
	protected static final String VALUESET_ADD_FORM_VIEW = "views/sysadmin/valueSetAdd";

	/** The Constant VALUESET_EDIT_FORM_VIEW. */
	protected static final String VALUESET_EDIT_FORM_VIEW = "views/sysadmin/valueSetEdit";

	/** The Constant VALUESET_LIST_VIEW. */
	protected static final String VALUESET_LIST_VIEW = "views/sysadmin/valueSetList";

	/** The Constant REQUEST_MAPPING_LIST. */
	protected static final String REQUEST_MAPPING_LIST = "/valueSetList";

	/** The Constant REDIRECT_MAPPING_LIST. */
	protected static final String REDIRECT_MAPPING_LIST = "../valueSetList";

	/** The Constant REDIRECT_ID_MAPPING_LIST. */
	protected static final String REDIRECT_ID_MAPPING_LIST = "../../valueSetList";

	/** The value set service. */
	@Resource
	private ValueSetService valueSetService;

	/** The value set category service. */
	@Resource
	private ValueSetCategoryService valueSetCategoryService;

	/** The user context. */
	@Autowired
	UserContext userContext;

	/**
	 * Batch upload.
	 *
	 * @param request the request
	 * @param file the file
	 * @param redirectAttribute the redirect attribute
	 * @return the string
	 * @throws Exception the exception
	 */
	@RequestMapping(value = "/valueSet/batchUpload", method = RequestMethod.POST)
	public String batchUpload(HttpServletRequest request, @RequestParam("batch_file") MultipartFile file,
			RedirectAttributes redirectAttribute) throws Exception {
		AuthenticatedUser currentUser = userContext.getCurrentUser();
		ValueSetDto valueSetDto = new ValueSetDto();
		valueSetDto.setUserName(currentUser.getUsername());

		try {

			valueSetDto = valueSetService.valueSetBatchUpload(valueSetDto, file);
			valueSetDto.setSuccessMessage("Added " + valueSetDto.getRowsUpdated() + " Value Sets");

		} catch (ValueSetNotFoundException ex) {
			LOGGER.debug("Invalid value set category found while doing batch upload: " + ex.getMessage());
			valueSetDto.setError(true);
		} catch (InvalidCSVException ex) {
			LOGGER.debug("Invalid csv format found while doing batch upload: " + ex.getMessage());
			valueSetDto.setError(true);
		} catch (DataIntegrityViolationException ex) {
			LOGGER.debug("Duplicate value set while doing batch upload: " + ex.getMessage());
			valueSetDto.setError(true);
		}
		redirectAttribute.addFlashAttribute(MODEL_ATTIRUTE_VALUESETDTO, valueSetDto);
		return "redirect:../valueSetList.html";
	}

	/**
	 * Processes delete valueSet requests.
	 *
	 * @param id The id of the deleted valueSet.
	 * @param redirectAttribute the redirect attribute
	 * @return the string
	 */
	@RequestMapping(value = "/valueSet/delete/{id}", method = RequestMethod.DELETE)
	public @ResponseBody String delete(@PathVariable("id") Long id,
			RedirectAttributes redirectAttribute) {
		LOGGER.debug("Deleting valueSet with id: " + id);
		ValueSetDto deleted = new ValueSetDto();
		try {
			deleted = valueSetService.delete(id);
			deleted.setError(false);
			deleted.setSuccessMessage("ValueSet with Code: "
					+ deleted.getCode() + " and Name: " + deleted.getName()
					+ " is deleted Successfully.");
		} catch (ValueSetNotFoundException e) {
			LOGGER.debug(e.getMessage());
			deleted.setError(true);
			deleted.setErrorMessage(e.getMessage());
			throw new AjaxException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());

		}

		redirectAttribute.addFlashAttribute(MODEL_ATTIRUTE_VALUESETDTO, deleted);

		if(deleted.isError == false){
			return deleted.getSuccessMessage();
		}else{
			throw new AjaxException(HttpStatus.INTERNAL_SERVER_ERROR, deleted.getErrorMessage());
		}
	}

	@RequestMapping("/valueSet/ajaxGetPagedValueSets/pageNumber/{pageNumber}")
	@ResponseStatus(HttpStatus.OK)
	public @ResponseBody Map<String, Object> getAllConceptCodes(@PathVariable("pageNumber") String pageNumber) {
		Map<String, Object> valueSetsMap = null;

		valueSetsMap = valueSetService.findAll(Integer.parseInt(pageNumber));

		return valueSetsMap;
	}

	/**
	 * Search value set.
	 *
	 * @param searchCategory the search category
	 * @param searchTerm the search term
	 * @return the list
	 */
	@RequestMapping("/valueSet/ajaxSearchValueSet/pageNumber/{pageNumber}/searchCategory/{searchCategory}/searchTerm/{searchTerm}/valueSetCategory/{valueSetCategory}")
	@ResponseStatus(HttpStatus.OK)
	public @ResponseBody Map<String, Object> searchValueSet(
			@PathVariable("searchCategory") String searchCategory,
			@PathVariable("searchTerm") String searchTerm,
			@PathVariable("valueSetCategory") String valueSetCategory,
			@PathVariable("pageNumber") String pageNumber) {

		valueSetCategory = validateEmptyFilterParams(valueSetCategory);
		searchTerm = validateEmptyFilterParams(searchTerm);

		Map<String, Object> valueSetsPagedMap = null;

		try{
			if(searchCategory.equals("code"))
				valueSetsPagedMap = valueSetService.findAllByCode(searchTerm, valueSetCategory, Integer.parseInt(pageNumber));
			else  if(searchCategory.equals("name"))
				valueSetsPagedMap = valueSetService.findAllByName(searchTerm, valueSetCategory, Integer.parseInt(pageNumber));
		}catch(IllegalArgumentException e){
			valueSetsPagedMap = null;
			throw new AjaxException(HttpStatus.BAD_REQUEST, "Unable to perform search because the request parameters contained invalid data.");
		}

		return valueSetsPagedMap;
	}

	/**
	 * This setter method should only be used by unit tests.
	 *
	 * @param valueSetService the new value set service
	 */
	protected void setValueSetService(ValueSetService valueSetService) {
		this.valueSetService = valueSetService;
	}

	/**
	 * Processes create valueSet requests.
	 *
	 * @param model the model
	 * @param request the request
	 * @return The name of the create valueSet form view.
	 */
	@RequestMapping(value = REQUEST_MAPPING_LIST, method = RequestMethod.GET)
	public String showCreateValueSetForm(Model model,
			@RequestParam(value = "panelState", required = false, defaultValue = "") String panelState) {

		LOGGER.debug("Rendering Value Set  list page");

		Map<String, Object> valueSetsPagedMap = valueSetService.findAll(0);
		List<ValueSetCategoryDto> valueSetCategories = valueSetCategoryService.findAll();

		if(panelState.equals("resetoptions")){
			model.addAttribute("panelState", "resetoptions");
		}else if(panelState.equals("addnew")){
			model.addAttribute("panelState", "addnew");
		}

		model.addAttribute(MODEL_ATTRIBUTE_VALUESETCATEGORYDTOS, valueSetCategories);
		model.addAttribute("valueSetsPagedMap", valueSetsPagedMap);
		return VALUESET_LIST_VIEW;
	}

	/**
	 * Processes edit valueSet requests.
	 *
	 * @param id The id of the edited valueSet.
	 * @param model the model
	 * @param attributes the attributes
	 * @return The name of the edit valueSet form view.
	 */
	@RequestMapping(value = "/valueSet/edit/{id}", method = RequestMethod.GET)
	public String showEditValueSetForm(@PathVariable("id") Long id,
			Model model, RedirectAttributes attributes) {
		LOGGER.debug("Rendering edit valueSet form for valueSet with id: " + id);
		ValueSetDto valueSetDto =  new ValueSetDto();
		try {
			valueSetDto = valueSetService.findById(id);
			if (valueSetDto == null) {
				LOGGER.debug("No valueSet found with id: " + id);
				valueSetDto = new ValueSetDto();
				valueSetDto.setError(true);
				valueSetDto
				.setErrorMessage(ERROR_MESSAGE_KEY_EDITED_VALUESET_WAS_NOT_FOUND);
				return createRedirectViewPath(REDIRECT_ID_MAPPING_LIST);
			}
		} catch (ValueSetCategoryNotFoundException e) {
			LOGGER.debug(e.getMessage());
			valueSetDto.setError(true);
			valueSetDto.setErrorMessage(e.getMessage());
		}

		model.addAttribute(MODEL_ATTIRUTE_VALUESETDTO, valueSetDto);

		return VALUESET_EDIT_FORM_VIEW;
	}

	/**
	 * Processes the submissions of create valueSet form.
	 *
	 * @param created The information of the created valueSets.
	 * @param redirectAttribute the redirect attribute
	 * @param model the model
	 * @return the string
	 */
	@RequestMapping(value = "/valueSet/create", method = RequestMethod.POST)
	public String submitCreateValueSetForm(
			@Valid @ModelAttribute(MODEL_ATTIRUTE_VALUESETDTO) ValueSetDto created,
			RedirectAttributes redirectAttribute, Model model) {
		LOGGER.debug("Create valueSet form was submitted with information: "
				+ created);

		AuthenticatedUser currentUser = userContext.getCurrentUser();
		String notification = "";
		ValueSetDto valueSetDto;
		String path = "../valueSetAdd.html";
		try {
			created.setUserName(currentUser.getUsername());
			valueSetDto = valueSetService.create(created);
			created.setError(false);
			created.setSuccessMessage("Value Set   with code:"
					+ valueSetDto.getCode() + " and Name: "
					+ valueSetDto.getName() + " is Added Successfully");
			path = REDIRECT_MAPPING_LIST;
		} catch (DataIntegrityViolationException ex) {
			LOGGER.info(ex.getLocalizedMessage());
			Throwable t = ex.getCause();
			String message = null;
			if (t != null) {
				message = "Cause: " + t.getMessage();
			}
			created.setError(true);
			created.setErrorMessage("Value Set  is not Added " + message);
		} catch (ValueSetCategoryNotFoundException e) {
			LOGGER.debug("No value set category found with id: "
					+ created.getValueSetCategoryId());
			created.setError(true);
			created.setErrorMessage(ERROR_MESSAGE_VALUSETCATEGORIES_NOT_FOUND);
		}
		model.addAttribute(MODEL_ATTIRUTE_VALUESETDTO, created);
		redirectAttribute
		.addFlashAttribute(MODEL_ATTIRUTE_VALUESETDTO, created);
		model.addAttribute("notification", notification);

		String panelState = "?panelState=addnew";

		return createRedirectViewPath(path) + panelState;
	}

	/**
	 * Processes the submissions of edit valueSet form.
	 *
	 * @param updated The information of the edited valueSet.
	 * @param id the id
	 * @return the string
	 */
	@RequestMapping(value = "/valueSet/edit/{id}", method = RequestMethod.POST)
	public String submitEditValueSetForm(
			@ModelAttribute(MODEL_ATTIRUTE_VALUESETDTO) ValueSetDto updated,
			RedirectAttributes attributes,
			@PathVariable("id") Long id) {
		LOGGER.debug("Edit valueSet form was submitted with information: "
				+ updated + id);

		try {
			AuthenticatedUser currentUser = userContext.getCurrentUser();
			updated.setUserName(currentUser.getUsername());
			updated.setId(id);
			updated = valueSetService.update(updated);
			updated.setError(false);
			updated.setSuccessMessage("Value Set   with Code: "
					+ updated.getCode() + " and Name: " + updated.getName()
					+ " is Edited Successfully");

		} catch (ValueSetNotFoundException e) {
			LOGGER.debug("No valueSet was found with id: " + updated.getId());
			updated.setError(true);
			updated.setErrorMessage("Edited Value Set is not found");
		} catch (ValueSetCategoryNotFoundException e) {
			LOGGER.debug(e.getMessage());
			updated.setError(true);
			updated.setErrorMessage(e.getMessage());
		}

		attributes
		.addFlashAttribute(MODEL_ATTIRUTE_VALUESETDTO, updated);

		return createRedirectViewPath(REDIRECT_ID_MAPPING_LIST);
	}

	/**
	 * Validate empty filter params.
	 *
	 * @param param the param
	 * @return the string
	 */
	private String validateEmptyFilterParams(String param) {
		return param.replace("empty", "");
	}

	/**
	 * Processes the submissions of create valueSet form.
	 *
	 * @param model the model
	 * @param request the request
	 * @return the string
	 */
	@RequestMapping(value = "valueSetAdd.html", method = RequestMethod.GET)
	public String valueSetAddForm(Model model, HttpServletRequest request) {
		LOGGER.debug("Rendering Value Set  Add Form ");
		String returnPage = VALUESET_ADD_FORM_VIEW;
		ValueSetVSCDto valueSetVSCDto = new ValueSetVSCDto();
		ValueSetDto valueSetDto = new ValueSetDto();

		try {
			valueSetVSCDto = valueSetService.create();
			valueSetDto = (ValueSetDto) model.asMap().get(
					MODEL_ATTIRUTE_VALUESETDTO);
			if (valueSetDto != null)
				valueSetVSCDto.setValueSetDto(valueSetDto);

		} catch (ValueSetCategoryNotFoundException e) {
			LOGGER.debug("No value sets found in the system");
			valueSetDto.setError(true);
			valueSetDto
			.setErrorMessage(ERROR_MESSAGE_VALUSETCATEGORIES_NOT_FOUND);
			returnPage = VALUESET_LIST_VIEW;
		}

		model.addAttribute(MODEL_ATTIRUTE_VALUESETDTO,
				(valueSetDto == null) ? new ValueSetDto() : valueSetDto);
		model.addAttribute(MODEL_ATTIRUTE_VALUESETVCSDTO, valueSetVSCDto);
		return returnPage;
	}

}


text:
package org.apache.wicket.feedback;

/**
 * Interface for components that present some kind of feedback to the user, normally based on the
 * feedback messages attached to various components on a given page.
 *
 * This is tells Wicket that a component's {@link Component#beforeRender()} must be called after all non
 * feedback components have been initialized.
 *
 * @author Jonathan Locke
 * @author Eelco Hillenius
 */
public interface IFeedback
{
	void beforeRender();
}


text:
<!--
  ~ Copyright (c) 2019 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<role xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
      xmlns:apti="http://midpoint.evolveum.com/xml/ns/public/common/api-types-3"
      xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
      xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"
      xmlns:org="http://midpoint.evolveum.com/xml/ns/public/common/org-3"
      xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
      xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"
      xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      oid="c89f31dd-8d4f-4e0a-82cb-58ff9d8c1b2f">
    <name>role-ldap-basic</name>
    <inducement id="1">
        <construction>
            <resourceRef oid="0a37121f-d515-4a23-9b6d-554c5ef61272" relation="org:default" type="c:ResourceType" />     <!-- LDAP -->
        </construction>
        <order>1</order>
    </inducement>
</role>


text:
package com.milkshakeapps.milkshake.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.milkshakeapps.milkshake.R;

public class WelcomeActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        findViewById(R.id.signupButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
                intent.putExtra("isLoginMode", false);
                startActivity(intent);
            }
        });
        findViewById(R.id.loginButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
                intent.putExtra("isLoginMode", true);
                startActivity(intent);
            }
        });
    }
}


text:
define(
    ['./objectlib'],
    function(objectlib) {
      function bind(instance) {
        var binder = instance || {};
        var handlers = [];

        binder.on = binder.bind = function (type, fn) {
          var filter, handler;

          filter = typeof(type) === "string" ? {type: type} : type;
          handler = objectlib.extend({fn: fn}, filter);
          handlers.push(handler);

          return binder;
        };

        binder.off = binder.unbind = function (type, fn) {
          var filter;

          filter = typeof(type) === "string" ? {type: type} : type;
          filter = fn === undefined ? filter : objectlib.extend({fn: fn}, filter);
          remove(handlers, filter);

          return binder;
        };

        binder.trigger = function (type, params, summary) {
          var j, count = 0, len,
              args = [{type: type}],
              filter = typeof(type) === "string" ? {type: type} : type,
              matches = find(handlers, filter),
              wildcards = find(handlers, {type: '*'}),
              items = [].concat(matches).concat(wildcards);

          // normalize args
          if (typeof params !== 'undefined' && params !== null) {
            if (typeof params === 'string' || typeof params === 'number') {
              args.push(params);
            } else if ('length' in params) { // array
              Array.prototype.push.apply(args, params);
            }
          }

          // callback all
          for (j = 0, len = items.length; j < len; j++) {
            count++;
            ret = items[j].fn.apply(this, args);
            if (ret === false) {
              break;
            }
          }
          summary && $.isFunction(summary) && summary(count);

          return binder;
        };

        return binder;
      }

      // -------------------------------------------
      //                 Utilities
      // -------------------------------------------
      function match(entry, filters) {
        var result = false,
            matchAll, matchSome,
            key;

        if (typeof filters !== 'function') {
          matchAll = true;
          matchSome = false;
          for (key in filters) {
            if (typeof entry === 'undefined') {
              // problematic
              matchAll = false;
              break;
            } else if (filters[key] !== entry[key]) {
              matchAll = false;
              break;
            }
            matchSome = true; // make sure filter is non-empty
          }
          result = matchSome && matchAll;
        } else {
          result = filters(entry);
        }
        return result;
      }

      function find(array, filters) {
        var result = [];
        for (var i=0, len=array.length; i<len; i++) {
          var item = array[i];
          if (match(item, filters)) {
            result.push(item);
          }
        }
        return result;
      }

      function remove(array, filter) {
        var result = [];
        for (var i=(array.length - 1); i>=0; i--) {
          var item = array[i];
          if (Matches.match(item, filter)) {
            result.push(item);
            array.splice(i, 1);
          }
        }
        return result.reverse();
      }

      return {
        bind: bind
      }
    }
);


text:
angular.module("cathacklic")

.factory("ExamineService", [function() {
  var _server = null;

  var _open_server = function() {
    var deferred = new Promise(function(resolve, reject) {
      if (_server) {
        resolve(_server);
      } else {
        db.open({
          server: 'Examinations',
          version: 2,
          schema: {
            DailyExamines: {
              key: {
                keyPath: 'id',
                autoIncrement: true
              },
              indexes: {
                start: {},
                type: {},
                date: {}
              }
            }
          }
        }).then(function(s) {
          _server = s;
          resolve(s);
        }, function(err) {
          reject(err);
        });
      }
    });
    return deferred;
  };

  var ExamineService = {
    NewExamination: function(examineType) {
      if (typeof examineType == "undefined") {
        return null;
      }
      var now = new Date();
      return {
        start: now,
        start_time: now.toLocaleTimeString(),
        date: now.toLocaleDateString(),
        type: examineType
      };
    },

    SaveExamination: function(examine) {
      return new Promise(function(resolve, reject) {
        _open_server().then(function(server) {
          examine.end = new Date();
          examine.end_time = examine.end.toLocaleTimeString();
          server.DailyExamines.add(examine).then(function(data) {
            resolve(data);
          }, function(err) {
            reject(err);
          });
        }, function(server_err) {
          reject(server_err);
        });
      });
    },

    RemoveItem: function(id) {
      return _server.DailyExamines.remove(id);
    },

    ListExaminations: function() {
      return new Promise(function(resolve, reject) {
        _open_server().then(function(server) {
          server.DailyExamines.query().filter().execute().then(function(data) {
            resolve(data);
          }, function(err) {
            reject(err);
          });
        }, function(server_err) {
          reject(server_err);
        });
      });
    },

    GetExamination: function(id) {
      return new Promise(function(resolve, reject) {
        _open_server().then(function(server) {
          console.log("Obtainted Server!");
          server.DailyExamines.query().filter("id", parseInt(id)).execute().then(function(data) {
            console.log("fetched data", data);
            resolve(data);
          }, function(err) {
            alert("Error!");
            reject(err);
          });
        }, function(server_err) {
          alert("Server Error!");
          reject(server_err);
        });
      });
    },

    CountExainations: function() {
      return _server.DailyExamines.count();
    },

    ClearData: function() {
      return _server.DailyExamines.clear();
    }
  };
  return ExamineService;
}]);


text:
<?php

namespace Sociable\View;

class RawDecorator extends Decorator {
    public function render($content, $print = true) {
        ob_start();
        echo $content;
        $output = ob_get_contents();
        ob_end_clean();

        if ($print)
            echo $output;
        return $output;
    }

}


text:
rest-template
=============

This is an example project showing Restful Interface.

Goal of this project is to implement a basic Restful Interface (HATEOAS) which can be used as templates for other projects.
It creates a modular structure using best practices using technolgies:

* JAX-RS: Restful Service
* Guice: DI Framework
* slf4j: Logging
* hibernate: JPA Provider


text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.WindowsAzure.Mobile.Service;
using Microsoft.WindowsAzure.Mobile.Service.ScheduledJobs;
using XamarinCRM.Models;
using XamarinCRMv2DataService.DataAccess;

namespace XamarinCRMv2DataService
{
    /// <summary>
    /// Reresh the dates on the orders. Via the Azure dashboard for the service, add a new scheduled job called RefreshOrders. The scheduler will link to the RefreshOrdersJob class by convention ([Your]Job).
    /// </summary>
    public class RefreshOrdersJob : ScheduledJob
    {
        private MobileServiceContext _MobileServiceContext;

        protected override void Initialize(ScheduledJobDescriptor scheduledJobDescriptor, CancellationToken cancellationToken)
        {
            base.Initialize(scheduledJobDescriptor, cancellationToken);

            _MobileServiceContext = new MobileServiceContext();
        }

        public async override Task ExecuteAsync()
        {
            try
            {
                var orderList = _MobileServiceContext.Orders as IList<Order> ?? _MobileServiceContext.Orders.ToList();

                var oldestUpdatedOrder = orderList.OrderBy(o => o.UpdatedAt).FirstOrDefault();

                if (oldestUpdatedOrder?.UpdatedAt != null)
                {
                    DateTime lastUpdatedDate = oldestUpdatedOrder.UpdatedAt.Value.UtcDateTime;

                    int daysSinceUpdate = (DateTime.UtcNow - lastUpdatedDate).Days;

                    foreach (var o in orderList)
                    {
                        o.OrderDate = o.OrderDate.AddDays(daysSinceUpdate);
                        o.DueDate = o.DueDate.AddDays(daysSinceUpdate);
                        o.ClosedDate = o.ClosedDate?.AddDays(daysSinceUpdate);

                        _MobileServiceContext.Entry(o).State = EntityState.Modified;

                        await _MobileServiceContext.SaveChangesAsync();
                    }

                    Services.Log.Info($"Orders successfully refreshed. Total orders: {orderList.Count}");
                    await Task.FromResult(true);
                }
                else
                {
                    Services.Log.Warn("None of the orders seem to have an UpdatedAt value. This may mean there's no orders at all in the database.");
                    await Task.FromResult(false);
                }
            }
            catch (Exception ex)
            {
                Services.Log.Error($"Orders failed to refresh refresh: {ex.Message}");
                throw;
            }
        }
    }
}


text:
package org.openkilda.wfm.topology.utils;

import org.openkilda.persistence.context.PersistenceContextRequired;

import org.apache.storm.Config;
import org.apache.storm.Constants;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * A base class for Bolts interested in doing TickTuples.
 */
public abstract class AbstractTickRichBolt extends BaseRichBolt {

    private static final Logger logger = LoggerFactory.getLogger(AbstractTickRichBolt.class);
    protected OutputCollector outputCollector;
    private Integer emitFrequency;

    public AbstractTickRichBolt() {
        emitFrequency = 1; // every second
    }

    public AbstractTickRichBolt(Integer frequency) {
        emitFrequency = frequency;
    }

    /*
     * Configure frequency of tick tuples for this bolt. This delivers a 'tick' tuple on a specific
     * interval, which is used to trigger certain actions
     */
    @Override
    public Map<String, Object> getComponentConfiguration() {
        Config conf = new Config();
        conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, emitFrequency);
        return conf;
    }

    protected boolean isTickTuple(Tuple tuple) {
        return (tuple.getSourceComponent().equals(Constants.SYSTEM_COMPONENT_ID)
                && tuple.getSourceStreamId().equals(Constants.SYSTEM_TICK_STREAM_ID));
    }

    @Override
    public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
        outputCollector = collector;
    }

    //execute is called to process tuples
    @Override
    @PersistenceContextRequired(requiresNew = true)
    public void execute(Tuple tuple) {
        //If it's a tick tuple, emit all words and counts
        if (isTickTuple(tuple)) {
            doTick(tuple);
        } else {
            doWork(tuple);
        }
    }

    protected abstract void doTick(Tuple tuple);

    protected abstract void doWork(Tuple tuple);

}


text:
require 'spec_helper'
require 'helpers/xml'

describe "Nessus Version 1: Scan" do
  include Helpers

  before(:all) do
    @xml = Nessus::Version1::XML.new(Helpers::DOT_NESSUS_V1)
  end

  it "should parse the scan title" do
    @xml.title.should == 'Ruby-Nessus Example Policy'
  end

  it "should parse the scan time" do
    @xml.time.to_s.should == '2009-11-08T02:21:22+00:00'
  end

  it "should parse the scan policy title" do
    @xml.policy_title.should == 'Ruby-Nessus Example Policy'
  end

  it "should parse the scan policy notes" do
    @xml.policy_notes.should == "This is an example .nessus file for testing the Ruby-Nessus gem."
  end

  it "should parse the scan start time" do
    @xml.start_time.to_s.should == '2009-11-08T02:21:23+00:00'
  end

  it "should parse the scan stop time" do
    @xml.stop_time.to_s.should == '2009-11-08T02:31:29+00:00'
  end

  it "should parse the scan runtime" do
    @xml.runtime.should == '0 hours 10 minutes and 6 seconds'
  end

  it "should parse the scan total host count" do
    @xml.host_count.should == 1
  end

  it "should calculate the percentage of low severity events" do
    @xml.event_percentage_for("low", true).should == "86"
  end

  it "should calculate the low severity event total" do
    @xml.low_severity_count.should == 19
  end

  it "should calculate the percentage of medium severity events" do
    @xml.event_percentage_for("medium", true).should == "14"
  end

  it "should calculate the medium severity event total" do
    @xml.medium_severity_count.should == 3
  end

  it "should calculate the percentage of high severity events" do
    @xml.event_percentage_for("high", true).should == "0"
  end

  it "should calculate the high severity event total" do
    @xml.high_severity_count.should == 0
  end

  it "should calculate the total for all severity events" do
    @xml.total_event_count.should == 22
  end

end


text:
/**
 * Created by seodonghyeon on 6/3/15.
 */

function showComment(page) {

    // Loading 0.5 seconds
    setTimeout(function() {

        $('#reply').load(
            contextPath + "/comment/list/"+boardId,
            {
                p:page
            }
        )
    }, 500);
}

function toggleWrite() {
    $('#write').toggle()
    $('#write_btn').toggle()
}

function toggleReply(id) {

    $('#'+id+'_reply').toggle()
    $('#'+id+'_reply').load(contextPath + "/comment/reply/"+id)
}

function updateComment(id) {

    $('#'+id).load(contextPath + "/comment/update/"+id)
}

function deleteComment(id) {

    $.ajax({
        type: "POST",
        url: contextPath + "/comment/delete",
        data: {
            commentId:id
        },
        success: function (data) {
            if (data === "404" || data === "400")
                alert("An error occurred while deleting the comment.");
            else {
                alert("Deleting the comment was successful.");

                // Reload reply
                showComment(1);
            }
        }
    });
}

function ajaxForm() {

    $("#comment_ajaxForm").unbind('submit').bind('submit',function(e) {
        if (isWriting == false) {
            isWriting = true;

            if ($("#content").val() == "") {
                $("#comment_write_warn").addClass("has-error");
                $("#content").focus();

                alert("Please input content for writing.");
                isWriting = false;
                e.preventDefault(); //STOP default action
                return;
            }

            var postData = $(this).serializeArray();
            var formURL = $(this).attr("action");

            $.ajax({
                type: "POST",
                url: formURL,
                data: postData,
                success: function (data) {
                    $("#comment_write_warn").removeClass("has-error")
                    alert("Writing the comment was successful.");

                    // Reload reply
                    showComment(1);

                    // Reset content
                    $("#content").val("");

                    // Reset
                    isWriting = false;
                },
                statusCode: {
                    400: function() {
                        alert("An error occurred while writing the comment.");
                    },
                    404: function() {
                        alert("An error occurred while writing the comment.");
                    },
                    500: function() {
                        alert("An error occurred while writing the comment.");
                    }
                }
            });
            e.preventDefault(); //STOP default action
        };
    });
    $("#comment_ajaxForm").submit();
}

function ajaxForm_reply(id) {

    $("#" + id + "_ajaxForm_reply").unbind('submit').bind('submit',function(e) {
        if (isReplying == false) {
            isReplying = true;

            if ($("#" + id + "_content_reply").val() == "") {
                $("#comment_reply_warn").addClass("has-error");
                $("#" + id + "_content_reply").focus();
                alert("Please input content for replying.");
                isReplying = false;
                e.preventDefault(); //STOP default action
                return;
            }

            var postData = $(this).serializeArray();
            var formURL = $(this).attr("action");

            $.ajax({
                type: "POST",
                url: formURL,
                data: postData,
                success: function (data) {
                    $("#comment_reply_warn").removeClass("has-error")
                    alert("Replying the comment was successful.");

                    // Reload reply
                    showComment(1);

                    // Reset content
                    $("#" + id + "_content_reply").val("");

                    // Reset
                    isReplying = false;
                },
                statusCode: {
                    400: function() {
                        alert("An error occurred while replying the comment.");
                    },
                    404: function() {
                        alert("An error occurred while replying the comment.");
                    },
                    500: function() {
                        alert("An error occurred while replying the comment.");
                    }
                }
            });
            e.preventDefault(); //STOP default action
        };
    });
    $("#" + id + "_ajaxForm_reply").submit();
}

function ajaxForm_update(id) {

    $("#" + id + "_ajaxForm_update").unbind('submit').bind('submit',function(e) {
        if (isUpdating == false) {
            isUpdating = true;

            if ($("#" + id + "_content_update").val() == "") {
                $("#comment_update_warn").addClass("has-error");
                $("#" + id + "_content_update").focus();
                alert("Please input content for updating.");
                isUpdating = false;
                e.preventDefault(); //STOP default action
                return;
            }

            var postData = $(this).serializeArray();
            var formURL = $(this).attr("action");

            $.ajax({
                type: "POST",
                url: formURL,
                data: postData,
                success: function (data) {
                    $("#comment_update_warn").removeClass("has-error")
                    alert("Updating the comment was successful.");

                    // Reload reply
                    $("#" + id + "_content_update").val("");

                    // Reset content
                    showComment(1);

                    // Reset
                    isUpdating = false;
                },
                statusCode: {
                    400: function () {
                        alert("An error occurred while updating the comment.");
                    },
                    404: function () {
                        alert("An error occurred while updating the comment.");
                    },
                    500: function () {
                        alert("An error occurred while updating the comment.");
                    }
                }
            });
            e.preventDefault(); //STOP default action
        };
    });
    $("#" + id + "_ajaxForm_update").submit();
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: calibration.proto

package edu.kit.ipd.crowdcontrol.workerservice.proto;

public interface CalibrationOrBuilder extends
    // @@protoc_insertion_point(interface_extends:crowdcontrol.Calibration)
    com.google.protobuf.MessageOrBuilder {

  /**
   * optional int32 answer_option = 1;
   */
  int getAnswerOption();
}