text:
package org.leguan.refactoring.api;

import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.leguan.container.Container;
import org.leguan.container.ContainerItem;
import org.leguan.language.java.delegates.JavaContainerItem;
import org.leguan.language.java.delegates.jdt.JavaSourceJdt;
import org.leguan.language.java.delegates.jdt.JavaTypeJdt;
import org.leguan.refactoring.steps.AbstractJavaRefactoringStep;

@Slf4j
public class JavaRefactoringItem extends ContainerBasedRefactoringItem<JavaContainerItem> {

  public JavaRefactoringItem(Container container, JavaRefactoring refactoring) {
    super(container, refactoring, false);
  }

  public JavaRefactoringItem(Container container, JavaRefactoring refactoring, boolean writeback) {
    super(container, refactoring, writeback);
  }

  public List<AbstractRefactoringStep> apply(RefactoringEnvironment environment) {
    List<AbstractRefactoringStep> steps = new ArrayList<AbstractRefactoringStep>();

    JavaRefactoringEnvironment javaRefactoringEnvironment = (JavaRefactoringEnvironment) environment.getLanguageEnvironment(JavaRefactoringEnvironment.class);

    JavaRefactoring currentRefactoring = (JavaRefactoring) getRefactoring();
    for (ContainerItem nextContainerItem : getContainer().getAllItems()) {

      JavaContainerItem javaContainerItem = (JavaContainerItem) nextContainerItem;

      log.info("     Applying " + currentRefactoring.getClass().getName() + " on next item " + nextContainerItem.getId());

      AbstractJavaRefactoringStep refactoringStep = currentRefactoring.createSteps(nextContainerItem);

      if (refactoringStep == null)
        throw new IllegalStateException("JavaRefactoring " + currentRefactoring.getClass().getName() + " was not connected with a refactoring step");

      log.info("     Found JavaRefactoring step " + refactoringStep.getClass().getName());

      JavaTypeJdt javaTypeJdt = (JavaTypeJdt) javaContainerItem.getJavaSource().getMainType();
      JavaSourceJdt javaSourceJdt = (JavaSourceJdt) javaTypeJdt.getJavaSource();

      if (!javaSourceJdt.isRefactoringStarted())
        javaSourceJdt.startRefactorings();

      try {
        refactoringStep.setJavaRefactoringEnvironment(javaRefactoringEnvironment);
        refactoringStep.setRefactoringEnvironment(environment);
        refactoringStep.setContainerItem(nextContainerItem);
        refactoringStep.configure();
        refactoringStep.rewriteCompilationUnit(javaSourceJdt);
        steps.add(refactoringStep);
      } catch (RefactoringException e) {
        throw new IllegalStateException("Exception occured in step " + refactoringStep.getClass().getSimpleName() + ":", e);
      }

      log.info("Finished migration step " + refactoringStep.getClass().getName());

    }

    if (isCommit()) {
      javaRefactoringEnvironment.commit();
    }

    return steps;
  }
}

redpajama_set_name: RedPajamaGithub


text:
using LibGit2Sharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace PoshGit2
{
    public abstract class RepositoryCache : IDisposable, IRepositoryCache
    {
        private static readonly Task<IRepositoryStatus> s_null = Task.FromResult<IRepositoryStatus>(null);

        private readonly IStatusWriterProvider _statusWriterProvider;

        public RepositoryCache(ILogger log, Func<string, ICurrentWorkingDirectory, IRepositoryStatus> factory, IStatusWriterProvider statusWriterProvider)
        {
            _statusWriterProvider = statusWriterProvider;

            Log = log;
            RepositoryFactory = factory;
        }

        protected abstract IEnumerable<IRepositoryStatus> Repositories { get; }

        protected Func<string, ICurrentWorkingDirectory, IRepositoryStatus> RepositoryFactory { get; }

        protected ILogger Log { get; }

        public Task<IEnumerable<IRepositoryStatus>> GetAllReposAsync(CancellationToken cancellationToken)
        {
            var all = Repositories
                .Select(o => new ReadonlyCopyRepositoryStatus(o))
                .ToList();

            return Task.FromResult<IEnumerable<IRepositoryStatus>>(all);
        }

        public Task<IRepositoryStatus> FindRepoAsync(ICurrentWorkingDirectory cwd, CancellationToken cancellationToken)
        {
            if (!cwd.IsValid)
            {
                return s_null;
            }

            var path = cwd.CWD;
            var repo = FindGitRepo(path);

            if (repo == null)
            {
                return s_null;
            }

            try
            {
                var result = FindRepo(repo, cwd);

                return Task.FromResult(result);
            }
            catch (RepositoryNotFoundException)
            {
                return s_null;
            }
            catch (Exception e)
            {
                Log.Warning(e, "Unknown exception in cache");
                return s_null;
            }
        }

        public async Task<string> GetStatusStringAsync(IGitPromptSettings settings, ICurrentWorkingDirectory cwd, CancellationToken token)
        {
            var status = await FindRepoAsync(cwd, token);

            if (status == null)
            {
                return null;
            }

            var writer = _statusWriterProvider.GetStatusWriter(settings);

            writer.WriteStatus(status);

            return writer.Status;
        }

        public Task<bool> RemoveRepoAsync(string path, CancellationToken cancellationToken)
        {
            var repoPath = FindGitRepo(path);

            return Task.FromResult(RemovePath(repoPath));
        }

        public Task<bool> ClearCacheAsync(CancellationToken cancellationToken)
        {
            Clear();
            return Task.FromResult(true);
        }

        protected abstract IRepositoryStatus FindRepo(string repo, ICurrentWorkingDirectory cwd);

        protected abstract void Clear();

        protected abstract bool Remove(string path);

        protected bool RemovePath(string path)
        {
            var mainPath = FindGitRepo(path);

            if (mainPath == null)
            {
                return false;
            }

            return Remove(mainPath);
        }

        private static string FindGitRepo(string path)
        {
            if (path == null)
            {
                return null;
            }

            if (Directory.Exists(Path.Combine(path, ".git")))
            {
                return path;
            }
            else
            {
                var up = Path.GetDirectoryName(path);

                return string.Equals(up, path, StringComparison.OrdinalIgnoreCase) ? null : FindGitRepo(up);
            }
        }

        private bool disposedValue = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                disposedValue = true;
            }
        }

        public void Dispose() => Dispose(true);
    }
}


text:
_Released 10/31/2019_

**Features:**

