text:
<?php

namespace Xelbot\TestBundle\Features\Context;

use Behat\Behat\Context\Context;
use Behat\MinkExtension\Context\MinkContext;

/**
 * Defines application features from the specific context.
 */
class FeatureContext extends MinkContext implements Context
{
    /**
     * Initializes context.
     *
     * Every scenario gets its own context instance.
     * You can also pass arbitrary arguments to the
     * context constructor through behat.yml.
     */
    public function __construct()
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
module WebDriver
  module SpecSupport
    module Helpers

      def driver
        GlobalTestEnv.driver_instance
      end

      def url_for(filename)
        GlobalTestEnv.url_for filename
      end

      def fix_windows_path(path)
        return path unless WebDriver::Platform.os == :windows

        if GlobalTestEnv.browser == :ie
          path = path[%r[file://(.*)], 1]
          path.gsub!("/", '\\')

          "file://#{path}"
        else
          path.sub(%r[file:/{0,2}], "file:///")
        end
      end

    end # Helpers
  end # SpecSupport
end # WebDriver


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

  angular.module('gradebookApp')
    .config(function($mdThemingProvider) {
      $mdThemingProvider.theme('default')
        .primaryPalette('blue')
        .accentPalette('orange');
    });
})();


text:
package gnu.java.lang.reflect;

import java.lang.reflect.GenericSignatureFormatError;
import java.lang.reflect.Type;

public final class FieldSignatureParser extends GenericSignatureParser
{
    private Type type;

    public FieldSignatureParser(Class container, String signature)
    {
        super(container, container.getClassLoader(), signature);

        switch (peekChar())
        {
            case 'L':
            case '[':
            case 'T':
                type = readFieldTypeSignature();
                break;
            case 'Z':
                consume('Z');
                type = boolean.class;
                break;
            case 'B':
                consume('B');
                type = byte.class;
                break;
            case 'S':
                consume('S');
                type = short.class;
                break;
            case 'C':
                consume('C');
                type = char.class;
                break;
            case 'I':
                consume('I');
                type = int.class;
                break;
            case 'F':
                consume('F');
                type = float.class;
                break;
            case 'J':
                consume('J');
                type = long.class;
                break;
            case 'D':
                consume('D');
                type = double.class;
                break;
            default:
                throw new GenericSignatureFormatError();
        }

        end();
    }

    public Type getFieldType()
    {
        type = TypeImpl.resolve(type);
        return type;
    }
}


text:
class AddEmptyToCategories < ActiveRecord::Migration[5.1]
  def change
    add_column :categories, :empty, :boolean, default: false
  end
end


text:
package main

import _ "github.com/benesch/cgosymbolizer"


text:
package v1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// Etcd provides information to configure an operator to manage kube-apiserver.
type Etcd struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata"`

	// +required
	Spec   EtcdSpec   `json:"spec"`
	// +optional
	Status EtcdStatus `json:"status"`
}

type EtcdSpec struct {
	StaticPodOperatorSpec `json:",inline"`

	// forceRedeploymentReason can be used to force the redeployment of the kube-apiserver by providing a unique string.
	// This provides a mechanism to kick a previously failed deployment and provide a reason why you think it will work
	// this time instead of failing again on the same config.
	ForceRedeploymentReason string `json:"forceRedeploymentReason"`
}

