text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
            new Symfony\Bundle\DoctrineFixturesBundle\DoctrineFixturesBundle(),
            new PizzaNight\IntranetBundle\PizzaNightIntranetBundle(),
            new PizzaNight\ManagementBundle\PizzaNightManagementBundle(),
            new PizzaNight\WebServiceBundle\PizzaNightWebServiceBundle(),
            new PizzaNight\AsistenteBundle\PizzaNightAsistenteBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'manager_dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
package org.apache.beam.sdk.extensions.sql;

import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.extensions.sql.impl.BeamSqlEnv;
import org.apache.beam.sdk.extensions.sql.impl.rel.BeamRelNode;
import org.apache.beam.sdk.extensions.sql.meta.store.MetaStore;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.sql.SqlExecutableStatement;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.parser.SqlParseException;
import org.apache.calcite.tools.RelConversionException;
import org.apache.calcite.tools.ValidationException;

/** {@link BeamSqlCli} provides methods to execute Beam SQL with an interactive client. */
@Experimental
public class BeamSqlCli {
  private BeamSqlEnv env;
  /** The store which persists all the table meta data. */
  private MetaStore metaStore;

  public BeamSqlCli metaStore(MetaStore metaStore) {
    this.metaStore = metaStore;
    this.env = new BeamSqlEnv(metaStore);

    return this;
  }

  public MetaStore getMetaStore() {
    return metaStore;
  }

  /** Returns a human readable representation of the query execution plan. */
  public String explainQuery(String sqlString)
      throws ValidationException, RelConversionException, SqlParseException {
    BeamRelNode exeTree = env.getPlanner().convertToBeamRel(sqlString);
    String beamPlan = RelOptUtil.toString(exeTree);
    return beamPlan;
  }