- [testFiles](/guides/references/configuration#Folders-Files) now also accepts
  an Array of glob patterns when specifying what test files to load in
  configuration. Addresses
  [#5401](https://github.com/cypress-io/cypress/issues/5401).

**Bugfixes:**

- We fixed a regression in [3.5.0](#3-5-0) where the maximum size of an HTTP
  header or body in a stubbed [cy.route()](/api/commands/route) was limited to
  8kb causing requests to fail with a 431 HTTP error. Fixes
  [#5431](https://github.com/cypress-io/cypress/issues/5431).
- We fixed a bug where certain types of uncaught errors originating from the
  application under test would not route through the
  [uncaught:exception](/api/events/catalog-of-events#Uncaught-Exceptions)
  handler, and thus could not caught and ignored. These errors will also now
  correctly indicate that they came from application code. Fixes
  [#987](https://github.com/cypress-io/cypress/issues/987).
- We fixed a regression in [3.5.0](#3-5-0) that would throw an error during
  `cypress verify` when running as a non-root user on a non-Windows machine. We
  now always set the `--no-sandbox` flag when verifying in Electron, even when
  running as a non-root user. Fixes
  [#5434](https://github.com/cypress-io/cypress/issues/5434).
- We fixed a regression in [3.5.0](#3-5-0) where sometimes cookies were not set
  on the correct URL during a redirect inside of a
  [cy.visit()](/api/commands/visit) or [cy.request()](/api/commands/request).
  Fixes [#5432](https://github.com/cypress-io/cypress/issues/5432).
- We fixed a regression in [3.5.0](#3-5-0) causing environment variables
  containing unicode values to be incorrectly resolved when read via
  [Cypress.env()](/api/cypress-api/env). Fixes
  [#5435](https://github.com/cypress-io/cypress/issues/5435).
- We fixed a regression in [3.5.0](#3-5-0) that prevented use of `.click()` or
  `.type()` inside of an iframe element. Fixes
  [#5449](https://github.com/cypress-io/cypress/issues/5449). Fixes
  [#5435](https://github.com/cypress-io/cypress/issues/5435).
- We now throw the proper error message when an element cannot be interacted
  with due to being covered by an element with `position:fixed`. Fixes
  [#5430](https://github.com/cypress-io/cypress/issues/5430).
- We fixed a regression in [3.5.0](#3-5-0) that caused some `click` events to
  not be sent to the correct elements during `.click()`. Fixes
  [#5459](https://github.com/cypress-io/cypress/issues/5459).
- We updated `.type()` to properly respect focus selection changes during
  typing. Fixes [#5456](https://github.com/cypress-io/cypress/issues/5456).
- We fixed a regression in [3.5.0](#3-5-0) that caused selected text to be
  overwritten while typing a modifer key during `.type()`. Fixes
  [#5439](https://github.com/cypress-io/cypress/issues/5439).
- We now send all the proper events during `.type()` to input elements with type
  `date`, `time`, and `datetime-local` so that it now behaves as it did prior to
  [3.5.0](#3-5-0). Fixes
  [#5476](https://github.com/cypress-io/cypress/issues/5476).
- We now properly render iframe placeholder content when previewing DOM
  snapshots. Fixes [#5295](https://github.com/cypress-io/cypress/issues/5295).

**Misc:**

- We no longer log the default option `{multiple: true}` in the Command Log or
  the console during [cy.dblclick()](/api/commands/dblclick). Addresses
  [#5406](https://github.com/cypress-io/cypress/issues/5406).
- The text color of inactive tabs within the Cypress Chrome browser has been set
  to white for better readability. Addresses
  [#1661](https://github.com/cypress-io/cypress/issues/1661).

**Dependency Updates**

- Replaced `express-handlebars` with `squirrelly` to reduce dependency size.
  Addressed in [#5521](https://github.com/cypress-io/cypress/pull/5521).
- Upgraded `graceful-fs` from `4.2.0` to `4.2.3`. Addressed in
  [#5497](https://github.com/cypress-io/cypress/pull/5497).


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>IPNetwork: System.Net.CidrClassLess Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

IPNetwork
    2.2.0

IPNetwork utility computes your ip, ipv4, ipv6, netmask, cidr, subnet, supernet and network

System

Net

CidrClassLess

Public Member Functions |
List of all members

System.Net.CidrClassLess Class Reference

Inheritance diagram for System.Net.CidrClassLess:

  <map id="System.Net.CidrClassLess_map" name="System.Net.CidrClassLess_map">
<area href="interface_system_1_1_net_1_1_i_cidr_guess.html" alt="System.Net.ICidrGuess" shape="rect" coords="0,0,160,24"/>
</map>

Public Member Functions

bool 	TryGuessCidr (string ip, out byte cidr)

Member Function Documentation

◆ TryGuessCidr()

          bool System.Net.CidrClassLess.TryGuessCidr
          (
          string
          ip,

          out byte
          cidr

          )

inline

IPV4 : 32 IPV6 : 128

Parameters

ip

cidr

Returns

Implements System.Net.ICidrGuess.

The documentation for this class was generated from the following file:

D:/perso/ipnetwork/src/System.Net.IPNetwork/CidrClassLess.cs

<address class="footer">
Generated by

 1.8.13
</address>


text:
"""HTTP handler to shut down the notebook server.
"""
from tornado import web, ioloop
from notebook.base.handlers import IPythonHandler

class ShutdownHandler(IPythonHandler):
    @web.authenticated
    def post(self):
        self.log.info("Shutting down on /api/shutdown request.")
        ioloop.IOLoop.current().stop()

default_handlers = [
    (r"/api/shutdown", ShutdownHandler),
]


text:
<components>
  <project-components>
    <component>
      <implementation-class>com.intellij.openapi.roots.ui.configuration.ModuleEditorState</implementation-class>
      <option name="workspace" value="true"/>
      <skipForDummyProject/>
    </component>

    <!--
    <component>
      <implementation-class>com.intellij.openapi.roots.ui.configuration.ProjectLibrariesConfigurable</implementation-class>
    </component>
    -->

    <!--<component>-->
    <!--  <implementation-class>com.intellij.j2ee.web.WebConfigurable</implementation-class>-->
    <!--</component>-->
  </project-components>
  <module-components>
    <component>
      <implementation-class>com.intellij.openapi.roots.ui.configuration.DefaultModuleEditorsProvider</implementation-class>
      <option name="type" value="JAVA_MODULE;J2EE_EJB_MODULE;J2EE_WEB_MODULE"/>
    </component>
    <component>
      <interface-class>com.intellij.openapi.roots.ui.configuration.ModuleConfigurationEditorProvider</interface-class>
      <implementation-class>com.intellij.openapi.roots.ui.configuration.ModuleLevelConfigurablesEditorProvider</implementation-class>
    </component>
  </module-components>
</components>


text:
/*
 * Problem 23. Series of letters
 * Write a program that reads a string from the console and replaces all series of consecutive identical letters with a single one.
 * Example:
 * input	                    output
 * aaaaabbbbbcdddeeeedssaa	    abcdedsa
*/
using System;
class SeriesOfLetters
{
    static void Main()
    {
        Console.Write("Enter a string: ");
        string input = Console.ReadLine();

        string result = input[0].ToString();

        for (int i = 1; i < input.Length; i++)
        {
            if (input[i] != result[result.Length - 1])
            {
                result += input[i];
            }
        }

        Console.WriteLine(result);
    }
}


text:
package org.openmuc.framework.driver.iec61850;

import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import javax.naming.ConfigurationException;

import org.junit.Assert;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openmuc.framework.config.ChannelScanInfo;
import org.openmuc.framework.data.BooleanValue;
import org.openmuc.framework.data.ByteArrayValue;
import org.openmuc.framework.data.Flag;
import org.openmuc.framework.data.FloatValue;
import org.openmuc.framework.data.Record;
import org.openmuc.framework.data.Value;
import org.openmuc.framework.dataaccess.Channel;
import org.openmuc.framework.driver.spi.ChannelRecordContainer;
import org.openmuc.framework.driver.spi.ChannelValueContainer;
import org.openmuc.framework.driver.spi.ConnectionException;

import com.beanit.iec61850bean.BasicDataAttribute;
import com.beanit.iec61850bean.ClientAssociation;
import com.beanit.iec61850bean.ClientEventListener;
import com.beanit.iec61850bean.ClientSap;
import com.beanit.iec61850bean.Fc;
import com.beanit.iec61850bean.FcModelNode;
import com.beanit.iec61850bean.ModelNode;
import com.beanit.iec61850bean.Report;
import com.beanit.iec61850bean.SclParseException;
import com.beanit.iec61850bean.SclParser;
import com.beanit.iec61850bean.ServerEventListener;
import com.beanit.iec61850bean.ServerModel;
import com.beanit.iec61850bean.ServerSap;
import com.beanit.iec61850bean.ServiceError;

public class Iec61850ConnectionTest extends Thread implements ClientEventListener, ServerEventListener {

    int port = TestHelper.getAvailablePort();
    String host = "127.0.0.1";
    ClientSap clientSap = new ClientSap();
    ServerSap serverSap = null;
    ClientAssociation clientAssociation = null;
    ServerModel serversServerModel = null;

    @BeforeEach
    public void initialize() throws SclParseException, IOException {
        clientSap.setTSelRemote(new byte[] { 0, 1 });
        clientSap.setTSelLocal(new byte[] { 0, 0 });

        // ---------------------------------------------------
        // ----------------- Start test server------------------
        serverSap = TestHelper.runServer("src/test/resources/testOpenmuc.icd", port, serverSap, serversServerModel,
                this);
        start();
        System.out.println("IED Server is running");
        clientSap.setApTitleCalled(new int[] { 1, 1, 999, 1 });
    }

    @Test
    public void testScanForChannels()
            throws IOException, ServiceError, ConfigurationException, javax.naming.ConfigurationException,
            SclParseException, InterruptedException, UnsupportedOperationException, ConnectionException {

        System.out.println("Attempting to connect to server " + host + " on port " + port);

        clientAssociation = clientSap.associate(InetAddress.getByName(host), port, null, this);

        ServerModel serverModel = SclParser.parse("src/test/resources/testOpenmuc.icd").get(0);
        clientAssociation.setServerModel(serverModel);
        getAllBdas(serverModel, clientAssociation);

        Iec61850Connection testConnection = new Iec61850Connection(clientAssociation, serverModel);
        List<ChannelScanInfo> testChannelScanList = testConnection.scanForChannels("");

        for (int i = 14; i < 23; i++) {
            System.out.print(testChannelScanList.get(i).getChannelAddress() + "\n");
            Assert.assertEquals("BYTE_ARRAY", testChannelScanList.get(i).getValueType().toString());
        }
        Assert.assertEquals("LONG", testChannelScanList.get(23).getValueType().toString());
        Assert.assertEquals("BOOLEAN", testChannelScanList.get(24).getValueType().toString());
        Assert.assertEquals("FLOAT", testChannelScanList.get(25).getValueType().toString());
        Assert.assertEquals("DOUBLE", testChannelScanList.get(26).getValueType().toString());
        Assert.assertEquals("BYTE", testChannelScanList.get(27).getValueType().toString());
        Assert.assertEquals("SHORT", testChannelScanList.get(28).getValueType().toString());
        Assert.assertEquals("SHORT", testChannelScanList.get(29).getValueType().toString());
        Assert.assertEquals("INTEGER", testChannelScanList.get(30).getValueType().toString());
        Assert.assertEquals("INTEGER", testChannelScanList.get(31).getValueType().toString());
        Assert.assertEquals("LONG", testChannelScanList.get(32).getValueType().toString());
        Assert.assertEquals("LONG", testChannelScanList.get(33).getValueType().toString());
        Assert.assertEquals("BYTE_ARRAY", testChannelScanList.get(34).getValueType().toString());

    }

    @Test
    public void testRead()
            throws IOException, ServiceError, ConfigurationException, javax.naming.ConfigurationException,
            SclParseException, InterruptedException, UnsupportedOperationException, ConnectionException {

        System.out.println("Attempting to connect to server " + host + " on port " + port);

        clientAssociation = clientSap.associate(InetAddress.getByName(host), port, null, this);

        ServerModel serverModel = SclParser.parse("src/test/resources/testOpenmuc.icd").get(0);
        clientAssociation.setServerModel(serverModel);
        getAllBdas(serverModel, clientAssociation);
        // ------------SCAN FOR CHANNELS-------------------
        Iec61850Connection testIec61850Connection = new Iec61850Connection(clientAssociation, serverModel);
        List<ChannelRecordContainer> testRecordContainers = new ArrayList<>();
        List<ChannelScanInfo> testChannelScanList = testIec61850Connection.scanForChannels("");

        for (int i = 14; i < 34; i++) {
            testRecordContainers.add(new ChannelRecordContainerImpl(testChannelScanList.get(i).getChannelAddress()));
        }
        // ----------READ-------------------
        testIec61850Connection.read(testRecordContainers, null, "");

        System.out.print("recordContainer:" + testRecordContainers.get(0).getRecord() + "\n");
        Assert.assertEquals("[64]", testRecordContainers.get(0).getRecord().getValue().toString());

        System.out.print("recordContainer:" + testRecordContainers.get(0).getRecord() + "\n");
        Assert.assertEquals("[64]", testRecordContainers.get(0).getRecord().getValue().toString());

    }

    @Test
    public void testWrite()
            throws IOException, ServiceError, ConfigurationException, javax.naming.ConfigurationException,
            SclParseException, InterruptedException, UnsupportedOperationException, ConnectionException {

        System.out.println("Attempting to connect to server " + host + " on port " + port);

        clientAssociation = clientSap.associate(InetAddress.getByName(host), port, null, this);

        ServerModel serverModel = SclParser.parse("src/test/resources/testOpenmuc.icd").get(0);
        clientAssociation.setServerModel(serverModel);
        getAllBdas(serverModel, clientAssociation);

        // ------------SCAN FOR CHANNELS-------------------

        Iec61850Connection testIec61850Connection = new Iec61850Connection(clientAssociation, serverModel);
        List<ChannelScanInfo> testChannelScanList = testIec61850Connection.scanForChannels("");

        // ----------WRITE-----------------
        List<ChannelValueContainer> testChannelValueContainers = new ArrayList<>();

        byte[] newValue = { 0x44 };
        testChannelValueContainers.add(new ChannelValueContainerImpl(testChannelScanList.get(14).getChannelAddress(),
                new ByteArrayValue(newValue)));
        testChannelValueContainers.add(new ChannelValueContainerImpl(testChannelScanList.get(25).getChannelAddress(),
                new FloatValue((float) 12.5)));
        testChannelValueContainers.add(
                new ChannelValueContainerImpl(testChannelScanList.get(24).getChannelAddress(), new BooleanValue(true)));

        testIec61850Connection.write(testChannelValueContainers, null);

        // Create record container to read the changes made by "write"
        List<ChannelRecordContainer> testRecordContainers = new ArrayList<>();
        for (int i = 0; i < 34; i++) {
            testRecordContainers.add(new ChannelRecordContainerImpl(testChannelScanList.get(i).getChannelAddress()));
        }
        testIec61850Connection.read(testRecordContainers, null, "");

        Assert.assertEquals("[68]", testRecordContainers.get(14).getRecord().getValue().toString());
        Assert.assertEquals("12.5", testRecordContainers.get(25).getRecord().getValue().toString());
        Assert.assertEquals("true", testRecordContainers.get(24).getRecord().getValue().toString());
    }

    @AfterEach
    public void closeServerSap() {
        clientAssociation.disconnect();
        serverSap.stop();

    }

    private void getAllBdas(ServerModel serverModel, ClientAssociation clientAssociation)
            throws ServiceError, IOException {

        for (ModelNode ld : serverModel) {
            for (ModelNode ln : ld) {
                getDataRecursive(ln, clientAssociation);
            }
        }
    }

    private static void getDataRecursive(ModelNode modelNode, ClientAssociation clientAssociation)
            throws ServiceError, IOException {
        if (modelNode.getChildren() == null) {
            return;
        }
        for (ModelNode childNode : modelNode) {
            FcModelNode fcChildNode = (FcModelNode) childNode;
            if (fcChildNode.getFc() != Fc.CO) {
                System.out.println("calling GetDataValues(" + childNode.getReference() + ")");
                clientAssociation.getDataValues(fcChildNode);
            }
            // clientAssociation.setDataValues(fcChildNode);
            getDataRecursive(childNode, clientAssociation);
        }
    }

    @Override
    public List<ServiceError> write(List<BasicDataAttribute> bdas) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void serverStoppedListening(ServerSap serverSAP) {
        // TODO Auto-generated method stub

    }

    @Override
    public void newReport(Report report) {
        // TODO Auto-generated method stub

    }

    @Override
    public void associationClosed(IOException e) {
        // TODO Auto-generated method stub

    }

    public static class ChannelRecordContainerImpl implements ChannelRecordContainer {

        private Object channelHandle;
        private Record record;
        private final String channelAddress;

        public ChannelRecordContainerImpl(String channelAddress) {
            this.channelAddress = channelAddress;
        }

        @Override
        public Record getRecord() {
            return this.record;
        }

        @Override
        public Channel getChannel() {
            return null;
        }

        @Override
        public String getChannelAddress() {
            return this.channelAddress;
        }

        @Override
        public Object getChannelHandle() {
            return this.channelHandle;
        }

        @Override
        public void setRecord(Record record) {
            this.record = record;
        }

        @Override
        public void setChannelHandle(Object handle) {
            this.channelHandle = handle;
        }

        @Override
        public ChannelRecordContainer copy() {
            return null;
        }

    }

    private static class ChannelValueContainerImpl implements ChannelValueContainer {

        private final String channelAddress;
        private final Value value;
        private Flag flag;

        public ChannelValueContainerImpl(String channelAddress, Value value) {
            this.channelAddress = channelAddress;
            this.value = value;
        }

        @Override
        public String getChannelAddress() {
            return this.channelAddress;
        }

        @Override
        public Object getChannelHandle() {
            return null;
        }

        @Override
        public void setChannelHandle(Object handle) {

        }

        @Override
        public Value getValue() {
            return this.value;
        }

        @Override
        public void setFlag(Flag flag) {
            this.flag = flag;
        }

        @Override
        public Flag getFlag() {
            return flag;
        }

    }

}


text:
package net.onrc.onos.core.topology.web;

import net.onrc.onos.core.datastore.topology.KVPort;

import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class DatastorePortsResource extends ServerResource {

    @Get("json")
    public Iterable<KVPort> retrieve() {
        return KVPort.getAllPorts();
    }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>Identifier Index</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Trees

         Indices

         Help

[hide private]

[frames] | no frames]

Identifier Index

[
 A
  B
  C
 D
  E
  F
 G
  H
 I
  J
  K
  L
 M
 N
 O
  P
  Q
 R
 S
  T
 U
 V
 W
 X
  Y
  Z
 _
]

A

add_link()

(in IOC)
add_parameter()

(in IOC)

D

date_regex

(in ioc_writer.ioc_api)
delete_namespace()

(in ioc_writer.xmlutils)

G

get_current_date()

(in ioc_writer.ioc_et)
get_guid()

(in ioc_writer.ioc_et)
get_top_level_indicator_node()

(in ioc_writer.ioc_api)

I

IOC

(in ioc_writer.ioc_api)
ioc_common

(in ioc_writer)
IOCParseError

(in ioc_writer.ioc_api)

ioc_api

(in ioc_writer)
ioc_et

(in ioc_writer)

M

make_authored_by_node()

(in ioc_writer.ioc_et)
make_fileitem_peinfo_petimestamp()

(in ioc_writer.ioc_common)
make_processitem_handlelist_handle_name()

(in ioc_writer.ioc_common)

make_authored_date_node()

(in ioc_writer.ioc_et)
make_fileitem_peinfo_resourceinfolist_resourceinfoitem_name()

(in ioc_writer.ioc_common)
make_processitem_name()

(in ioc_writer.ioc_common)

make_content_node()

(in ioc_writer.ioc_et)
make_fileitem_peinfo_sections_section_name()

(in ioc_writer.ioc_common)
make_processitem_path()

(in ioc_writer.ioc_common)

make_context_node()

(in ioc_writer.ioc_et)
make_fileitem_peinfo_type()

(in ioc_writer.ioc_common)
make_processitem_portlist_portitem_remoteip()

(in ioc_writer.ioc_common)

make_criteria_node()

(in ioc_writer.ioc_et)
make_fileitem_peinfo_versioninfoitem()

(in ioc_writer.ioc_common)
make_processitem_sectionlist_memorysection_name()

(in ioc_writer.ioc_common)

make_description_node()

(in ioc_writer.ioc_et)
make_fileitem_sizeinbytes()

(in ioc_writer.ioc_common)
make_processitem_sectionlist_memorysection_peinfo_exports_exportedfunctions_string()

(in ioc_writer.ioc_common)

make_dnsentryitem_recordname()

(in ioc_writer.ioc_common)
make_fileitem_streamlist_stream_name()

(in ioc_writer.ioc_common)
make_processitem_stringlist_string()

(in ioc_writer.ioc_common)

make_driveritem_deviceitem_devicename()

(in ioc_writer.ioc_common)
make_fileitem_stringlist_string()

(in ioc_writer.ioc_common)
make_processitem_username()

(in ioc_writer.ioc_common)

make_driveritem_drivername()

(in ioc_writer.ioc_common)
make_fileitem_username()

(in ioc_writer.ioc_common)
make_registryitem_keypath()

(in ioc_writer.ioc_common)

make_eventlogitem_eid()

(in ioc_writer.ioc_common)
make_hookitem_hookedfunction()

(in ioc_writer.ioc_common)
make_registryitem_path()

(in ioc_writer.ioc_common)

make_eventlogitem_log()

(in ioc_writer.ioc_common)
make_hookitem_hookingmodule()

(in ioc_writer.ioc_common)
make_registryitem_text()

(in ioc_writer.ioc_common)

make_eventlogitem_message()

(in ioc_writer.ioc_common)
make_Indicator_node()

(in ioc_writer.ioc_api)
make_registryitem_valuename()

(in ioc_writer.ioc_common)

make_fileitem_fileattributes()

(in ioc_writer.ioc_common)
make_IndicatorItem_node()

(in ioc_writer.ioc_api)
make_serviceitem_description()

(in ioc_writer.ioc_common)

make_fileitem_fileextension()

(in ioc_writer.ioc_common)
make_ioc()

(in IOC)
make_serviceitem_descriptivename()

(in ioc_writer.ioc_common)

make_fileitem_filename()

(in ioc_writer.ioc_common)
make_IOC_root()

(in ioc_writer.ioc_et)
make_serviceitem_name()

(in ioc_writer.ioc_common)

make_fileitem_filepath()

(in ioc_writer.ioc_common)
make_keywords_node()

(in ioc_writer.ioc_et)
make_serviceitem_path()

(in ioc_writer.ioc_common)

make_fileitem_fullpath()

(in ioc_writer.ioc_common)
make_link_node()

(in ioc_writer.ioc_et)
make_serviceitem_pathmd5sum()

(in ioc_writer.ioc_common)

make_fileitem_md5sum()

(in ioc_writer.ioc_common)
make_links_node()

(in ioc_writer.ioc_et)
make_serviceitem_servicedll()

(in ioc_writer.ioc_common)

make_fileitem_peinfo_detectedanomalies_string()

(in ioc_writer.ioc_common)
make_metadata_node()

(in ioc_writer.ioc_et)
make_serviceitem_servicedllmd5sum()

(in ioc_writer.ioc_common)

make_fileitem_peinfo_detectedentrypointsignature_name()

(in ioc_writer.ioc_common)
make_param_node()

(in ioc_writer.ioc_et)
make_serviceitem_servicedllsignatureexists()

(in ioc_writer.ioc_common)

make_fileitem_peinfo_digitalsignature_signatureexists()

(in ioc_writer.ioc_common)
make_parameters_node()

(in ioc_writer.ioc_et)
make_serviceitem_servicedllsignatureverified()

(in ioc_writer.ioc_common)

make_fileitem_peinfo_digitalsignature_signatureverified()

(in ioc_writer.ioc_common)
make_portitem_remoteip()

(in ioc_writer.ioc_common)
make_short_description_node()

(in ioc_writer.ioc_et)

make_fileitem_peinfo_exports_dllname()

(in ioc_writer.ioc_common)
make_portitem_remoteport()

(in ioc_writer.ioc_common)
make_systeminfoitem_hostname()

(in ioc_writer.ioc_common)

make_fileitem_peinfo_exports_exportedfunctions_string()

(in ioc_writer.ioc_common)
make_prefetchitem_accessedfilelist_accessedfile()

(in ioc_writer.ioc_common)
make_systemrestoreitem_originalfilename()

(in ioc_writer.ioc_common)

make_fileitem_peinfo_exports_numberoffunctions()

(in ioc_writer.ioc_common)
make_prefetchitem_applicationfilename()

(in ioc_writer.ioc_common)
make_taskitem_name()

(in ioc_writer.ioc_common)

make_fileitem_peinfo_importedmodules_module_importedfunctions_string()

(in ioc_writer.ioc_common)
make_prefetchitem_applicationfullpath()

(in ioc_writer.ioc_common)

make_fileitem_peinfo_importedmodules_module_name()

(in ioc_writer.ioc_common)
make_processitem_arguments()

(in ioc_writer.ioc_common)

N

NSMAP

(in ioc_writer.ioc_et)

O

open_ioc()

(in IOC)

R

read_xml()

(in ioc_writer.xmlutils)
remove_indicator()

(in IOC)
remove_namespace()

(in ioc_writer.xmlutils)

read_xml_no_ns()

(in ioc_writer.xmlutils)
remove_link()

(in IOC)
remove_parameter()

(in IOC)

remove_description()

(in IOC)
remove_name()

(in IOC)

S

set_created_date()

(in IOC)
set_published_date()

(in IOC)
set_root_lastmodified()

(in ioc_writer.ioc_et)

set_lastmodified_date()

(in IOC)
set_root_created_date()

(in ioc_writer.ioc_et)
set_root_published_date()

(in ioc_writer.ioc_et)

U

update_description()

(in IOC)
update_link_rewrite()

(in IOC)
update_node_text()

(in ioc_writer.ioc_et)

update_link_rel_based()

(in IOC)
update_name()

(in IOC)
update_parameter()

(in IOC)

V

valid_indicatoritem_conditions

(in ioc_writer.ioc_api)

W

write_ioc()

(in ioc_writer.ioc_api)
write_ioc_to_file()

(in IOC)

X

xmlutils

(in ioc_writer)

_

__init__()

(in IOC)
__package__

(in ioc_writer.ioc_common)
__package__

(in ioc_writer.xmlutils)

__package__

(in ioc_writer.ioc_api)
__package__

(in ioc_writer.ioc_et)

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Wed Jul 24 17:29:33 2013

      http://epydoc.sourceforge.net


text:
from __future__ import absolute_import, division, print_function

import datetime as dt
import os
import sys
import types
import ctypes
import ctypes.util
import traceback
import re
import inspect
import glob
import importlib
import functools

import pyodbc

import dateutil.relativedelta

try:
    import win32com.client
except ImportError:
    pass

from .vfpdatabase import DatabaseContext

SET_PROPS = {
    'bell': ['ON', ''],
    'century': ['OFF', 19, 67, 2029],
    'compatible': ['OFF', 'PROMPT'],
    'cursor': ['ON'],
    'deleted': ['OFF'],
    'escape': ['OFF'],
    'exact': ['OFF'],
    'index': [''],
    'multilocks': ['OFF'],
    'near': ['OFF'],
    'notify': ['ON', 'ON'],
    'procedure': None,
    'refresh': [0, 5],
    'status': ['OFF'],
    'status bar': ['ON'],
    'talk': ['ON'],
    'unique': ['OFF'],
}

HOME = sys.argv[0]
if not HOME:
    HOME = sys.executable
HOME = os.path.dirname(os.path.abspath(HOME))

SEARCH_PATH = [HOME]

PCOUNTS = []

_str = str
try:
    from PySide import QtGui, QtCore

    QTGUICLASSES = [c[1] for c in inspect.getmembers(QtGui, inspect.isclass)]

    def _in_qtgui(cls):
        if cls in QTGUICLASSES:
            return True
        return any(_in_qtgui(c) for c in inspect.getmro(cls) if c is not cls)

    class HasColor(object):
        @property
        def backcolor(self):
            return self.palette().color(QtGui.QPalette.Background)

        @backcolor.setter
        def backcolor(self, color):
            palette = self.palette()
            palette.setColor(self.backgroundRole(), color)
            self.setPalette(palette)

        @property
        def forecolor(self):
            return self.palette().color(QtGui.QPalette.Foreground)

        @forecolor.setter
        def forecolor(self, color):
            palette = self.palette()
            palette.setColor(self.foregroundRole(), color)
            self.setPalette(palette)

    class HasFont(object):
        @property
        def fontname(self):
            return self.font().family()

        @fontname.setter
        def fontname(self, val):
            font = self.font()
            font.setFamily(val)
            self.setFont(font)

        @property
        def fontbold(self):
            return self.font().bold()

        @fontbold.setter
        def fontbold(self, val):
            font = self.font()
            font.setBold(val)
            self.setFont(font)

        @property
        def fontitalic(self):
            return self.font().italic()

        @fontitalic.setter
        def fontitalic(self, val):
            font = self.font()
            font.setItalic(val)
            self.setFont(font)

        @property
        def fontstrikethru(self):
            return self.font().strikeOut()

        @fontstrikethru.setter
        def fontstrikethru(self, val):
            font = self.font()
            font.setStrikeOut(val)
            self.setFont(font)

        @property
        def fontunderline(self):
            return self.font().fontunderline()

        @fontunderline.setter
        def fontunderline(self, val):
            font = self.font()
            font.setUnderline(val)
            self.setFont(font)

        @property
        def fontsize(self):
            return self.font().pointSize()

        @fontsize.setter
        def fontsize(self, val):
            font = self.font()
            font.setPointSize(val)
            self.setFont(font)

    class Custom(object):
        def __init__(self, *args, **kwargs):
            self._assign()
            for key in kwargs:
                setattr(self, key, kwargs[key])
            if _in_qtgui(type(self)) and 'parent' in kwargs:
                self.parent.add_object(self)
            self.init(*args)

        def init(self, *args, **kwargs):
            pass

        def add_object(self, obj):
            try:
                self.addWidget(obj)
            except:
                pass

        def addobject(self, name, *args):
            name = name.lower()
            setattr(self, name, create_object(*args, name=name, parent=self))

        @property
        def parentform(self):
            try:
                t = self
                while not isinstance(t, (Form, Toolbar)):
                    t = t.parent
                return t
            except:
                raise _EXCEPTION('object is not a member of a form')

        def _assign(self):
            pass

    class MainWindow(QtGui.QMainWindow):
        def __init__(self):
            super(type(self), self).__init__()
            self.mdiarea = QtGui.QMdiArea()
            self.mdiarea.setSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding);
            self.setCentralWidget(self.mdiarea)

        def add_object(self, obj):
            if isinstance(obj, Toolbar):
                self.addToolBar(obj)
            else:
                self.mdiarea.addSubWindow(obj)

        @property
        def caption(self):
            return self.windowTitle()

        @caption.setter
        def caption(self, val):
            self.setWindowTitle(val)

        @property
        def height(self):
            return QtGui.QMainWindow.height(self)

        @height.setter
        def height(self, val):
            self.setFixedHeight(val)

        @property
        def icon(self):
            return self.windowIcon()

        @icon.setter
        def icon(self, iconfile):
            self.setWindowIcon(QtGui.QIcon(iconfile))

    class Formset(Custom):
        pass

    class Form(QtGui.QMdiSubWindow, Custom, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QMdiSubWindow.__init__(self)
            self._centralwidget = QtGui.QWidget(self)
            self._vbox = QtGui.QVBoxLayout()
            self._centralwidget.setLayout(self._vbox)
            self.setWidget(self._centralwidget)
            Custom.__init__(self, *args, **kwargs)

        def addWidget(self, obj):
            self._vbox.addWidget(obj)

        def release(self):
            self.close()

        def destroy(self):
            pass

        def closeEvent(self, event):
            self.destroy()

        @property
        def caption(self):
            return self.windowTitle()

        @caption.setter
        def caption(self, val):
            self.setWindowTitle(val)

        @property
        def height(self):
            return self._centralwidget.height()

        @height.setter
        def height(self, val):
            self._centralwidget.setFixedHeight(val)

        @property
        def width(self):
            return self._centralwidget.width()

        @height.setter
        def width(self, val):
            self._centralwidget.setFixedWidth(val)

        @property
        def icon(self):
            return self.windowIcon()

        @icon.setter
        def icon(self, iconfile):
            self.setWindowIcon(QtGui.QIcon(iconfile))

    class Commandbutton(QtGui.QPushButton, Custom, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QPushButton.__init__(self)
            Custom.__init__(self, *args, **kwargs)
            self.clicked.connect(self.click)

        def click(self):
            pass

        @property
        def caption(self):
            return self.text()

        @caption.setter
        def caption(self, val):
            self.setText(val)

        @property
        def height(self):
            return QtGui.QPushButton.height(self)

        @height.setter
        def height(self, val):
            self.setFixedHeight(val)

        @property
        def width(self):
            return QtGui.QPushButton.width(self)

        @height.setter
        def width(self, val):
            self.setFixedWidth(val)

        @property
        def enabled(self):
            return self.isEnabled()

        @enabled.setter
        def enabled(self, val):
            self.setEnabled(val)

        @property
        def visible(self):
            return self.isVisible()

        @visible.setter
        def visible(self, val):
            self.setVisible(val)

        @property
        def picture(self):
            return QtGui.QPushButton.icon(self)

        @picture.setter
        def picture(self, iconfile):
            self.setIcon(QtGui.QIcon(iconfile))

        @property
        def tooltiptext(self):
            return self.toolTip()

        @tooltiptext.setter
        def tooltiptext(self, val):
            self.setToolTip(val)

        @property
        def specialeffect(self):
            if self.isFlat():
                return 2
            else:
                return 0

        @specialeffect.setter
        def specialeffect(self, val):
            self.setFlat(val == 2)

    class Label(QtGui.QLabel, Custom, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QLabel.__init__(self)
            Custom.__init__(self, *args, **kwargs)

        @property
        def caption(self):
            return self.text()

        @caption.setter
        def caption(self, val):
            self.setText(val)

        @property
        def height(self):
            return QtGui.QLabel.height(self)

        @height.setter
        def height(self, val):
            self.setFixedHeight(val)

        @property
        def width(self):
            return QtGui.QLabel.width(self)

        @height.setter
        def width(self, val):
            self.setFixedWidth(val)

    class Textbox(QtGui.QLineEdit, Custom, HasColor, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QLineEdit.__init__(self)
            Custom.__init__(self, *args, **kwargs)

        @property
        def height(self):
            return QtGui.QLabel.height(self)

        @height.setter
        def height(self, val):
            self.setFixedHeight(val)

        @property
        def value(self):
            return self.text()

        @value.setter
        def value(self, val):
            self.setText(val)

        @property
        def visible(self):
            return self.isVisible()

        @visible.setter
        def visible(self, val):
            self.setVisible(val)

        def focusInEvent(self, event):
            self.gotfocus()

        def focusOutEvent(self, event):
            self.lostfocus()

        def setfocus(self):
            self.setFocus()

    class Checkbox(QtGui.QCheckBox, Custom, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QCheckBox.__init__(self)
            Custom.__init__(self, *args, **kwargs)
            self.clicked.connect(self.click)
            self.clicked.connect(self.interactivechange)

        def click(self):
            pass

        def interactivechange(self):
            pass

        @property
        def caption(self):
            return self.text()

        @caption.setter
        def caption(self, val):
            self.setText(val)

        @property
        def height(self):
            return QtGui.QLabel.height(self)

        @height.setter
        def height(self, val):
            self.setFixedHeight(val)

    class Combobox(QtGui.QComboBox, Custom, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QComboBox.__init__(self)
            Custom.__init__(self, *args, **kwargs)
            self.currentIndexChanged.connect(self.interactivechange)

        def additem(self, val):
            index = self.currentIndex()
            self.blockSignals(True)
            self.addItem(val)
            self.setCurrentIndex(index)
            self.blockSignals(False)

        @property
        def value(self):
            return self.currentText()

        @value.setter
        def value(self, val):
            index = self.findText(val, QtCore.Qt.MatchFixedString)
            self.blockSignals(True)
            self.setCurrentIndex(index)
            self.blockSignals(False)
            self.programmaticchange()

        def programmaticchange(self):
            pass

        def interactivechange(self):
            pass

        @property
        def caption(self):
            return self.text()

        @caption.setter
        def caption(self, val):
            self.setText(val)

        @property
        def height(self):
            return QtGui.QComboBox.height(self)

        @height.setter
        def height(self, val):
            self.setFixedHeight(val)

        @property
        def width(self):
            return QtGui.QComboBox.width(self)

        @height.setter
        def width(self, val):
            self.setFixedWidth(val)

        @property
        def style(self):
            if self.isEditable():
                return 0
            else:
                return 2

        @style.setter
        def style(self, val):
            self.setEditable(val == 0)

    class Spinner(QtGui.QSpinBox, Custom, HasFont, HasColor):
        def __init__(self, *args, **kwargs):
            QtGui.QSpinBox.__init__(self)
            Custom.__init__(self, *args, **kwargs)
            self.pressed = False
            self.installEventFilter(self)
            self.valueChanged.connect(self.interactivechange)

        def eventFilter(self, widget, event):
            if event.type() == QtCore.QEvent.Type.MouseButtonPress:
                self.pressed = True
            if event.type() == QtCore.QEvent.Type.MouseButtonRelease:
                if self.pressed:
                    self.click()
                self.pressed = False
            return QtGui.QWidget.eventFilter(self, widget, event)

        def click(self):
            pass

        def interactivechange(self):
            pass

        def programmaticchange(self):
            pass

        @property
        def value(self):
            return QtGui.QSpinBox.value(self)

        @value.setter
        def value(self, val):
            self.blockSignals(True)
            self.setValue(val)
            self.blockSignals(False)
            self.programmaticchange()

    class Shape(QtGui.QFrame, Custom):
        def __init__(self, *args, **kwargs):
            QtGui.QFrame.__init__(self)
            Custom.__init__(self, *args, **kwargs)
            self.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)

        @property
        def height(self):
            return QtGui.QComboBox.height(self)

        @height.setter
        def height(self, val):
            self.setFixedHeight(val)

        @property
        def width(self):
            return QtGui.QComboBox.width(self)

        @height.setter
        def width(self, val):
            self.setFixedWidth(val)

    class Separator(QtGui.QFrame, Custom):
        def __init__(self, *args, **kwargs):
            QtGui.QFrame.__init__(self)
            Custom.__init__(self, *args, **kwargs)
            self.setFrameStyle(QtGui.QFrame.VLine | QtGui.QFrame.Plain)
            palette = self.palette()
            palette.setColor(self.foregroundRole(), QtGui.QColor(0, 0, 0, 0))
            self.setPalette(palette)
            margin = 4
            self.setContentsMargins(margin, 0, margin, 0)

    class Toolbar(QtGui.QToolBar, Custom):
        def __init__(self, *args, **kwargs):
            QtGui.QToolBar.__init__(self)
            Custom.__init__(self, *args, **kwargs)

    class Listbox(QtGui.QListWidget, Custom):
        def __init__(self, *args, **kwargs):
            QtGui.QListWidget.__init__(self)
            self.multiselect = 0
            Custom.__init__(self, *args, **kwargs)
            self._source = ''

        @property
        def rowsource(self):
            return self._source

        @rowsource.setter
        def rowsource(self, source):
            self._source = source
            table = DB._get_table_info(source).table
            for record in table:
                self.addItem(QtGui.QListWidgetItem(_str(record[0])))

        @property
        def multiselect(self):
            return int(self.selectionMode() == QtGui.QAbstractItemView.MultiSelection)

        @multiselect.setter
        def multiselect(self, mode):
            self.setSelectionMode(QtGui.QAbstractItemView.MultiSelection if mode else QtGui.QAbstractItemView.SingleSelection)

    class Grid(QtGui.QTableWidget, Custom, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QTableWidget.__init__(self)
            Custom.__init__(self, *args, **kwargs)
            self.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
            self._source = ''
            self.cellClicked.connect(self._update_recno)
            self.cellClicked.connect(self.click)
            self.cellDoubleClicked.connect(self.dblclick)

        def _update_recno(self):
            table = DB._get_table_info(self._source).table.goto(self.currentRow())
            self.refresh()

        def click(self):
            pass

        def dblclick(self):
            pass

        def refresh(self):
            table = DB._get_table_info(self._source).table
            labels = table.field_names
            self.setColumnCount(len(labels))
            self.setRowCount(len(table))
            self.setVerticalHeaderLabels(['>' if record is table.current_record else '  ' for record in table])
            self.setHorizontalHeaderLabels(labels)

            for i, record in enumerate(table):
                for j, val in enumerate(record):
                    self.setItem(i, j, QtGui.QTableWidgetItem(_str(val)))

        def focusInEvent(self, event):
            self.refresh()

        @property
        def allowrowsizing(self):
            return self.verticalHeader().resizeMode(0) == QtGui.QHeaderView.Interactive

        @allowrowsizing.setter
        def allowrowsizing(self, val):
            self.verticalHeader().setResizeMode(QtGui.QHeaderView.Interactive if val else QtGui.QHeaderView.Fixed)

        @property
        def recordsource(self):
            return self._source

        @recordsource.setter
        def recordsource(self, source):
            self._source = source
            self.refresh()

        @property
        def allowcellselection(self):
            return self.selectionBehavior() != QtGui.QAbstractItemView.SelectItems

        @allowcellselection.setter
        def allowcellselection(self, mode):
            self.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems if mode else QtGui.QAbstractItemView.SelectRows)
            self.setEditTriggers(QtGui.QAbstractItemView.AllEditTriggers if mode else QtGui.QAbstractItemView.NoEditTriggers)

    class Optiongroup(QtGui.QWidget, Custom):
        def __init__(self, *args, **kwargs):
            QtGui.QWidget.__init__(self)
            self._group = QtGui.QButtonGroup()
            self._vbox = QtGui.QVBoxLayout()
            self.setLayout(self._vbox)
            Custom.__init__(self, *args, **kwargs)

        def add_object(self, obj):
            self._vbox.addWidget(obj)
            self._group.addButton(obj)

        @property
        def enabled(self):
            return any(button.enabled for button in self._group.buttons())

        @enabled.setter
        def enabled(self, val):
            for button in self._group.buttons():
                button.enabled = val

        @property
        def buttoncount(self):
            return len(self._group.buttons())

        @buttoncount.setter
        def buttoncount(self, val):
            for i in range(val, self.buttoncount):
                self._group.buttons()[-1].deleteLater()
            for i in range(self.buttoncount, val):
                caption = 'option {}'.format(i + 1)
                name = caption.replace(' ', '')
                setattr(self, name, Optionbutton(caption=caption, name=name, parent=self))

    class Optionbutton(QtGui.QRadioButton, Custom, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QRadioButton.__init__(self)
            Custom.__init__(self, *args, **kwargs)

        @property
        def caption(self):
            return self.text()

        @caption.setter
        def caption(self, val):
            self.setText(val)

        @property
        def enabled(self):
            return self.isEnabled()

        @enabled.setter
        def enabled(self, val):
            self.setEnabled(val)

    class Pageframe(QtGui.QTabWidget, Custom, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QTabWidget.__init__(self)
            Custom.__init__(self, *args, **kwargs)

        def addWidget(self, widget):
            self.addTab(widget, widget.caption)

    class Page(QtGui.QWidget, Custom, HasFont):
        def __init__(self, *args, **kwargs):
            QtGui.QWidget.__init__(self)
            self._vbox = QtGui.QVBoxLayout()
            self.setLayout(self._vbox)
            self.caption = kwargs['name']
            Custom.__init__(self, *args, **kwargs)

        def addWidget(self, widget):
            self._vbox.addWidget(widget)

    class Image(Custom):
        pass

    class Timer(Custom):
        pass

    class Container(Custom):
        pass

    class Editbox(Custom):
        pass

    class Dataenvironment(Custom):
        pass

    qt_app = QtGui.QApplication(())

    def _exec():
        S['_screen'].show()
        return qt_app.exec_()

except ImportError:
    class Custom(object):
        pass

    class MainWindow(Custom):
        pass

    class Formset(Custom):
        pass

    class Form(Custom):
        pass

    class Commandbutton(Custom):
        pass

    class Label(Custom):
        pass

    class Textbox(Custom):
        pass

    class Checkbox(Custom):
        pass

    class Combobox(Custom):
        pass

    class Spinner(Custom):
        pass

    class Shape(Custom):
        pass

    class Separator(Custom):
        pass

    class Toolbar(Custom):
        pass

    class Listbox(Custom):
        pass

    class Grid(Custom):
        pass

    class Optiongroup(Custom):
        pass

    class Optionbutton(Custom):
        pass

    class Pageframe(Custom):
        pass

    class Page(Custom):
        pass

    class Image(Custom):
        pass

    class Timer(Custom):
        pass

    class Container(Custom):
        pass

    class Editbox(Custom):
        pass

    class Dataenvironment(Custom):
        pass

_EXCEPTION = Exception

class Exception(object):
    def __init__(self):
        self.message = ''
        self.lineno = 0
        self.errorno = 0
        self.procedure = ''
        self.stacklevel = 0
        self.linecontents = ''

    @classmethod
    def from_pyexception(cls, exc):
        trace = traceback.extract_stack()
        obj = cls()
        obj.message = _str(exc)
        if hasattr(exc, '__traceback__'):
            tb = exc.__traceback__
        else:
            tb = sys.exc_info()[2]
        obj.lineno = tb.tb_lineno
        filename = os.path.splitext(os.path.basename(tb.tb_frame.f_code.co_filename))[0]
        obj.procedure = filename + '.' + tb.tb_frame.f_code.co_name
        obj.stacklevel = len(trace) - 1
        return obj

class Array(object):
    def __init__(self, dim1, dim2=0, offset=0):
        self.columns = bool(dim2)
        self.offset = offset
        if not dim2:
            dim2 = 1
        self.dim1 = int(dim1)
        self.data = [False]*self.dim1*int(dim2)

    def _subarray(self, inds):
        def modify_slice(ind):
            def modify_slice_ind(slice_ind):
                return slice_ind - 1 if slice_ind is not None else None
            return slice(modify_slice_ind(ind.start), modify_slice_ind(ind.stop), ind.step)

        ind = modify_slice(inds)
        data = self.data[ind]
        new_array = Array(len(data), 1, ind.start)
        new_array.data = data
        return new_array

    def _get_index(self, inds):
        if not isinstance(inds, tuple):
            inds = (inds, 1)
        if len(inds) < 2:
            inds = (inds[0], 1)
        ind1, ind2 = [int(ind) - 1 for ind in inds]
        ind = (len(self) // self.dim1)*ind1 + ind2 - self.offset
        if ind < 0:
            raise IndexError('invalid indices')
        return ind

    def __getitem__(self, inds):
        if isinstance(inds, slice):
            return self._subarray(inds)
        return self.data[self._get_index(inds)]

    def __setitem__(self, inds, val):
        self.data[self._get_index(inds)] = val

    def __call__(self, *args):
        return self[args]

    def __len__(self):
        return len(self.data)

    def alen(self, arr_attr=0):
        if arr_attr == 2 and not self.columns:
            return 0
        return {
            0: len(self),
            1: self.dim1,
            2: len(self) // self.dim1,
        }[arr_attr]

    def index(self, val):
        try:
            return self.data.index(val) + 1 + self.offset
        except ValueError:
            return 0

    def __iter__(self):
        return iter(self.data)

    def __repr__(self):
        dims = (self.dim1,) if self.dim1 == len(self) else (self.dim1, len(self) // self.dim1)
        return '{}({})'.format(type(self).__name__, ', '.join(_str(dim) for dim in dims))

class _Memvar(object):
    def __init__(self):
        self.__dict__['public_scopes'] = []
        self.__dict__['local_scopes'] = []

    def _get_scope(self, key):
        if len(self.local_scopes) > 0 and key in self.local_scopes[-1]:
            return self.local_scopes[-1]
        for scope in reversed(self.public_scopes):
            if key in scope:
                return scope

    def __contains__(self, key):
        try:
            self[key]
            return True
        except:
            return False

    def __getattr__(self, key):
        return self[key]

    def __getitem__(self, key):
        scope = self._get_scope(key)
        if scope is not None:
            return scope[key]
        raise NameError('name {} is not defined'.format(key))

    def __setitem__(self, key, val):
        (self._get_scope(key) or self.public_scopes[-1])[key] = val

    def __setattr__(self, key, val):
        if key in self.__dict__:
            super(_Variable, self).__setattr__(key, val)
        else:
            self[key] = val

    def __delitem__(self, key):
        scope = self._get_scope(key)
        if scope:
            del scope[key]

    def __delattr__(self, key):
        del self[key]

    def _add_to_scopes(self, scope, *args, **kwargs):
        for arg in args:
            scope[arg] = False
        for key in kwargs:
            scope[key] = kwargs[key]

    def add_local(self, *args, **kwargs):
        self._add_to_scopes(self.local_scopes[-1], *args, **kwargs)

    def add_private(self, *args, **kwargs):
        self._add_to_scopes(self.public_scopes[-1], *args, **kwargs)

    def add_public(self, *args, **kwargs):
        self._add_to_scopes(self.public_scopes[0], *args, **kwargs)

    def pushscope(self):
        self.public_scopes.append({})
        self.local_scopes.append({})

    def popscope(self, *args):
        self.public_scopes.pop()
        self.local_scopes.pop()
        if args:
            return args[0] if len(args) == 1 else args

    def release(self, mode='Normal', skeleton=None):
        if mode == 'Extended':
            pass
        elif mode == 'Like':
            pass
        elif mode == 'Except':
            pass
        else:
            for var in list(self.local_scopes[-1]) + list(self.public_scopes[-1]):
                del self[var]

class _Variable(object):
    def __init__(self, memvar, db):
        self.__dict__['memvar'] = memvar
        self.__dict__['db'] = db

    def __getattr__(self, key):
        return self[key]

    def __getitem__(self, key):
        try:
            return self.db._get_table_info(key).table.current_record
        except:
            pass
        table_info = self.db._get_table_info()
        if table_info is not None and key in table_info.table.field_names:
            return table_info.table.current_record[key]
        return self.memvar[key]

    def __setitem__(self, key, val):
        self.memvar[key] = val

    def __setattr__(self, key, val):
        if key in self.__dict__:
            super(_Variable, self).__setattr__(key, val)
        else:
            self.memvar[key] = val

class _Function(object):
    def __init__(self):
        self.__dict__['modules'] = []
        self.__dict__['dlls'] = []

    def __getattr__(self, key):
        return self[key]

    def __getitem__(self, key):
        for dll in self.dlls:
            if hasattr(dll, key):
                return getattr(dll, key)
        for module in self.modules:
            if not hasattr(module, key) or (hasattr(module, '_CLASSES') and key in module._CLASSES):
                continue
            obj = getattr(module, key)
            if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType)):
                return obj
        for scope in M.public_scopes:
            if key in scope and isinstance(scope[key], Array):
                return scope[key]
        raise _EXCEPTION('{} is not a procedure'.format(key))

    def set_procedure(self, module, additive=False):
        if not additive:
            self.modules[:] = []
        elif module in self.modules:
            self.modules.remove(module)
        self.modules.insert(0, module)

    def release_procedure(self, *modules):
        for module in modules:
            self.modules.remove(module)

    def dll_declare(self, dllname, funcname, alias):
        # need something here to determine more about the dll file.
        try:
            dll = ctypes.CDLL(dllname)
        except:
            dll = ctypes.CDLL(ctypes.util.find_library(dllname))
        try:
            dll = next(d for d in self.dlls if d._name == dll._name)
        except:
            pass
        func = getattr(dll, funcname)
        alias = alias or funcname
        setattr(dll, alias, func)
        if dll not in self.dlls:
            self.dlls.append(dll)

    def dll_clear(self, *funcs):
        if not funcs:
            self.dlls = []
        else:
            for dll in self.dlls:
                for func in funcs:
                    if hasattr(dll, func):
                        delattr(dll, func)

class _Class(object):
    def __init__(self):
        self.modules = []

    def __getattr__(self, key):
        return self[key]

    def __getitem__(self, key):
        for module in self.modules:
            if hasattr(module, '_CLASSES') and key in module._CLASSES:
                return module._CLASSES[key]()
            elif hasattr(module, key) and inspect.isclass(getattr(module, key)):
                return getattr(module, key)
        raise KeyError(key)

    def set_procedure(self, module, additive=False):
        if not additive:
            self.modules[:] = []
        elif module in self.modules:
            self.modules.remove(module)
        self.modules.insert(0, module)

    def release_procedure(self, *modules):
        for module in modules:
            self.modules.remove(module)

def atline(search, string):
    return string[:string.find(search)+1].count('\r') + 1

def capslock(on=None):
    pass

def cdx(index, workarea):
    pass

def chrtran(expr, fchrs, rchrs):
     return ''.join(rchrs[fchrs.index(c)] if c in fchrs else c for c in expr)

def ctod(string):
    return dt.datetime.strptime(string, '%m/%d/%Y').date()

def ddeinitiate(service, topic):
    import dde
    import win32ui
    try:
        server = win32ui.GetApp().ddeServer
        conn = dde.CreateConversation(server)
        conn.ConnectTo(service, topic)
        return conn
    except dde.error:
        return -1

def ddesetoption(a, b):
    pass

def ddeterminate(a):
    pass

def ddesetservice(a, b, c=False):
    pass

def ddesettopic(a, b, c):
    pass

def dow_fix(weekday, firstday=0):
    return (weekday + 2 - (firstday or 1)) % 7 + 1

def dtos(dateobj):
    fmt = '%Y%m%d'
    if hasattr(dateobj, 'hour'):
        fmt += '%H%M%S'
    return dateobj.strftime(fmt)

def dtoc(dateobj):
    fmt = '%m/%d/%Y'
    if hasattr(dateobj, 'hour'):
        fmt += '%H:%M:%S'
    return dateobj.strftime(fmt)

def error(txt):
    raise _EXCEPTION(txt)

def fdate(filename, datetype=0):
    if datetype not in (0, 1):
        raise ValueError('datetype is invalid')
    mod_date = dt.datetime.fromtimestamp(os.path.getmtime(filename))
    return mod_date if datetype else mod_date.date()

def ftime(filename):
    return fdate(filename, 1).time()

def filetostr(filename):
    with open(filename) as fid:
        return fid.read().decode('ISO-8859-1')

def getdir(dir='.', text='', caption='Select Text', flags=0, root_only=False):
    return QtGui.QFileDialog.getExistingDirectory(parent=S['_screen'], caption=caption, dir=dir)

def getfile(file_ext='', text='', button_caption='', button_type=0, title=''):
    filter = {
        '': '',
        'txt': 'File (*.txt)',
        'dbf': 'Table/DBF (*.dbf)',
    }.get(file_ext, '*.' + file_ext)
    t = QtGui.QFileDialog()
    t.setFilter('All Files (*.*);;' + filter)
    t.selectFilter(filter or 'All Files (*.*);;')
    if text:
        (next(x for x in t.findChildren(QtGui.QLabel) if x.text() == 'File &name:')).setText(text)
    if button_caption:
        t.setLabelText(QtGui.QFileDialog.Accept, button_caption)
    if title:
        t.setWindowTitle(title)
    t.exec_()
    return t.selectedFiles()[0]

def _getwords(string, delim=None):
    return [w for w in string.split(delim) if w]

def getwordcount(string, delim=None):
    return len(_getwords(string, delim))

def getwordnum(string, index, delim=None):
    str_list = _getwords(string, delim)
    if 0 <= index <= len(str_list):
        return str_list[index-1]
    return ''

def gomonth(dateval, delta):
    return dateval + dateutil.relativedelta.relativedelta(months=delta)

def home(location=0):
    if location != 0:
        raise _EXCEPTION('not implemented')
    return HOME

def inkey(seconds=0, hide_cursor=False):
    pass

def isblank(expr):
    try:
        return not expr.strip()
    except:
        return expr is None

def like(matchstr, string):
    matchstr = matchstr.replace('.', r'\.').replace('*', '.*').replace('?', '.')
    return bool(re.match(matchstr, string))

def lineno(flag=None):
    exc_type, exc_obj, exc_tb = sys.exc_info()
    return exc_tb.tb_lineno

def locfile(filename, ext='', caption=''):
    '''find file on path'''
    if os.path.isfile(filename):
        return os.path.abspath(filename)
    dirname = os.path.dirname(filename)
    filename = os.path.basename(filename)
    for path in SEARCH_PATH:
        testpath = os.path.join(path, filename)
        if os.path.isfile(testpath):
            return os.path.abspath(testpath)
    return getfile(file_ext=ext, title=caption)

def message(flag=None):
    exc_type, exc_obj, exc_tb = sys.exc_info()
    if flag is None:
        return exc_obj.message
    return traceback.extract_tb(exc_tb)[0][3]

def messagebox(msg, arg1=None, arg2=None, timeout=None, details=''):
    OK_ONLY = 0
    OK_CANCEL = 1
    ABORT_RETRY_IGNORE = 2
    YES_NO_CANCEL = 3
    YES_NO = 4
    RETRY_CANCEL = 5

    NOICON = 0
    STOPSIGN = 16
    QUESTION = 32
    EXCLAMATION = 48
    INFORMATION = 64

    FIRSTBUTTON = 0
    SECONDBUTTON = 256
    THIRDBUTTON = 512

    OK = QtGui.QMessageBox.Ok
    CANCEL = QtGui.QMessageBox.Cancel
    ABORT = QtGui.QMessageBox.Abort
    RETRY = QtGui.QMessageBox.Retry
    IGNORE = QtGui.QMessageBox.Ignore
    YES = QtGui.QMessageBox.Yes
    NO = QtGui.QMessageBox.No

    RETURN_OK = 1
    RETURN_CANCEL = 2
    RETURN_ABORT = 3
    RETURN_RETRY = 4
    RETURN_IGNORE = 5
    RETURN_YES = 6
    RETURN_NO = 7

    def center_widget(widget):
        '''center the widget on the screen'''
        widget_pos = widget.frameGeometry()
        screen_center = QtGui.QDesktopWidget().screenGeometry().center()
        widget_pos.moveCenter(screen_center)
        widget.move(widget_pos.topLeft())

    flags=0
    title='vfp2py'
    if arg1 is not None:
        if isinstance(arg1, _str):
            title = arg1
            if arg2 is not None:
                flags = arg2
        else:
            flags = arg1
            if arg2 is not None:
                title = arg2
    flags = int(flags) & 1023

    buttons = {
        OK_ONLY: ((OK,), OK),
        OK_CANCEL: ((OK, CANCEL), CANCEL),
        ABORT_RETRY_IGNORE: ((ABORT, RETRY, IGNORE), IGNORE),
        YES_NO_CANCEL: ((YES, NO, CANCEL), CANCEL),
        YES_NO: ((YES, NO), NO),
        RETRY_CANCEL: ((RETRY, CANCEL), CANCEL)
    }[flags & 15]

    buttonobj = buttons[0][0]
    for button in buttons[0][1:]:
        buttonobj |= button

    icon = {
        NOICON: QtGui.QMessageBox.NoIcon,
        STOPSIGN: QtGui.QMessageBox.Critical,
        QUESTION: QtGui.QMessageBox.Question,
        EXCLAMATION: QtGui.QMessageBox.Warning,
        INFORMATION: QtGui.QMessageBox.Information
    }[flags & (15 << 4)]

    default_button = min(len(buttons[0])-1, (flags >> 8))

    msg_box = QtGui.QMessageBox(icon, title, msg, buttons=buttonobj)
    msg_box.setDefaultButton(buttons[0][default_button])
    msg_box.setEscapeButton(buttons[1])
    if details:
        msg_box.setDetailedText(details)

    msg_box.show()

    retval = [0]
    def closebox():
        t = retval
        t[0] = -1
        msg_box.close()

    if timeout:
        timer = QtCore.QTimer()
        timer.setSingleShot(True)
        timer.timeout.connect(closebox)
        timer.start(float(timeout)*1000)
        timeout = timer
    button = msg_box.exec_()
    if timeout and timeout.isActive():
        timeout.stop()
    retval = retval[0]
    center_widget(msg_box)
    return {
        OK: RETURN_OK,
        CANCEL: RETURN_CANCEL,
        ABORT: RETURN_ABORT,
        RETRY: RETURN_RETRY,
        IGNORE: RETURN_IGNORE,
        YES: RETURN_YES,
        NO: RETURN_NO
    }[button] if retval != -1 else -1

def pcount():
    return PCOUNTS[-1]

def program(level=None):
    trace = traceback.extract_stack()[:-1]
    if level is None:
        level = -1
    elif level < 0:
        return len(trace) - 1
    elif level == 0:
        level = 1
    if level >= len(trace):
        return ''
    prg = trace[level][2]
    if prg == '_program_main':
        prg = re.sub(r'.py$', '', trace[level][0])
    return prg.upper()

def quarter(datetime, start_month=1):
    if not datetime:
        return 0
    month = (datetime.month - start_month) % 12
    return (month - (month % 3)) // 3 + 1

def quit(message=None, flags=None, title=None):
    sys.exit()

def ratline(search, string):
    return string[:string.rfind(search)+1].count('\r') + 1

def rgb(red, green, blue):
    return QtGui.QColor(red, green, blue)

def seconds():
    now = dt.datetime.now()
    return (now - dt.datetime.combine(now, dt.time(0, 0))).seconds

def str(num, length=10, decimals=0):
    length = int(length)
    string = '{{:.{}f}}'.format(int(decimals)).format(num)
    if len(string) > length and len(string) - (decimals - 1) <= length:
        string = string[:length]
    elif len(string) > length:
        string = string.split('.')[0]
        if len(string) >= length:
            string = '{:E}'.format(num)
            groups = list(re.match(r'(\d.)(\d+)(E[+-])0*(\d+)', string).groups())
            trim = sum(len(x) for x in groups) - length
            if trim > 0:
                groups[1] = groups[1][:-trim]
            string = ''.join(groups)
    string = string.rjust(length)
    return string if len(string) == length else '*' * length

def strextract(string, begin, end='', occurance=1, flag=0):
    begin = re.escape(begin)
    end = re.escape(end)
    if end:
        between = '.*?'
    else:
        between = '.*'
    if flag & 4:
        regstr = '({}{}{})'.format(begin, between, end)
    else:
        regstr = '{}({}){}'.format(begin, between, end)
    try:
        if flag & 1:
            flags = re.IGNORECASE
        else:
            flags = 0
        return re.findall(regstr, string, flags=flags)[occurance - 1]
    except:
        if flag & 2 and end:
            return strextract(string, begin, '', occurance, flag & 5)
        return ''

def strtofile(string, filename, flag=0):
    flag = int(flag)
    if flag not in (0, 1, 2, 4):
        raise ValueError('invalid flag')

    mode = 'ab' if flag == 1 else 'wb'

    if flag == 2:
        output = string.encode('utf-16')
    elif flag == 4:
        output = b'\xef\xbb\xbf' + string.encode('utf-8')
    else:
        output = string

    try:
        with open(filename, mode) as fid:
            fid.write(output)
        return len(output)
    except:
        return 0

def strtran(string, old, new='', start=0, maxreplace=None, flags=0):
    retstr = ''
    while start > 0:
        try:
            ind = string.find(old) + len(old)
            retstr += string[:ind]
            string = string[ind:]
        except:
            break
        start -= 1
    if maxreplace:
        retstr += string.replace(old, new, maxreplace)
    else:
        retstr += string.replace(old, new)
    return retstr

def stuff(string, start, num_replaced, repl):
    return string[:int(start)-1] + repl + string[int(start)-1+int(num_replaced):]

def sqlcommit(conn):
    try:
        conn.commit()
        return 1
    except:
        return -1

def sqlconnect(name, userid=None, password=None, shared=False):
    return pyodbc.connect('dsn=' + name)

def sqlstringconnect(*args):
    if len(args) == 0 or len(args) == 1 and isinstance(args[0], bool):
        connect_string = None #should pop up a dialog
        shared = args[0] if args else False
    else:
        connect_string = args[0]
        shared = args[1] if len(args) > 1 else False
    return pyodbc.connect(connect_string)

def _odbc_cursor_to_db(results, cursor_name):
    if not cursor_name:
        cursor_name = 'sqlresult'
    try:
        values = results.fetchall()
        if not values:
            raise _EXCEPTION('')
        column_info = values[0].cursor_description
        columns = []
        for i, column in enumerate(column_info):
            field_name = column[0][:10]
            field_type = {
                int: 'N',
                _str: 'C',
                bool: 'L',
                float: 'N',
            }[column[1]]
            if field_type == 'N':
                field_lens = column[4:6]
            elif field_type == 'L':
                field_lens = ''
            else:
                field_lens = '({})'.format(column[4])
            columns.append('{} {}{}'.format(field_name, field_type, field_lens))
        DB.use(None, DB.select_function(cursor_name), None)
        DB.create_table(cursor_name + '.dbf', columns, 'free')
        for value in values:
            DB.insert(cursor_name, tuple(value))
        DB.goto(cursor_name, 0)
    except:
        pass

def sqlexec(conn, cmd='', cursor_name='', count_info=''):
    try:
        results = conn.execute(cmd)
        _odbc_cursor_to_db(results, cursor_name)
        return 1
    except:
        return -1

def sqlrollback(conn):
    try:
        conn.rollback()
        return 1
    except:
        return -1

def sqltables(conn, table_type='', cursor_name=''):
    try:
        _odbc_cursor_to_db(conn.cursor().tables(), cursor_name)
        return 1
    except:
        return -1

def sqldisconnect(connection):
    connection.close()

SYS2000iter = None
def vfp_sys(funcnum, *args):
    global SYS2000iter
    if funcnum == 16:
        import imp
        if hasattr(sys, "frozen") or hasattr(sys, "importers") or imp.is_frozen("__main__"):
            return os.path.dirname(sys.executable)
        return os.path.dirname(sys.argv[0])
    if funcnum == 2000:
        #seems to implement FindFirstFile and FindNextFile in win32api
        if len(args) == 1:
            skel, = args
            next_file = False
        else:
            skel, next_file = args[:2]
        if next_file:
            try:
                return next(SYS2000iter)
            except:
                return ''
        SYS2000iter = glob.iglob(skel)
        return vfp_sys(2000, skel, 1)

TYPE_MAP = {
    _str: 'C',
    dt.date: 'D',
    bool: 'L',
    int: 'N',
    float: 'N',
    dt.datetime: 'T',
    type(None): 'X',
}
if sys.version_info < (3,):
    TYPE_MAP[unicode] = 'C'

def vartype(var):
    return TYPE_MAP.get(type(var), 'O')

def version(ver_type=4):
    if ver_type == 4:
        return 'Not FoxPro 9'
    if ver_type == 5:
        return 900

def wait(msg, to=None, window=[-1, -1], nowait=False, noclear=False, timeout=-1):
    pass
def gather(val=None, fields=None, fieldstype=None, memo=None):
    DB._update_from(val)

def scatter(totype=None, name=None, fields=None, fieldstype=None, memo=False, blank=False):
    record = DB._current_record_copy()
    if totype == 'name':
        return record

def set(setword, *args, **kwargs):
    setword = setword.lower()
    settings = SET_PROPS[setword]
    if not kwargs.get('set_value', False):
        return settings[args[0]] if args else settings[0]
    if setword == 'bell':
        if args[0].lower() not in ('to', 'on', 'off'):
            raise ValueError('Bad argument: {}'.format(args[0]))
        if args[0] == 'TO':
            settings[1] = '' if len(args) == 1 else args[1]
        else:
            settings[0] = args[0].upper()
    elif setword == 'century':
        if len(args) > 0:
            settings[0] = args[0]
        if 'century' in kwargs:
            settings[1] = kwargs['century']
        if 'rollover' in kwargs:
            settings[2] = kwargs['rollover']
    elif setword == 'compatible':
        if args[0].lower() not in ('on', 'off'):
            raise ValueError('Bad argument: {}'.format(args[0]))
        settings[0] = args[0].upper()
        if len(args) > 1:
            if args[1].lower() not in ('prompt', 'noprompt'):
                settings[1] = args[1].upper()
    elif setword == 'notify':
        if 'cursor' in kwargs:
            settings[1] = kwargs['cursor']
        else:
            settings[0] = args[0]
    elif setword in ('cursor', 'deleted', 'escape', 'exact', 'multilocks', 'near', 'status', 'status bar', 'talk', 'unique'):
        if args[0].lower() not in ('on', 'off'):
            raise ValueError('Bad argument: {}'.format(args[0]))
        settings[0] = args[0].upper()
    elif setword in ('index', 'refresh'):
        settings = args
    elif setword == 'procedure':
        module = importlib.import_module(args[0])
        F.set_procedure(module, additive=kwargs.get('additive', False))
        C.set_procedure(module, additive=kwargs.get('additive', False))
    SET_PROPS[setword] = settings

def text(text_lines, show=True):
    text = ''.join(l.strip() for l in text_lines)
    if show:
        print(text)
    return text

def create_object(objtype, *args, **kwargs):
    objtype = objtype.title()
    frame = inspect.getouterframes(inspect.currentframe())[2][0]
    if objtype in frame.f_globals:
        return frame.f_globals[objtype](*args, **kwargs)
    try:
        return C[objtype]()
    except:
        pass
    try:
        return win32com.client.Dispatch(objtype)
    except:
        pass
    raise _EXCEPTION('class definition \'{}\' not found'.format(objtype))

def clearall():
    pass

def clear(*args):
    pass

DB = DatabaseContext()
M = _Memvar()
S = _Variable(M, DB)
F = _Function()
C = _Class()

def module(module_name):
    return __import__(module_name.lower())

error_func = None
M.pushscope()
M.add_public('_screen')
S._screen = MainWindow()
S._screen.caption = 'VFP To Python'

def _parameters(scope_func, *varnames):
    def decorator(fn):
        fn_args = fn.__code__.co_varnames
        if len(fn_args) == 1 and fn_args[0] == 'self' and varnames:
            @functools.wraps(fn)
            def scoper(self, *args):
                global PARAMETERS
                M.pushscope()
                PARAMETERS = len(args)
                PCOUNTS.append(PARAMETERS)
                kwargs = {name: arg for name, arg in zip(varnames, args)}
                args = varnames[len(args):]
                scope_func(*args, **kwargs)
                retval = fn(self)
                PCOUNTS.pop()
                M.popscope()
                return retval
        elif varnames:
            @functools.wraps(fn)
            def scoper(*args):
                global PARAMETERS
                M.pushscope()
                PARAMETERS = len(args)
                PCOUNTS.append(PARAMETERS)
                kwargs = {name: arg for name, arg in zip(varnames, args)}
                args = varnames[len(args):]
                scope_func(*args, **kwargs)
                retval = fn()
                PCOUNTS.pop()
                M.popscope()
                return retval
        else:
            @functools.wraps(fn)
            def scoper(*args):
                global PARAMETERS
                M.pushscope()
                PARAMETERS = 0
                PCOUNTS.append(PARAMETERS)
                retval = fn(*args)
                PCOUNTS.pop()
                M.popscope()
                return retval
        scoper.__name__ = fn.__name__
        return scoper
    return decorator

def parameters(*varnames):
    return _parameters(M.add_private, *varnames)

def lparameters(*varnames):
    return _parameters(M.add_local, *varnames)

def vfpclass(fn):
    if '_CLASSES' not in fn.__globals__:
        fn.__globals__['_CLASSES'] = {}
    fn.__globals__['_CLASSES'][fn.__name__] = fn
    @functools.wraps(fn)
    def double_caller(*args, **kwargs):
        return fn()(*args, **kwargs)
    fn.__globals__[fn.__name__ + 'Type'] = fn
    return double_caller

set('procedure', 'vfp2py.vfpfunc', set_value=True)