type EtcdStatus struct {
	StaticPodOperatorStatus `json:",inline"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// KubeAPISOperatorConfigList is a collection of items
type EtcdList struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	metav1.ListMeta `json:"metadata"`
	// Items contains the items
	Items []Etcd `json:"items"`
}


text:
.. Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.

.. include:: ../../common.defs

.. _admin-plugins-healthchecks:

Health Checks Plugin
********************

This is a simple plugin, to provide basic (but configurable) health checks.
This is a server intercept plugin, and it takes one single configuration
option in plugin.config, the configuration file name.

Configuration
=============

To enable the healthchecks plugin, insert the following line in
:file:`plugin.config`::

    healthchecks.so <healthcheck-configuration-file>

The required ``<healthcheck-configuration-file>`` may reference either an
absolute or relative path to the file containing the healthcheck configuration.

This configuration may contain one or more lines of the format::

   <URI-path> <file-path> <mime> <file-exists-code> <file-missing-code>

.. note:: The ``URI-path`` can *not* be "/" only.

.. note:: This configuration is *not* reloadable.

The content of the file specified in the ``file-path``, if any, is sent as the
body of the response. The existence of the file is sufficient to get an "OK"
status.  Performance wise, everything is served out of memory, and it only
stats / opens files as necessary. However, the content of the status file is
limited to 16KB, so this is not a generic static file serving plugin.

Example
=======

This line would define a health check link available at
http://www.example.com/__hc that would check if the file
``/var/run/ts-alive`` existed on the server.  If the file exists,
a response is built with the contents of the ``ts-alive`` file, a mime
type of ``text/plain`` and a status code of ``200``.  If the file does not
exist, a ``403`` response is sent::

   /__hc  /var/run/ts-alive  text/plain 200  403


text:
package API::DeliveryServiceServer;
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#

# JvD Note: you always want to put Utils as the first use. Sh*t don't work if it's after the Mojo lines.
use UI::Utils;
use Mojo::Base 'Mojolicious::Controller';
use Data::Dumper;
use Utils::Helper;

sub index {
	my $self = shift;
	my @data;
	my $orderby = $self->param('orderby') || "deliveryservice";

	# defaulted pagination and limits because there are 38129 rows in this table and counting...
	my $page  = $self->param('page')  || 1;
	my $limit = $self->param('limit') || 20;
	my $rs_data = $self->db->resultset("DeliveryserviceServer")->search( undef, { page => $page, rows => $limit, order_by => $orderby } );
	while ( my $row = $rs_data->next ) {
		push(
			@data, {
				"deliveryService" => $row->deliveryservice->id,
				"server"          => $row->server->id,
				"lastUpdated"     => $row->last_updated,
			}
		);
	}
	$self->success( \@data, undef, $orderby, $limit, $page );
}

sub domains {
	my $self = shift;
	my @data;

	my @ccrprofs = $self->db->resultset('Profile')->search( { name => { -like => 'CCR%' } } )->get_column('id')->all();
	my $rs_pp =
		$self->db->resultset('ProfileParameter')
		->search( { profile => { -in => \@ccrprofs }, 'parameter.name' => 'domain_name', 'parameter.config_file' => 'CRConfig.json' },
		{ prefetch => [ 'parameter', 'profile' ] } );
	while ( my $row = $rs_pp->next ) {
		push(
			@data, {
				"domainName"         => $row->parameter->value,
				"parameterId"        => $row->parameter->id,
				"profileId"          => $row->profile->id,
				"profileName"        => $row->profile->name,
				"profileDescription" => $row->profile->description,
			}
		);

	}
	$self->success( \@data );
}

sub assign_ds_to_cachegroup {
	my $self   = shift;
	my $cg_id  = $self->param('id');
	my $params = $self->req->json;

	if ( !&is_oper($self) ) {
		return $self->forbidden();
	}

	my $cachegroup = $self->db->resultset('Cachegroup')->search( { id => $cg_id } )->single();
	if ( !defined($cachegroup) ) {
		return $self->not_found();
	}

	if ( ($cachegroup->type->name ne "EDGE_LOC") and ($cachegroup->type->name ne "ORG_LOC") ) {
		return $self->alert("cachegroup should be type EDGE_LOC or ORG_LOC.");
	}

	if ( !defined($params) ) {
		return $self->alert("parameters should in json format.");
	}

	if ( !defined($params->{deliveryServices}) ) {
		return $self->alert("parameter deliveryServices is must.");
	}

	if ( ref($params->{deliveryServices}) ne 'ARRAY' ) {
		return $self->alert("parameter deliveryServices must be array.");
	}

	my $cdn = "";
	my $servers = $self->db->resultset('Server')->search(
		{
			cachegroup => $cg_id,
			'type.name' => { -in => ['EDGE', 'ORG'] }
		},
		{ prefetch => ['type'] }
	);
	while ( my $server = $servers->next ) {
		if ($cdn eq "") {
			$cdn = $server->cdn_id;
		} elsif ($cdn ne $server->cdn_id) {
			return $self->alert("servers do not belong to same cdn.");
		}
	}

	my $deliveryservice_IDs = "";
	foreach my $ds_id (@{ $params->{deliveryServices} }) {
		my $ds = $self->db->resultset('Deliveryservice')->find( { id => $ds_id } );
		if ( !defined($ds) ) {
			return $self->alert("deliveryservice with id $ds_id does not existed");
		}
		if ($cdn eq "") {
			$cdn = $ds->cdn_id;
		} elsif ($cdn ne $ds->cdn_id) {
			return $self->alert("servers/deliveryservices do not belong to same cdn.");
		}
		$deliveryservice_IDs = $deliveryservice_IDs . " " .  $ds_id;
	}

	$servers = $self->db->resultset('Server')->search(
		{
			cachegroup => $cg_id,
			'type.name' => { -in => ['EDGE', 'ORG'] }
		},
		{ prefetch => ['type'] }
	);

	my @server_names = ();
	while ( my $server = $servers->next ) {
		push(@server_names, $server->host_name);
		foreach my $ds_id (@{ $params->{deliveryServices} }) {
			my $find = $self->db->resultset('DeliveryserviceServer')->find(
				{
					deliveryservice => $ds_id,
					server          => $server->id
				}
			);

			if (!defined($find)) {
				my $insert = $self->db->resultset('DeliveryserviceServer')->create(
					{
						deliveryservice => $ds_id,
						server          => $server->id
					}
				);
				$insert->insert();

				if ($server->type->name eq 'EDGE') {
					my $ds = $self->db->resultset('Deliveryservice')->search( { id => $ds_id } )->single();
					&UI::DeliveryService::header_rewrite( $self, $ds->id, $ds->profile, $ds->xml_id, $ds->edge_header_rewrite, "edge" );
					&UI::DeliveryService::regex_remap( $self, $ds->id, $ds->profile, $ds->xml_id, $ds->regex_remap );
					&UI::DeliveryService::cacheurl( $self, $ds->id, $ds->profile, $ds->xml_id, $ds->cacheurl );
				}
				$self->app->log->info("assign server " . $server->id . " to ds " . $ds_id);
			}
		}
	}

	&log( $self, "assign servers in cache group $cg_id to deliveryservices $deliveryservice_IDs", "APICHANGE" );

	my $response;
	$response->{id} = $cg_id;
	$response->{serverNames} = \@server_names;
	$response->{deliveryServices} = $params->{deliveryServices};
	$self->success( $response, "Delivery services successfully assigned to all the servers of cache group $cg_id" );
}

1;


text:
#ifndef DIAG_DCI_H
#define DIAG_DCI_H

#define MAX_DCI_CLIENTS		10
#define DCI_PKT_RSP_CODE	0x93
#define DCI_DELAYED_RSP_CODE	0x94
#define DCI_CONTROL_PKT_CODE	0x9A
#define LOG_CMD_CODE		0x10
#define EVENT_CMD_CODE		0x60
#define DCI_PKT_RSP_TYPE	0
#define DCI_LOG_TYPE		-1
#define DCI_EVENT_TYPE		-2
#define SET_LOG_MASK		1
#define DISABLE_LOG_MASK	0
#define MAX_EVENT_SIZE		512
#define DCI_CLIENT_INDEX_INVALID -1
#define DCI_PKT_REQ_MIN_LEN		9
#define DCI_LOG_CON_MIN_LEN		14
#define DCI_EVENT_CON_MIN_LEN		16

#define DIAG_DATA_TYPE		1
#define DIAG_CNTL_TYPE		2

#define DCI_BUF_PRIMARY		1
#define DCI_BUF_SECONDARY	2
#define DCI_BUF_CMD		3

#ifdef CONFIG_DEBUG_FS
#define DIAG_DCI_DEBUG_CNT	100
#define DIAG_DCI_DEBUG_LEN	100
#endif

/* 16 log code categories, each has:
 * 1 bytes equip id + 1 dirty byte + 512 byte max log mask
 */
#define DCI_LOG_MASK_SIZE		(16*514)
#define DCI_EVENT_MASK_SIZE		512
#define DCI_MASK_STREAM			2
#define DCI_MAX_LOG_CODES		16
#define DCI_MAX_ITEMS_PER_LOG_CODE	512

#define DCI_LOG_MASK_CLEAN		0
#define DCI_LOG_MASK_DIRTY		1

#define MIN_DELAYED_RSP_LEN		12
/*
 * Maximum data size that peripherals send = 8.5K log +
 * DCI header + footer (6 bytes)
 */
#define MAX_DCI_PACKET_SZ		8710

#define DCI_LOCAL_PROC	0
#define DCI_REMOTE_BASE 1
#define DCI_MDM_PROC	DCI_REMOTE_BASE
#define DCI_REMOTE_LAST (DCI_REMOTE_BASE + 1)
#ifndef CONFIG_DIAGFWD_BRIDGE_CODE
#define NUM_DCI_PROC 1
#else
#define NUM_DCI_PROC DCI_REMOTE_LAST
#endif

#define DCI_BRIDGE_MDM_IDX	1
#define DCI_HSIC_CH_IDX		0

#define DCI_REMOTE_DATA	0

extern unsigned int dci_max_reg;
extern unsigned int dci_max_clients;

struct dci_pkt_req_entry_t {
	int client_id;
	int uid;
	int tag;
	struct list_head track;
} __packed;

struct diag_dci_reg_tbl_t {
	int client_id;
	uint16_t notification_list;
	int signal_type;
	int token;
} __packed;

struct diag_dci_health_t {
	int dropped_logs;
	int dropped_events;
	int received_logs;
	int received_events;
};

struct diag_dci_partial_pkt_t {
	unsigned char *data;
	uint32_t total_len;
	uint32_t read_len;
	uint32_t remaining;
	uint8_t processing;
} __packed;

struct diag_dci_buffer_t {
	unsigned char *data;
	unsigned int data_len;
	struct mutex data_mutex;
	uint8_t in_busy;
	uint8_t buf_type;
	int data_source;
	int capacity;
	uint8_t in_list;
	struct list_head buf_track;
};

struct diag_dci_buf_peripheral_t {
	struct diag_dci_buffer_t *buf_curr;
	struct diag_dci_buffer_t *buf_primary;
	struct diag_dci_buffer_t *buf_cmd;
	struct diag_dci_health_t health;
	struct mutex health_mutex;
	struct mutex buf_mutex;
};

struct diag_dci_client_tbl {
	struct diag_dci_reg_tbl_t client_info;
	struct task_struct *client;
	unsigned char *dci_log_mask;
	unsigned char *dci_event_mask;
	uint8_t real_time;
	struct list_head track;
	struct diag_dci_buf_peripheral_t *buffers;
	uint8_t num_buffers;
	uint8_t in_service;
	struct list_head list_write_buf;
	struct mutex write_buf_mutex;
};

struct diag_dci_health_stats {
	struct diag_dci_health_t stats;
	int reset_status;
};

struct diag_dci_health_stats_proc {
	int client_id;
	struct diag_dci_health_stats health;
	int proc;
} __packed;

struct diag_dci_peripherals_t {
	int proc;
	uint16_t list;
} __packed;

/* This is used for querying DCI Log
   or Event Mask */
struct diag_log_event_stats {
	int client_id;
	uint16_t code;
	int is_set;
} __packed;

struct diag_dci_pkt_header_t {
	uint8_t start;
	uint8_t version;
	uint16_t len;
	uint8_t pkt_code;
	int tag;
} __packed;

struct diag_dci_header_t {
	uint8_t start;
	uint8_t version;
	uint16_t length;
	uint8_t cmd_code;
} __packed;

struct dci_ops_tbl_t {
	unsigned char log_mask_composite[DCI_LOG_MASK_SIZE];
	unsigned char event_mask_composite[DCI_EVENT_MASK_SIZE];
	int (*send_log_mask)(int token);
	int (*send_event_mask)(int token);
	uint16_t peripheral_status;
} __packed;

extern struct dci_ops_tbl_t *dci_ops_tbl;

enum {
	DIAG_DCI_NO_ERROR = 1001,	/* No error */
	DIAG_DCI_NO_REG,		/* Could not register */
	DIAG_DCI_NO_MEM,		/* Failed memory allocation */
	DIAG_DCI_NOT_SUPPORTED,	/* This particular client is not supported */
	DIAG_DCI_HUGE_PACKET,	/* Request/Response Packet too huge */
	DIAG_DCI_SEND_DATA_FAIL,/* writing to kernel or peripheral fails */
	DIAG_DCI_TABLE_ERR	/* Error dealing with registration tables */
};

#ifdef CONFIG_DEBUG_FS
/* To collect debug information during each smd read */
struct diag_dci_data_info {
	unsigned long iteration;
	int data_size;
	char time_stamp[DIAG_TS_SIZE];
	uint8_t peripheral;
	uint8_t ch_type;
	uint8_t proc;
};

extern struct diag_dci_data_info *dci_traffic;
extern struct mutex dci_stat_mutex;
#endif

int diag_dci_init(void);
void diag_dci_exit(void);
int diag_dci_register_client(struct diag_dci_reg_tbl_t *reg_entry);
int diag_dci_deinit_client(struct diag_dci_client_tbl *entry);
void diag_update_smd_dci_work_fn(struct work_struct *);
void diag_dci_notify_client(int peripheral_mask, int data, int proc);
void diag_dci_wakeup_clients(void);
void diag_process_apps_dci_read_data(int data_type, void *buf, int recd_bytes);
int diag_process_smd_dci_read_data(struct diag_smd_info *smd_info, void *buf,
								int recd_bytes);
int diag_process_dci_transaction(unsigned char *buf, int len);
void extract_dci_pkt_rsp(unsigned char *buf, int len, int data_source,
			 int token);
void extract_dci_ctrl_pkt(unsigned char *buf, int len, int token);
struct diag_dci_client_tbl *diag_dci_get_client_entry(int client_id);
struct diag_dci_client_tbl *dci_lookup_client_entry_pid(int pid);
int diag_process_hsic_dci_read_data(int index, void *buf, int recd_bytes);
int diag_dci_get_support_list(struct diag_dci_peripherals_t *support_list);
/* DCI Log streaming functions */
void update_dci_cumulative_log_mask(int offset, unsigned int byte_index,
						uint8_t byte_mask, int token);
void diag_dci_invalidate_cumulative_log_mask(int token);
int diag_send_dci_log_mask(int token);
void extract_dci_log(unsigned char *buf, int len, int data_source, int token);
int diag_dci_clear_log_mask(int client_id);
int diag_dci_query_log_mask(struct diag_dci_client_tbl *entry,
			    uint16_t log_code);
/* DCI event streaming functions */
void update_dci_cumulative_event_mask(int offset, uint8_t byte_mask, int token);
void diag_dci_invalidate_cumulative_event_mask(int token);
int diag_send_dci_event_mask(int token);
void extract_dci_events(unsigned char *buf, int len, int data_source,
			int token);
int diag_dci_clear_event_mask(int client_id);
int diag_dci_query_event_mask(struct diag_dci_client_tbl *entry,
			      uint16_t event_id);
void diag_dci_record_traffic(int read_bytes, uint8_t ch_type,
			     uint8_t peripheral, uint8_t proc);
uint8_t diag_dci_get_cumulative_real_time(int token);
int diag_dci_set_real_time(struct diag_dci_client_tbl *entry,
			   uint8_t real_time);
int diag_dci_copy_health_stats(struct diag_dci_health_stats_proc *stats_proc);
int diag_dci_write_proc(int peripheral, int pkt_type, char *buf, int len);

#ifdef CONFIG_DIAGFWD_BRIDGE_CODE
int diag_send_dci_log_mask_remote(int token);
int diag_send_dci_event_mask_remote(int token);
unsigned char *dci_get_buffer_from_bridge(int index);
int diag_dci_write_bridge(int index, unsigned char *buf, int len);
#endif

#endif


text:
package com.mobapphome.appcrosspromoter.sample;

/**
 * Created by settar on 6/30/17.
 */

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.mobapphome.appcrosspromoter.ACPController;
import com.mobapphome.appcrosspromoter.ACPDlgExit;
import com.mobapphome.appcrosspromoter.tools.Constants;

import java.util.ArrayList;
import java.util.Arrays;

public class SampleActivityJava extends AppCompatActivity implements ACPDlgExit.ACPDlgExitListener, View.OnClickListener, AdapterView.OnItemSelectedListener {

    final public static String LOG_TAG_MAH_ADS_SAMPLE = "mah_ads_sample_log";
    ACPController ACPController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //This block is only in Java sample---------------
        {
            findViewById(R.id.mahBtnOpenJavaSample).setVisibility(View.GONE);
            setTitle(getString(R.string.title_java_sample));
        }

        ImageView imageView = (ImageView) findViewById(R.id.ivForkMeOnGithub);
        Drawable forkMeImg = getResources().getDrawable(R.drawable.forkme_green);
        // setting the opacity (alpha)
        forkMeImg.setAlpha(180);
        // setting the images on the ImageViews
        imageView.setImageDrawable(forkMeImg);

        imageView.setOnClickListener(this);
        findViewById(R.id.btnProgramsDlgTest).setOnClickListener(this);
        findViewById(R.id.btnExitDlgTest).setOnClickListener(this);

        ((TextView) findViewById(R.id.tvMAHAdsLibGithubUrl)).setMovementMethod(LinkMovementMethod.getInstance());
        ((TextView) findViewById(R.id.tvMAHAdsLibJCenterURL)).setMovementMethod(LinkMovementMethod.getInstance());
        ((TextView) findViewById(R.id.tvMAHAdsLibContrubute)).setMovementMethod(LinkMovementMethod.getInstance());

        String[] langsArray = new String[]{
                "Azerbaijani",
                "English",
                "French",
                "German",
                "Hindi",
                "Italian",
                "Portuguese",
                "Russian",
                "Spanish",
                "Turkish"};

        Spinner langSpinner = (Spinner) findViewById(R.id.langSpinner);
        ArrayAdapter adapter = new ArrayAdapter<CharSequence>(
                this,
                android.R.layout.simple_spinner_item,
                new ArrayList<CharSequence>(Arrays.asList(langsArray)));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        langSpinner.setAdapter(adapter);

        //Setting local.
        LocaleHelper.onCreate(this, "en");
        String currentLang = LocaleHelper.getLanguage(this);
        if (currentLang.equals("az")) {
            currentLang = "azerbaijani";
        } else if (currentLang.equals("en")) {
            currentLang = "english";
        } else if (currentLang.equals("fr")) {
            currentLang = "french";
        } else if (currentLang.equals("de")) {
            currentLang = "german";
        } else if (currentLang.equals("hi")) {
            currentLang = "hindi";
        } else if (currentLang.equals("it")) {
            currentLang = "italian";
        } else if (currentLang.equals("pt")) {
            currentLang = "portuguese";
        } else if (currentLang.equals("ru")) {
            currentLang = "russian";
        } else if (currentLang.equals("es")) {
            currentLang = "spanish";
        } else if (currentLang.equals("tr")) {
            currentLang = "turkey";
        }

        //Setting spinner to right language
        for (int i = 0; i < langsArray.length; i++) {
            if (langsArray[i].toLowerCase().startsWith(currentLang)) {
                langSpinner.setSelection(i);
            }

        }
        langSpinner.setOnItemSelectedListener(this);

        // For MAHAds init
        // METHOD 1
        ACPController = ACPController.getInstance();
        ACPController.init(this, savedInstanceState, "https://project-943403214286171762.firebaseapp.com/mah_ads_dir/",
                "github_apps_prg_version.json", "github_apps_prg_list.json");
        // METHOD 1
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        ACPController.onSaveInstanceState(outState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        } else if (id == R.id.action_mahads) {
            // For MAHAds programs dialog
            //METHOD 3
            ACPController.callProgramsDialog(this);
            //METHOD 3
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //Click method for buttons
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btnProgramsDlgTest) {
            // For MAHAds programs dialog
            //METHOD 3
            ACPController.callProgramsDialog(this);
            //METHOD 3
        } else if (view.getId() == R.id.btnExitDlgTest) {
            // For MAHAds exit
            //METHOD 2
            ACPController.callExitDialog(this);
            //METHOD 2
        } else if (view.getId() == R.id.ivForkMeOnGithub) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.MAH_ADS_GITHUB_LINK));
            startActivity(browserIntent);
        }
    }

    //Yes call back from Exit dialog for yes button
    @Override
    public void onYes() {

    }

    //Yes call back from Exit dialog for no button
    @Override
    public void onNo() {

    }

    //Yes call back from Exit dialog for onExitWithoutExitDlg
    @Override
    public void onExitWithoutExitDlg() {
        //Don't call here onBackPresses(). It will go to loop
        finish();
    }

    @Override
    public void onEventHappened(String eventStr) {
        Log.i(LOG_TAG_MAH_ADS_SAMPLE, eventStr);
    }

    //Selection event for language spinner
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        String item = parent.getItemAtPosition(pos).toString();

        // Showing selected spinner item
        Toast.makeText(parent.getContext(), "Selected: " + item + " id:" + id, Toast.LENGTH_LONG).show();
        if (item.toLowerCase().startsWith("azerbaijani")) {
            LocaleHelper.setLocale(this, "az");
        } else if (item.toLowerCase().startsWith("english")) {
            LocaleHelper.setLocale(this, "en");
        } else if (item.toLowerCase().startsWith("french")) {
            LocaleHelper.setLocale(this, "fr");
        } else if (item.toLowerCase().startsWith("german")) {
            LocaleHelper.setLocale(this, "de");
        } else if (item.toLowerCase().startsWith("hindi")) {
            LocaleHelper.setLocale(this, "hi");
        } else if (item.toLowerCase().startsWith("italian")) {
            LocaleHelper.setLocale(this, "it");
        } else if (item.toLowerCase().startsWith("portuguese")) {
            LocaleHelper.setLocale(this, "pt");
        } else if (item.toLowerCase().startsWith("russian")) {
            LocaleHelper.setLocale(this, "ru");
        } else if (item.toLowerCase().startsWith("spanish")) {
            LocaleHelper.setLocale(this, "es");
        } else if (item.toLowerCase().startsWith("turkish")) {
            LocaleHelper.setLocale(this, "tr");
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    public void onBackPressed() {
        // For MAHAds exit
        //METHOD 2
        ACPController.callExitDialog(this);
        //METHOD 2
    }
}


text:
require "thor"
require "optparse"
require "nokogiri"
require "xdg"
require "debugger"
require "erb"
require "singleton"
require "builder"  # XML Builder, not our builder
require "pathname"
require "tmpdir"
require "rbconfig"
require "kramdown"
require "fun_with_gems"
require "fun_with_templates"
require "fun_with_configurations"
require "fun_with_string_colors"
require "fun_with_patterns"
require "json"

FunWith::StringColors.activate
String.colorize( true )
FunWith::Patterns::GetAndSet.activate

FunWith::Gems.make_gem_fun( "EpubForge" )

EpubForge::CoreExtensions.install_extensions

module EpubForge
  GLOBAL_SETTINGS = EpubForge.root( "config", "settings" )
  USER_SETTINGS = XDG['CONFIG_HOME'].fwf_filepath( "epubforge" )
  DEBUG = false

  ACTIONS_DIR  = EpubForge.root.join( "config", "actions" )
  USER_ACTIONS_DIR  = USER_SETTINGS.join( "actions" )
  CONVERTERS_DIR = EpubForge.root.join( "config", "converters" )
  USER_CONVERTERS_DIR = USER_SETTINGS.join( "converters" )

  HTML_TRANSLATORS_DIR = EpubForge.root.join( "config", "html_translators" )
  USER_HTML_TRANSLATORS_DIR = USER_SETTINGS.join( "html_translators" )

  TEMPLATES_DIR  = EpubForge.root.join( "templates" )
  USER_GLOBALS_FILE = USER_SETTINGS.join( "globals.rb" )

  puts "Warning:  Cannot create user settings folder." unless USER_ACTIONS_DIR.touch_dir
  puts "Warning:  Cannot create globals file."         unless USER_GLOBALS_FILE.touch
end

EpubForge.install_fwc_config_from_file( EpubForge::USER_GLOBALS_FILE )

EpubForge.extend( EpubForge::CustomHelpers )

EpubForge::Action::Action2.loader_pattern_load_from_dir( EpubForge::ACTIONS_DIR, EpubForge::USER_ACTIONS_DIR )
EpubForge::Utils::Converter.loader_pattern_load_from_dir( EpubForge::CONVERTERS_DIR, EpubForge::USER_CONVERTERS_DIR )
EpubForge::Utils::HtmlTranslator.loader_pattern_load_from_dir( EpubForge::HTML_TRANSLATORS_DIR, EpubForge::USER_HTML_TRANSLATORS_DIR )

EpubForge::Fonts.install_fwc_config_from_file( EpubForge::GLOBAL_SETTINGS.join( "font_cache_config.rb" ) )


text:
__author__ = 'luke.beer'
import ConfigParser
import logging
import os

import host

log_file = os.path.dirname(__file__) + 'budweiser.log'
logging.basicConfig(filename=log_file, level=logging.DEBUG)

def create_hosts_from_conf(config_file='hosts.conf'):
    Config = ConfigParser.ConfigParser()
    Config.read(config_file)
    hosts = []
    for section in Config.sections():
        options = Config.options(section)
        x = host.Host(**options)
        hosts.append(x)
    return hosts


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

namespace Mastersign.Bench
{
    public class PathResolver : IGroupedValueResolver
    {
        public PropertyCriteria Selector { get; set; }

        public BasePathSource BasePathSource { get; set; }

        public PathResolver()
        {
        }

        public PathResolver(PropertyCriteria selector, BasePathSource basePathSource)
            : this()
        {
            Selector = selector;
            BasePathSource = basePathSource;
        }

        public object ResolveGroupValue(string group, string name, object value)
        {
            if (value == null) return null;
            if (Selector == null || !Selector(group, name)) return value;
            if (value is string[])
            {
                return Array.ConvertAll((string[])value, v => (string)ResolveGroupValue(group, name, v));
            }
            if (value is string)
            {
                var path = (string)value;
                if (!Path.IsPathRooted(path) && BasePathSource != null)
                {
                    value = Path.Combine(BasePathSource(group, name), path);
                }
            }
            return value;
        }
    }
}


text:
using Microsoft.Extensions.Logging;

namespace NetFusion.Base.Logging
{
    /// <summary>
    /// Interface implemented by a component responsible for changing the log level at runtime.
    /// </summary>
    public interface ILogLevelControl
    {
        /// <summary>
        /// Sets the minimum log level at runtime.
        /// </summary>
        /// <param name="logLevel">Log level.</param>
        /// <returns>The set log level.</returns>
        string SetMinimumLevel(LogLevel logLevel);
    }
}


text:
namespace grpc_core {

namespace promise_detail {

template <typename FMain, typename FPush, typename FPull>
class CallPushPull {
 public:
  CallPushPull(FMain f_main, FPush f_push, FPull f_pull)
      : push_(std::move(f_push)), pull_(std::move(f_pull)) {
    Construct(&main_, std::move(f_main));
  }

  CallPushPull(const CallPushPull&) = delete;
  CallPushPull& operator=(const CallPushPull&) = delete;
  CallPushPull(CallPushPull&& other) noexcept
      : done_(other.done_),
        push_(std::move(other.push_)),
        pull_(std::move(other.pull_)) {
    assert(!done_.is_set(kDoneMain));
    Construct(&main_, std::move(other.main_));
  }

  CallPushPull& operator=(CallPushPull&& other) noexcept {
    assert(!done_.is_set(kDoneMain));
    done_ = other.done_;
    assert(!done_.is_set(kDoneMain));
    push_ = std::move(other.push_);
    main_ = std::move(other.main_);
    pull_ = std::move(other.pull_);
    return *this;
  }

  ~CallPushPull() {
    if (done_.is_set(kDoneMain)) {
      Destruct(&result_);
    } else {
      Destruct(&main_);
    }
  }

  using Result =
      typename PollTraits<decltype(std::declval<PromiseLike<FMain>>()())>::Type;

  Poll<Result> operator()() {
    if (!done_.is_set(kDonePush)) {
      auto p = push_();
      if (auto* status = absl::get_if<kPollReadyIdx>(&p)) {
        if (IsStatusOk(*status)) {
          done_.set(kDonePush);
        } else {
          return Result(std::move(*status));
        }
      }
    }
    if (!done_.is_set(kDoneMain)) {
      auto p = main_();
      if (auto* status = absl::get_if<kPollReadyIdx>(&p)) {
        if (IsStatusOk(*status)) {
          done_.set(kDoneMain);
          Destruct(&main_);
          Construct(&result_, std::move(*status));
        } else {
          return std::move(*status);
        }
      }
    }
    if (!done_.is_set(kDonePull)) {
      auto p = pull_();
      if (auto* status = absl::get_if<kPollReadyIdx>(&p)) {
        if (IsStatusOk(*status)) {
          done_.set(kDonePull);
        } else {
          return Result(std::move(*status));
        }
      }
    }
    if (done_.all()) return std::move(result_);
    return Pending{};
  }

 private:
  enum { kDonePull = 0, kDoneMain = 1, kDonePush = 2 };
  BitSet<3> done_;
  GPR_NO_UNIQUE_ADDRESS PromiseLike<FPush> push_;
  union {
    PromiseLike<FMain> main_;
    Result result_;
  };
  GPR_NO_UNIQUE_ADDRESS PromiseLike<FPull> pull_;
};

}  // namespace promise_detail

// For promises representing calls a common pattern emerges:
// There's a process pushing data down the stack, a process handling the main
// call part, and a process pulling data back up the stack.
//
// This can reasonably be represented by the right combinations of TryJoins and
// Maps, but since the structure is fundamental to the domain we introduce
// this simple helper to make it easier to write the common case.
//
// It takes three promises: the main call, the push and the pull.
// When polling, the push is polled first, then the main call (descending the
// stack), then the pull (as we ascend once more).
//
// This strategy minimizes repolls.
template <typename FMain, typename FPush, typename FPull>
promise_detail::CallPushPull<FMain, FPush, FPull> CallPushPull(FMain f_main,
                                                               FPush f_push,
                                                               FPull f_pull) {
  return promise_detail::CallPushPull<FMain, FPush, FPull>(
      std::move(f_main), std::move(f_push), std::move(f_pull));
}

}  // namespace grpc_core

#endif  // GRPC_CORE_LIB_PROMISE_CALL_PUSH_PULL_H


text:
package main

import (
	"os"
	"path/filepath"

	"github.com/opencontainers/runtime-tools/validation/util"
)

func main() {
	g, err := util.GetDefaultGenerator()
	if err != nil {
		util.Fatal(err)
	}
	g.SetProcessCwd("/test")
	g.AddProcessEnv("testa", "valuea")
	g.AddProcessEnv("testb", "123")

	err = util.RuntimeInsideValidate(g, nil, func(path string) error {
		pathName := filepath.Join(path, "test")
		return os.MkdirAll(pathName, 0700)
	})
	if err != nil {
		util.Fatal(err)
	}
}


text:
---
layout: post
title: "Migrate from google code to github or bitbucket in easy steps"
date: 2015-03-13 10:17:53
categories: github, git
---

Google code disappears

Repent, the end is near. Google has just announced that they are shutting down google code project hosting. In the email of the announcement they make some suggestions to find a new house for your code such as bitbucket or github. I hope that they have been warned in order to be ready for a massive repository creation from the upcoming exodus of coder refugees.

At the time of writing this, there is a button to automate the migration only to github but it is NOT working due to the high amount of traffic and workload that they are experiencing.

But you can still move your stuff manually. Here are some easy-to-follow steps to move your code from google to github just using your command line.

0 .Go to google code

It is not as obvious as it may seem. Once you log in google is impossible to find a simple link to see your projects. Google is not specially good at usability, but hey, when your shares are valued at >500$ who gives a fuck. Nevermind, go to https://code.google.com/hosting/
and check My favorites

1. Checkout project

Enter into the project you want to migrate and select Source. Copy the command to checkout your code, with read-only is enough.

For example for:
http://code.google.com/p/erps-2dam-4vientos/

Go to source and:

svn checkout http://erps-2dam-4vientos.googlecode.com/svn/trunk/ erps-2dam-4vientos-read-only

2. Do some cleaning

Enter the directory and erase all svn files

find . -type d -name .svn -exec rm -rf {} +

Remove any other unnecessary stuff, binaries, jars,.. and the like.

3. Create repo on github or bitbucket

They both have free repository services, sign up and you can create repos.

4. Clone the repo

Once your repo is created they will provide you with a clone url or even the exact command you need to clone the repo locally.

git clone http://clone...

5. Copy files to your local git project directory

Move/copy files from your google-code local copy to git local copy.

mv google-code-dir/* git-project-dir/

6. Add and commit code

Now it's time to add to git the newly copied code files. You can achieve this with to easy commands, Bob Marley style:

git add *

git commit -m 'Exodus: Movement of Jah people! Oh-oh-oh, yea-eah!'

7. Push to remote

Final step to have your code online again and safe for [hopefully] [some] years to come. You'll be prompted to enter your username and password.

git push origin master

Greets for you, lucky bitbucket user. Your nice arse is safe at the moment


text:
{{category}}

					{{props.label}}


text:
<?php
namespace Nitra\ManagerBundle\Form\Type\Manager;

use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
use Nitra\ManagerBundle\Form\Type\Manager\EditType;

/**
 * NewType
 */
class NewType extends EditType
{

    /**
     * buildForm
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        // родитель формы
        parent::buildForm($builder, $options);

        // добавить валидатор NotBlank для виджета
        $widget = $builder->get('password');
        $formOptions = $widget->getOptions();
        $formOptions['constraints'] = array(new NotBlank());
        $builder->add($widget->getName(),  $widget->getType()->getName(), $formOptions);
    }

    /**
     * Получить имя типа-формы
     * @return string
     */
    public function getName()
    {
        return 'new_manager';
    }

}


text:
'use strict';

// MODULES //

var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var isObjectArray = require( '@stdlib/assert/is-plain-object-array' );
var wages = require( './../lib' );

// VARIABLES //

var opts = {
	'skip': IS_BROWSER
};

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof wages, 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns an array of objects', opts, function test( t ) {
	var data = wages();
	t.equal( isObjectArray( data ), true, 'returns an array of objects' );
	t.end();
});

tape( 'the function returns a copy', opts, function test( t ) {
	var d1;
	var d2;
	var v;

	d1 = wages();
	d2 = wages();

	t.notEqual( d1, d2, 'different references' );

	v = d2[ 5 ];
	d1[ 5 ] = 'beep';

	t.equal( d1[ 5 ], 'beep', 'expected element' );
	t.notEqual( d1[ 5 ], d2[ 5 ], 'no shared state' );
	t.equal( d2[ 5 ], v, 'expected element' );

	t.end();
});


text:
var mongodb = require('mongodb');

//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;

// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/datas';

module.exports = {

insert : function(){
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
  } else {
    //HURRAY!! We are connected. :)
    console.log('Connection established to', url);

    // Get the documents collection
    var collection = db.collection('student');

    //Create some users
    var ets = [{nom: "Seydou Berthe", ab: "0"},
    				{nom: "Bouh Oualid", ab: "0"},
    				{nom: "Ayachi Mohamed", ab: "0"},
    				{nom: "Messaoudi Oussama", ab: "0"},
    				{nom: "Kotb Rahbi", ab: "0"},
    				{nom: "Ouali Yassir", ab: "0"},
    				{nom: "Malek Yassir", ab: "0"},
    				{nom: "Rhorbal Zakaria", ab: "0"},
    				{nom: "Fadellah Abdelilah", ab: "0"},
    				{nom: "Alraj Zouhair", ab: "0"},
    				{nom: "Soufian Chalouh", ab: "0"}
    			  ];

    // Insert some users
    collection.insert(ets, function (err, result) {
      if (err) {
        console.log(err);
      } else {
        console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
      }
      //Close connection
      db.close();
    });
  }
});

},

retrieve : function(retour){
   var resp = [];
	MongoClient.connect(url, function (err, db) {
   if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
   } else {
    	//HURRAY!! We are connected. :)
    	console.log('Connection established to', url);

    	// Get the documents collection
    	var collection = db.collection('student');

    	// Insert some users
    	   collection.find().toArray(function (err, result) {
      	if (err) {
        		console.log(err);
        		retour(err, null);
      	} else if (result.length) {
        		console.log('Found:', result.length);
        		retour(null, result);
      	} else {
       		 console.log('No document(s) found with defined "find" criteria!');
     	   }
          //Close connection
        db.close();
        });
      }
    });

},

update : function(n, num){

	MongoClient.connect(url, function (err, db) {
  		if (err) {
    		console.log('Unable to connect to the mongoDB server. Error:', err);
  		} else {
    		//HURRAY!! We are connected. :)
    		console.log('Connection established to', url);
			var collection = db.collection('student');

			// Insert some users
			collection.update({nom: n}, {$set: {ab: num}}, function (err, numUpdated) {
  				if (err) {
    				console.log(err);
 			 	} else if (numUpdated) {
   			 	console.log('Updated '+n+'to '+num+' Successfully %d document(s).', numUpdated);
  			 	} else {
    				console.log('No document found with defined "find" criteria!');
 		   	}
  				//Close connection
  				db.close();
			});
		}
	});
},

nothing : function(){
	MongoClient.connect(url, function (err, db) {
  		if (err) {
    		console.log('Unable to connect to the mongoDB server. Error:', err);
  		} else {
  			db.close();
		}
	});
},

ajout : function(n){
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the mongoDB server. Error:', err);
  } else {
    //HURRAY!! We are connected. :)
    console.log('Connection established to', url);

    // Get the documents collection
    var collection = db.collection('student');

    //Create some users
    var ets = [{nom: n, ab: "0"}];

    // Insert some users
    collection.insert(ets, function (err, result) {
      if (err) {
        console.log(err);
      } else {
        console.log('Inserted %d documents into the "users" collection. The documents inserted with "_id" are:', result.length, result);
      }
      //Close connection
      db.close();
    });
  }
});

}

}


text:
// See docs in ../ops/linalg_ops.cc.

#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#endif  // GOOGLE_CUDA

#include "third_party/eigen3/Eigen/Cholesky"
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/framework/kernel_def_builder.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/linalg_ops_common.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"

#if GOOGLE_CUDA
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/kernels/cuda_solvers.h"
#include "tensorflow/core/kernels/matrix_band_part_op.h"
#include "tensorflow/core/platform/stream_executor.h"
#endif

namespace tensorflow {

static const char kErrMsg[] =
    "Cholesky decomposition was not successful. The input might not be valid.";

template <class Scalar>
class CholeskyOp : public LinearAlgebraOp<Scalar> {
 public:
  INHERIT_LINALG_TYPEDEFS(Scalar);

  explicit CholeskyOp(OpKernelConstruction* context) : Base(context) {}

  void ComputeMatrix(OpKernelContext* context, const ConstMatrixMaps& inputs,
                     MatrixMaps* outputs) final {
    const ConstMatrixMap& input = inputs[0];
    if (input.rows() == 0) {
      // If X is an empty matrix (0 rows, 0 col), X * X' == X.
      // Therefore, we return X.
      return;
    }
    // Perform the actual LL^T Cholesky decomposition. This will only use
    // the lower triangular part of data_in by default. The upper triangular
    // part of the matrix will not be read.
    Eigen::LLT<
        Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>
        llt_decomposition(input);

    OP_REQUIRES(context, llt_decomposition.info() == Eigen::Success,
                errors::InvalidArgument(kErrMsg));

    // Output the lower triangular in a dense form.
    outputs->at(0) = llt_decomposition.matrixL();
  }
};

#if GOOGLE_CUDA
typedef Eigen::GpuDevice GPUDevice;

namespace functor {
#define DECLARE_GPU_SPEC(T)                                            \
  template <>                                                          \
  struct MatrixBandPartFunctor<GPUDevice, T> {                         \
    void operator()(OpKernelContext* context, const GPUDevice& device, \
                    int num_upper_diags, int num_lower_diags,          \
                    typename TTypes<T, 3>::ConstTensor input,          \
                    typename TTypes<T, 3>::Tensor output);             \
  };                                                                   \
  extern template struct MatrixBandPartFunctor<GPUDevice, T>;

TF_CALL_GPU_NUMBER_TYPES(DECLARE_GPU_SPEC);
TF_CALL_complex64(DECLARE_GPU_SPEC);
TF_CALL_complex128(DECLARE_GPU_SPEC);
}  // namespace functor

template <class Scalar>
class CholeskyOpGpu : public AsyncOpKernel {
 public:
  explicit CholeskyOpGpu(OpKernelConstruction* context)
      : AsyncOpKernel(context) {}

  void ComputeAsync(OpKernelContext* context, DoneCallback done) final {
    const Tensor& input = context->input(0);
    const int ndims = input.dims();
    const int64 n = input.dim_size(ndims - 1);
    // Validate inputs.
    OP_REQUIRES_ASYNC(
        context, ndims >= 2,
        errors::InvalidArgument("Input must have rank >= 2, got ", ndims),
        done);
    OP_REQUIRES_ASYNC(
        context, input.dim_size(ndims - 2) == n,
        errors::InvalidArgument("Input matrices must be squares, got",
                                input.dim_size(ndims - 2), " != ", n),
        done);

    if (input.NumElements() == 0) {
      // If X is an empty matrix (0 rows, 0 col), X * X' == X.
      // Therefore, we return X.
      context->set_output(0, input);
      done();
      return;
    }

    // Allocate output.
    // TODO(rmlarsen): Convert to std::make_unique when available.
    std::unique_ptr<CudaSolver> solver(new CudaSolver(context));
    Tensor* output;
    OP_REQUIRES_OK_ASYNC(context,
                         context->forward_input_or_allocate_output(
                             {0}, 0, input.shape(), &output),
                         done);

    // Copy the lower triangular part of the input matrices to the output and
    // set the strictly upper triangular part to zero. We use a pre-existing
    // kernel MatrixBandPart to do this for all matrices in the batch at once,
    // before we launch each of the Cholesky factorization kernels in paralle.
    auto input_reshaped = input.template flat_inner_dims<Scalar, 3>();
    auto output_reshaped = output->template flat_inner_dims<Scalar, 3>();
    functor::MatrixBandPartFunctor<GPUDevice, Scalar> band_part;
    band_part(context, context->eigen_device<GPUDevice>(),
              n /* num_lower_diags */, 0 /* num_upper_diags */, input_reshaped,
              output_reshaped);

    // Launch a Cholesky kernel for each matrix in the batch.
    const int64 batch_size = input_reshaped.dimension(0);
    std::vector<DeviceLapackInfo> dev_info;
    dev_info.push_back(solver->GetDeviceLapackInfo(batch_size, "potrf"));
    // TODO(rmlarsen): Parallelize over batches if it turns out to be
    // an important use case.
    for (int batch = 0; batch < batch_size; ++batch) {
      OP_REQUIRES_OK_ASYNC(context,
                           solver->Potrf(CUBLAS_FILL_MODE_UPPER, n,
                                         &output_reshaped(batch, 0, 0), n,
                                         &dev_info.back()(batch)),
                           done);
    }

    // Register callback to check info after kernels finish.
    auto info_checker = [context, done](
                            const Status& status,
                            const std::vector<HostLapackInfo>& /* unused */) {
      OP_REQUIRES_ASYNC(context, status.ok(), errors::InvalidArgument(kErrMsg),
                        done);
      done();
    };
    CudaSolver::CheckLapackInfoAndDeleteSolverAsync(std::move(solver), dev_info,
                                                    std::move(info_checker));
  }
};

REGISTER_LINALG_OP_GPU("Cholesky", (CholeskyOpGpu<float>), float);
REGISTER_LINALG_OP_GPU("Cholesky", (CholeskyOpGpu<double>), double);
REGISTER_LINALG_OP_GPU("Cholesky", (CholeskyOpGpu<complex64>), complex64);
REGISTER_LINALG_OP_GPU("Cholesky", (CholeskyOpGpu<complex128>), complex128);

#endif  // GOOGLE_CUDA

REGISTER_LINALG_OP("Cholesky", (CholeskyOp<float>), float);
REGISTER_LINALG_OP("Cholesky", (CholeskyOp<double>), double);
REGISTER_LINALG_OP("Cholesky", (CholeskyOp<complex64>), complex64);
REGISTER_LINALG_OP("Cholesky", (CholeskyOp<complex128>), complex128);
REGISTER_LINALG_OP("BatchCholesky", (CholeskyOp<float>), float);
REGISTER_LINALG_OP("BatchCholesky", (CholeskyOp<double>), double);

}  // namespace tensorflow


text:
package org.slc.sli.sif.domain.slientity;

/**
 * Corresponding to the (personal) telephone defined in SLI schema.
 *
 * @author slee
 *
 */
public class PersonalTelephone {
    private String telephoneNumber;
    private String telephoneNumberType;

    public PersonalTelephone() {
        // Empty Default constructor
    }

    public String getTelephoneNumber() {
        return this.telephoneNumber;
    }

    public void setTelephoneNumber(String telephoneNumber) {
        this.telephoneNumber = telephoneNumber;
    }

    public String getTelephoneNumberType() {
        return this.telephoneNumberType;
    }

    public void setTelephoneNumberType(
            String telephoneNumberType) {
        this.telephoneNumberType = telephoneNumberType;
    }
}


text:
package v1beta1

type RunServiceExpansion interface{}


text:
#ifndef DIJKSTRA_H
#define DIJKSTRA_H
#include "Graph.hpp"

#define MAXV 1000

class Dijkstra
{

public:
	Dijkstra();
	~Dijkstra();

	int execute( Graph, int, int );
	int executeMaximum( Graph, int, int );
	vector<int> shortestPath(int);

private:

	vector<int> parent;
};

#endif


text:
"""
    pyfire.tests.jid
    ~~~~~~~~~~~~~~~~

    Tests for JID

    :copyright: 2011 by the pyfire Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""

from pyfire.tests import PyfireTestCase

from pyfire.jid import JID

class TestJID(PyfireTestCase):

    def test_parse_full_jid(self):
        jid = JID("user@host/res")
        self.assertEqual(jid.local, "user")
        self.assertEqual(jid.domain, "host")
        self.assertEqual(jid.resource, "res")

    def test_parse_domain_partial_jid(self):
        jid = JID("host/res")
        self.assertEqual(jid.local, None)
        self.assertEqual(jid.domain, "host")
        self.assertEqual(jid.resource, "res")

    def test_parse_domain_jid(self):
        jid = JID("host")
        self.assertEqual(jid.local, None)
        self.assertEqual(jid.domain, "host")
        self.assertEqual(jid.resource, None)

    def test_jid_compare(self):
        jid1 = JID("user1@host/res")
        jid2 = JID("user2@host/res")
        self.assertTrue(jid1 == jid1)
        self.assertFalse(jid1 == jid2)

    def test_jid_ip(self):
        JID("user@127.0.0.1/res")
        JID("user@fe80::1/res")

    def test_bare_jid(self):
        jid = JID("user@host/res")
        self.assertEqual(jid.bare, "user@host")
        jid = JID("host/res")
        self.assertEqual(jid.bare, "host")

    def test_jid_operators(self):
        a = JID("user@host/res")
        b = JID("user@host/res")
        self.assertTrue(a == b)
        self.assertFalse(a != b)
        self.assertTrue(a is not b)
        self.assertFalse(a is b)

    def test_str(self):
        jids = [
            "host",
            "user@host",
            "host/res",
            "user@host/res"
        ]

        for testjid in jids:
            jid = JID(testjid)
            self.assertEqual(str(jid), testjid)

    def test_jid_true(self):
        jid = JID("user@host/res")
        self.assertTrue(jid.validate())

    badjids = [
        "",
        "1.2.3.256",
        "a" * 128 + "." + "a" * 128,
        unichr(0x100) * 512 + "a",  # results in 1025 byte
        "fg::",  # looks like ipv6 but is invalid
        "test/",
        unichr(0x100) * 512 + "a@testhost",
        "@testhost",
        unichr(0xD800) + "@testhost",
        "testhost/" + unichr(0x100) * 512 + "a",
        "testhost/" + unichr(0xD800)
    ]

    def test_bad_jids_raise(self):
        for testjid in self.badjids:
            try:
                with self.assertRaises(ValueError) as cm:
                    jid = JID(testjid)
            except AssertionError:
                raise AssertionError("ValueError not raised for JID '%s'" % testjid)

    def test_bad_jids_false(self):
        for testjid in self.badjids:
            jid = JID(testjid, validate_on_init=False)
            self.assertFalse(jid.validate())

    def test_bad_jid_inject(self):
        jid = JID('test')
        jid.domain = None
        with self.assertRaises(ValueError) as cm:
            jid.validate(True)


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

namespace Juice.Mvc {
	public partial class JuiceHelpers {

		private Mobile.MobileHelpers _mobileHelpers = null;

		public Mobile.MobileHelpers Mobile {
			get {
				if(_mobileHelpers == null) {
					_mobileHelpers = new Mobile.MobileHelpers(_helper);
				}

				return _mobileHelpers;
			}
		}

	}
}

namespace Juice.Mvc.Mobile {

	public partial class MobileHelpers {

		protected HtmlHelper _helper;

		public HtmlHelper Helper { get { return _helper; } }

		public MobileHelpers(HtmlHelper helper) {
			_helper = helper;
		}

	}
}


text: Conda packaging for testresources


text:
import os
import json
import re
import sys

prefix = sys.argv[1] if len(sys.argv) > 1 else ''

class Congress(object):
    def __init__(self, congress):
        self.congress = congress
        self.cache_sponsor = {}
        self.cache_voters = {}

    def get_sponsor_data(self, sponsor):
        if sponsor is None:
            return None
        cache_key = sponsor['title'], sponsor['name'], sponsor['state']
        if cache_key in self.cache_sponsor:
            return self.cache_sponsor[cache_key]
        congress_str = str(self.congress)
        for y in (1787, 1788):
            year_str = str(self.congress * 2 + y)
            directory = 'h' if sponsor['title'] == 'Rep' else 's'
            p = os.path.join(congress_str, 'votes', year_str)
            for root, dirs, files in os.walk(p):
                for d in dirs:
                    path = os.path.join(p, d, 'data.json')
                    if path in self.cache_voters:
                        data = self.cache_voters[path]
                    else:
                        with open(path) as fp:
                            data = json.loads(fp.read())
                        self.cache_voters[path] = data
                    for voters in data['votes'].values():
                        for voter in voters:
                            if not isinstance(voter, dict):
                                continue
                            display_name = re.sub(r'\(.*\)', '',
                                    voter['display_name']).strip()
                            if (sponsor['name'].startswith(display_name) and
                               sponsor['state'] == voter['state']):
                                self.cache_sponsor[cache_key] = voter
                                return voter
        # sys.stderr.write('Unable to find sponsor {}\n'.format(sponsor))
        self.cache_sponsor[cache_key] = None
        return None

votes = {}
for i in range(101, 114):
    congress = Congress(i)
    votes[i] = []
    for root, dirs, files in os.walk(os.path.join(str(i), 'votes')):
        for f in files:
            if f == 'data.json':
                if not os.path.basename(root).startswith(prefix):
                    continue
                # sys.stderr.write('{}/{}\n'.format(root, f))
                # print (os.path.join(root, f))
                with open(os.path.join(root, f)) as fp:
                    vote_data = json.loads(fp.read())
                if 'bill' not in vote_data:
                    continue
                # if 'amendment' in vote_data:
                #     # 101/amendments/samdt/samdt225/data.json
                #     amdt = vote_data['amendment']['type'] + 'amdt'
                #     number = str(vote_data['amendment']['number'])
                #     with open(os.path.join(str(i), 'amendments', amdt,
                #                 amdt + number, 'data.json')) as fp:
                #         amendment_data = json.loads(fp.read())
                if 'bill' in vote_data:
                    # 101/amendments/samdt/samdt225/data.json
                    t = vote_data['bill']['type']
                    number = str(vote_data['bill']['number'])
                    with open(os.path.join(str(i), 'bills', t, t + number,
                                'data.json')) as fp:
                        bill_data = json.loads(fp.read())
                    # print json.dumps(bill_data, indent=2)
                # print json.dumps(vote_data, indent=2)
                sponsors = [congress.get_sponsor_data(bill_data['sponsor'])]
                for cosponsor in bill_data['cosponsors']:
                    sponsors.append(congress.get_sponsor_data(cosponsor))
                if 'Yea' not in vote_data['votes'] and 'Aye' in vote_data['votes']:
                    vote_data['votes']['Yea'] = vote_data['votes']['Aye']
                if 'Nay' not in vote_data['votes'] and 'No' in vote_data['votes']:
                    vote_data['votes']['Nay'] = vote_data['votes']['No']
                yea_d = len(tuple(1 for v in vote_data['votes']['Yea']
                            if isinstance(v, dict) and v['party'] == 'D'))
                yea_r = len(tuple(1 for v in vote_data['votes']['Yea']
                            if isinstance(v, dict) and v['party'] == 'R'))
                nay_d = len(tuple(1 for v in vote_data['votes']['Nay']
                            if isinstance(v, dict) and v['party'] == 'D'))
                nay_r = len(tuple(1 for v in vote_data['votes']['Nay']
                            if isinstance(v, dict) and v['party'] == 'R'))

                subject = bill_data['subjects_top_term']
                d, r = None, None
                if yea_d > nay_d:
                    d = 'yea'
                elif yea_d < nay_d:
                    d = 'nay'

                if yea_r > nay_r:
                    r = 'yea'
                elif yea_r < nay_r:
                    r = 'nay'
                votes[i].append((subject, d, r, sponsors))

print json.dumps(votes, indent=2)
sys.exit(0)


text:
package net.daw.dao.implementation;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import net.daw.bean.implementation.PartidoBean;
import net.daw.dao.publicinterface.TableDaoInterface;
import net.daw.dao.publicinterface.ViewDaoInterface;
import net.daw.data.implementation.MysqlDataSpImpl;
import net.daw.helper.statics.ExceptionBooster;
import net.daw.helper.statics.FilterBeanHelper;
import net.daw.helper.statics.SqlBuilder;

public class PartidoDao implements ViewDaoInterface<PartidoBean>, TableDaoInterface<PartidoBean> {

    private String strTable = "partido";
    private String strSQL = "select * from partido where 1=1 ";
    private MysqlDataSpImpl oMysql = null;
    private Connection oConnection = null;

    public PartidoDao(Connection oPooledConnection) throws Exception {
        try {
            oConnection = oPooledConnection;
            oMysql = new MysqlDataSpImpl(oConnection);
        } catch (Exception ex) {
            ExceptionBooster.boost(new Exception(this.getClass().getName() + ":constructor ERROR: " + ex.getMessage()));
        }
    }

    @Override
    public int getPages(int intRegsPerPag, ArrayList<FilterBeanHelper> hmFilter) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(hmFilter);
        int pages = 0;
        try {
            pages = oMysql.getPages(strSQL, intRegsPerPag);
        } catch (Exception ex) {
            ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getPages ERROR: " + ex.getMessage()));
        }
        return pages;
    }

    @Override
    public int getCount(ArrayList<FilterBeanHelper> hmFilter) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(hmFilter);
        int pages = 0;
        try {
            pages = oMysql.getCount(strSQL);
        } catch (Exception ex) {
            ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getCount ERROR: " + ex.getMessage()));
        }
        return pages;
    }

    @Override
    public ArrayList<PartidoBean> getPage(int intRegsPerPag, int intPage, ArrayList<FilterBeanHelper> hmFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(hmFilter);
        strSQL += SqlBuilder.buildSqlOrder(hmOrder);
        strSQL += SqlBuilder.buildSqlLimit(oMysql.getCount(strSQL), intRegsPerPag, intPage);
        ArrayList<PartidoBean> alPartido = new ArrayList<>();
        try {
            ResultSet oResultSet = oMysql.getAllSql(strSQL);
            if (oResultSet != null) {
                while (oResultSet.next()) {
                    PartidoBean oPartidoBean = new PartidoBean();
                    alPartido.add(oPartidoBean.fill(oResultSet, oConnection, expand));
                }
            }
        } catch (Exception ex) {
            ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getPage ERROR: " + ex.getMessage()));
        }
        return alPartido;
    }

    @Override
    public ArrayList<PartidoBean> getAll(ArrayList<FilterBeanHelper> alFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
        strSQL += SqlBuilder.buildSqlOrder(hmOrder);
        ArrayList<PartidoBean> alPartido = new ArrayList<>();
        try {
            ResultSet oResultSet = oMysql.getAllSql(strSQL);
            if (oResultSet != null) {
                while (oResultSet.next()) {
                    PartidoBean oPartidoBean = new PartidoBean();
                    alPartido.add(oPartidoBean.fill(oResultSet, oConnection, expand));
                }
            }
        } catch (Exception ex) {
            ExceptionBooster.boost(new Exception(this.getClass().getName() + ":getPage ERROR: " + ex.getMessage()));
        }
        return alPartido;
    }

    @Override
    public PartidoBean get(PartidoBean oPartidoBean, Integer expand) throws Exception {
        if (oPartidoBean.getId() > 0) {
            try {
                ResultSet oResultSet = oMysql.getAllSql(strSQL + " And id= " + oPartidoBean.getId() + " ");
                if (oResultSet != null) {
                    while (oResultSet.next()) {
                        oPartidoBean = oPartidoBean.fill(oResultSet, oConnection, expand);
                    }
                }
            } catch (Exception ex) {
                ExceptionBooster.boost(new Exception(this.getClass().getName() + ":get ERROR: " + ex.getMessage()));
            }
        } else {
            oPartidoBean.setId(0);
        }
        return oPartidoBean;
    }

    @Override
    public Integer set(PartidoBean oPartidoBean) throws Exception {
        Integer iResult = null;
        try {
            if (oPartidoBean.getId() == 0) {
                strSQL = "INSERT INTO " + strTable + " ";
                strSQL += "(" + oPartidoBean.getColumns() + ")";
                strSQL += "VALUES(" + oPartidoBean.getValues() + ")";
                iResult = oMysql.executeInsertSQL(strSQL);
            } else {
                strSQL = "UPDATE " + strTable + " ";
                strSQL += " SET " + oPartidoBean.toPairs();
                strSQL += " WHERE id=" + oPartidoBean.getId();
                iResult = oMysql.executeUpdateSQL(strSQL);
            }

        } catch (Exception ex) {
            ExceptionBooster.boost(new Exception(this.getClass().getName() + ":set ERROR: " + ex.getMessage()));
        }
        return iResult;
    }

    @Override
    public Integer remove(Integer id) throws Exception {
        int result = 0;
        try {
            result = oMysql.removeOne(id, strTable);
        } catch (Exception ex) {
            ExceptionBooster.boost(new Exception(this.getClass().getName() + ":remove ERROR: " + ex.getMessage()));
        }
        return result;
    }

}


text:
"""PIX public APIs."""

from dm_pix._src import augment
from dm_pix._src import color_conversion
from dm_pix._src import depth_and_space
from dm_pix._src import interpolation
from dm_pix._src import metrics
from dm_pix._src import patch

__version__ = "0.3.4"

# Augmentations.
adjust_brightness = augment.adjust_brightness
adjust_contrast = augment.adjust_contrast
adjust_gamma = augment.adjust_gamma
adjust_hue = augment.adjust_hue
adjust_saturation = augment.adjust_saturation
affine_transform = augment.affine_transform
elastic_deformation = augment.elastic_deformation
flip_left_right = augment.flip_left_right
flip_up_down = augment.flip_up_down
gaussian_blur = augment.gaussian_blur
random_brightness = augment.random_brightness
random_contrast = augment.random_contrast
random_crop = augment.random_crop
random_flip_left_right = augment.random_flip_left_right
random_flip_up_down = augment.random_flip_up_down
random_gamma = augment.random_gamma
random_hue = augment.random_hue
random_saturation = augment.random_saturation
rotate = augment.rotate
rot90 = augment.rot90
solarize = augment.solarize

# Color conversions.
hsl_to_rgb = color_conversion.hsl_to_rgb
hsv_to_rgb = color_conversion.hsv_to_rgb
rgb_to_hsl = color_conversion.rgb_to_hsl
rgb_to_hsv = color_conversion.rgb_to_hsv
rgb_to_grayscale = color_conversion.rgb_to_grayscale

# Depth and space transformations.
depth_to_space = depth_and_space.depth_to_space
space_to_depth = depth_and_space.space_to_depth

# Interpolation functions.
flat_nd_linear_interpolate = interpolation.flat_nd_linear_interpolate
flat_nd_linear_interpolate_constant = (
    interpolation.flat_nd_linear_interpolate_constant)

# Metrics.
mae = metrics.mae
mse = metrics.mse
psnr = metrics.psnr
rmse = metrics.rmse
simse = metrics.simse
ssim = metrics.ssim

# Patch extraction functions.
extract_patches = patch.extract_patches

del augment, color_conversion, depth_and_space, interpolation, metrics, patch

__all__ = (
    "adjust_brightness",
    "adjust_contrast",
    "adjust_gamma",
    "adjust_hue",
    "adjust_saturation",
    "affine_transform",
    "depth_to_space",
    "elastic_deformation",
    "extract_patches",
    "flat_nd_linear_interpolate",
    "flat_nd_linear_interpolate_constant",
    "flip_left_right",
    "flip_up_down",
    "gaussian_blur",
    "hsl_to_rgb",
    "hsv_to_rgb",
    "mae",
    "mse",
    "psnr",
    "random_brightness",
    "random_contrast",
    "random_crop",
    "random_flip_left_right",
    "random_flip_up_down",
    "random_gamma",
    "random_hue",
    "random_saturation",
    "rotate",
    "rgb_to_hsl",
    "rgb_to_hsv",
    "rgb_to_grayscale",
    "rmse",
    "rot90",
    "simse",
    "ssim",
    "solarize",
    "space_to_depth",
)

#  _________________________________________
# / Please don't use symbols in `_src` they \
# \ are not part of the PIX public API.     /
#  -----------------------------------------
#         \   ^__^
#          \  (oo)\_______
#             (__)\       )\/\
#                 ||----w |
#                 ||     ||
#
try:
  del _src  # pylint: disable=undefined-variable
except NameError:
  pass


text:
package v2

import (
	"os"

	"code.cloudfoundry.org/cli/cf/cmd"
	"code.cloudfoundry.org/cli/commands"
	"code.cloudfoundry.org/cli/commands/flags"
)

type UnsetSpaceQuotaCommand struct {
	RequiredArgs    flags.SetSpaceQuotaArgs `positional-args:"yes"`
	usage           interface{}             `usage:"CF_NAME unset-space-quota SPACE QUOTA\n\n"`
	relatedCommands interface{}             `related_commands:"space"`
}

func (_ UnsetSpaceQuotaCommand) Setup(config commands.Config, ui commands.UI) error {
	return nil
}

func (_ UnsetSpaceQuotaCommand) Execute(args []string) error {
	cmd.Main(os.Getenv("CF_TRACE"), os.Args)
	return nil
}


text:
module Control.Isomorphism.Partial
  ( module Control.Isomorphism.Partial.Prim
  , module Control.Isomorphism.Partial.Derived
  , module Control.Isomorphism.Partial.Constructors
  ) where

import Control.Isomorphism.Partial.Prim
import Control.Isomorphism.Partial.Derived
import Control.Isomorphism.Partial.Constructors


text: ActionController::Base.send :include, SubdomainFu::Controller


text:
import unittest
from test import support

import posixpath, os
from posixpath import realpath, abspath, join, dirname, basename, relpath

# An absolute path to a temporary filename for testing. We can't rely on TESTFN
# being an absolute path, so we need this.

ABSTFN = abspath(support.TESTFN)

def safe_rmdir(dirname):
    try:
        os.rmdir(dirname)
    except OSError:
        pass

class PosixPathTest(unittest.TestCase):

    def setUp(self):
        self.tearDown()

    def tearDown(self):
        for suffix in ["", "1", "2"]:
            support.unlink(support.TESTFN + suffix)
            safe_rmdir(support.TESTFN + suffix)

    def assertIs(self, a, b):
        self.assert_(a is b)

    def test_normcase(self):
        # Check that normcase() is idempotent
        p = "FoO/./BaR"
        self.assertEqual(p, posixpath.normcase(p))

        p = b"FoO/./BaR"
        self.assertEqual(p, posixpath.normcase(p))

        self.assertRaises(TypeError, posixpath.normcase)

    def test_join(self):
        self.assertEqual(posixpath.join("/foo", "bar", "/bar", "baz"),
                         "/bar/baz")
        self.assertEqual(posixpath.join("/foo", "bar", "baz"), "/foo/bar/baz")
        self.assertEqual(posixpath.join("/foo/", "bar/", "baz/"),
                         "/foo/bar/baz/")

        self.assertEqual(posixpath.join(b"/foo", b"bar", b"/bar", b"baz"),
                         b"/bar/baz")
        self.assertEqual(posixpath.join(b"/foo", b"bar", b"baz"),
                         b"/foo/bar/baz")
        self.assertEqual(posixpath.join(b"/foo/", b"bar/", b"baz/"),
                         b"/foo/bar/baz/")

        self.assertRaises(TypeError, posixpath.join)
        self.assertRaises(TypeError, posixpath.join, b"bytes", "str")
        self.assertRaises(TypeError, posixpath.join, "str", b"bytes")

    def test_splitdrive(self):
        self.assertEqual(posixpath.splitdrive("/foo/bar"), ("", "/foo/bar"))
        self.assertEqual(posixpath.splitdrive(b"/foo/bar"), (b"", b"/foo/bar"))

        self.assertRaises(TypeError, posixpath.splitdrive)

    def test_split(self):
        self.assertEqual(posixpath.split("/foo/bar"), ("/foo", "bar"))
        self.assertEqual(posixpath.split("/"), ("/", ""))
        self.assertEqual(posixpath.split("foo"), ("", "foo"))
        self.assertEqual(posixpath.split("////foo"), ("////", "foo"))
        self.assertEqual(posixpath.split("//foo//bar"), ("//foo", "bar"))

        self.assertEqual(posixpath.split(b"/foo/bar"), (b"/foo", b"bar"))
        self.assertEqual(posixpath.split(b"/"), (b"/", b""))
        self.assertEqual(posixpath.split(b"foo"), (b"", b"foo"))
        self.assertEqual(posixpath.split(b"////foo"), (b"////", b"foo"))
        self.assertEqual(posixpath.split(b"//foo//bar"), (b"//foo", b"bar"))

        self.assertRaises(TypeError, posixpath.split)

    def splitextTest(self, path, filename, ext):
        self.assertEqual(posixpath.splitext(path), (filename, ext))
        self.assertEqual(posixpath.splitext("/" + path), ("/" + filename, ext))
        self.assertEqual(posixpath.splitext("abc/" + path),
                         ("abc/" + filename, ext))
        self.assertEqual(posixpath.splitext("abc.def/" + path),
                         ("abc.def/" + filename, ext))
        self.assertEqual(posixpath.splitext("/abc.def/" + path),
                         ("/abc.def/" + filename, ext))
        self.assertEqual(posixpath.splitext(path + "/"),
                         (filename + ext + "/", ""))

        path = bytes(path, "ASCII")
        filename = bytes(filename, "ASCII")
        ext = bytes(ext, "ASCII")

        self.assertEqual(posixpath.splitext(path), (filename, ext))
        self.assertEqual(posixpath.splitext(b"/" + path),
                         (b"/" + filename, ext))
        self.assertEqual(posixpath.splitext(b"abc/" + path),
                         (b"abc/" + filename, ext))
        self.assertEqual(posixpath.splitext(b"abc.def/" + path),
                         (b"abc.def/" + filename, ext))
        self.assertEqual(posixpath.splitext(b"/abc.def/" + path),
                         (b"/abc.def/" + filename, ext))
        self.assertEqual(posixpath.splitext(path + b"/"),
                         (filename + ext + b"/", b""))

    def test_splitext(self):
        self.splitextTest("foo.bar", "foo", ".bar")
        self.splitextTest("foo.boo.bar", "foo.boo", ".bar")
        self.splitextTest("foo.boo.biff.bar", "foo.boo.biff", ".bar")
        self.splitextTest(".csh.rc", ".csh", ".rc")
        self.splitextTest("nodots", "nodots", "")
        self.splitextTest(".cshrc", ".cshrc", "")
        self.splitextTest("...manydots", "...manydots", "")
        self.splitextTest("...manydots.ext", "...manydots", ".ext")
        self.splitextTest(".", ".", "")
        self.splitextTest("..", "..", "")
        self.splitextTest("........", "........", "")
        self.splitextTest("", "", "")
        self.assertRaises(TypeError, posixpath.splitext)

    def test_isabs(self):
        self.assertIs(posixpath.isabs(""), False)
        self.assertIs(posixpath.isabs("/"), True)
        self.assertIs(posixpath.isabs("/foo"), True)
        self.assertIs(posixpath.isabs("/foo/bar"), True)
        self.assertIs(posixpath.isabs("foo/bar"), False)

        self.assertIs(posixpath.isabs(b""), False)
        self.assertIs(posixpath.isabs(b"/"), True)
        self.assertIs(posixpath.isabs(b"/foo"), True)
        self.assertIs(posixpath.isabs(b"/foo/bar"), True)
        self.assertIs(posixpath.isabs(b"foo/bar"), False)

        self.assertRaises(TypeError, posixpath.isabs)

    def test_basename(self):
        self.assertEqual(posixpath.basename("/foo/bar"), "bar")
        self.assertEqual(posixpath.basename("/"), "")
        self.assertEqual(posixpath.basename("foo"), "foo")
        self.assertEqual(posixpath.basename("////foo"), "foo")
        self.assertEqual(posixpath.basename("//foo//bar"), "bar")

        self.assertEqual(posixpath.basename(b"/foo/bar"), b"bar")
        self.assertEqual(posixpath.basename(b"/"), b"")
        self.assertEqual(posixpath.basename(b"foo"), b"foo")
        self.assertEqual(posixpath.basename(b"////foo"), b"foo")
        self.assertEqual(posixpath.basename(b"//foo//bar"), b"bar")

        self.assertRaises(TypeError, posixpath.basename)

    def test_dirname(self):
        self.assertEqual(posixpath.dirname("/foo/bar"), "/foo")
        self.assertEqual(posixpath.dirname("/"), "/")
        self.assertEqual(posixpath.dirname("foo"), "")
        self.assertEqual(posixpath.dirname("////foo"), "////")
        self.assertEqual(posixpath.dirname("//foo//bar"), "//foo")

        self.assertEqual(posixpath.dirname(b"/foo/bar"), b"/foo")
        self.assertEqual(posixpath.dirname(b"/"), b"/")
        self.assertEqual(posixpath.dirname(b"foo"), b"")
        self.assertEqual(posixpath.dirname(b"////foo"), b"////")
        self.assertEqual(posixpath.dirname(b"//foo//bar"), b"//foo")

        self.assertRaises(TypeError, posixpath.dirname)

    def test_commonprefix(self):
        self.assertEqual(
            posixpath.commonprefix([]),
            ""
        )
        self.assertEqual(
            posixpath.commonprefix(["/home/swenson/spam", "/home/swen/spam"]),
            "/home/swen"
        )
        self.assertEqual(
            posixpath.commonprefix(["/home/swen/spam", "/home/swen/eggs"]),
            "/home/swen/"
        )
        self.assertEqual(
            posixpath.commonprefix(["/home/swen/spam", "/home/swen/spam"]),
            "/home/swen/spam"
        )

        self.assertEqual(
            posixpath.commonprefix([b"/home/swenson/spam", b"/home/swen/spam"]),
            b"/home/swen"
        )
        self.assertEqual(
            posixpath.commonprefix([b"/home/swen/spam", b"/home/swen/eggs"]),
            b"/home/swen/"
        )
        self.assertEqual(
            posixpath.commonprefix([b"/home/swen/spam", b"/home/swen/spam"]),
            b"/home/swen/spam"
        )

        testlist = ['', 'abc', 'Xbcd', 'Xb', 'XY', 'abcd', 'aXc', 'abd', 'ab', 'aX', 'abcX']
        for s1 in testlist:
            for s2 in testlist:
                p = posixpath.commonprefix([s1, s2])
                self.assert_(s1.startswith(p))
                self.assert_(s2.startswith(p))
                if s1 != s2:
                    n = len(p)
                    self.assertNotEqual(s1[n:n+1], s2[n:n+1])

    def test_getsize(self):
        f = open(support.TESTFN, "wb")
        try:
            f.write(b"foo")
            f.close()
            self.assertEqual(posixpath.getsize(support.TESTFN), 3)
        finally:
            if not f.closed:
                f.close()

    def test_time(self):
        f = open(support.TESTFN, "wb")
        try:
            f.write(b"foo")
            f.close()
            f = open(support.TESTFN, "ab")
            f.write(b"bar")
            f.close()
            f = open(support.TESTFN, "rb")
            d = f.read()
            f.close()
            self.assertEqual(d, b"foobar")

            self.assert_(
                posixpath.getctime(support.TESTFN) <=
                posixpath.getmtime(support.TESTFN)
            )
        finally:
            if not f.closed:
                f.close()

    def test_islink(self):
        self.assertIs(posixpath.islink(support.TESTFN + "1"), False)
        f = open(support.TESTFN + "1", "wb")
        try:
            f.write(b"foo")
            f.close()
            self.assertIs(posixpath.islink(support.TESTFN + "1"), False)
            if hasattr(os, "symlink"):
                os.symlink(support.TESTFN + "1", support.TESTFN + "2")
                self.assertIs(posixpath.islink(support.TESTFN + "2"), True)
                os.remove(support.TESTFN + "1")
                self.assertIs(posixpath.islink(support.TESTFN + "2"), True)
                self.assertIs(posixpath.exists(support.TESTFN + "2"), False)
                self.assertIs(posixpath.lexists(support.TESTFN + "2"), True)
        finally:
            if not f.close():
                f.close()

        self.assertRaises(TypeError, posixpath.islink)

    def test_exists(self):
        self.assertIs(posixpath.exists(support.TESTFN), False)
        f = open(support.TESTFN, "wb")
        try:
            f.write(b"foo")
            f.close()
            self.assertIs(posixpath.exists(support.TESTFN), True)
            self.assertIs(posixpath.lexists(support.TESTFN), True)
        finally:
            if not f.close():
                f.close()

        self.assertRaises(TypeError, posixpath.exists)

    def test_isdir(self):
        self.assertIs(posixpath.isdir(support.TESTFN), False)
        f = open(support.TESTFN, "wb")
        try:
            f.write(b"foo")
            f.close()
            self.assertIs(posixpath.isdir(support.TESTFN), False)
            os.remove(support.TESTFN)
            os.mkdir(support.TESTFN)
            self.assertIs(posixpath.isdir(support.TESTFN), True)
            os.rmdir(support.TESTFN)
        finally:
            if not f.close():
                f.close()

        self.assertRaises(TypeError, posixpath.isdir)

    def test_isfile(self):
        self.assertIs(posixpath.isfile(support.TESTFN), False)
        f = open(support.TESTFN, "wb")
        try:
            f.write(b"foo")
            f.close()
            self.assertIs(posixpath.isfile(support.TESTFN), True)
            os.remove(support.TESTFN)
            os.mkdir(support.TESTFN)
            self.assertIs(posixpath.isfile(support.TESTFN), False)
            os.rmdir(support.TESTFN)
        finally:
            if not f.close():
                f.close()

        self.assertRaises(TypeError, posixpath.isdir)

    def test_samefile(self):
        f = open(support.TESTFN + "1", "wb")
        try:
            f.write(b"foo")
            f.close()
            self.assertIs(
                posixpath.samefile(
                    support.TESTFN + "1",
                    support.TESTFN + "1"
                ),
                True
            )
            # If we don't have links, assume that os.stat doesn't return resonable
            # inode information and thus, that samefile() doesn't work
            if hasattr(os, "symlink"):
                os.symlink(
                    support.TESTFN + "1",
                    support.TESTFN + "2"
                )
                self.assertIs(
                    posixpath.samefile(
                        support.TESTFN + "1",
                        support.TESTFN + "2"
                    ),
                    True
                )
                os.remove(support.TESTFN + "2")
                f = open(support.TESTFN + "2", "wb")
                f.write(b"bar")
                f.close()
                self.assertIs(
                    posixpath.samefile(
                        support.TESTFN + "1",
                        support.TESTFN + "2"
                    ),
                    False
                )
        finally:
            if not f.close():
                f.close()

        self.assertRaises(TypeError, posixpath.samefile)

    def test_samestat(self):
        f = open(support.TESTFN + "1", "wb")
        try:
            f.write(b"foo")
            f.close()
            self.assertIs(
                posixpath.samestat(
                    os.stat(support.TESTFN + "1"),
                    os.stat(support.TESTFN + "1")
                ),
                True
            )
            # If we don't have links, assume that os.stat() doesn't return resonable
            # inode information and thus, that samefile() doesn't work
            if hasattr(os, "symlink"):
                if hasattr(os, "symlink"):
                    os.symlink(support.TESTFN + "1", support.TESTFN + "2")
                    self.assertIs(
                        posixpath.samestat(
                            os.stat(support.TESTFN + "1"),
                            os.stat(support.TESTFN + "2")
                        ),
                        True
                    )
                    os.remove(support.TESTFN + "2")
                f = open(support.TESTFN + "2", "wb")
                f.write(b"bar")
                f.close()
                self.assertIs(
                    posixpath.samestat(
                        os.stat(support.TESTFN + "1"),
                        os.stat(support.TESTFN + "2")
                    ),
                    False
                )
        finally:
            if not f.close():
                f.close()

        self.assertRaises(TypeError, posixpath.samestat)

    def test_ismount(self):
        self.assertIs(posixpath.ismount("/"), True)

        self.assertRaises(TypeError, posixpath.ismount)

    def test_expanduser(self):
        self.assertEqual(posixpath.expanduser("foo"), "foo")
        self.assertEqual(posixpath.expanduser(b"foo"), b"foo")
        try:
            import pwd
        except ImportError:
            pass
        else:
            self.assert_(isinstance(posixpath.expanduser("~/"), str))
            self.assert_(isinstance(posixpath.expanduser(b"~/"), bytes))
            # if home directory == root directory, this test makes no sense
            if posixpath.expanduser("~") != '/':
                self.assertEqual(
                    posixpath.expanduser("~") + "/",
                    posixpath.expanduser("~/")
                )
                self.assertEqual(
                    posixpath.expanduser(b"~") + b"/",
                    posixpath.expanduser(b"~/")
                )
            self.assert_(isinstance(posixpath.expanduser("~root/"), str))
            self.assert_(isinstance(posixpath.expanduser("~foo/"), str))
            self.assert_(isinstance(posixpath.expanduser(b"~root/"), bytes))
            self.assert_(isinstance(posixpath.expanduser(b"~foo/"), bytes))

            with support.EnvironmentVarGuard() as env:
                env['HOME'] = '/'
                self.assertEqual(posixpath.expanduser("~"), "/")

        self.assertRaises(TypeError, posixpath.expanduser)

    def test_expandvars(self):
        with support.EnvironmentVarGuard() as env:
            env.clear()
            env["foo"] = "bar"
            env["{foo"] = "baz1"
            env["{foo}"] = "baz2"
            self.assertEqual(posixpath.expandvars("foo"), "foo")
            self.assertEqual(posixpath.expandvars("$foo bar"), "bar bar")
            self.assertEqual(posixpath.expandvars("${foo}bar"), "barbar")
            self.assertEqual(posixpath.expandvars("$[foo]bar"), "$[foo]bar")
            self.assertEqual(posixpath.expandvars("$bar bar"), "$bar bar")
            self.assertEqual(posixpath.expandvars("$?bar"), "$?bar")
            self.assertEqual(posixpath.expandvars("${foo}bar"), "barbar")
            self.assertEqual(posixpath.expandvars("$foo}bar"), "bar}bar")
            self.assertEqual(posixpath.expandvars("${foo"), "${foo")
            self.assertEqual(posixpath.expandvars("${{foo}}"), "baz1}")
            self.assertEqual(posixpath.expandvars("$foo$foo"), "barbar")
            self.assertEqual(posixpath.expandvars("$bar$bar"), "$bar$bar")

            self.assertEqual(posixpath.expandvars(b"foo"), b"foo")
            self.assertEqual(posixpath.expandvars(b"$foo bar"), b"bar bar")
            self.assertEqual(posixpath.expandvars(b"${foo}bar"), b"barbar")
            self.assertEqual(posixpath.expandvars(b"$[foo]bar"), b"$[foo]bar")
            self.assertEqual(posixpath.expandvars(b"$bar bar"), b"$bar bar")
            self.assertEqual(posixpath.expandvars(b"$?bar"), b"$?bar")
            self.assertEqual(posixpath.expandvars(b"${foo}bar"), b"barbar")
            self.assertEqual(posixpath.expandvars(b"$foo}bar"), b"bar}bar")
            self.assertEqual(posixpath.expandvars(b"${foo"), b"${foo")
            self.assertEqual(posixpath.expandvars(b"${{foo}}"), b"baz1}")
            self.assertEqual(posixpath.expandvars(b"$foo$foo"), b"barbar")
            self.assertEqual(posixpath.expandvars(b"$bar$bar"), b"$bar$bar")
            self.assertRaises(TypeError, posixpath.expandvars)

    def test_normpath(self):
        self.assertEqual(posixpath.normpath(""), ".")
        self.assertEqual(posixpath.normpath("/"), "/")
        self.assertEqual(posixpath.normpath("//"), "//")
        self.assertEqual(posixpath.normpath("///"), "/")
        self.assertEqual(posixpath.normpath("///foo/.//bar//"), "/foo/bar")
        self.assertEqual(posixpath.normpath("///foo/.//bar//.//..//.//baz"),
                         "/foo/baz")
        self.assertEqual(posixpath.normpath("///..//./foo/.//bar"), "/foo/bar")

        self.assertEqual(posixpath.normpath(b""), b".")
        self.assertEqual(posixpath.normpath(b"/"), b"/")
        self.assertEqual(posixpath.normpath(b"//"), b"//")
        self.assertEqual(posixpath.normpath(b"///"), b"/")
        self.assertEqual(posixpath.normpath(b"///foo/.//bar//"), b"/foo/bar")
        self.assertEqual(posixpath.normpath(b"///foo/.//bar//.//..//.//baz"),
                         b"/foo/baz")
        self.assertEqual(posixpath.normpath(b"///..//./foo/.//bar"),
                         b"/foo/bar")

        self.assertRaises(TypeError, posixpath.normpath)

    def test_abspath(self):
        self.assert_("foo" in posixpath.abspath("foo"))
        self.assert_(b"foo" in posixpath.abspath(b"foo"))

        self.assertRaises(TypeError, posixpath.abspath)

    def test_realpath(self):
        self.assert_("foo" in realpath("foo"))
        self.assert_(b"foo" in realpath(b"foo"))
        self.assertRaises(TypeError, posixpath.realpath)

    if hasattr(os, "symlink"):
        def test_realpath_basic(self):
            # Basic operation.
            try:
                os.symlink(ABSTFN+"1", ABSTFN)
                self.assertEqual(realpath(ABSTFN), ABSTFN+"1")
            finally:
                support.unlink(ABSTFN)

        def test_realpath_symlink_loops(self):
            # Bug #930024, return the path unchanged if we get into an infinite
            # symlink loop.
            try:
                old_path = abspath('.')
                os.symlink(ABSTFN, ABSTFN)
                self.assertEqual(realpath(ABSTFN), ABSTFN)

                os.symlink(ABSTFN+"1", ABSTFN+"2")
                os.symlink(ABSTFN+"2", ABSTFN+"1")
                self.assertEqual(realpath(ABSTFN+"1"), ABSTFN+"1")
                self.assertEqual(realpath(ABSTFN+"2"), ABSTFN+"2")

                # Test using relative path as well.
                os.chdir(dirname(ABSTFN))
                self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
            finally:
                os.chdir(old_path)
                support.unlink(ABSTFN)
                support.unlink(ABSTFN+"1")
                support.unlink(ABSTFN+"2")

        def test_realpath_resolve_parents(self):
            # We also need to resolve any symlinks in the parents of a relative
            # path passed to realpath. E.g.: current working directory is
            # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call
            # realpath("a"). This should return /usr/share/doc/a/.
            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/y")
                os.symlink(ABSTFN + "/y", ABSTFN + "/k")

                os.chdir(ABSTFN + "/k")
                self.assertEqual(realpath("a"), ABSTFN + "/y/a")
            finally:
                os.chdir(old_path)
                support.unlink(ABSTFN + "/k")
                safe_rmdir(ABSTFN + "/y")
                safe_rmdir(ABSTFN)

        def test_realpath_resolve_before_normalizing(self):
            # Bug #990669: Symbolic links should be resolved before we
            # normalize the path. E.g.: if we have directories 'a', 'k' and 'y'
            # in the following hierarchy:
            # a/k/y
            #
            # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
            # then realpath("link-y/..") should return 'k', not 'a'.
            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.mkdir(ABSTFN + "/k/y")
                os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y")

                # Absolute path.
                self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
                # Relative path.
                os.chdir(dirname(ABSTFN))
                self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."), ABSTFN + "/k")
            finally:
                os.chdir(old_path)
                support.unlink(ABSTFN + "/link-y")
                safe_rmdir(ABSTFN + "/k/y")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN)

        def test_realpath_resolve_first(self):
            # Bug #1213894: The first component of the path, if not absolute,
            # must be resolved too.

            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.symlink(ABSTFN, ABSTFN + "link")
                os.chdir(dirname(ABSTFN))

                base = basename(ABSTFN)
                self.assertEqual(realpath(base + "link"), ABSTFN)
                self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
            finally:
                os.chdir(old_path)
                support.unlink(ABSTFN + "link")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN)

    def test_relpath(self):
        (real_getcwd, os.getcwd) = (os.getcwd, lambda: r"/home/user/bar")
        try:
            curdir = os.path.split(os.getcwd())[-1]
            self.assertRaises(ValueError, posixpath.relpath, "")
            self.assertEqual(posixpath.relpath("a"), "a")
            self.assertEqual(posixpath.relpath(posixpath.abspath("a")), "a")
            self.assertEqual(posixpath.relpath("a/b"), "a/b")
            self.assertEqual(posixpath.relpath("../a/b"), "../a/b")
            self.assertEqual(posixpath.relpath("a", "../b"), "../"+curdir+"/a")
            self.assertEqual(posixpath.relpath("a/b", "../c"),
                             "../"+curdir+"/a/b")
            self.assertEqual(posixpath.relpath("a", "b/c"), "../../a")
            self.assertEqual(posixpath.relpath("a", "a"), ".")
        finally:
            os.getcwd = real_getcwd

    def test_relpath_bytes(self):
        (real_getcwdb, os.getcwdb) = (os.getcwdb, lambda: br"/home/user/bar")
        try:
            curdir = os.path.split(os.getcwdb())[-1]
            self.assertRaises(ValueError, posixpath.relpath, b"")
            self.assertEqual(posixpath.relpath(b"a"), b"a")
            self.assertEqual(posixpath.relpath(posixpath.abspath(b"a")), b"a")
            self.assertEqual(posixpath.relpath(b"a/b"), b"a/b")
            self.assertEqual(posixpath.relpath(b"../a/b"), b"../a/b")
            self.assertEqual(posixpath.relpath(b"a", b"../b"),
                             b"../"+curdir+b"/a")
            self.assertEqual(posixpath.relpath(b"a/b", b"../c"),
                             b"../"+curdir+b"/a/b")
            self.assertEqual(posixpath.relpath(b"a", b"b/c"), b"../../a")
            self.assertEqual(posixpath.relpath(b"a", b"a"), b".")

            self.assertRaises(TypeError, posixpath.relpath, b"bytes", "str")
            self.assertRaises(TypeError, posixpath.relpath, "str", b"bytes")
        finally:
            os.getcwdb = real_getcwdb

def test_main():
    support.run_unittest(PosixPathTest)

if __name__=="__main__":
    test_main()