  /** Executes the given sql. */
  public void execute(String sqlString)
      throws ValidationException, RelConversionException, SqlParseException {
    SqlNode sqlNode = env.getPlanner().parse(sqlString);

    // DDL nodes are SqlExecutableStatement
    if (sqlNode instanceof SqlExecutableStatement) {
      ((SqlExecutableStatement) sqlNode).execute(env.getContext());
    } else {
      PipelineOptions options =
          PipelineOptionsFactory.fromArgs(new String[] {})
              .withValidation()
              .as(PipelineOptions.class);
      options.setJobName("BeamPlanCreator");
      Pipeline pipeline = Pipeline.create(options);
      env.getPlanner().compileBeamPipeline(sqlString, pipeline);
      pipeline.run();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Andyskl.Data.Templates.Factories
{
    public interface IFactory<out T>
    {
        T Get();
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>libtcod documentation | System layer</title>

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

libtcoddocumentation

you are here: Index > 3. System layer

2. Console | 4. Line drawing toolkit

<input type="checkbox" id="chk_c" name="chk_c" onchange="enable('c',this.checked)" checked='checked' > C   <input type="checkbox" id="chk_cpp" name="chk_cpp" onchange="enable('cpp',this.checked)" checked='checked' > C++   <input type="checkbox" id="chk_cs" name="chk_cs" onchange="enable('cs',this.checked)" checked='checked' > C#   <input type="checkbox" id="chk_py" name="chk_py" onchange="enable('py',this.checked)" checked='checked' > Py   <input type="checkbox" id="chk_lua" name="chk_lua" onchange="enable('lua',this.checked)" checked='checked' > Lua

3. System layer

3.1. High precision time functions

3.2. Easy screenshots

3.3. Filesystem utilities

3.4. Draw custom graphics on top of the root console

3.5. Miscellaneous utilities

3.6. Clipboard integration

This toolkit contains some system specific miscellaneous utilities. Use them is you want your code to be easily portable.

libtcod 1.5.1, © 2008, 2009, 2010, 2012 Jice & Mingos

	This file has been generated by doctcod.

libtcod website
	libtcod on Roguecentral forums
  libtcod HOWTO video tutorials


text:
*This blog post originally appeared on David Broman's blog on 11/4/2009*

Profiler attach is a feature that allows you to attach a profiler to an already running process. The usefulness of this is fairly obvious to anyone who's ever attached a debugger to a running-process: It's helpful when diagnosing hard-to-reproduce problems, and particularly useful when encountering issues in production.

Please note!  You can't just take any profiler you bought and suddenly be able to attach it to a running application.  The profiler must be built with "attachability" in mind.  So if you're a profiler developer looking to pump some attachability into your product, read on--this article is for you.  Everyone else, this article will probably be less useful--but just as riveting.

#

# The Players

So how do you get your profiler attached to a running process?  The process has already started, and the CLR code which interrogates the environment to determine whether to load a profiler has already run.  So how do you kick the process into loading your profiler?  The answer: Another process!

![](media/Attach.jpg)

In order to force your profiler DLL to load into the target profilee process, you'll need to create a "trigger" process to send the attach message to the target profilee.  Many profilers already ship with a GUI shell to control launching processes to profile.  That shell will typically act as your trigger process as well.

# Inside the Trigger Process

Your trigger uses a simple API method, AttachProfiler, to request the target process to load your profiler.  Where is this method defined?  Well, it doesn't make much sense to put it on ICorProfilerInfo, since that interface is only available to a profiler after it's been loaded.  You could imagine a C export from mscoree.dll.  But because of in-process side-by-side CLR instances, we're moving away from mscoree.dll exports to a COM-based interface model called "metahost".

## Meta-whos-its?

Whereas the "hosting" interfaces enable one to host and manage a CLR in a process, the "metahost" interfaces allow one to manage multiple CLRs that may be installed onto a machine or loaded into a single process.  Here's a high-level view of how you navigate your way through metahost to find AttachProfiler() (there's a pointer to actual sample code below).

- Get ICLRMetaHost
- Enumerate the CLRs loaded into the target process
- Get ICLRRuntimeInfo for the particular CLR in the target process you want to profile
- Get the corresponding ICLRProfiling
- Call ICLRProfiling::AttachProfiler

## Users and Integrity

The permissions required to attach a profiler are similar to those required to attach a debugger.  First, the trigger process must run as the same user as the target profilee OR as an administrator.  Second, on OS's that support process integrity levels, the trigger process must be running at an integrity level higher than or equal to that of the target profilee process.  For more information about integrity and mandatory labels, [here's](http://msdn.microsoft.com/en-us/library/bb625964.aspx) some reference from MSDN.

## Sample Trigger Source Code

For some sample code to attach a profiler to a process, take a look at the sample uploaded to the MSDN Code Gallery [here](http://code.msdn.microsoft.com/ProfilerAttacher/).

You'll notice the code attempts to enable the SE\_DEBUG\_NAME privilege, as this is required to open a process running as another user with PROCESS\_ALL\_ACCESS.  Again, cross-user attach (i.e., trigger runs as a different user than the target profilee process) is only supported when the trigger is run as an administrator.  Otherwise, only same-user attach is supported, and would not need to enable the SE\_DEBUG\_NAME privilege.

# Inside the Profilee Process

Once your trigger has called AttachProfiler(), a message is sent to the target profilee process to load your actual profiler DLL, containing info such as your profiler's GUID.  At this point, it's business as usual in the profilee.  The profilee locates and loads your profiler DLL, the CLR then calls your class factory object to create an instance of your profiler's ICorProfilerCallback implementation.

Note that, instead of the CLR calling your Initialize() method, the CLR will call your ICorProfilerCallback3::InitializeForAttach() method.  There are two reasons for this difference.  First, this ensures that only profilers that have been upgraded to work with CLR V4 and opt into attaching will actually be attached.  All other profilers can simply return an error from their InitializeForAttach() method (or won't have an ICorProfilerCallback3 implementation to begin with).

The second reason is that InitializeForAttach allows for some extra data to be passed from the trigger to your profilee via a blob of binary data.  What's that for?  Many profiler products pass configuration information from their shell to their startup-loaded profiler DLL via environment variables.  After all, the shell has to set COR\_PROFILER & COR\_ENABLE\_PROFILING in the environment anyway, so why not set some more values there to be read by their profiler?  This scheme doesn't work for an attaching profiler, since the shell cannot affect the environment of the already-running profilee.  Instead, the AttachProfiler API allows the caller to specify a pointer to a buffer containing whatever data the caller wishes.  The CLR makes a copy of the data, sends it to the profilee, and then passes a pointer to this data to the profiler DLL via InitializeForAttach.

The management of the memory containing this binary data follows the usual COM rules.  In the trigger process, your trigger code allocates memory for the blob, passes it to AttachProfiler (which will make its own copy of the data), and then your trigger code frees it once AttachProfiler returns.  Stack allocation is perfect here; your trigger could just push your own custom structure of data onto the stack and pass a pointer to it in your call to AttachProfiler.  Inside the profilee process, your profiler gets access to the blob of data from its InitializeForAttach method.  Inside InitializeForAttach, your profiler accesses that memory.  If your profiler will need to use that memory later on, your profiler should make a copy of the memory now.  After InitializeForAttach returns, the CLR will free the memory.

From your InitializeForAttach implementation, your profiler will call SetEventMask as usual to announce your intentions, and you're off to the races.

# Limitations

It was impossible to enable all profiling scenarios for attach in the time we had for the V4 release.  So only profilers that do **sampling** and **memory** analysis will function properly after attaching to a live process.  Attempts to use other profiling APIs after attach will be met with CORPROF\_E\_UNSUPPORTED\_FOR\_ATTACHING\_PROFILER.

###

## Specific Callback Limitations

When your attaching profiler calls SetEventMask, you will be limited to only those event mask flags present in the COR\_PRF\_ALLOWABLE\_AFTER\_ATTACH bitmask (you'll find it in corprof.idl).  Any other flags, and SetEventMask will return CORPROF\_E\_UNSUPPORTED\_FOR\_ATTACHING\_PROFILER.

## Specific Info Limitations

Most of the ICorProfilerInfo\* methods are available to your attaching profiler, however some are not--particularly those involved in **IL rewriting**.  Here's a list of all ICorProfilerInfo\* methods NOT supported for attaching profilers:

- GetILFunctionBody
- GetILFunctionBodyAllocator
- SetILFunctionBody
- SetILInstrumentedCodeMap
- SetEnterLeaveFunctionHooks\*
- SetFunctionIDMapper\*
- GetNotifiedExceptionClauseInfo
- All methods related to Enter/Leave/Tailcall

It's expected that future releases of the CLR will enable more API methods for use by attaching profilers.

## GC Limitations

### GC Modes

To understand limitations around the GC modes, here's a quick review of the GC modes an app can run under:

- **Workstation Blocking mode**.  The thread that triggered the GC performs the GC while all other threads executing managed code must wait.
- **Workstation Concurrent / Background mode (the default)**.  Concurrent GC (V1 & V2) allows portions of a full GC to execute while other threads are allowed to run.  Background GC (its replacement in V4) takes it one step further, and also allows an ephemeral GC (i.e., gen 0 or gen 1) to execute while a gen 2 GC is executing.
- **Server mode**.  Hosts like ASP.NET may choose to enable server mode which creates a heap + dedicated GC thread per CPU.  This allows GCs to be fanned out to multiple threads.

Of course, [Maoni's blog](http://blogs.msdn.com/maoni/) is required reading for anyone who wants to understand how the GC works.

The profiling API is able to work against workstation blocking mode and server mode, but not concurrent / background mode.  This has been the case in V1 & V2, and remains the case in V4.  When the app starts up, if a profiler is configured to load, then the CLR forcibly turns off concurrent / background mode, and you end up in workstation blocking mode (or you end up in server mode if the host requested that instead).  Again, this has been the case in V1 & V2, and remains true in V4.

So here's the catch.  What if a V4 app starts up in background GC mode _without_ a profiler loading on startup, and you later attach a profiler to the process?  If the profiler specifies COR\_PRF\_MONITOR\_GC in its call to SetEventMask, then the CLR returns the error CORPROF\_E\_CONCURRENT\_GC\_NOT\_PROFILABLE.  In other words, if the profiler is late to the party, then it simply won't work if background GC is on.  Since this is the default for client apps, the bottom line is that you can generally successfully attach your memory profiler to server apps (e.g., ASP.NET), but probably not to client apps.

Of course, you could forcibly turn off concurrent / background mode every time the app starts up via a config file:

|

\<configuration\>
    \<runtime\>
        \<gcConcurrent enabled="false"/\>
    \</runtime\>
\</configuration\>

 |

But you don't really want to be running your apps with a sub-optimal GC mode all the time, just on the off-chance you might need to attach a memory profiler to it.  If you suspect you might need to do some memory profiling of a client app, you should just start up your app with the memory profiler to begin with.

### ObjectAllocated

The ObjectAllocated callback is disallowed for attaching profilers (i.e., COR\_PRF\_ENABLE\_OBJECT\_ALLOCATED is not part of the COR\_PRF\_ALLOWABLE\_AFTER\_ATTACH mask).

# Go Forth and Attach

All right, dig through that sample trigger code, and see if you can add "attach" to your list of features.  In later posts, I'll talk about how to catch up on application state once your profiler attaches, and also how to detach your profiler when it's done with its business.


text:
import "./component.tag"

export default {
    title: "Demo",
    editLink: "https://github.com/elbywan/bosket/edit/master/docs/riot/plan/treeview/demo/index.js",
    content: "treeview-demo-section"
}


text:
package org.elasticsearch.bootstrap;

import org.apache.lucene.util.Constants;
import org.elasticsearch.common.logging.Loggers;

import java.lang.management.ManagementFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/** Checks that the JVM is ok and won't cause index corruption */
final class JVMCheck {
    /** no instantiation */
    private JVMCheck() {}

    /**
     * URL with latest JVM recommendations
     */
    static final String JVM_RECOMMENDATIONS = "http://www.elastic.co/guide/en/elasticsearch/reference/current/_installation.html";

    /**
     * System property which if set causes us to bypass the check completely (but issues a warning in doing so)
     */
    static final String JVM_BYPASS = "es.bypass.vm.check";

    /**
     * Metadata and messaging for hotspot bugs.
     */
    static final class HotspotBug {

        /** OpenJDK bug URL */
        final String bugUrl;

        /** Compiler workaround flag (null if there is no workaround) */
        final String workAround;

        HotspotBug(String bugUrl, String workAround) {
            this.bugUrl = bugUrl;
            this.workAround = workAround;
        }

        /** Returns an error message to the user for a broken version */
        String getErrorMessage() {
            StringBuilder sb = new StringBuilder();
            sb.append("Java version: ").append(fullVersion());
            sb.append(" suffers from critical bug ").append(bugUrl);
            sb.append(" which can cause data corruption.");
            sb.append(System.lineSeparator());
            sb.append("Please upgrade the JVM, see ").append(JVM_RECOMMENDATIONS);
            sb.append(" for current recommendations.");
            if (workAround != null) {
                sb.append(System.lineSeparator());
                sb.append("If you absolutely cannot upgrade, please add ").append(workAround);
                sb.append(" to the JAVA_OPTS environment variable.");
                sb.append(System.lineSeparator());
                sb.append("Upgrading is preferred, this workaround will result in degraded performance.");
            }
            return sb.toString();
        }

        /** Warns the user when a workaround is being used to dodge the bug */
        String getWarningMessage() {
            StringBuilder sb = new StringBuilder();
            sb.append("Workaround flag ").append(workAround);
            sb.append(" for bug ").append(bugUrl);
            sb.append(" found. ");
            sb.append(System.lineSeparator());
            sb.append("This will result in degraded performance!");
            sb.append(System.lineSeparator());
            sb.append("Upgrading is preferred, see ").append(JVM_RECOMMENDATIONS);
            sb.append(" for current recommendations.");
            return sb.toString();
        }
    }

    /** mapping of hotspot version to hotspot bug information for the most serious bugs */
    static final Map<String,HotspotBug> JVM_BROKEN_HOTSPOT_VERSIONS;

    static {
        Map<String,HotspotBug> bugs = new HashMap<>();

        // 1.7.0: loop optimizer bug
        bugs.put("21.0-b17",  new HotspotBug("https://bugs.openjdk.java.net/browse/JDK-7070134", "-XX:-UseLoopPredicate"));
        // register allocation issues (technically only x86/amd64). This impacted update 40, 45, and 51
        bugs.put("24.0-b56",  new HotspotBug("https://bugs.openjdk.java.net/browse/JDK-8024830", "-XX:-UseSuperWord"));
        bugs.put("24.45-b08", new HotspotBug("https://bugs.openjdk.java.net/browse/JDK-8024830", "-XX:-UseSuperWord"));
        bugs.put("24.51-b03", new HotspotBug("https://bugs.openjdk.java.net/browse/JDK-8024830", "-XX:-UseSuperWord"));

        JVM_BROKEN_HOTSPOT_VERSIONS = Collections.unmodifiableMap(bugs);
    }

    /**
     * Checks that the current JVM is "ok". This means it doesn't have severe bugs that cause data corruption.
     */
    static void check() {
        if (Boolean.parseBoolean(System.getProperty(JVM_BYPASS))) {
            Loggers.getLogger(JVMCheck.class).warn("bypassing jvm version check for version [{}], this can result in data corruption!", fullVersion());
        } else if ("Oracle Corporation".equals(Constants.JVM_VENDOR)) {
            HotspotBug bug = JVM_BROKEN_HOTSPOT_VERSIONS.get(Constants.JVM_VERSION);
            if (bug != null) {
                if (bug.workAround != null && ManagementFactory.getRuntimeMXBean().getInputArguments().contains(bug.workAround)) {
                    Loggers.getLogger(JVMCheck.class).warn(bug.getWarningMessage());
                } else {
                    throw new RuntimeException(bug.getErrorMessage());
                }
            }
        } else if ("IBM Corporation".equals(Constants.JVM_VENDOR)) {
            // currently some old JVM versions from IBM will easily result in index corruption.
            // 2.8+ seems ok for ES from testing.
            float version = Float.POSITIVE_INFINITY;
            try {
                version = Float.parseFloat(Constants.JVM_VERSION);
            } catch (NumberFormatException ignored) {
                // this is just a simple best-effort to detect old runtimes,
                // if we cannot parse it, we don't fail.
            }
            if (version < 2.8f) {
                StringBuilder sb = new StringBuilder();
                sb.append("IBM J9 runtimes < 2.8 suffer from several bugs which can cause data corruption.");
                sb.append(System.lineSeparator());
                sb.append("Your version: " + fullVersion());
                sb.append(System.lineSeparator());
                sb.append("Please upgrade the JVM to a recent IBM JDK");
                throw new RuntimeException(sb.toString());
            }
        }
    }

    /**
     * Returns java + jvm version, looks like this:
     * {@code Oracle Corporation 1.8.0_45 [Java HotSpot(TM) 64-Bit Server VM 25.45-b02]}
     */
    static String fullVersion() {
        StringBuilder sb = new StringBuilder();
        sb.append(Constants.JAVA_VENDOR);
        sb.append(" ");
        sb.append(Constants.JAVA_VERSION);
        sb.append(" [");
        sb.append(Constants.JVM_NAME);
        sb.append(" ");
        sb.append(Constants.JVM_VERSION);
        sb.append("]");
        return sb.toString();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NuGetGallery.Operations.Tasks.DataManagement
{
    [Command("normalizepackageversions", "Sets the NormalizedVersion column for packages which do not have a value for that column", AltName = "npv")]
    public class NormalizePackageVersionsTask : DatabaseTask
    {
        private const string UpdateQuery = @"
            UPDATE Packages
            SET NormalizedVersion = ut.NormalizedVersion
            OUTPUT
                pr.Id,
                INSERTED.[Version],
                INSERTED.NormalizedVersion
            FROM @updateTable ut
                INNER JOIN Packages p ON ut.PackageKey = p.[Key]
                INNER JOIN PackageRegistrations pr ON p.PackageRegistrationKey = pr.[Key]";
        private const string CommitQuery = @"BEGIN TRAN
            " + UpdateQuery + @"
            COMMIT TRAN";
        private const string WhatIfQuery = @"BEGIN TRAN
            " + UpdateQuery + @"
            ROLLBACK TRAN";

        public override void ExecuteCommand()
        {
            WithConnection((c, db) =>
            {
                Log.Trace("Collecting list of packages...");
                var packages = db.Query<Package>(@"
                    SELECT pr.Id, p.[Key], p.Version
                    FROM Packages p
                        INNER JOIN PackageRegistrations pr ON pr.[Key] = p.PackageRegistrationKey
                    WHERE p.NormalizedVersion IS NULL")
                        .ToList();
                Log.Trace("Collected {0} packages", packages.Count);

                DataTable output;
                int count = 0;
                WithTableType(c, "Temp_NormalizePackageVersionsInputType", "PackageKey int, NormalizedVersion nvarchar(64)", () =>
                {
                    // Build a table to hold the new data
                    var updateTable = new DataTable();
                    updateTable.Columns.Add(new DataColumn("PackageKey", typeof(int)));
                    updateTable.Columns.Add(new DataColumn("NormalizedVersion", typeof(string)));
                    foreach (var package in packages)
                    {
                        string normalized = SemanticVersionExtensions.Normalize(package.Version);
                        var row = updateTable.NewRow();
                        row.SetField("PackageKey", package.Key);
                        row.SetField("NormalizedVersion", normalized);
                        updateTable.Rows.Add(row);
                    }

                    // Run the query with the table parameter
                    var cmd = c.CreateCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = WhatIf ? WhatIfQuery : CommitQuery;
                    cmd.Parameters.Add(new SqlParameter("@updateTable", SqlDbType.Structured)
                    {
                        TypeName = "Temp_NormalizePackageVersionsInputType",
                        Value = updateTable
                    });
                    Log.Trace("Updating Database...");
                    var reader = cmd.ExecuteReader();
                    Log.Trace("Database Update Complete");

                    // Load the results into a datatable and render them
                    output = new DataTable();
                    output.Load(reader);
                    foreach (var row in output.Rows.Cast<DataRow>())
                    {
                        string version = row.Field<string>("Version");
                        string normalized = row.Field<string>("NormalizedVersion");
                        if (!String.Equals(version, normalized, StringComparison.Ordinal))
                        {
                            count++;
                        }
                    }
                    Log.Info("Updated {0} packages", count);
                });
            });
        }
    }
}


text:
package com.itlijunjie.andrioddemo1.ui.view;

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.itlijunjie.andrioddemo1.R;
import com.itlijunjie.andrioddemo1.ui.MainActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.orhanobut.logger.Logger;
import com.squareup.picasso.Picasso;

public class UseImageViewActivity extends AppCompatActivity {
    private DisplayImageOptions options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.use_image_view);
        this.setTitle("ImageView使用");
        ImageView imageView = (ImageView)findViewById(R.id.imageView);
// 使用DisplayImageOptions.Builder()创建DisplayImageOptions
//        options = new DisplayImageOptions.Builder()
//                .showImageOnLoading(R.drawable.checkbox_checked)          // 设置图片下载期间显示的图片
//                .showImageForEmptyUri(R.drawable.checkbox_checked)  // 设置图片Uri为空或是错误的时候显示的图片
//                .showImageOnFail(R.drawable.checkbox_checked)       // 设置图片加载或解码过程中发生错误显示的图片
//                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
//                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
////                .displayer(new CircleBitmapDisplayer(50))  // 设置成圆角图片
//                .build();                                   // 创建配置过得DisplayImageOption对象
//        ImageLoader imageLoader = ImageLoader.getInstance();
//        String url = "http://f.hiphotos.baidu.com/image/pic/item/060828381f30e924bd73bbdf48086e061c95f70c.jpg";
//        imageLoader.displayImage(url, imageView, options);
        Picasso.with(this).load("http://f.hiphotos.baidu.com/image/pic/item/060828381f30e924bd73bbdf48086e061c95f70c.jpg").into(imageView);
    }
}


text:
import React from 'react';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import BaseNumberType from '../../Type/NumberType';
import AbstractRenderer from './AbstractRenderer';

export default class NumberType extends BaseNumberType {
    static defaultProps = {
        doRenderOperatorList: AbstractRenderer.doRenderOperatorList({ width: 140 }),
    };

    /**
     * @inheritDoc
     */
    doRenderValueInput(value, onChange) {
        return <TextField type="number" value={value} onChanged={(val) => onChange(val)}/>;
    }
}


text:
typedef struct z_stream_s z_stream;

namespace remoting {

// A lossless decompressor using zlib.
class DecompressorZlib : public Decompressor {
 public:
  DecompressorZlib();
  virtual ~DecompressorZlib();

  virtual void Reset() OVERRIDE;

  // Decompressor implementations.
  virtual bool Process(const uint8* input_data, int input_size,
                       uint8* output_data, int output_size,
                       int* consumed, int* written) OVERRIDE;

 private:
  void InitStream();
  scoped_ptr<z_stream> stream_;
};

}  // namespace remoting

#endif  // REMOTING_BASE_DECOMPRESSOR_ZLIB_H_


text:
"""
Support for an exposed aREST RESTful API of a device.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.arest/
"""

import logging

import requests
import voluptuous as vol

from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
from homeassistant.const import (CONF_NAME, CONF_RESOURCE)
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

CONF_FUNCTIONS = 'functions'
CONF_PINS = 'pins'

DEFAULT_NAME = 'aREST switch'

PIN_FUNCTION_SCHEMA = vol.Schema({
    vol.Optional(CONF_NAME): cv.string,
})

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_RESOURCE): cv.url,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
    vol.Optional(CONF_PINS, default={}):
        vol.Schema({cv.string: PIN_FUNCTION_SCHEMA}),
    vol.Optional(CONF_FUNCTIONS, default={}):
        vol.Schema({cv.string: PIN_FUNCTION_SCHEMA}),
})

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the aREST switches."""
    resource = config.get(CONF_RESOURCE)

    try:
        response = requests.get(resource, timeout=10)
    except requests.exceptions.MissingSchema:
        _LOGGER.error("Missing resource or schema in configuration. "
                      "Add http:// to your URL")
        return False
    except requests.exceptions.ConnectionError:
        _LOGGER.error("No route to device at %s", resource)
        return False

    dev = []
    pins = config.get(CONF_PINS)
    for pinnum, pin in pins.items():
        dev.append(ArestSwitchPin(
            resource, config.get(CONF_NAME, response.json()[CONF_NAME]),
            pin.get(CONF_NAME), pinnum))

    functions = config.get(CONF_FUNCTIONS)
    for funcname, func in functions.items():
        dev.append(ArestSwitchFunction(
            resource, config.get(CONF_NAME, response.json()[CONF_NAME]),
            func.get(CONF_NAME), funcname))

    add_devices(dev)

class ArestSwitchBase(SwitchDevice):
    """Representation of an aREST switch."""

    def __init__(self, resource, location, name):
        """Initialize the switch."""
        self._resource = resource
        self._name = '{} {}'.format(location.title(), name.title())
        self._state = None
        self._available = True

    @property
    def name(self):
        """Return the name of the switch."""
        return self._name

    @property
    def is_on(self):
        """Return true if device is on."""
        return self._state

    @property
    def available(self):
        """Could the device be accessed during the last update call."""
        return self._available

class ArestSwitchFunction(ArestSwitchBase):
    """Representation of an aREST switch."""

    def __init__(self, resource, location, name, func):
        """Initialize the switch."""
        super().__init__(resource, location, name)
        self._func = func

        request = requests.get(
            '{}/{}'.format(self._resource, self._func), timeout=10)

        if request.status_code != 200:
            _LOGGER.error("Can't find function")
            return

        try:
            request.json()['return_value']
        except KeyError:
            _LOGGER.error("No return_value received")
        except ValueError:
            _LOGGER.error("Response invalid")

    def turn_on(self, **kwargs):
        """Turn the device on."""
        request = requests.get(
            '{}/{}'.format(self._resource, self._func), timeout=10,
            params={'params': '1'})

        if request.status_code == 200:
            self._state = True
        else:
            _LOGGER.error(
                "Can't turn on function %s at %s", self._func, self._resource)

    def turn_off(self, **kwargs):
        """Turn the device off."""
        request = requests.get(
            '{}/{}'.format(self._resource, self._func), timeout=10,
            params={'params': '0'})

        if request.status_code == 200:
            self._state = False
        else:
            _LOGGER.error(
                "Can't turn off function %s at %s", self._func, self._resource)

    def update(self):
        """Get the latest data from aREST API and update the state."""
        try:
            request = requests.get(
                '{}/{}'.format(self._resource, self._func), timeout=10)
            self._state = request.json()['return_value'] != 0
            self._available = True
        except requests.exceptions.ConnectionError:
            _LOGGER.warning("No route to device %s", self._resource)
            self._available = False

class ArestSwitchPin(ArestSwitchBase):
    """Representation of an aREST switch. Based on digital I/O."""

    def __init__(self, resource, location, name, pin):
        """Initialize the switch."""
        super().__init__(resource, location, name)
        self._pin = pin

        request = requests.get(
            '{}/mode/{}/o'.format(self._resource, self._pin), timeout=10)
        if request.status_code != 200:
            _LOGGER.error("Can't set mode")
            self._available = False

    def turn_on(self, **kwargs):
        """Turn the device on."""
        request = requests.get(
            '{}/digital/{}/1'.format(self._resource, self._pin), timeout=10)
        if request.status_code == 200:
            self._state = True
        else:
            _LOGGER.error(
                "Can't turn on pin %s at %s", self._pin, self._resource)

    def turn_off(self, **kwargs):
        """Turn the device off."""
        request = requests.get(
            '{}/digital/{}/0'.format(self._resource, self._pin), timeout=10)
        if request.status_code == 200:
            self._state = False
        else:
            _LOGGER.error(
                "Can't turn off pin %s at %s", self._pin, self._resource)

    def update(self):
        """Get the latest data from aREST API and update the state."""
        try:
            request = requests.get(
                '{}/digital/{}'.format(self._resource, self._pin), timeout=10)
            self._state = request.json()['return_value'] != 0
            self._available = True
        except requests.exceptions.ConnectionError:
            _LOGGER.warning("No route to device %s", self._resource)
            self._available = False


text:
drop index ACT_GE_BYTEARRAY.ACT_IDX_BYTEARRAY_RM_TIME;
drop index ACT_GE_BYTEARRAY.ACT_IDX_BYTEARRAY_ROOT_PI;
drop index ACT_RU_EXECUTION.ACT_IDX_EXEC_ROOT_PI;
drop index ACT_RU_EXECUTION.ACT_IDX_EXEC_BUSKEY;
drop index ACT_RU_TASK.ACT_IDX_TASK_CREATE;
drop index ACT_RU_TASK.ACT_IDX_TASK_ASSIGNEE;
drop index ACT_RU_IDENTITYLINK.ACT_IDX_IDENT_LNK_USER;
drop index ACT_RU_IDENTITYLINK.ACT_IDX_IDENT_LNK_GROUP;
drop index ACT_RU_VARIABLE.ACT_IDX_VARIABLE_TASK_ID;
drop index ACT_RU_EVENT_SUBSCR.ACT_IDX_EVENT_SUBSCR_CONFIG_;
drop index ACT_RU_INCIDENT.ACT_IDX_INC_CONFIGURATION;
drop index ACT_RU_JOB.ACT_IDX_JOB_PROCINST;
drop index ACT_RU_AUTHORIZATION.ACT_UNIQ_AUTH_GROUP;
drop index ACT_RU_AUTHORIZATION.ACT_UNIQ_AUTH_USER;
drop index ACT_RU_VARIABLE.ACT_UNIQ_VARIABLE;
drop index ACT_RU_AUTHORIZATION.ACT_IDX_AUTH_GROUP_ID;

-- new metric milliseconds column
DROP INDEX ACT_RU_METER_LOG.ACT_IDX_METER_LOG_MS;
DROP INDEX ACT_RU_METER_LOG.ACT_IDX_METER_LOG_NAME_MS;
DROP INDEX ACT_RU_METER_LOG.ACT_IDX_METER_LOG_REPORT;

-- old metric timestamp column
DROP INDEX ACT_RU_METER_LOG.ACT_IDX_METER_LOG_TIME;
DROP INDEX ACT_RU_METER_LOG.ACT_IDX_METER_LOG;

-- indexes for concurrency problems - https://app.camunda.com/jira/browse/CAM-1646 --
drop index ACT_RU_EXECUTION.ACT_IDX_EXECUTION_PROC;
drop index ACT_RU_EXECUTION.ACT_IDX_EXECUTION_PARENT;
drop index ACT_RU_EXECUTION.ACT_IDX_EXECUTION_SUPER;
drop index ACT_RU_EXECUTION.ACT_IDX_EXECUTION_PROCINST;
drop index ACT_RU_EVENT_SUBSCR.ACT_IDX_EVENT_SUBSCR_EXEC;
drop index ACT_GE_BYTEARRAY.ACT_IDX_BA_DEPLOYMENT;
drop index ACT_RU_IDENTITYLINK.ACT_IDX_IDENT_LNK_TASK;
drop index ACT_RU_INCIDENT.ACT_IDX_INCIDENT_EXEC;
drop index ACT_RU_INCIDENT.ACT_IDX_INCIDENT_PROCINST;
drop index ACT_RU_INCIDENT.ACT_IDX_INCIDENT_PROC_DEF_ID;
drop index ACT_RU_INCIDENT.ACT_IDX_INCIDENT_CAUSE;
drop index ACT_RU_INCIDENT.ACT_IDX_INCIDENT_ROOT_CAUSE;
drop index ACT_RU_INCIDENT.ACT_IDX_INCIDENT_JOB_DEF;
drop index ACT_RU_JOB.ACT_IDX_JOB_EXCEPTION_STACK;
drop index ACT_RU_VARIABLE.ACT_IDX_VARIABLE_BA;
drop index ACT_RU_VARIABLE.ACT_IDX_VARIABLE_EXEC;
drop index ACT_RU_VARIABLE.ACT_IDX_VARIABLE_PROCINST;
drop index ACT_RU_TASK.ACT_IDX_TASK_EXEC;
drop index ACT_RU_TASK.ACT_IDX_TASK_PROCINST;
drop index ACT_RU_TASK.ACT_IDX_TASK_PROC_DEF_ID;
drop index ACT_RU_AUTHORIZATION.ACT_IDX_AUTH_RESOURCE_ID;
drop index ACT_RU_EXT_TASK.ACT_IDX_EXT_TASK_TOPIC;
drop index ACT_RU_EXT_TASK.ACT_IDX_EXT_TASK_EXEC;

drop index ACT_GE_BYTEARRAY.ACT_IDX_BYTEARRAY_NAME;
drop index ACT_RE_DEPLOYMENT.ACT_IDX_DEPLOYMENT_NAME;
drop index ACT_RU_JOBDEF.ACT_IDX_JOBDEF_PROC_DEF_ID;
drop index ACT_RU_JOB.ACT_IDX_JOB_HANDLER_TYPE;
drop index ACT_RU_EVENT_SUBSCR.ACT_IDX_EVENT_SUBSCR_EVT_NAME;
drop index ACT_RE_PROCDEF.ACT_IDX_PROCDEF_DEPLOYMENT_ID;

drop index ACT_RU_EXT_TASK.ACT_IDX_EXT_TASK_TENANT_ID;
drop index ACT_RU_EXT_TASK.ACT_IDX_EXT_TASK_PRIORITY;
drop index ACT_RU_EXT_TASK.ACT_IDX_EXT_TASK_ERR_DETAILS;
drop index ACT_RU_INCIDENT.ACT_IDX_INC_TENANT_ID;
drop index ACT_RU_JOBDEF.ACT_IDX_JOBDEF_TENANT_ID;
drop index ACT_RU_JOB.ACT_IDX_JOB_TENANT_ID;
drop index ACT_RU_EVENT_SUBSCR.ACT_IDX_EVENT_SUBSCR_TENANT_ID;
drop index ACT_RU_VARIABLE.ACT_IDX_VARIABLE_TENANT_ID;
drop index ACT_RU_TASK.ACT_IDX_TASK_TENANT_ID;
drop index ACT_RU_EXECUTION.ACT_IDX_EXEC_TENANT_ID;
drop index ACT_RE_PROCDEF.ACT_IDX_PROCDEF_TENANT_ID;
drop index ACT_RE_DEPLOYMENT.ACT_IDX_DEPLOYMENT_TENANT_ID;

drop index ACT_RU_JOB.ACT_IDX_JOB_JOB_DEF_ID;
drop index ACT_RU_BATCH.ACT_IDX_BATCH_SEED_JOB_DEF;
drop index ACT_RU_BATCH.ACT_IDX_BATCH_MONITOR_JOB_DEF;
drop index ACT_RU_BATCH.ACT_IDX_BATCH_JOB_DEF;

drop index ACT_RU_JOB.ACT_IDX_JOB_EXECUTION_ID;

alter table ACT_GE_BYTEARRAY
    drop constraint ACT_FK_BYTEARR_DEPL;

alter table ACT_RU_EXECUTION
    drop constraint ACT_FK_EXE_PROCINST;

alter table ACT_RU_EXECUTION
    drop constraint ACT_FK_EXE_PROCDEF;

alter table ACT_RU_EXECUTION
    drop constraint ACT_FK_EXE_PARENT;

alter table ACT_RU_EXECUTION
    drop constraint ACT_FK_EXE_SUPER;

alter table ACT_RU_IDENTITYLINK
    drop constraint ACT_FK_TSKASS_TASK;

alter table ACT_RU_IDENTITYLINK
    drop constraint ACT_FK_ATHRZ_PROCEDEF;

alter table ACT_RU_TASK
	drop constraint ACT_FK_TASK_EXE;

alter table ACT_RU_TASK
	drop constraint ACT_FK_TASK_PROCINST;

alter table ACT_RU_TASK
	drop constraint ACT_FK_TASK_PROCDEF;

alter table ACT_RU_VARIABLE
    drop constraint ACT_FK_VAR_EXE;

alter table ACT_RU_VARIABLE
	drop constraint ACT_FK_VAR_PROCINST;

alter table ACT_RU_VARIABLE
    drop constraint ACT_FK_VAR_BYTEARRAY;

alter table ACT_RU_JOB
    drop constraint ACT_FK_JOB_EXCEPTION;

alter table ACT_RU_EVENT_SUBSCR
    drop constraint ACT_FK_EVENT_EXEC;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_EXE;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_PROCINST;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_PROCDEF;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_CAUSE;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_RCAUSE;

alter table ACT_RU_INCIDENT
    drop constraint ACT_FK_INC_JOB_DEF;

alter table ACT_RU_EXT_TASK
    drop constraint ACT_FK_EXT_TASK_EXE;

alter table ACT_RU_BATCH
    drop constraint ACT_FK_BATCH_SEED_JOB_DEF;

alter table ACT_RU_BATCH
    drop constraint ACT_FK_BATCH_MONITOR_JOB_DEF;

alter table ACT_RU_BATCH
    drop constraint ACT_FK_BATCH_JOB_DEF;

alter table ACT_RU_EXT_TASK
    drop CONSTRAINT ACT_FK_EXT_TASK_ERROR_DETAILS;

drop index ACT_RU_IDENTITYLINK.ACT_IDX_ATHRZ_PROCEDEF;

drop index ACT_RE_PROCDEF.ACT_IDX_PROCDEF_VER_TAG;

if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_GE_PROPERTY') drop table ACT_GE_PROPERTY;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_GE_BYTEARRAY') drop table ACT_GE_BYTEARRAY;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RE_PROCDEF') drop table ACT_RE_PROCDEF;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RE_DEPLOYMENT') drop table ACT_RE_DEPLOYMENT;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_IDENTITYLINK') drop table ACT_RU_IDENTITYLINK;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_TASK') drop table ACT_RU_TASK;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_VARIABLE') drop table ACT_RU_VARIABLE;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_EXECUTION') drop table ACT_RU_EXECUTION;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_EVENT_SUBSCR') drop table ACT_RU_EVENT_SUBSCR;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_JOB') drop table ACT_RU_JOB;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_JOBDEF') drop table ACT_RU_JOBDEF;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_INCIDENT') drop table ACT_RU_INCIDENT;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_AUTHORIZATION') drop table ACT_RU_AUTHORIZATION;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_FILTER') drop table ACT_RU_FILTER;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_METER_LOG') drop table ACT_RU_METER_LOG;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_EXT_TASK') drop table ACT_RU_EXT_TASK;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_RU_BATCH') drop table ACT_RU_BATCH;
if exists (select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'ACT_GE_SCHEMA_LOG') drop table ACT_GE_SCHEMA_LOG;


text:
package containerengine

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
)

// KeyDetails The properties that define the kms keys used by OKE for Image Signature verification.
type KeyDetails struct {

	// The OCIDs of the KMS key that will be used to verify whether the images are signed by an approved source.
	KmsKeyId *string `mandatory:"false" json:"kmsKeyId"`
}

func (m KeyDetails) String() string {
	return common.PointerString(m)
}


text:
class CAccessibilityData
{
public:
	CAccessibilityData()
	{
		Clear();
	}

	void Clear()
	{
		m_nAccRole = 0;
		m_bAccState = 0;
		m_nAccHit = 0;
		m_rectAccLocation = CRect(0, 0, 0, 0);
		m_ptAccHit = CPoint(0, 0);

		m_strAccName.Empty();
		m_strAccValue.Empty();
		m_strDescription.Empty();
		m_strAccKeys.Empty();
		m_strAccHelp.Empty();
		m_strAccName.Empty();
		m_strAccDefAction.Empty();
	}

	CString m_strAccName;
	CString m_strAccValue;
	CString m_strDescription;
	CString m_strAccKeys;
	CString m_strAccHelp;
	CString m_strAccDefAction;

	int    m_nAccRole;
	UINT   m_bAccState;
	UINT   m_nAccHit;
	CRect  m_rectAccLocation;
	CPoint m_ptAccHit;
};

#ifdef _AFX_MINREBUILD
#pragma component(minrebuild, on)
#endif

#ifdef _AFX_PACKING
#pragma pack(pop)
#endif


text:
module Dashboards
  class RecentWorkfilesController < ApplicationController
    wrap_parameters :recent_workfiles

    def create
      authorize! :update, current_user
      if (params[:recent_workfiles][:action] == 'updateOption')
        option_value = params[:recent_workfiles][:option_value]
        config = DashboardConfig.new(current_user)
        config.set_options('RecentWorkfiles', option_value)
      elsif (params[:recent_workfiles][:action] == 'clearList')
        OpenWorkfileEvent.where(:user_id => current_user).destroy_all
      end
      render :json => {}
    end
  end

end


text:
namespace :setup do

  desc <<-DESC
    Setup all the folders that are needed

  DESC
  task :dirs do
    run "#{try_sudo} mkdir -p #{deploy_to}"
    run "#{try_sudo} mkdir -p #{deploy_to}shared"
    run "#{try_sudo} mkdir -p #{deploy_to}releases"
    run "#{try_sudo} mkdir -p #{deploy_to}shared/mysql_uploads"
    run "#{try_sudo} mkdir -p #{deploy_to}shared/solr"
    run "#{try_sudo} mkdir -p #{deploy_to}shared/mysql_backups"
    run "#{try_sudo} chown #{user}:#{group} #{deploy_to}"
    run "#{try_sudo} chown #{user}:#{group} #{deploy_to}shared"
    run "#{try_sudo} chown #{user}:#{group} #{deploy_to}releases"
    run "#{try_sudo} chown #{user}:#{group} #{deploy_to}shared/mysql_uploads"
    run "#{try_sudo} chown #{user}:#{group} #{deploy_to}shared/solr"
    run "#{try_sudo} chown #{user}:#{group} #{deploy_to}shared/mysql_backups"
  end
end


text:
Bunto::Assets::Hook.register :env, :init do
  self.logger = Bunto::Assets::Logger.new
end


text:
"""
Tests align_on_col
"""
import os
import unittest
import logging
from md_utils.align_on_col import main
from md_utils.md_common import capture_stdout, capture_stderr, diff_lines, silent_remove

__author__ = 'hmayes'

# logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
DISABLE_REMOVE = logger.isEnabledFor(logging.DEBUG)

TEST_DIR = os.path.dirname(__file__)
MAIN_DIR = os.path.dirname(TEST_DIR)
DATA_DIR = os.path.join(TEST_DIR, 'test_data')
SUB_DATA_DIR = os.path.join(DATA_DIR, 'align_col')

DEF_CMP_LIST = os.path.join(SUB_DATA_DIR, 'compare_list.txt')
MULTI_FILE_CMP_LIST = os.path.join(SUB_DATA_DIR, 'compare_list_4files.txt')
MULTI_LINE_CMP_LIST = os.path.join(SUB_DATA_DIR, 'compare_list_multi_lines.txt')
NO_OVER_CMP_LIST = os.path.join(SUB_DATA_DIR, 'compare_list_no_overlap.txt')
DUP_COL_CMP_LIST = os.path.join(SUB_DATA_DIR, 'compare_list_dup_col.txt')
NO_COL_CMP_LIST = os.path.join(SUB_DATA_DIR, 'compare_list_no_timestep.txt')
NO_FILE_CMP_LIST = os.path.join(SUB_DATA_DIR, 'compare_list_no_file.txt')

# noinspection PyUnresolvedReferences
DEF_OUT = os.path.join(MAIN_DIR, 'comb.csv')

GOOD_OUT = os.path.join(SUB_DATA_DIR, 'align12_output_good.csv')
GOOD_MULTI_FILE_OUT = os.path.join(SUB_DATA_DIR, 'combined_multi_good.csv')
GOOD_MULTI_LINE_OUT = os.path.join(SUB_DATA_DIR, 'combined_multi_line_good.csv')
LINE1_OUT = os.path.join(SUB_DATA_DIR, '0.750_20c_comb.csv')
GOOD_LINE1_OUT = os.path.join(SUB_DATA_DIR, '0.750_20c_comb_good.csv')
LINE2_OUT = os.path.join(SUB_DATA_DIR, '0.875_20c_comb.csv')
GOOD_LINE2_OUT = os.path.join(SUB_DATA_DIR, '0.875_20c_comb_good.csv')
LINE3_OUT = os.path.join(SUB_DATA_DIR, '2_comb.csv')
LINE4_OUT = os.path.join(SUB_DATA_DIR, '3_comb.csv')

class TestAlignColNoOutput(unittest.TestCase):
    def testNoArgs(self):
        with capture_stdout(main, []) as output:
            self.assertTrue("optional arguments" in output)
        with capture_stderr(main, []) as output:
            self.assertTrue("Problems reading file" in output)

    def testNoFile(self):
        with capture_stderr(main, ["-f", NO_FILE_CMP_LIST]) as output:
            self.assertTrue("Did not find file" in output)

    def testNoTimestep(self):
        test_input = ["-f", NO_COL_CMP_LIST]
        main(test_input)
        # with capture_stderr(main, test_input) as output:
        #     self.assertTrue("Could not find value" in output)
        silent_remove(DEF_OUT, disable=DISABLE_REMOVE)

    def testNoOverlap(self):
        with capture_stderr(main, ["-f", NO_OVER_CMP_LIST]) as output:
            self.assertTrue("Problems reading data" in output)
        silent_remove(DEF_OUT, disable=DISABLE_REMOVE)

    def testHelp(self):
        test_input = ['-h']
        if logger.isEnabledFor(logging.DEBUG):
            main(test_input)
        with capture_stderr(main, test_input) as output:
            self.assertFalse(output)
        with capture_stdout(main, test_input) as output:
            self.assertTrue("optional arguments" in output)

    def testUnregArg(self):
        test_input = ['-@@@', "-f", DEF_CMP_LIST]
        if logger.isEnabledFor(logging.DEBUG):
            main(test_input)
        with capture_stderr(main, test_input) as output:
            self.assertTrue("unrecognized arguments" in output)

class TestAlignCol(unittest.TestCase):

    def testDefIni(self):
        try:
            main(["-f", DEF_CMP_LIST])
            self.assertFalse(diff_lines(DEF_OUT, GOOD_OUT))
        finally:
            silent_remove(DEF_OUT, disable=DISABLE_REMOVE)

    def testMultiFileIni(self):
        try:
            main(["-f", MULTI_FILE_CMP_LIST])
            self.assertFalse(diff_lines(DEF_OUT, GOOD_MULTI_FILE_OUT))
        finally:
            silent_remove(DEF_OUT, disable=DISABLE_REMOVE)

    def testDupCol(self):
        test_input = ["-f", DUP_COL_CMP_LIST]
        if logger.isEnabledFor(logging.DEBUG):
            main(test_input)
        with capture_stderr(main, test_input) as output:
            self.assertFalse(diff_lines(DEF_OUT, GOOD_OUT))
            self.assertTrue("Non-unique column" in output)
        silent_remove(DEF_OUT, disable=DISABLE_REMOVE)

    def testMultiLineIni(self):
        try:
            main(["-f", MULTI_LINE_CMP_LIST])
            self.assertFalse(diff_lines(DEF_OUT, GOOD_MULTI_LINE_OUT))
        finally:
            silent_remove(DEF_OUT, disable=DISABLE_REMOVE)

    def testMultiLineSepIni(self):
        # have different rows create different files
        # test that if the prefix is already used, number it
        # test if nothing common in the file base names, number it
        try:
            main(["-f", MULTI_LINE_CMP_LIST, "-s", "-l", SUB_DATA_DIR])
            self.assertFalse(diff_lines(LINE1_OUT, GOOD_LINE1_OUT))
            self.assertFalse(diff_lines(LINE2_OUT, GOOD_LINE2_OUT))
            self.assertFalse(diff_lines(LINE3_OUT, GOOD_LINE1_OUT))
            self.assertFalse(diff_lines(LINE4_OUT, GOOD_LINE1_OUT))
        finally:
            silent_remove(LINE1_OUT, disable=DISABLE_REMOVE)
            silent_remove(LINE2_OUT, disable=DISABLE_REMOVE)
            silent_remove(LINE3_OUT, disable=DISABLE_REMOVE)
            silent_remove(LINE4_OUT, disable=DISABLE_REMOVE)


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class DvsPuntNetworkRuleAction extends DvsNetworkRuleAction {
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>OpenHDS</display-name>

    <description>
        Open Source Health and Demographic System Web Application
    </description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/META-INF/spring/application*.xml</param-value>
    </context-param>

    <context-param>
        <param-name>facelets.SKIP_COMMENTS</param-name>
        <param-value>true</param-value>
    </context-param>

    <!-- Without this, I get a warning. It is suggested this is dangerous, so disable:
     http://stackoverflow.com/questions/3889393/how-to-resolve-this-facelets-warning-message -->
    <context-param>
        <param-name>facelets.RECREATE_VALUE_EXPRESSION_ON_BUILD_BEFORE_RESTORE</param-name>
        <param-value>false</param-value>
    </context-param>

    <context-param>
    	<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    	<param-value>client</param-value>
    </context-param>

    <context-param>
		<param-name>javax.faces.DEFAULT_SUFFIX</param-name>
		<param-value>.xhtml</param-value>
	</context-param>

    <!-- description>
            Comma separated list of URIs of additional faces files.
            (e.g. /WEB-INF/my-config.xml) Attention: /WEB-INF/faces.config.xml is added automatically.
    </description -->
	<!-- context-param>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value></param-value>
    </context-param -->

	<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>*.flow</url-pattern>
	</servlet-mapping>

    <servlet>
        <servlet-name>webServices</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/META-INF/spring/webserviceApplicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>webServices</servlet-name>
        <url-pattern>/api/rest/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>

    <servlet>
		<servlet-name>autocomplete</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>autocomplete</servlet-name>
		<url-pattern>*.autocomplete</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>reporter</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>reporter</servlet-name>
		<url-pattern>*.report</url-pattern>
	</servlet-mapping>

	<filter>
		<filter-name>hibernateFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
	</filter>

	<!-- maps to the /* pattern so all requests are processed -->
	<filter-mapping>
		<filter-name>hibernateFilter</filter-name>
		<url-pattern>/amendment/*</url-pattern>
		<url-pattern>*.faces</url-pattern>
		<url-pattern>*.report</url-pattern>
		<url-pattern>*.autocomplete</url-pattern>
		<url-pattern>/loginProcess</url-pattern>
		<url-pattern>/api/rest/*</url-pattern>
		<url-pattern>/validationRoutine</url-pattern>
		<url-pattern>/module/dsl/*</url-pattern>
		<url-pattern>/webservice/dhisGenerator/*</url-pattern>
	</filter-mapping>

     <!-- Enables Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <!-- maps to the /* pattern so all requests are processed -->
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <context-param>
		<param-name>com.ocpsoft.pretty.BASE_PACKAGES</param-name>
		<param-value>none</param-value>
	</context-param>

	<filter>
		<filter-name>ResourceFilter</filter-name>
		<filter-class>org.openfaces.util.ResourceFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>ResourceFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter>
	   <filter-name>Pretty Filter</filter-name>
	   <filter-class>com.ocpsoft.pretty.PrettyFilter</filter-class>
	</filter>

	<filter-mapping>
	   <filter-name>Pretty Filter</filter-name>
	   <url-pattern>/*</url-pattern>
	   <dispatcher>FORWARD</dispatcher>
	   <dispatcher>REQUEST</dispatcher>
	   <dispatcher>ERROR</dispatcher>
	</filter-mapping>

</web-app>


text:
class Elaborator;

Expr*    convert(Expr*, Type const*);
Expr_seq convert(Expr_seq const&, Type_seq const&);

Expr* convert_to_value(Expr*);
Type const* get_promotion_target(Expr*, Expr*);
Type const* get_promotion_target(Expr*);
Expr* promote(Expr*, Type const*);

#endif


text:
require 'spec_helper'
require 'gulp-runner/command_utils'

describe GulpRunner::CommandUtils do
	let (:utils) { GulpRunner::CommandUtils }
	describe 'find_command' do
		it 'returns nil for unexistent command' do
			expect(utils.find_command('testing-command')).to be_nil
		end
	end

	describe 'get_command' do
		it 'raises exception for unexistent command' do
			expect { utils.get_command('testing-command') }.to raise_error
		end

		it 'do not raises exception if command found' do
			expect(utils).to receive(:find_command).and_return(true)
			expect { utils.get_command('testing-command') }.to_not raise_error
		end
	end
end


text:
<app-suppliers-screen inline-template>

            @include('components.supplier-create')

@{{ supplier.name }}

@{{ supplier.location}}

                    <button class="btn btn-sm btn-danger pull-right" @click.prevent="deleteSupplier(supplier)">
                        delete
                    </button>

local_shipping
Seems like you have no suppliers.

</app-suppliers-screen>


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>QFocusEvent Class Reference</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />

QFocusEvent Class Reference

[com.trolltech.qt.gui package]

Inherits QEvent.

Constructor

void QFocusEvent(Type type, FocusReason reason)

Constructor Properties

prototype: The QFocusEvent prototype object

Prototype Object Properties

The QFocusEvent prototype object inherits properties from the QEvent prototype object and also has the following properties.

bool gotFocus()

bool lostFocus()

Instance Properties

QFocusEvent objects have no special properties beyond those inherited from the QFocusEvent prototype object.


text:
"""Middleware for Shibboleth (R).

It logs out the user from the application if the user logged out from SSO.

"""

from django.conf import settings
from django.contrib import auth
from django.contrib.auth import BACKEND_SESSION_KEY
from django.core.exceptions import ImproperlyConfigured
from django.utils.deprecation import MiddlewareMixin

class ShibSSOMiddleware(MiddlewareMixin):
    """Middleware for Shibboleth (R).

    It logs out the user from the application if the user logged out from SSO.

    """

    def process_request(self, request):

        if request.session.get(BACKEND_SESSION_KEY) != 'shibsso.backends.ShibSSOBackend':
            return

        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                                       "The Django remote user auth middleware requires the"
                                       " authentication middleware to be installed.  Edit your"
                                       " MIDDLEWARE_CLASSES setting to insert"
                                       " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                                       " before the RemoteUserMiddleware class.")

        username = request.META.get(settings.META_USERNAME)

        if request.user.is_authenticated():
            if request.user.username != username:
                auth.logout(request)


text:
package cart

import java.net.URI

final case class Item(id: URI, name: String, price: BigDecimal, count: Int = 1)


text:
using Flurl.Http;

namespace SolrExpress.Connection
{
    /// <summary>
    /// Set custom authentication settings to use in connection to SOLR
    /// </summary>
    public interface ICustomSolrConnectionAuthenticationSettings
    {
        /// <summary>
        /// Configure FlurlClient to use in connection to SOLR
        /// </summary>
        /// <param name="flurlClient">Fluent URL client to configure</param>
#if NETCOREAPP2_1
        void Configure(IFlurlRequest flurlClient);
#else
        void Configure(IFlurlClient flurlClient);
#endif
    }
}


text:
namespace WebApiDoodle.Net.Http.Client.Model {

    public interface IDto {

    }
}


text:
package iso20022

// Amount of money associated with a service.
type Charge18 struct {

	// Type of service for which a charge is asked or paid.
	Type *ChargeType11Code `xml:"Tp"`

	// Type of service for which a charge is asked or paid.
	ExtendedType *Extended350Code `xml:"XtndedTp"`

	// Method used to calculate a charge.
	ChargeBasis *TaxationBasis2Code `xml:"ChrgBsis,omitempty"`

	// Method used to calculate a charge.
	ExtendedChargeBasis *Extended350Code `xml:"XtndedChrgBsis,omitempty"`

	// Amount of money asked or paid for the charge.
	Amount *ActiveCurrencyAnd13DecimalAmount `xml:"Amt"`

	// Rate used to calculate the amount of the charge or fee.
	Rate *PercentageRate `xml:"Rate,omitempty"`

	// Party entitled to the amount of money resulting from a charge.
	RecipientIdentification *PartyIdentification2Choice `xml:"RcptId,omitempty"`
}

func (c *Charge18) SetType(value string) {
	c.Type = (*ChargeType11Code)(&value)
}

func (c *Charge18) SetExtendedType(value string) {
	c.ExtendedType = (*Extended350Code)(&value)
}

func (c *Charge18) SetChargeBasis(value string) {
	c.ChargeBasis = (*TaxationBasis2Code)(&value)
}

func (c *Charge18) SetExtendedChargeBasis(value string) {
	c.ExtendedChargeBasis = (*Extended350Code)(&value)
}

func (c *Charge18) SetAmount(value, currency string) {
	c.Amount = NewActiveCurrencyAnd13DecimalAmount(value, currency)
}

func (c *Charge18) SetRate(value string) {
	c.Rate = (*PercentageRate)(&value)
}

func (c *Charge18) AddRecipientIdentification() *PartyIdentification2Choice {
	c.RecipientIdentification = new(PartyIdentification2Choice)
	return c.RecipientIdentification
}


text:
#include <stdlib.h>
#include <string.h>

#include <curl/curl.h>
#include <jansson.h>

#define BUFFER_SIZE (256 * 1024) /* 256 KB */

#define URL_FORMAT "https://api.github.com/repos/%s/%s/commits"
#define URL_SIZE   256

/* Return the offset of the first newline in text or the length of
   text if there's no newline */
static int newline_offset(const char *text) {
    const char *newline = strchr(text, '\n');
    if (!newline)
        return strlen(text);
    else
        return (int)(newline - text);
}

struct write_result {
    char *data;
    int pos;
};

static size_t write_response(void *ptr, size_t size, size_t nmemb, void *stream) {
    struct write_result *result = (struct write_result *)stream;

    if (result->pos + size * nmemb >= BUFFER_SIZE - 1) {
        fprintf(stderr, "error: too small buffer\n");
        return 0;
    }

    memcpy(result->data + result->pos, ptr, size * nmemb);
    result->pos += size * nmemb;

    return size * nmemb;
}

static char *request(const char *url) {
    CURL *curl = NULL;
    CURLcode status;
    struct curl_slist *headers = NULL;
    char *data = NULL;
    long code;

    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (!curl)
        goto error;

    data = malloc(BUFFER_SIZE);
    if (!data)
        goto error;

    struct write_result write_result = {.data = data, .pos = 0};

    curl_easy_setopt(curl, CURLOPT_URL, url);

    /* GitHub commits API v3 requires a User-Agent header */
    headers = curl_slist_append(headers, "User-Agent: Jansson-Tutorial");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_response);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &write_result);

    status = curl_easy_perform(curl);
    if (status != 0) {
        fprintf(stderr, "error: unable to request data from %s:\n", url);
        fprintf(stderr, "%s\n", curl_easy_strerror(status));
        goto error;
    }

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
    if (code != 200) {
        fprintf(stderr, "error: server responded with code %ld\n", code);
        goto error;
    }

    curl_easy_cleanup(curl);
    curl_slist_free_all(headers);
    curl_global_cleanup();

    /* zero-terminate the result */
    data[write_result.pos] = '\0';

    return data;

error:
    if (data)
        free(data);
    if (curl)
        curl_easy_cleanup(curl);
    if (headers)
        curl_slist_free_all(headers);
    curl_global_cleanup();
    return NULL;
}

int main(int argc, char *argv[]) {
    size_t i;
    char *text;
    char url[URL_SIZE];

    json_t *root;
    json_error_t error;

    if (argc != 3) {
        fprintf(stderr, "usage: %s USER REPOSITORY\n\n", argv[0]);
        fprintf(stderr, "List commits at USER's REPOSITORY.\n\n");
        return 2;
    }

    snprintf(url, URL_SIZE, URL_FORMAT, argv[1], argv[2]);

    text = request(url);
    if (!text)
        return 1;

    root = json_loads(text, 0, &error);
    free(text);

    if (!root) {
        fprintf(stderr, "error: on line %d: %s\n", error.line, error.text);
        return 1;
    }

    if (!json_is_array(root)) {
        fprintf(stderr, "error: root is not an array\n");
        json_decref(root);
        return 1;
    }

    for (i = 0; i < json_array_size(root); i++) {
        json_t *data, *sha, *commit, *message;
        const char *message_text;

        data = json_array_get(root, i);
        if (!json_is_object(data)) {
            fprintf(stderr, "error: commit data %d is not an object\n", (int)(i + 1));
            json_decref(root);
            return 1;
        }

        sha = json_object_get(data, "sha");
        if (!json_is_string(sha)) {
            fprintf(stderr, "error: commit %d: sha is not a string\n", (int)(i + 1));
            json_decref(root);
            return 1;
        }

        commit = json_object_get(data, "commit");
        if (!json_is_object(commit)) {
            fprintf(stderr, "error: commit %d: commit is not an object\n", (int)(i + 1));
            json_decref(root);
            return 1;
        }

        message = json_object_get(commit, "message");
        if (!json_is_string(message)) {
            fprintf(stderr, "error: commit %d: message is not a string\n", (int)(i + 1));
            json_decref(root);
            return 1;
        }

        message_text = json_string_value(message);
        printf("%.8s %.*s\n", json_string_value(sha), newline_offset(message_text),
               message_text);
    }

    json_decref(root);
    return 0;
}


text:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include <stdbool.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <grp.h>
#include <dirent.h>
#include <sys/sysmacros.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "udev.h"

static int symlink_create(const char *target, const char *slink)
{
	int err = 0;

	do {
		err = mkdir_parents_label(slink, 0755);
		if (err != 0 && err != -ENOENT)
				break;
		label_context_set(slink, S_IFLNK);
		err = symlink(target, slink);
		if (err != 0)
				err = -errno;
		label_context_clear();
	} while (err == -ENOENT);

	return err;
}

static int node_symlink(const char *devnum, const char *node, const char *slink)
{
        struct stat stats;
        char target[UTIL_PATH_SIZE];
        char slink_tmp[UTIL_PATH_SIZE + 32];

        /* use relative link */
        if (!path_relative(target, node, slink, sizeof(target)))
        	return -1;

        /* preserve link with correct target, do not replace node of other device */
        if (lstat(slink, &stats) == 0) {
                if (S_ISBLK(stats.st_mode) || S_ISCHR(stats.st_mode)) {
                        log_error("conflicting device node '%s' found, link to '%s' will not be created", slink, node);
                        return 0;
                }

                if (S_ISLNK(stats.st_mode)) {
                        char buf[UTIL_PATH_SIZE];
                        int len;

                        len = readlink(slink, buf, sizeof(buf));
                        if (len > 0 && len < (int)sizeof(buf)) {
                                buf[len] = '\0';
                                if (str_eq(target, buf)) {
                                        log_debug("preserve already existing symlink '%s' to '%s'", slink, target);
                                        label_fix(slink, true, false);
                                        utimensat(AT_FDCWD, slink, NULL, AT_SYMLINK_NOFOLLOW);
                                        return 0;
                                }
                        }
                }
        } else {
                log_debug("creating symlink '%s' to '%s'", slink, target);
                if (!symlink_create(target, slink))
                        return 0;
        }

        log_debug("atomically replace '%s'", slink);
        strscpyl(slink_tmp, sizeof(slink_tmp), slink, ".tmp-", devnum, NULL);
        unlink(slink_tmp);
        if (symlink_create(target, slink_tmp) != 0) {
                log_error("symlink '%s' '%s' failed: %m", target, slink_tmp);

                return -1;
        }

        if (rename(slink_tmp, slink) < 0) {
                log_error("rename '%s' '%s' failed: %m", slink_tmp, slink);
                unlink(slink_tmp);

                return -1;
        }

        return 0;
}

/* find device node of device with highest priority */
static const char *link_find_prioritized(struct udev_device *dev, bool add, const char *stackdir, char *buf, size_t bufsize)
{
        struct udev *udev = udev_device_get_udev(dev);
        DIR *dir;
        struct dirent *dent;
        int priority = 0;
        const char *target = NULL;

        if (add) {
                priority = udev_device_get_devlink_priority(dev);
                strscpy(buf, bufsize, udev_device_get_devnode(dev));
                target = buf;
        }

        dir = opendir(stackdir);
        if (dir == NULL)
                return target;
        for (;;) {
                struct udev_device *dev_db;

                dent = readdir(dir);
                if (dent == NULL || dent->d_name[0] == '\0')
                        break;
                if (dent->d_name[0] == '.')
                        continue;

                log_debug("found '%s' claiming '%s'", dent->d_name, stackdir);

                /* did we find ourself? */
                if (str_eq(dent->d_name, udev_device_get_id_filename(dev)))
                        continue;

                dev_db = udev_device_new_from_device_id(udev, dent->d_name);
                if (dev_db != NULL) {
                        const char *devnode;

                        devnode = udev_device_get_devnode(dev_db);
                        if (devnode != NULL) {
                                if (target == NULL || udev_device_get_devlink_priority(dev_db) > priority) {
                                        log_debug("'%s' claims priority %i for '%s'",
                                                  udev_device_get_syspath(dev_db), udev_device_get_devlink_priority(dev_db), stackdir);
                                        priority = udev_device_get_devlink_priority(dev_db);
                                        strscpy(buf, bufsize, devnode);
                                        target = buf;
                                }
                        }
                        udev_device_unref(dev_db);
                }
        }
        closedir(dir);
        return target;
}

/* manage "stack of names" with possibly specified device priorities */
static void link_update(struct udev_device *dev, const char *slink, bool add)
{
        char name_enc[UTIL_PATH_SIZE];
        char filename[UTIL_PATH_SIZE * 2];
        char dirname[UTIL_PATH_SIZE];
        const char *target;
        char buf[UTIL_PATH_SIZE];
        const char *devnum;

        devnum = udev_device_get_id_filename(dev);

        path_encode(name_enc, slink + strlen("/dev"), sizeof(name_enc));
        strscpyl(dirname, sizeof(dirname), UDEVRUNDIR "/links/", name_enc, NULL);
        strscpyl(filename, sizeof(filename), dirname, "/", devnum, NULL);

        if (!add && unlink(filename) == 0)
                rmdir(dirname);

        target = link_find_prioritized(dev, add, dirname, buf, sizeof(buf));
        if (target == NULL) {
                log_debug("no reference left, remove '%s'", slink);
                if (unlink(slink) == 0)
                        path_remove(slink);
        } else {
                log_debug("creating link '%s' to '%s'", slink, target);
                node_symlink(devnum, target, slink);
        }

        if (add) {
                int fd;

                do {
                        if (path_create(filename, 0755) < 0)
                                break;

                } while (errno == ENOENT);

                fd = open(filename, O_WRONLY|O_CREAT|O_CLOEXEC|O_TRUNC|O_NOFOLLOW, 0444);
                if (fd >= 0)
                        close(fd);
        }
}

void udev_node_update_old_links(struct udev_device *dev, struct udev_device *dev_old)
{
        struct udev_list_entry *list_entry;

        /* update possible left-over symlinks */
        udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev_old)) {
                const char *name = udev_list_entry_get_name(list_entry);
                struct udev_list_entry *list_entry_current;
                int found;

                /* check if old link name still belongs to this device */
                found = 0;
                udev_list_entry_foreach(list_entry_current, udev_device_get_devlinks_list_entry(dev)) {
                        const char *name_current = udev_list_entry_get_name(list_entry_current);

                        if (str_eq(name, name_current)) {
                                found = 1;
                                break;
                        }
                }
                if (found)
                        continue;

                log_debug("update old name, '%s' no longer belonging to '%s'",
                     name, udev_device_get_devpath(dev));
                link_update(dev, name, false);
        }
}

static int node_permissions_apply(struct udev_device *dev, bool apply,
                                  mode_t mode, uid_t uid, gid_t gid,
                                  struct udev_list *seclabel_list) {
        const char *devnode = udev_device_get_devnode(dev);
        dev_t devnum = udev_device_get_devnum(dev);
        struct stat stats;
        struct udev_list_entry *entry;

        if (str_eq(udev_device_get_subsystem(dev), "block"))
                mode |= S_IFBLK;
        else
                mode |= S_IFCHR;

        if (lstat(devnode, &stats) < 0) {
                log_debug("can not stat() node '%s' (%m)", devnode);
                return -1;
        }

        if (((stats.st_mode & S_IFMT) != (mode & S_IFMT)) || (stats.st_rdev != devnum)) {
                errno = EEXIST;
                log_debug("found node '%s' with non-matching devnum %s, skip handling",
                          udev_device_get_devnode(dev), udev_device_get_id_filename(dev));
                return -1;
        }

        if (apply) {
                bool selinux = false;

                if ((stats.st_mode & 0777) != (mode & 0777) || stats.st_uid != uid || stats.st_gid != gid) {
                        log_debug("set permissions %s, %#o, uid=%u, gid=%u", devnode, mode, uid, gid);
                        chmod(devnode, mode);
                        chown(devnode, uid, gid);
                } else {
                        log_debug("preserve permissions %s, %#o, uid=%u, gid=%u", devnode, mode, uid, gid);
                }

                /* apply SECLABEL{$module}=$label */
                udev_list_entry_foreach(entry, udev_list_get_entry(seclabel_list)) {
                        const char *name, *label;

                        name = udev_list_entry_get_name(entry);
                        label = udev_list_entry_get_value(entry);

                        if (str_eq(name, "selinux")) {
                                selinux = true;
                                if (label_apply(devnode, label) < 0)
                                        log_error("SECLABEL: failed to set SELinux label '%s': %m", label);
                                else
                                        log_debug("SECLABEL: set SELinux label '%s'", label);

                        } else
                                log_error("SECLABEL: unknown subsystem, ignoring '%s'='%s'", name, label);
                }

                /* set the defaults */
                if (!selinux)
                        label_fix(devnode, true, false);
        }

        /* always update timestamp when we re-use the node, like on media change events */
        utimensat(AT_FDCWD, devnode, NULL, 0);

        return 0;
}

void udev_node_add(struct udev_device *dev, bool apply,
                   mode_t mode, uid_t uid, gid_t gid,
                   struct udev_list *seclabel_list) {
        char filename[UTIL_PATH_SIZE];
        struct udev_list_entry *list_entry;
        const char *devnum;

        devnum = udev_device_get_id_filename(dev);

        log_debug("handling device node '%s', devnum=%s, mode=%#o, uid=%d, gid=%d",
                  udev_device_get_devnode(dev), devnum, mode, uid, gid);

        if (node_permissions_apply(dev, apply, mode, uid, gid, seclabel_list) < 0)
                return;

        /* always add /dev/{block,char}/$major:$minor */
        snprintf(filename, sizeof(filename), "/dev/%s/%u:%u",
                 str_eq(udev_device_get_subsystem(dev), "block") ? "block" : "char",
                 major(udev_device_get_devnum(dev)), minor(udev_device_get_devnum(dev)));
        node_symlink(devnum, udev_device_get_devnode(dev), filename);

        /* create/update symlinks, add symlinks to name index */
        udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev))
                        link_update(dev, udev_list_entry_get_name(list_entry), true);
}

void udev_node_remove(struct udev_device *dev)
{
        struct udev_list_entry *list_entry;
        char filename[UTIL_PATH_SIZE];

        /* remove/update symlinks, remove symlinks from name index */
        udev_list_entry_foreach(list_entry, udev_device_get_devlinks_list_entry(dev))
                link_update(dev, udev_list_entry_get_name(list_entry), false);

        /* remove /dev/{block,char}/$major:$minor */
        snprintf(filename, sizeof(filename), "/dev/%s/%u:%u",
                 str_eq(udev_device_get_subsystem(dev), "block") ? "block" : "char",
                 major(udev_device_get_devnum(dev)), minor(udev_device_get_devnum(dev)));
        unlink(filename);
}


text:
/**
 * @module ol/render/canvas/ImageBuilder
 */
import CanvasInstruction from './Instruction.js';
import CanvasBuilder from './Builder.js';

class CanvasImageBuilder extends CanvasBuilder {
  /**
   * @param {number} tolerance Tolerance.
   * @param {import("../../extent.js").Extent} maxExtent Maximum extent.
   * @param {number} resolution Resolution.
   * @param {number} pixelRatio Pixel ratio.
   */
  constructor(tolerance, maxExtent, resolution, pixelRatio) {
    super(tolerance, maxExtent, resolution, pixelRatio);

    /**
     * @private
     * @type {import("../canvas.js").DeclutterGroups}
     */
    this.declutterGroups_ = null;

    /**
     * @private
     * @type {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement}
     */
    this.hitDetectionImage_ = null;

    /**
     * @private
     * @type {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement}
     */
    this.image_ = null;

    /**
     * @private
     * @type {number|undefined}
     */
    this.anchorX_ = undefined;

    /**
     * @private
     * @type {number|undefined}
     */
    this.anchorY_ = undefined;

    /**
     * @private
     * @type {number|undefined}
     */
    this.height_ = undefined;

    /**
     * @private
     * @type {number|undefined}
     */
    this.opacity_ = undefined;

    /**
     * @private
     * @type {number|undefined}
     */
    this.originX_ = undefined;

    /**
     * @private
     * @type {number|undefined}
     */
    this.originY_ = undefined;

    /**
     * @private
     * @type {boolean|undefined}
     */
    this.rotateWithView_ = undefined;

    /**
     * @private
     * @type {number|undefined}
     */
    this.rotation_ = undefined;

    /**
     * @private
     * @type {number|undefined}
     */
    this.scale_ = undefined;

    /**
     * @private
     * @type {number|undefined}
     */
    this.width_ = undefined;

  }

  /**
   * @param {Array<number>} flatCoordinates Flat coordinates.
   * @param {number} offset Offset.
   * @param {number} end End.
   * @param {number} stride Stride.
   * @private
   * @return {number} My end.
   */
  drawCoordinates_(flatCoordinates, offset, end, stride) {
    return this.appendFlatCoordinates(flatCoordinates, offset, end, stride, false, false);
  }

  /**
   * @param {import("../../geom/Point.js").default|import("../Feature.js").default} pointGeometry Point geometry.
   * @param {import("../../Feature.js").FeatureLike} feature Feature.
   */
  drawPoint(pointGeometry, feature) {
    if (!this.image_) {
      return;
    }
    this.beginGeometry(pointGeometry, feature);
    const flatCoordinates = pointGeometry.getFlatCoordinates();
    const stride = pointGeometry.getStride();
    const myBegin = this.coordinates.length;
    const myEnd = this.drawCoordinates_(flatCoordinates, 0, flatCoordinates.length, stride);
    this.instructions.push([
      CanvasInstruction.DRAW_IMAGE, myBegin, myEnd, this.image_,
      // Remaining arguments to DRAW_IMAGE are in alphabetical order
      this.anchorX_, this.anchorY_, this.declutterGroups_, this.height_, this.opacity_,
      this.originX_, this.originY_, this.rotateWithView_, this.rotation_,
      this.scale_ * this.pixelRatio, this.width_
    ]);
    this.hitDetectionInstructions.push([
      CanvasInstruction.DRAW_IMAGE, myBegin, myEnd, this.hitDetectionImage_,
      // Remaining arguments to DRAW_IMAGE are in alphabetical order
      this.anchorX_, this.anchorY_, this.declutterGroups_, this.height_, this.opacity_,
      this.originX_, this.originY_, this.rotateWithView_, this.rotation_,
      this.scale_, this.width_
    ]);
    this.endGeometry(feature);
  }

  /**
   * @param {import("../../geom/MultiPoint.js").default|import("../Feature.js").default} multiPointGeometry MultiPoint geometry.
   * @param {import("../../Feature.js").FeatureLike} feature Feature.
   */
  drawMultiPoint(multiPointGeometry, feature) {
    if (!this.image_) {
      return;
    }
    this.beginGeometry(multiPointGeometry, feature);
    const flatCoordinates = multiPointGeometry.getFlatCoordinates();
    const stride = multiPointGeometry.getStride();
    const myBegin = this.coordinates.length;
    const myEnd = this.drawCoordinates_(
      flatCoordinates, 0, flatCoordinates.length, stride);
    this.instructions.push([
      CanvasInstruction.DRAW_IMAGE, myBegin, myEnd, this.image_,
      // Remaining arguments to DRAW_IMAGE are in alphabetical order
      this.anchorX_, this.anchorY_, this.declutterGroups_, this.height_, this.opacity_,
      this.originX_, this.originY_, this.rotateWithView_, this.rotation_,
      this.scale_ * this.pixelRatio, this.width_
    ]);
    this.hitDetectionInstructions.push([
      CanvasInstruction.DRAW_IMAGE, myBegin, myEnd, this.hitDetectionImage_,
      // Remaining arguments to DRAW_IMAGE are in alphabetical order
      this.anchorX_, this.anchorY_, this.declutterGroups_, this.height_, this.opacity_,
      this.originX_, this.originY_, this.rotateWithView_, this.rotation_,
      this.scale_, this.width_
    ]);
    this.endGeometry(feature);
  }

  /**
   * @return {import("./Builder.js").SerializableInstructions} the serializable instructions.
   */
  finish() {
    this.reverseHitDetectionInstructions();
    // FIXME this doesn't really protect us against further calls to draw*Geometry
    this.anchorX_ = undefined;
    this.anchorY_ = undefined;
    this.hitDetectionImage_ = null;
    this.image_ = null;
    this.height_ = undefined;
    this.scale_ = undefined;
    this.opacity_ = undefined;
    this.originX_ = undefined;
    this.originY_ = undefined;
    this.rotateWithView_ = undefined;
    this.rotation_ = undefined;
    this.width_ = undefined;
    return super.finish();
  }

  /**
   * @param {import("../../style/Image.js").default} imageStyle Image style.
   * @param {import("../canvas.js").DeclutterGroup} declutterGroups Declutter.
   */
  setImageStyle(imageStyle, declutterGroups) {
    const anchor = imageStyle.getAnchor();
    const size = imageStyle.getSize();
    const hitDetectionImage = imageStyle.getHitDetectionImage(1);
    const image = imageStyle.getImage(1);
    const origin = imageStyle.getOrigin();
    this.anchorX_ = anchor[0];
    this.anchorY_ = anchor[1];
    this.declutterGroups_ = declutterGroups;
    this.hitDetectionImage_ = hitDetectionImage;
    this.image_ = image;
    this.height_ = size[1];
    this.opacity_ = imageStyle.getOpacity();
    this.originX_ = origin[0];
    this.originY_ = origin[1];
    this.rotateWithView_ = imageStyle.getRotateWithView();
    this.rotation_ = imageStyle.getRotation();
    this.scale_ = imageStyle.getScale();
    this.width_ = size[0];
  }
}

export default CanvasImageBuilder;


text:
using NUnit.Framework;

namespace PeanutButter.Utils.Tests
{
    [TestFixture]
    public class TestExpressionHelper
    {
        public class SomeThing
        {
            public string StringProperty { get; set; }
            public SomeThing Child { get; set; }
        }

        [Test]
        public void GetMemberPathFor_ShouldReturnPathToImmediateMemberFromExpression()
        {
            //---------------Set up test pack-------------------
            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var result = ExpressionUtil.GetMemberPathFor<SomeThing>(o => o.StringProperty);

            //---------------Test Result -----------------------
            Assert.AreEqual("StringProperty", result);
        }

        [Test]
        public void GetMemberPathFor_ShouldBeAbleToResolveChildPaths()
        {
            //---------------Set up test pack-------------------

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var result = ExpressionUtil.GetMemberPathFor<SomeThing>(o => o.Child.StringProperty);

            //---------------Test Result -----------------------
            Assert.AreEqual("Child.StringProperty", result);
        }

        [Test]
        public void GetPropertyTypeFor_ShouldReturnTypeOfPropertyReferencedByExpression()
        {
            //---------------Set up test pack-------------------

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var result = ExpressionUtil.GetPropertyTypeFor<SomeThing>(o => o.StringProperty);

            //---------------Test Result -----------------------
            Assert.AreEqual(typeof(string), result);
        }

    }
}


text:
// search nearby places, in this project we just select parking places in 2000 radius
function searchPlaces() {
    // info window for search places
    infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);
    service.nearbySearch({
        location: new google.maps.LatLng(combo.options[combo.selectedIndex].latitude, combo.options[combo.selectedIndex].longitude),
        radius: 2000,
        type: ['parking']
    }, callback);
}

function callback(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
        if (document.getElementById('TravelMode').value === 'TRANSIT' || document.getElementById('TravelMode').value === 'WALKING'){
            for (var i = 0; i < parkMarker.length; i++){
                parkMarker[i].setMap(null);
            }
            parkMarker.length=0;
        }
        else{
            for (var j = 0; j < results.length; j++) {
                createMarker(results[j]);
            }
        }
    }
}

function createMarker(place) {
    var placeLoc = place.geometry.location;
    var img ={
        url:"https://www.clipartmax.com/png/middle/283-2830878_x-parking-comments-parking-icon-vector-png.png",
        scaledSize: new google.maps.Size(30,30)
    };
    var markerOptions = {
        position: placeLoc,
        map: map,
        icon: img
    };
    var markers = new google.maps.Marker(markerOptions);

    // create info window for nearby parking
    google.maps.event.addListener(markers, 'click', function() {
        infowindow.setContent("Parking Name: " + place.name);
        infowindow.open(map, this);
    });
    parkMarker.push(markers)
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface com.thinkaurelius.titan.core.Idfiable (Titan 1.0.0 API)</title>
<meta name="date" content="2015-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.thinkaurelius.titan.core.Idfiable

Packages that use Idfiable

Package
Description

com.thinkaurelius.titan.core

com.thinkaurelius.titan.graphdb.internal

com.thinkaurelius.titan.graphdb.olap.computer

com.thinkaurelius.titan.graphdb.relations

com.thinkaurelius.titan.graphdb.types

com.thinkaurelius.titan.graphdb.types.system

com.thinkaurelius.titan.graphdb.types.vertices

com.thinkaurelius.titan.graphdb.vertices

Uses of Idfiable in com.thinkaurelius.titan.core

Subinterfaces of Idfiable in com.thinkaurelius.titan.core

Modifier and Type
Interface and Description

interface
EdgeLabel

EdgeLabel is an extension of RelationType for edges.

interface
PropertyKey

PropertyKey is an extension of RelationType for properties.

interface
RelationType

RelationType defines the schema for TitanRelation.

interface
TitanEdge

A TitanEdge connects two TitanVertex.

interface
TitanElement

TitanElement represents the abstract concept of an entity in the graph and specifies basic methods for interacting
 with entities.

interface
TitanRelation

TitanRelation is the most abstract form of a relation between a vertex and some other entity, where
 relation is understood in its mathematical sense.

interface
TitanVertex

TitanVertex is the basic unit of a TitanGraph.

interface
TitanVertexProperty<V>

TitanProperty is a TitanRelation connecting a vertex to a value.

interface
VertexLabel

A vertex label is a label attached to vertices in a Titan graph.

Uses of Idfiable in com.thinkaurelius.titan.graphdb.internal

Subinterfaces of Idfiable in com.thinkaurelius.titan.graphdb.internal

Modifier and Type
Interface and Description

interface
InternalElement

Internal Element interface adding methods that should only be used by Titan

interface
InternalRelation

Internal Relation interface adding methods that should only be used by Titan.

interface
InternalRelationType

Internal Type interface adding methods that should only be used by Titan

interface
InternalVertex

Internal Vertex interface adding methods that should only be used by Titan

interface
InternalVertexLabel

Classes in com.thinkaurelius.titan.graphdb.internal that implement Idfiable

Modifier and Type
Class and Description

class
AbstractElement

AbstractElement is the base class for all elements in Titan.

Uses of Idfiable in com.thinkaurelius.titan.graphdb.olap.computer

Classes in com.thinkaurelius.titan.graphdb.olap.computer that implement Idfiable

Modifier and Type
Class and Description

class
FulgoraVertexProperty<V>

Uses of Idfiable in com.thinkaurelius.titan.graphdb.relations

Subinterfaces of Idfiable in com.thinkaurelius.titan.graphdb.relations

Modifier and Type
Interface and Description

interface
StandardRelation

Classes in com.thinkaurelius.titan.graphdb.relations that implement Idfiable

Modifier and Type
Class and Description

class
AbstractEdge

class
AbstractTypedRelation

class
AbstractVertexProperty<V>

class
CacheEdge

class
CacheVertexProperty

class
StandardEdge

class
StandardVertexProperty

Uses of Idfiable in com.thinkaurelius.titan.graphdb.types

Classes in com.thinkaurelius.titan.graphdb.types that implement Idfiable

Modifier and Type
Class and Description

class
VertexLabelVertex

Uses of Idfiable in com.thinkaurelius.titan.graphdb.types.system

Subinterfaces of Idfiable in com.thinkaurelius.titan.graphdb.types.system

Modifier and Type
Interface and Description

interface
SystemRelationType

Classes in com.thinkaurelius.titan.graphdb.types.system that implement Idfiable

Modifier and Type
Class and Description

class
BaseKey

class
BaseLabel

class
BaseRelationType

class
BaseVertexLabel

class
EmptyRelationType

class
EmptyVertex

class
ImplicitKey

Uses of Idfiable in com.thinkaurelius.titan.graphdb.types.vertices

Classes in com.thinkaurelius.titan.graphdb.types.vertices that implement Idfiable

Modifier and Type
Class and Description

class
EdgeLabelVertex

class
PropertyKeyVertex

class
RelationTypeVertex

class
TitanSchemaVertex

Uses of Idfiable in com.thinkaurelius.titan.graphdb.vertices

Classes in com.thinkaurelius.titan.graphdb.vertices that implement Idfiable

Modifier and Type
Class and Description

class
AbstractVertex

class
CacheVertex

class
PreloadedVertex

class
StandardVertex

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2012–2015. All rights reserved.


text:
import path from 'node:path';
import fs from 'node:fs';
import http from 'node:http';
import {fileURLToPath} from 'node:url';
import cookie from 'cookie';
import getPort from 'get-port';
import pify from 'pify';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export const host = 'localhost';

export type TestServer = {
	host: string;
	port: number;
	url: string;
	protocol: string;
} & http.Server;

const baseCreateServer = (fn: http.RequestListener): (() => Promise<TestServer>) => async (): Promise<TestServer> => {
	const port = await getPort();
	const server = http.createServer(fn) as unknown as TestServer;

	server.host = host;
	server.port = port;
	server.url = `http://${host}:${port}`;
	server.protocol = 'http';
	server.listen(port);
	// @ts-expect-error - The `pify` types are not strict.
	server.close = pify(server.close) as typeof server.close;

	return server;
};

export const createServer = baseCreateServer((_request, response) => {
	response.writeHead(200, {'content-type': 'text/html'});
	response.end(fs.readFileSync(path.join(__dirname, 'fixture.html'), 'utf8'));
});

export const createCookieServer = baseCreateServer((request, response) => {
	const color = cookie.parse(String(request.headers.cookie)).pageresColor ?? 'white';
	response.writeHead(200, {'content-type': 'text/html'});
	response.end(`<body><div style="background: ${color}; position: absolute; top: 0; bottom: 0; left: 0; right: 0;"></div></body`);
});