text:
"""
    sphinx.highlighting
    ~~~~~~~~~~~~~~~~~~~

    Highlight code blocks using Pygments.

    :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

from six import text_type

from sphinx.util.pycompat import htmlescape
from sphinx.util.texescape import tex_hl_escape_map_new
from sphinx.ext import doctest

from pygments import highlight
from pygments.lexers import PythonLexer, Python3Lexer, PythonConsoleLexer, \
    CLexer, TextLexer, RstLexer
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.formatters import HtmlFormatter, LatexFormatter
from pygments.filters import ErrorToken
from pygments.styles import get_style_by_name
from pygments.util import ClassNotFound
from sphinx.pygments_styles import SphinxStyle, NoneStyle

lexers = dict(
    none = TextLexer(stripnl=False),
    python = PythonLexer(stripnl=False),
    python3 = Python3Lexer(stripnl=False),
    pycon = PythonConsoleLexer(stripnl=False),
    pycon3 = PythonConsoleLexer(python3=True, stripnl=False),
    rest = RstLexer(stripnl=False),
    c = CLexer(stripnl=False),
)
for _lexer in lexers.values():
    _lexer.add_filter('raiseonerror')

escape_hl_chars = {ord(u'\\'): u'\\PYGZbs{}',
                   ord(u'{'): u'\\PYGZob{}',
                   ord(u'}'): u'\\PYGZcb{}'}

# used if Pygments is available
# use textcomp quote to get a true single quote
_LATEX_ADD_STYLES = r'''
\renewcommand\PYGZsq{\textquotesingle}
'''

class PygmentsBridge(object):
    # Set these attributes if you want to have different Pygments formatters
    # than the default ones.
    html_formatter = HtmlFormatter
    latex_formatter = LatexFormatter

    def __init__(self, dest='html', stylename='sphinx',
                 trim_doctest_flags=False):
        self.dest = dest
        if stylename is None or stylename == 'sphinx':
            style = SphinxStyle
        elif stylename == 'none':
            style = NoneStyle
        elif '.' in stylename:
            module, stylename = stylename.rsplit('.', 1)
            style = getattr(__import__(module, None, None, ['__name__']),
                            stylename)
        else:
            style = get_style_by_name(stylename)
        self.trim_doctest_flags = trim_doctest_flags
        self.formatter_args = {'style': style}
        if dest == 'html':
            self.formatter = self.html_formatter
        else:
            self.formatter = self.latex_formatter
            self.formatter_args['commandprefix'] = 'PYG'

    def get_formatter(self, **kwargs):
        kwargs.update(self.formatter_args)
        return self.formatter(**kwargs)

    def unhighlighted(self, source):
        if self.dest == 'html':
            return '<pre>' + htmlescape(source) + '</pre>\n'
        else:
            # first, escape highlighting characters like Pygments does
            source = source.translate(escape_hl_chars)
            # then, escape all characters nonrepresentable in LaTeX
            source = source.translate(tex_hl_escape_map_new)
            return '\\begin{Verbatim}[commandchars=\\\\\\{\\}]\n' + \
                   source + '\\end{Verbatim}\n'

    def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
        if not isinstance(source, text_type):
            source = source.decode()

        # find out which lexer to use
        if lang in ('py', 'python'):
            if source.startswith('>>>'):
                # interactive session
                lexer = lexers['pycon']
            else:
                lexer = lexers['python']
        elif lang in ('py3', 'python3', 'default'):
            if source.startswith('>>>'):
                lexer = lexers['pycon3']
            else:
                lexer = lexers['python3']
        elif lang == 'guess':
            try:
                lexer = guess_lexer(source)
            except Exception:
                lexer = lexers['none']
        else:
            if lang in lexers:
                lexer = lexers[lang]
            else:
                try:
                    lexer = lexers[lang] = get_lexer_by_name(lang, **(opts or {}))
                except ClassNotFound:
                    if warn:
                        warn('Pygments lexer name %r is not known' % lang)
                        lexer = lexers['none']
                    else:
                        raise
                else:
                    lexer.add_filter('raiseonerror')

        # trim doctest options if wanted
        if isinstance(lexer, PythonConsoleLexer) and self.trim_doctest_flags:
            source = doctest.blankline_re.sub('', source)
            source = doctest.doctestopt_re.sub('', source)

        # highlight via Pygments
        formatter = self.get_formatter(**kwargs)
        try:
            hlsource = highlight(source, lexer, formatter)
        except ErrorToken as exc:
            # this is most probably not the selected language,
            # so let it pass unhighlighted
            if lang == 'default':
                pass  # automatic highlighting failed.
            elif warn:
                warn('Could not lex literal_block as "%s". '
                     'Highlighting skipped.' % lang)
            else:
                raise exc
            hlsource = highlight(source, lexers['none'], formatter)
        if self.dest == 'html':
            return hlsource
        else:
            if not isinstance(hlsource, text_type):  # Py2 / Pygments < 1.6
                hlsource = hlsource.decode()
            return hlsource.translate(tex_hl_escape_map_new)

    def get_stylesheet(self):
        formatter = self.get_formatter()
        if self.dest == 'html':
            return formatter.get_style_defs('.highlight')
        else:
            return formatter.get_style_defs() + _LATEX_ADD_STYLES


text:
package dryrun

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	errorsutil "k8s.io/apimachinery/pkg/util/errors"

	kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
	"k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient"
)

// FileToPrint represents a temporary file on disk that might want to be aliased when printing
// Useful for things like loading a file from /tmp/ but saying to the user "Would write file foo to /etc/kubernetes/..."
type FileToPrint struct {
	RealPath  string
	PrintPath string
}

// NewFileToPrint makes a new instance of FileToPrint with the specified arguments
func NewFileToPrint(realPath, printPath string) FileToPrint {
	return FileToPrint{
		RealPath:  realPath,
		PrintPath: printPath,
	}
}

// PrintDryRunFile is a helper method around PrintDryRunFiles
func PrintDryRunFile(fileName, realDir, printDir string, w io.Writer) error {
	return PrintDryRunFiles([]FileToPrint{
		NewFileToPrint(filepath.Join(realDir, fileName), filepath.Join(printDir, fileName)),
	}, w)
}

// PrintDryRunFiles prints the contents of the FileToPrints given to it to the writer w
func PrintDryRunFiles(files []FileToPrint, w io.Writer) error {
	errs := []error{}
	for _, file := range files {
		if len(file.RealPath) == 0 {
			continue
		}

		fileBytes, err := os.ReadFile(file.RealPath)
		if err != nil {
			errs = append(errs, err)
			continue
		}

		// Make it possible to fake the path of the file; i.e. you may want to tell the user
		// "Here is what would be written to /etc/kubernetes/admin.conf", although you wrote it to /tmp/kubeadm-dryrun/admin.conf and are loading it from there
		// Fall back to the "real" path if PrintPath is not set
		outputFilePath := file.PrintPath
		if len(outputFilePath) == 0 {
			outputFilePath = file.RealPath
		}

		fmt.Fprintf(w, "[dryrun] Would write file %q with content:\n", outputFilePath)
		apiclient.PrintBytesWithLinePrefix(w, fileBytes, "\t")
	}
	return errorsutil.NewAggregate(errs)
}

// Waiter is an implementation of apiclient.Waiter that should be used for dry-running
type Waiter struct{}

// NewWaiter returns a new Waiter object that talks to the given Kubernetes cluster
func NewWaiter() apiclient.Waiter {
	return &Waiter{}
}

// WaitForAPI just returns a dummy nil, to indicate that the program should just proceed
func (w *Waiter) WaitForAPI() error {
	fmt.Println("[dryrun] Would wait for the API Server's /healthz endpoint to return 'ok'")
	return nil
}

// WaitForPodsWithLabel just returns a dummy nil, to indicate that the program should just proceed
func (w *Waiter) WaitForPodsWithLabel(kvLabel string) error {
	fmt.Printf("[dryrun] Would wait for the Pods with the label %q in the %s namespace to become Running\n", kvLabel, metav1.NamespaceSystem)
	return nil
}

// WaitForPodToDisappear just returns a dummy nil, to indicate that the program should just proceed
func (w *Waiter) WaitForPodToDisappear(podName string) error {
	fmt.Printf("[dryrun] Would wait for the %q Pod in the %s namespace to be deleted\n", podName, metav1.NamespaceSystem)
	return nil
}

// WaitForHealthyKubelet blocks until the kubelet /healthz endpoint returns 'ok'
func (w *Waiter) WaitForHealthyKubelet(_ time.Duration, healthzEndpoint string) error {
	fmt.Printf("[dryrun] Would make sure the kubelet %q endpoint is healthy\n", healthzEndpoint)
	return nil
}

// WaitForKubeletAndFunc is a wrapper for WaitForHealthyKubelet that also blocks for a function
func (w *Waiter) WaitForKubeletAndFunc(f func() error) error {
	return nil
}

// SetTimeout is a no-op; we don't wait in this implementation
func (w *Waiter) SetTimeout(_ time.Duration) {}

// WaitForStaticPodControlPlaneHashes returns an empty hash for all control plane images;
func (w *Waiter) WaitForStaticPodControlPlaneHashes(_ string) (map[string]string, error) {
	return map[string]string{
		kubeadmconstants.KubeAPIServer:         "",
		kubeadmconstants.KubeControllerManager: "",
		kubeadmconstants.KubeScheduler:         "",
	}, nil
}

// WaitForStaticPodSingleHash returns an empty hash
// but the empty strings there are needed
func (w *Waiter) WaitForStaticPodSingleHash(_ string, _ string) (string, error) {
	return "", nil
}

// WaitForStaticPodHashChange returns a dummy nil error in order for the flow to just continue as we're dryrunning
func (w *Waiter) WaitForStaticPodHashChange(_, _, _ string) error {
	return nil
}

// PrintFilesIfDryRunning prints the static pod manifests to stdout and informs about the temporary directory to go and lookup when dry running
func PrintFilesIfDryRunning(needPrintManifest bool, manifestDir string, outputWriter io.Writer) error {
	var files []FileToPrint
	// Print static pod manifests if it is a control plane
	if needPrintManifest {
		fmt.Printf("[dryrun] Wrote certificates, kubeconfig files and control plane manifests to the %q directory\n", manifestDir)
		for _, component := range kubeadmconstants.ControlPlaneComponents {
			realPath := kubeadmconstants.GetStaticPodFilepath(component, manifestDir)
			outputPath := kubeadmconstants.GetStaticPodFilepath(component, kubeadmconstants.GetStaticPodDirectory())
			files = append(files, NewFileToPrint(realPath, outputPath))
		}
	} else {
		fmt.Printf("[dryrun] Wrote certificates and kubeconfig files to the %q directory\n", manifestDir)
	}

	fmt.Println("[dryrun] The certificates or kubeconfig files would not be printed due to their sensitive nature")
	fmt.Printf("[dryrun] Please examine the %q directory for details about what would be written\n", manifestDir)

	// Print kubelet config manifests
	kubeletConfigFiles := []string{kubeadmconstants.KubeletConfigurationFileName, kubeadmconstants.KubeletEnvFileName}
	for _, filename := range kubeletConfigFiles {
		realPath := filepath.Join(manifestDir, filename)
		outputPath := filepath.Join(kubeadmconstants.KubeletRunDirectory, filename)
		files = append(files, NewFileToPrint(realPath, outputPath))
	}

	return PrintDryRunFiles(files, outputWriter)
}

redpajama_set_name: RedPajamaGithub


text:
package com.evolveum.midpoint.testing.conntest;

import java.io.File;

import org.testng.annotations.AfterClass;
import org.testng.annotations.Listeners;

import com.evolveum.midpoint.test.util.MidPointTestConstants;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;

/**
 * @author semancik
 *
 */
@Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class })
public class TestOpenDj extends AbstractLdapConnTest {

	private static final String OPENDJ_TEMPLATE_NAME = "opendj-4000.template";

	private static final int INITIAL_SYNC_TOKEN = 23;

	@Override
	protected String getResourceOid() {
		return "371ffc38-c424-11e4-8467-001e8c717e5b";
	}

	@Override
	protected File getBaseDir() {
		return new File(MidPointTestConstants.TEST_RESOURCES_DIR, "opendj");
	}

	@Override
	public String getStartSystemCommand() {
		return null;
	}

	@Override
	public String getStopSystemCommand() {
		return null;
	}

	@Override
	protected void startResources() throws Exception {
		super.startResources();
		openDJController.startCleanServer(OPENDJ_TEMPLATE_NAME);
	}

	@AfterClass
    public static void stopResources() throws Exception {
		AbstractLdapConnTest.stopResources();
		openDJController.stop();
	}

	@Override
	protected String getLdapServerHost() {
		return "localhost";
	}

	@Override
	protected int getLdapServerPort() {
		return 10389;
	}

	@Override
	protected String getLdapBindDn() {
		return "cn=directory manager";
	}

	@Override
	protected String getLdapBindPassword() {
		return "secret";
	}

	@Override
	protected String getPeopleLdapSuffix() {
		return "ou=people,"+getLdapSuffix();
	}

	@Override
	protected String getAccount0Cn() {
		return "Warlaz Kunjegjul (00000000)";
	}

	@Override
	protected boolean isIdmAdminInteOrgPerson() {
		return true;
	}

	@Override
	protected int getSearchSizeLimit() {
		return 1000;
	}

	@Override
	protected String getLdapGroupObjectClass() {
		return "groupOfUniqueNames";
	}

	@Override
	protected String getLdapGroupMemberAttribute() {
		return "uniqueMember";
	}

	@Override
	protected boolean needsGroupFakeMemeberEntry() {
		return true;
	}

	@Override
	protected String getSyncTaskOid() {
		return "cd1e0ff2-0099-11e5-9e22-001e8c717e5b";
	}

	protected int getInitialSyncToken() {
		return INITIAL_SYNC_TOKEN;
	}

	@Override
	protected boolean isAssertOpenFiles() {
		// Cannot do this here. OpenDJ is embedded, the
		// number of open files for the whole process may
		// vary significantly because of OpenDJ.
		return false;
	}

	@Override
	protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd)
			throws ObjectNotFoundException, SchemaException {
		assertSyncToken(syncTaskOid, (Integer)(step + getInitialSyncToken()));
	}

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.cosmos.internal;

import com.azure.data.cosmos.internal.FailureValidator;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * This is a helper class for validating a partition address for tests.
 */
public interface ShouldRetryValidator {

    void validate(IRetryPolicy.ShouldRetryResult shouldRetryResult);

    static Builder builder() {
        return new Builder();
    }

    class Builder {
        private List<ShouldRetryValidator> validators = new ArrayList<>();

        public ShouldRetryValidator build() {
            return new ShouldRetryValidator() {

                @Override
                public void validate(IRetryPolicy.ShouldRetryResult shouldRetryResult) {
                    for (ShouldRetryValidator validator : validators) {
                        validator.validate(shouldRetryResult);
                    }
                }
            };
        }

        public Builder nullException() {
            validators.add(new ShouldRetryValidator() {

                @Override
                public void validate(IRetryPolicy.ShouldRetryResult shouldRetryResult) {
                    assertThat(shouldRetryResult.exception).isNull();
                }
            });
            return this;
        }

        public Builder hasException() {
            validators.add(new ShouldRetryValidator() {

                @Override
                public void validate(IRetryPolicy.ShouldRetryResult shouldRetryResult) {
                    assertThat(shouldRetryResult.exception).isNotNull();
                }
            });
            return this;
        }

        public Builder exceptionOfType(Class<? extends Exception> klass) {
            validators.add(new ShouldRetryValidator() {

                @Override
                public void validate(IRetryPolicy.ShouldRetryResult shouldRetryResult) {
                    assertThat(shouldRetryResult.exception).isNotNull();
                    assertThat(shouldRetryResult.exception).isInstanceOf(klass);
                }
            });
            return this;
        }

        public Builder withException(FailureValidator failureValidator) {
            validators.add(new ShouldRetryValidator() {

                @Override
                public void validate(IRetryPolicy.ShouldRetryResult shouldRetryResult) {
                    assertThat(shouldRetryResult.exception).isNotNull();
                    failureValidator.validate(shouldRetryResult.exception);
                }
            });
            return this;
        }

        public Builder withException(Exception exception) {
            validators.add(new ShouldRetryValidator() {

                @Override
                public void validate(IRetryPolicy.ShouldRetryResult shouldRetryResult) {
                    assertThat(shouldRetryResult.exception).isNotNull();
                    assertThat(shouldRetryResult.exception).isEqualTo(exception);
                }
            });
            return this;
        }

        public Builder shouldRetry(boolean value) {
            validators.add(new ShouldRetryValidator() {

                @Override
                public void validate(IRetryPolicy.ShouldRetryResult shouldRetryResult) {
                    assertThat(shouldRetryResult.shouldRetry).isEqualTo(value);
                }
            });
            return this;
        }

        public Builder backOfTime(Duration backOfTime) {
            validators.add(new ShouldRetryValidator() {

                @Override
                public void validate(IRetryPolicy.ShouldRetryResult shouldRetryResult) {
                    assertThat(shouldRetryResult.backOffTime).isEqualTo(backOfTime);
                }
            });
            return this;
        }
    }
}


text:
All URIs are relative to *https://api.artik.cloud/v1.1*

Method | HTTP request | Description
------------- | ------------- | -------------
[**deleteVdid**](WhitelistingApi.md#deleteVdid) | **DELETE** /devicetypes/{dtid}/whitelist/{vdid} | Delete a vdid from the devicetype whitelist.
[**deleteWhitelistCertificate**](WhitelistingApi.md#deleteWhitelistCertificate) | **DELETE** /devicetypes/{dtid}/whitelist/certificates/{cid} | Delete a whitelist certificate associated with a devicetype.
[**enableWhitelist**](WhitelistingApi.md#enableWhitelist) | **PUT** /devicetypes/:dtid/whitelist/enable | Enable or disble whitelist feature of a device type
[**getRejectedRowList**](WhitelistingApi.md#getRejectedRowList) | **GET** /devicetypes/{dtid}/whitelist/{uploadId}/rejectedRows | Get the list of rejected rows for an uploaded CSV file.
[**getUploadStatus**](WhitelistingApi.md#getUploadStatus) | **GET** /devicetypes/{dtid}/whitelist/{uploadId}/status | Get the status of a uploaded CSV file.
[**getWhitelist**](WhitelistingApi.md#getWhitelist) | **GET** /devicetypes/{dtid}/whitelist | Get whitelisted vdids of a device type.
[**getWhitelistCertificate**](WhitelistingApi.md#getWhitelistCertificate) | **GET** /devicetypes/{dtid}/whitelist/certificates | Get whitelist certificate of device type.
[**getWhitelistStatus**](WhitelistingApi.md#getWhitelistStatus) | **GET** /devicetypes/{dtid}/whitelist/status | Get the status of whitelist feature (enabled/disabled) of a device type.
[**uploadCSV**](WhitelistingApi.md#uploadCSV) | **POST** /devicetypes/{dtid}/whitelist | Upload a CSV file related to the Device Type.

# **deleteVdid**
> WhitelistEnvelope deleteVdid(dtid, vdid)

Delete a vdid from the devicetype whitelist.

Delete a vdid from the devicetype whitelist.

### Example
```java
// Import classes:
//import cloud.artik.client.ApiClient;
//import cloud.artik.client.ApiException;
//import cloud.artik.client.Configuration;
//import cloud.artik.client.auth.*;
//import cloud.artik.api.WhitelistingApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure OAuth2 access token for authorization: artikcloud_oauth
OAuth artikcloud_oauth = (OAuth) defaultClient.getAuthentication("artikcloud_oauth");
artikcloud_oauth.setAccessToken("YOUR ACCESS TOKEN");

WhitelistingApi apiInstance = new WhitelistingApi();
String dtid = "dtid_example"; // String | Device Type ID.
String vdid = "vdid_example"; // String | Vendor Device ID.
try {
    WhitelistEnvelope result = apiInstance.deleteVdid(dtid, vdid);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling WhitelistingApi#deleteVdid");
    e.printStackTrace();
}
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **dtid** | **String**| Device Type ID. |
 **vdid** | **String**| Vendor Device ID. |

### Return type

[**WhitelistEnvelope**](WhitelistEnvelope.md)

### Authorization

[artikcloud_oauth](../README.md#artikcloud_oauth)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json

# **deleteWhitelistCertificate**
> WhitelistEnvelope deleteWhitelistCertificate(dtid, cid)

Delete a whitelist certificate associated with a devicetype.

Delete a whitelist certificate associated with a devicetype.

### Example
```java
// Import classes:
//import cloud.artik.client.ApiClient;
//import cloud.artik.client.ApiException;
//import cloud.artik.client.Configuration;
//import cloud.artik.client.auth.*;
//import cloud.artik.api.WhitelistingApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure OAuth2 access token for authorization: artikcloud_oauth
OAuth artikcloud_oauth = (OAuth) defaultClient.getAuthentication("artikcloud_oauth");
artikcloud_oauth.setAccessToken("YOUR ACCESS TOKEN");

WhitelistingApi apiInstance = new WhitelistingApi();
String dtid = "dtid_example"; // String | Device Type ID.
String cid = "cid_example"; // String | Certificate ID.
try {
    WhitelistEnvelope result = apiInstance.deleteWhitelistCertificate(dtid, cid);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling WhitelistingApi#deleteWhitelistCertificate");
    e.printStackTrace();
}
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **dtid** | **String**| Device Type ID. |
 **cid** | **String**| Certificate ID. |

### Return type

[**WhitelistEnvelope**](WhitelistEnvelope.md)

### Authorization

[artikcloud_oauth](../README.md#artikcloud_oauth)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json

# **enableWhitelist**
> WhitelistEnvelope enableWhitelist(dtid, deviceTypeUpdateInfo)

Enable or disble whitelist feature of a device type

Enable or disble whitelist feature of a device type

### Example
```java
// Import classes:
//import cloud.artik.client.ApiClient;
//import cloud.artik.client.ApiException;
//import cloud.artik.client.Configuration;
//import cloud.artik.client.auth.*;
//import cloud.artik.api.WhitelistingApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure OAuth2 access token for authorization: artikcloud_oauth
OAuth artikcloud_oauth = (OAuth) defaultClient.getAuthentication("artikcloud_oauth");
artikcloud_oauth.setAccessToken("YOUR ACCESS TOKEN");

WhitelistingApi apiInstance = new WhitelistingApi();
String dtid = "dtid_example"; // String | Device Type ID.
DeviceTypeUpdateInput deviceTypeUpdateInfo = new DeviceTypeUpdateInput(); // DeviceTypeUpdateInput | Device type update input.
try {
    WhitelistEnvelope result = apiInstance.enableWhitelist(dtid, deviceTypeUpdateInfo);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling WhitelistingApi#enableWhitelist");
    e.printStackTrace();
}
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **dtid** | **String**| Device Type ID. |
 **deviceTypeUpdateInfo** | [**DeviceTypeUpdateInput**](DeviceTypeUpdateInput.md)| Device type update input. |

### Return type

[**WhitelistEnvelope**](WhitelistEnvelope.md)

### Authorization

[artikcloud_oauth](../README.md#artikcloud_oauth)

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

# **getRejectedRowList**
> RejectedCSVRowsEnvelope getRejectedRowList(dtid, uploadId, count, offset)

Get the list of rejected rows for an uploaded CSV file.

Get the list of rejected rows for an uploaded CSV file.

### Example
```java
// Import classes:
//import cloud.artik.client.ApiClient;
//import cloud.artik.client.ApiException;
//import cloud.artik.client.Configuration;
//import cloud.artik.client.auth.*;
//import cloud.artik.api.WhitelistingApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure OAuth2 access token for authorization: artikcloud_oauth
OAuth artikcloud_oauth = (OAuth) defaultClient.getAuthentication("artikcloud_oauth");
artikcloud_oauth.setAccessToken("YOUR ACCESS TOKEN");

WhitelistingApi apiInstance = new WhitelistingApi();
String dtid = "dtid_example"; // String | Device type id related to the uploaded CSV file.
String uploadId = "uploadId_example"; // String | Upload id related to the uploaded CSV file.
Integer count = 56; // Integer | Max results count.
Integer offset = 56; // Integer | Result starting offset.
try {
    RejectedCSVRowsEnvelope result = apiInstance.getRejectedRowList(dtid, uploadId, count, offset);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling WhitelistingApi#getRejectedRowList");
    e.printStackTrace();
}
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **dtid** | **String**| Device type id related to the uploaded CSV file. |
 **uploadId** | **String**| Upload id related to the uploaded CSV file. |
 **count** | **Integer**| Max results count. | [optional]
 **offset** | **Integer**| Result starting offset. | [optional]

### Return type

[**RejectedCSVRowsEnvelope**](RejectedCSVRowsEnvelope.md)

### Authorization

[artikcloud_oauth](../README.md#artikcloud_oauth)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json

# **getUploadStatus**
> UploadStatusEnvelope getUploadStatus(dtid, uploadId)

Get the status of a uploaded CSV file.

Get the status of a uploaded CSV file.

### Example
```java
// Import classes:
//import cloud.artik.client.ApiClient;
//import cloud.artik.client.ApiException;
//import cloud.artik.client.Configuration;
//import cloud.artik.client.auth.*;
//import cloud.artik.api.WhitelistingApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure OAuth2 access token for authorization: artikcloud_oauth
OAuth artikcloud_oauth = (OAuth) defaultClient.getAuthentication("artikcloud_oauth");
artikcloud_oauth.setAccessToken("YOUR ACCESS TOKEN");

WhitelistingApi apiInstance = new WhitelistingApi();
String dtid = "dtid_example"; // String | Device type id related to the uploaded CSV file.
String uploadId = "uploadId_example"; // String | Upload id related to the uploaded CSV file.
try {
    UploadStatusEnvelope result = apiInstance.getUploadStatus(dtid, uploadId);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling WhitelistingApi#getUploadStatus");
    e.printStackTrace();
}
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **dtid** | **String**| Device type id related to the uploaded CSV file. |
 **uploadId** | **String**| Upload id related to the uploaded CSV file. |

### Return type

[**UploadStatusEnvelope**](UploadStatusEnvelope.md)

### Authorization

[artikcloud_oauth](../README.md#artikcloud_oauth)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json

# **getWhitelist**
> WhitelistResultEnvelope getWhitelist(dtid, count, offset)

Get whitelisted vdids of a device type.

Get whitelisted vdids of a device type.

### Example
```java
// Import classes:
//import cloud.artik.client.ApiClient;
//import cloud.artik.client.ApiException;
//import cloud.artik.client.Configuration;
//import cloud.artik.client.auth.*;
//import cloud.artik.api.WhitelistingApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure OAuth2 access token for authorization: artikcloud_oauth
OAuth artikcloud_oauth = (OAuth) defaultClient.getAuthentication("artikcloud_oauth");
artikcloud_oauth.setAccessToken("YOUR ACCESS TOKEN");

WhitelistingApi apiInstance = new WhitelistingApi();
String dtid = "dtid_example"; // String | Device Type ID.
Integer count = 56; // Integer | Max results count.
Integer offset = 56; // Integer | Result starting offset.
try {
    WhitelistResultEnvelope result = apiInstance.getWhitelist(dtid, count, offset);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling WhitelistingApi#getWhitelist");
    e.printStackTrace();
}
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **dtid** | **String**| Device Type ID. |
 **count** | **Integer**| Max results count. | [optional]
 **offset** | **Integer**| Result starting offset. | [optional]

### Return type

[**WhitelistResultEnvelope**](WhitelistResultEnvelope.md)

### Authorization

[artikcloud_oauth](../README.md#artikcloud_oauth)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json

# **getWhitelistCertificate**
> CertificateEnvelope getWhitelistCertificate(dtid)

Get whitelist certificate of device type.

Get whitelist certificate of device type.

### Example
```java
// Import classes:
//import cloud.artik.client.ApiClient;
//import cloud.artik.client.ApiException;
//import cloud.artik.client.Configuration;
//import cloud.artik.client.auth.*;
//import cloud.artik.api.WhitelistingApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure OAuth2 access token for authorization: artikcloud_oauth
OAuth artikcloud_oauth = (OAuth) defaultClient.getAuthentication("artikcloud_oauth");
artikcloud_oauth.setAccessToken("YOUR ACCESS TOKEN");

WhitelistingApi apiInstance = new WhitelistingApi();
String dtid = "dtid_example"; // String | Device Type ID.
try {
    CertificateEnvelope result = apiInstance.getWhitelistCertificate(dtid);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling WhitelistingApi#getWhitelistCertificate");
    e.printStackTrace();
}
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **dtid** | **String**| Device Type ID. |

### Return type

[**CertificateEnvelope**](CertificateEnvelope.md)

### Authorization

[artikcloud_oauth](../README.md#artikcloud_oauth)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json

# **getWhitelistStatus**
> WhitelistEnvelope getWhitelistStatus(dtid)

Get the status of whitelist feature (enabled/disabled) of a device type.

Get the status of whitelist feature (enabled/disabled) of a device type.

### Example
```java
// Import classes:
//import cloud.artik.client.ApiClient;
//import cloud.artik.client.ApiException;
//import cloud.artik.client.Configuration;
//import cloud.artik.client.auth.*;
//import cloud.artik.api.WhitelistingApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure OAuth2 access token for authorization: artikcloud_oauth
OAuth artikcloud_oauth = (OAuth) defaultClient.getAuthentication("artikcloud_oauth");
artikcloud_oauth.setAccessToken("YOUR ACCESS TOKEN");

WhitelistingApi apiInstance = new WhitelistingApi();
String dtid = "dtid_example"; // String | Device Type ID.
try {
    WhitelistEnvelope result = apiInstance.getWhitelistStatus(dtid);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling WhitelistingApi#getWhitelistStatus");
    e.printStackTrace();
}
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **dtid** | **String**| Device Type ID. |

### Return type

[**WhitelistEnvelope**](WhitelistEnvelope.md)

### Authorization

[artikcloud_oauth](../README.md#artikcloud_oauth)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json

# **uploadCSV**
> UploadIdEnvelope uploadCSV(dtid, file)

Upload a CSV file related to the Device Type.

Upload a CSV file related to the Device Type.

### Example
```java
// Import classes:
//import cloud.artik.client.ApiClient;
//import cloud.artik.client.ApiException;
//import cloud.artik.client.Configuration;
//import cloud.artik.client.auth.*;
//import cloud.artik.api.WhitelistingApi;

ApiClient defaultClient = Configuration.getDefaultApiClient();

// Configure OAuth2 access token for authorization: artikcloud_oauth
OAuth artikcloud_oauth = (OAuth) defaultClient.getAuthentication("artikcloud_oauth");
artikcloud_oauth.setAccessToken("YOUR ACCESS TOKEN");

WhitelistingApi apiInstance = new WhitelistingApi();
String dtid = "dtid_example"; // String | Device Type ID.
byte[] file = BINARY_DATA_HERE; // byte[] | Device Type ID.
try {
    UploadIdEnvelope result = apiInstance.uploadCSV(dtid, file);
    System.out.println(result);
} catch (ApiException e) {
    System.err.println("Exception when calling WhitelistingApi#uploadCSV");
    e.printStackTrace();
}
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **dtid** | **String**| Device Type ID. |
 **file** | **byte[]**| Device Type ID. |

### Return type

[**UploadIdEnvelope**](UploadIdEnvelope.md)

### Authorization

[artikcloud_oauth](../README.md#artikcloud_oauth)

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json


text:
title: Estates
is_name: false

---

Estates


text:
/**
 * @ngdoc controller
 * @name Vehicals
 *
 * @description
 * _Please update the description and dependencies._
 *
 * @requires $scope
 * */
angular.module('UserApp')
    .controller('Vehicals', function ($scope, $http, vehicleslist) {
        $scope.vehical_sele_type = "";
        $scope.vehicles = vechicals_c;
        //vehicleslist.GetList($http, $scope);
        $scope.vehicles_types = vechicaal_types_c;
        //vehicleslist.GetVehicalsList($http, $scope);
        $scope.changetype = function (type) {
            $scope.vehical_sele_type = type;
        }
        $scope.findVehicles = function () {
            vehicleslist.GetList($http, $scope);
        }

    });


text:
using System;
using System.Web.Mvc;
using NUnit.Framework;
using Shuhari.Framework.DomainModel;

namespace Shuhari.Framework.UnitTests.Web.Mvc
{
    [TestFixture]
    public class FrameworkControllerTest
    {
        [SetUp]
        public void SetUp()
        {
            _controller = new TestController();
        }

        private TestController _controller;

        [Test]
        public void CustomJson()
        {
            Assert.IsNotNull(_controller.CustomJson("abc", JsonRequestBehavior.AllowGet));
        }

        [Test]
        public void TempMessage()
        {
            const string MSG = "test msg";
            _controller.TempMessage = MSG;
            Assert.AreEqual(MSG, _controller.TempMessage);
        }

        [Test]
        public void ExecuteJsonResult_Success_ShouldReturnOk()
        {
            var result = _controller.ExecuteJson("abc", x => { });
            var dto = (ResultDto)result.Data;
            Assert.IsTrue(dto.Success);
        }

        [Test]
        public void ExecuteAndRedirect_ActionExecOk_ShouldRedirect()
        {
            var result = (RedirectResult)_controller.ExecuteAndRedirect("abc", x => { }, "redirect", "msg");

            Assert.IsNotNull(result);
            Assert.AreEqual("redirect", result.Url);
        }

        [Test]
        public void ExecuteAndRedirect_Throws_ShouldReturnView()
        {
            var result = (ViewResult)_controller.ExecuteAndRedirect("abc",
                x => { throw new Exception("test error"); },
                "redirect", "msg");

            Assert.IsNotNull(result);
            Assert.AreEqual("abc", result.Model);
        }

        [Test]
        public void ExecuteJsonResult_Throws_ShouldReturnError()
        {
            const string msg = "test error";
            var result = _controller.ExecuteJson("abc", x => { throw new Exception(msg); });
            var dto = (ResultDto)result.Data;
            Assert.IsFalse(dto.Success);
            Assert.AreEqual(msg, dto.Message);
        }
    }
}


text:
package com.example.burakkara.gameoflife;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment implements View.OnClickListener,
        CalculationListener {

    private static final int UPDATE_PERIOD = 300;
    private static final String KEY_BUNDLE = "key.bundle";

    private GameView gameView;
    private Handler gameUpdateHandler;

    int[][] cells1;
    int[][] cells2;

    private boolean isFirstArrayBuffer = false;

    private Button buttonRun;
    private Button buttonStep;
    private Button buttonClear;

    private boolean isRunning = false;

    private int callCount;

    public MainActivityFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        gameUpdateHandler = new Handler();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        findViews(view);
        setListeners();

        if (savedInstanceState == null) {
            cells1 = new int[GameView.GRID_EDGE_LENGTH][GameView.GRID_EDGE_LENGTH];
        } else {
            GameBundle bundle = (GameBundle) savedInstanceState.getSerializable(KEY_BUNDLE);
            cells1 = bundle.getCells1();
        }

        gameView.setSeedData(cells1);
        gameView.invalidate();
        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(KEY_BUNDLE, new GameBundle(gameView.getCells()));
    }

    private void setListeners() {
        buttonClear.setOnClickListener(this);
        buttonRun.setOnClickListener(this);
        buttonStep.setOnClickListener(this);
    }

    private void findViews(View view) {
        gameView = (GameView) view.findViewById(R.id.gameview);
        buttonRun = (Button) view.findViewById(R.id.run);
        buttonStep = (Button) view.findViewById(R.id.step);
        buttonClear = (Button) view.findViewById(R.id.clear);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.run:
                if (isRunning) {
                    buttonRun.setText(getString(R.string.run));
                    stop();
                } else {
                    buttonRun.setText(getString(R.string.stop));
                    run();
                }
                break;
            case R.id.step:
                step();
                break;
            case R.id.clear:
                clear();
                break;
            default:
                break;

        }
    }

    private void run() {
        cells1 = gameView.getCells();
        isFirstArrayBuffer = false;
        isRunning = true;
        calculateNextStep();
    }

    private void step() {
        cells1 = gameView.getCells();
        isFirstArrayBuffer = false;
        calculateNextStep();
    }

    private void clear() {

        gameView.clearCells();
    }

    private void stop() {
        isRunning = false;
        gameUpdateHandler.removeCallbacks(gameUpdateRunnable);
    }

    final Runnable gameUpdateRunnable = new Runnable() {
        @Override
        public void run() {
            gameView.setSeedData(isFirstArrayBuffer ? cells1 : cells2);
            gameView.invalidate();
            isFirstArrayBuffer = !isFirstArrayBuffer;
            if (isRunning) {
                calculateNextStep();
            }
        }
    };

    private void calculateNextStep() {

        callCount = (int) Math.pow(GameView.BLOCK_COUNT, 2);

        if (isFirstArrayBuffer) {
            cells1 = Util.deepCopy(cells2);
        } else {
            cells2 = Util.deepCopy(cells1);
        }

        for (int i = 0; i < GameView.BLOCK_COUNT; i++) {
            for (int j = 0; j < GameView.BLOCK_COUNT; j++) {
                if (isFirstArrayBuffer) {
                    new CalculationTask(this, i, j, cells2, cells1).execute();
                } else {
                    new CalculationTask(this, i, j, cells1, cells2).execute();
                }
            }
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        stop();
    }

    @Override
    public void onCalculationComplete() {
        if (--callCount == 0) {
            gameUpdateHandler.postDelayed(gameUpdateRunnable, UPDATE_PERIOD);
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Diagnostics;

namespace BlueYonder.BookingService.Implementation.Extensions
{
    class LoggingErrorHandler : IErrorHandler
    {
        private TraceSource _traceSource = new TraceSource("ErrorHandlerTrace");
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {

        }

        public bool HandleError(Exception error)
        {
            ParametersInfo parametersInfo =
                OperationContext.Current.Extensions.Find<ParametersInfo>();
            if (parametersInfo != null)
            {
                string errParams = parametersInfo.Parameters
                    .Select(ErrorLoggingUtils
                    .GetObjectAsXml).Aggregate((prev, next) => $"{prev}\n{next}");
                string message =
                    $"Exception of type {error.GetType().Name} occured: {error.Message}\n operation parameters are:\n{errParams}\n";
                _traceSource.TraceEvent(TraceEventType.Error, 0, message);
            }
            return true;
        }
    }
}


text:
package com.amazonaws.services.chimesdkvoice.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SipRule implements Serializable, Cloneable, StructuredPojo {

    private String sipRuleId;

    private String name;

    private Boolean disabled;

    private String triggerType;

    private String triggerValue;

    private java.util.List<SipRuleTargetApplication> targetApplications;

    private java.util.Date createdTimestamp;

    private java.util.Date updatedTimestamp;

    /**
     * @param sipRuleId
     */

    public void setSipRuleId(String sipRuleId) {
        this.sipRuleId = sipRuleId;
    }

    /**
     * @return
     */

    public String getSipRuleId() {
        return this.sipRuleId;
    }

    /**
     * @param sipRuleId
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SipRule withSipRuleId(String sipRuleId) {
        setSipRuleId(sipRuleId);
        return this;
    }

    /**
     * @param name
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return
     */

    public String getName() {
        return this.name;
    }

    /**
     * @param name
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SipRule withName(String name) {
        setName(name);
        return this;
    }

    /**
     * @param disabled
     */

    public void setDisabled(Boolean disabled) {
        this.disabled = disabled;
    }

    /**
     * @return
     */

    public Boolean getDisabled() {
        return this.disabled;
    }

    /**
     * @param disabled
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SipRule withDisabled(Boolean disabled) {
        setDisabled(disabled);
        return this;
    }

    /**
     * @return
     */

    public Boolean isDisabled() {
        return this.disabled;
    }

    /**
     * @param triggerType
     * @see SipRuleTriggerType
     */

    public void setTriggerType(String triggerType) {
        this.triggerType = triggerType;
    }

    /**
     * @return
     * @see SipRuleTriggerType
     */

    public String getTriggerType() {
        return this.triggerType;
    }

    /**
     * @param triggerType
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see SipRuleTriggerType
     */

    public SipRule withTriggerType(String triggerType) {
        setTriggerType(triggerType);
        return this;
    }

    /**
     * @param triggerType
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see SipRuleTriggerType
     */

    public SipRule withTriggerType(SipRuleTriggerType triggerType) {
        this.triggerType = triggerType.toString();
        return this;
    }

    /**
     * @param triggerValue
     */

    public void setTriggerValue(String triggerValue) {
        this.triggerValue = triggerValue;
    }

    /**
     * @return
     */

    public String getTriggerValue() {
        return this.triggerValue;
    }

    /**
     * @param triggerValue
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SipRule withTriggerValue(String triggerValue) {
        setTriggerValue(triggerValue);
        return this;
    }

    /**
     * @return
     */

    public java.util.List<SipRuleTargetApplication> getTargetApplications() {
        return targetApplications;
    }

    /**
     * @param targetApplications
     */

    public void setTargetApplications(java.util.Collection<SipRuleTargetApplication> targetApplications) {
        if (targetApplications == null) {
            this.targetApplications = null;
            return;
        }

        this.targetApplications = new java.util.ArrayList<SipRuleTargetApplication>(targetApplications);
    }

    /**
     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setTargetApplications(java.util.Collection)} or {@link #withTargetApplications(java.util.Collection)} if
     * you want to override the existing values.
     *

     *
     * @param targetApplications
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SipRule withTargetApplications(SipRuleTargetApplication... targetApplications) {
        if (this.targetApplications == null) {
            setTargetApplications(new java.util.ArrayList<SipRuleTargetApplication>(targetApplications.length));
        }
        for (SipRuleTargetApplication ele : targetApplications) {
            this.targetApplications.add(ele);
        }
        return this;
    }

    /**
     * @param targetApplications
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SipRule withTargetApplications(java.util.Collection<SipRuleTargetApplication> targetApplications) {
        setTargetApplications(targetApplications);
        return this;
    }

    /**
     * @param createdTimestamp
     */

    public void setCreatedTimestamp(java.util.Date createdTimestamp) {
        this.createdTimestamp = createdTimestamp;
    }

    /**
     * @return
     */

    public java.util.Date getCreatedTimestamp() {
        return this.createdTimestamp;
    }

    /**
     * @param createdTimestamp
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SipRule withCreatedTimestamp(java.util.Date createdTimestamp) {
        setCreatedTimestamp(createdTimestamp);
        return this;
    }

    /**
     * @param updatedTimestamp
     */

    public void setUpdatedTimestamp(java.util.Date updatedTimestamp) {
        this.updatedTimestamp = updatedTimestamp;
    }

    /**
     * @return
     */

    public java.util.Date getUpdatedTimestamp() {
        return this.updatedTimestamp;
    }

    /**
     * @param updatedTimestamp
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public SipRule withUpdatedTimestamp(java.util.Date updatedTimestamp) {
        setUpdatedTimestamp(updatedTimestamp);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getSipRuleId() != null)
            sb.append("SipRuleId: ").append(getSipRuleId()).append(",");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getDisabled() != null)
            sb.append("Disabled: ").append(getDisabled()).append(",");
        if (getTriggerType() != null)
            sb.append("TriggerType: ").append(getTriggerType()).append(",");
        if (getTriggerValue() != null)
            sb.append("TriggerValue: ").append(getTriggerValue()).append(",");
        if (getTargetApplications() != null)
            sb.append("TargetApplications: ").append(getTargetApplications()).append(",");
        if (getCreatedTimestamp() != null)
            sb.append("CreatedTimestamp: ").append(getCreatedTimestamp()).append(",");
        if (getUpdatedTimestamp() != null)
            sb.append("UpdatedTimestamp: ").append(getUpdatedTimestamp());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof SipRule == false)
            return false;
        SipRule other = (SipRule) obj;
        if (other.getSipRuleId() == null ^ this.getSipRuleId() == null)
            return false;
        if (other.getSipRuleId() != null && other.getSipRuleId().equals(this.getSipRuleId()) == false)
            return false;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getDisabled() == null ^ this.getDisabled() == null)
            return false;
        if (other.getDisabled() != null && other.getDisabled().equals(this.getDisabled()) == false)
            return false;
        if (other.getTriggerType() == null ^ this.getTriggerType() == null)
            return false;
        if (other.getTriggerType() != null && other.getTriggerType().equals(this.getTriggerType()) == false)
            return false;
        if (other.getTriggerValue() == null ^ this.getTriggerValue() == null)
            return false;
        if (other.getTriggerValue() != null && other.getTriggerValue().equals(this.getTriggerValue()) == false)
            return false;
        if (other.getTargetApplications() == null ^ this.getTargetApplications() == null)
            return false;
        if (other.getTargetApplications() != null && other.getTargetApplications().equals(this.getTargetApplications()) == false)
            return false;
        if (other.getCreatedTimestamp() == null ^ this.getCreatedTimestamp() == null)
            return false;
        if (other.getCreatedTimestamp() != null && other.getCreatedTimestamp().equals(this.getCreatedTimestamp()) == false)
            return false;
        if (other.getUpdatedTimestamp() == null ^ this.getUpdatedTimestamp() == null)
            return false;
        if (other.getUpdatedTimestamp() != null && other.getUpdatedTimestamp().equals(this.getUpdatedTimestamp()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getSipRuleId() == null) ? 0 : getSipRuleId().hashCode());
        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getDisabled() == null) ? 0 : getDisabled().hashCode());
        hashCode = prime * hashCode + ((getTriggerType() == null) ? 0 : getTriggerType().hashCode());
        hashCode = prime * hashCode + ((getTriggerValue() == null) ? 0 : getTriggerValue().hashCode());
        hashCode = prime * hashCode + ((getTargetApplications() == null) ? 0 : getTargetApplications().hashCode());
        hashCode = prime * hashCode + ((getCreatedTimestamp() == null) ? 0 : getCreatedTimestamp().hashCode());
        hashCode = prime * hashCode + ((getUpdatedTimestamp() == null) ? 0 : getUpdatedTimestamp().hashCode());
        return hashCode;
    }

    @Override
    public SipRule clone() {
        try {
            return (SipRule) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.chimesdkvoice.model.transform.SipRuleMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
# rubocop:disable Metrics/MethodLength

# Format an ISO8601 Duration
module WinRM
  module WSMV
    # Converts seconds to ISO8601 duration format
    module Iso8601Duration
      # Convert the number of seconds to an ISO8601 duration format
      # @see http://tools.ietf.org/html/rfc2445#section-4.3.6
      # @param [Integer] seconds The amount of seconds for this duration
      def self.sec_to_dur(seconds)
        seconds = seconds.to_i
        iso_str = 'P'
        if seconds > 604_800 # more than a week
          weeks = seconds / 604_800
          seconds -= (604_800 * weeks)
          iso_str << "#{weeks}W"
        end
        if seconds > 86_400 # more than a day
          days = seconds / 86_400
          seconds -= (86_400 * days)
          iso_str << "#{days}D"
        end
        if seconds > 0
          iso_str << 'T'
          if seconds > 3600 # more than an hour
            hours = seconds / 3600
            seconds -= (3600 * hours)
            iso_str << "#{hours}H"
          end
          if seconds > 60 # more than a minute
            minutes = seconds / 60
            seconds -= (60 * minutes)
            iso_str << "#{minutes}M"
          end
          iso_str << "#{seconds}S"
        end

        iso_str
      end
    end
  end
end
# rubocop:enable Metrics/MethodLength


text:
from django.shortcuts import render
from api.views import e_search, e_definition, e_instances, e_dependency

# Not sure if they are needed
# get names for all feeds - this is for autocomplete - cache it
# needed for autocomplete in case of editing/updating a process

# get names for all process - this is for autocomplete - cache it
# get names for all clusters - this is for autocomplete - cache it

#TODO: check if different functions are needed for feed,process and cluster ????

# search for the entity containing this text (case insensitive)
def dashboard_index(request, template_name='dashboard/dashboard_index.html'):
    current_app = 'dashboard'
    type = request.GET.get('type')
    query = request.GET.get('name')
    # dictionary containing entity name and entity type
    if type and query:
        results =  e_search(type, query)
    else:
        results = []
    return render(request, template_name, locals())

def entity_details(request, type, name, template_name='dashboard/entity_details.html'):
    """Show details of the entity with given type and name"""
    current_app='dashboard'
    entity_definition = e_definition(type, name)
    dependencies = e_dependency(type,name)
    instances = e_instances(type,name) # return last 5 instances of this process
    return render(request, template_name, locals() )

def edit_process(request, name):
    pass

def edit_process(request, name):
    pass

def edit_process(request, name):
    pass

def edit_entity(request, type, name):

    if type == 'process':
        return edit_process(request, name)
    elif type == 'feed':
        return edit_feed(request, name)
    else:
        return edit_cluster(request, name)


text:
package org.kie.server.services.taskassigning.planning;

import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.kie.server.services.taskassigning.planning.SolverHandlerConfigTest.IMPROVE_SOLUTION_ON_BACKGROUND_DURATION;
import static org.kie.server.services.taskassigning.planning.SolverHandlerConfigTest.PUBLISH_WINDOW_SIZE;
import static org.kie.server.services.taskassigning.planning.SolverHandlerConfigTest.SYNC_INTERVAL;
import static org.kie.server.services.taskassigning.planning.SolverHandlerConfigTest.SYNC_QUERIES_SHIFT;
import static org.kie.server.services.taskassigning.planning.SolverHandlerConfigTest.TARGET_USER;
import static org.kie.server.services.taskassigning.planning.SolverHandlerConfigTest.USERS_SYNC_INTERVAL;
import static org.kie.server.services.taskassigning.planning.SolverHandlerConfigTest.WAIT_FOR_IMPROVED_SOLUTION_DURATION;

public class TaskAssigningServiceConfigTest {

    @Test
    public void getSolverHandlerConfig() {
        TaskAssigningServiceConfig serviceConfig = new TaskAssigningServiceConfig(TARGET_USER,
                                                                                PUBLISH_WINDOW_SIZE,
                                                                                SYNC_INTERVAL,
                                                                                SYNC_QUERIES_SHIFT,
                                                                                USERS_SYNC_INTERVAL,
                                                                                WAIT_FOR_IMPROVED_SOLUTION_DURATION,
                                                                                IMPROVE_SOLUTION_ON_BACKGROUND_DURATION);

        SolverHandlerConfig handlerConfig = serviceConfig.getSolverHandlerConfig();
        assertThat(handlerConfig).isNotNull();
        assertThat(handlerConfig.getTargetUserId()).isEqualTo(TARGET_USER);
        assertThat(handlerConfig.getPublishWindowSize()).isEqualTo(PUBLISH_WINDOW_SIZE);
        assertThat(handlerConfig.getSyncInterval()).isEqualTo(SYNC_INTERVAL);
        assertThat(handlerConfig.getSyncQueriesShift()).isEqualTo(SYNC_QUERIES_SHIFT);
        assertThat(handlerConfig.getUsersSyncInterval()).isEqualTo(USERS_SYNC_INTERVAL);
        assertThat(handlerConfig.getWaitForImprovedSolutionDuration()).isEqualTo(WAIT_FOR_IMPROVED_SOLUTION_DURATION);
        assertThat(handlerConfig.getImproveSolutionOnBackgroundDuration()).isEqualTo(IMPROVE_SOLUTION_ON_BACKGROUND_DURATION);
    }
}


text:
package org.andengine.util;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.WindowManager;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 13:04:09 - 12.05.2011
 */
public final class DialogUtils {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	// ===========================================================
	// Constructors
	// ===========================================================

	private DialogUtils() {

	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	// ===========================================================
	// Methods
	// ===========================================================

	public static void keepScreenOn(final Dialog pDialog) {
		pDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	@Deprecated
	public static void showDialogOnUiThread(final Activity pActivity, final int pDialogID) {
		DialogUtils.showDialogOnUiThread(pActivity, pDialogID, null);
	}

	@Deprecated
	public static void showDialogOnUiThread(final Activity pActivity, final int pDialogID, final Bundle pBundle) {
		if (ActivityUtils.isOnUiThread()) {
			pActivity.showDialog(pDialogID, pBundle);
		} else {
			pActivity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					pActivity.showDialog(pDialogID, pBundle);
				}
			});
		}
	}

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
package com.wiley.basetests;

import com.wiley.assertions.MethodType;
import com.wiley.holders.AssertionsHolder;
import com.wiley.page.BasePage;
import com.wiley.page.PageProvider;
import org.testng.ITestResult;

import static com.wiley.driver.WebDriverFactory.initDriver;

/**
 * Base test for Selenium tests
 */
public class SeleniumBaseTest extends BaseTest {

    protected <T extends BasePage> T get(Class<T> page) {
        return PageProvider.get(page);
    }

    protected <T extends BasePage> T get(Class<T> page, String url) {
        initDriver();
        return PageProvider.get(page, url);
    }

    @Override
    protected void setThrowable(ITestResult testResult, MethodType methodType) {
        final Throwable testResultThrowable = testResult.getThrowable();

        AssertionsHolder.softAssert().add(testResultThrowable, MethodType.TEST);
    }
}


text:
package com.intellij.platform;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.openapi.wm.ToolWindowType;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author yole
 */
public class PlatformProjectViewOpener implements DirectoryProjectConfigurator {
  public void configureProject(final Project project, @NotNull final VirtualFile baseDir) {
    StartupManager.getInstance(project).registerPostStartupActivity(new DumbAwareRunnable() {
      public void run() {
        // ensure the dialog is shown after all startup activities are done
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            ApplicationManager.getApplication().invokeLater(new Runnable() {
              public void run() {
                if (project.isDisposed()) return;
                final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.PROJECT_VIEW);
                if (toolWindow != null && toolWindow.getType() != ToolWindowType.SLIDING) {
                  toolWindow.activate(null);
                }
              }
            }, ModalityState.NON_MODAL);
          }
        });
      }
    });
  }
}


text:
namespace utl {
class Logger;
}

namespace fin {

using utl::Logger;

////////////////////////////////////////////////////////////////

class Finale
{
 public:
  Finale();

  void init(odb::dbDatabase* db, Logger* logger);

  void densityFill(const char* rules_filename, const odb::Rect& fill_area);

  void setDebug();

 private:
  odb::dbDatabase* db_;
  Logger* logger_;
  bool debug_;
};

}  // namespace fin


text:
package javas.extra.thread.concurrent.threadpool;

/**
 * @Description:ScheduledThreadPoolExecutor
 * @author:sunny
 * @since:2012-12-25 17:18
 * @version:1.0.0
 */

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 1.public interface ScheduledExecutorService extends ExecutorService 2.public
 * class ScheduledThreadPoolExecutor extends ThreadPoolExecutor implements
 * ScheduledExecutorService
 */
public class ScheduledExecutorServiceScheduledThreadPoolExecutorTest {

    public static void main(String[] args) {

        // Creates a thread pool that can schedule commands to run after a
        // given delay, or to execute periodically.
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

        // new a ScheduledThreadPoolExecutor object
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);

        Runnable runnable = new Runnable() {
            public void run() {
                System.out.println("Thread is running ");
            }
        };

        /**
         * 1.executor at fixed time 2.param : Runnable
         * ,initialDelay,period,TimeUnit
         */

        scheduledThreadPoolExecutor.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS);

    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>VanillaJS • TodoMVC</title>
    <link rel="stylesheet" href="styles/base.css">

todos

        <input id="new-todo" placeholder="What needs to be done?" autofocus>

Currently syncing

There was a problem syncing

Double-click to edit a todo

Template by Sindre Sorhus

Created by Florian Fesseler

Cleanup, edits by Aaron Boushley


text:
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.

namespace DemoStartUp
{
    using Client;
    using Common.ServiceContracts;
    using Server;
    using static CommonHelper;

    internal static class Program
    {
        private static void Main(string[] args)
        {
            ParseContextArgs(args);
            Title("Custom Result Handler");
            const string url = "net.pipe://localhost/8080/query";

            PrintSetup("Starting WCF service...");
            using var serviceHost = WcfHelper.CreateServiceHost<QueryService>()
                .AddNetNamedPipeEndpoint<IQueryService>(url)
                .OpenService();

            PrintSetup("Staring client demo...");
            PrintSetup("-------------------------------------------------");
            new Demo(() => new RemoteRepository(url)).RunDemo();

            PrintSetup();
            PrintSetup("-------------------------------------------------");
            PrintSetup("Done.");
            WaitForEnterKey();
        }
    }
}


text:
package org.apache.camel.component.jcache;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;

import javax.cache.Cache;
import javax.cache.configuration.CompleteConfiguration;
import javax.cache.configuration.Factory;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.expiry.AccessedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.expiry.ExpiryPolicy;
import javax.cache.integration.CacheLoader;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriter;
import javax.cache.integration.CacheWriterException;

import org.apache.camel.BindToRegistry;
import org.apache.camel.EndpointInject;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.Test;

public class JCacheConfigurationTest extends JCacheComponentTestSupport {

    @BindToRegistry("myExpiryPolicyFactory")
    private static final Factory<ExpiryPolicy> EXPIRY_POLICY_FACTORY = AccessedExpiryPolicy.factoryOf(Duration.ONE_MINUTE);
    @BindToRegistry("myCacheWriterFactory")
    private static final Factory<CacheWriter<Object, Object>> CACHE_WRITER_FACTORY = MyCacheWriter.factory();
    @BindToRegistry("myCacheLoaderFactory")
    private static final Factory<CacheLoader<Object, Object>> CACHE_LOADER_FACTORY = MyCacheLoader.factory();

    @EndpointInject(value = "jcache://test-cache" + "?expiryPolicyFactory=#myExpiryPolicyFactory" + "&cacheWriterFactory=#myCacheWriterFactory"
                            + "&cacheLoaderFactory=#myCacheLoaderFactory")
    JCacheEndpoint from;

    @EndpointInject("mock:to")
    MockEndpoint to;

    @Test
    public void testConfigurations() throws Exception {
        final Cache<Object, Object> cache = from.getManager().getCache();
        final CompleteConfiguration<Object, Object> conf = cache.getConfiguration(CompleteConfiguration.class);

        assertEquals(EXPIRY_POLICY_FACTORY, conf.getExpiryPolicyFactory());
        assertEquals(CACHE_WRITER_FACTORY, conf.getCacheWriterFactory());
        assertEquals(CACHE_LOADER_FACTORY, conf.getCacheLoaderFactory());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() {
                from(from).to(to);
            }
        };
    }

    private static final class MyCacheLoader implements CacheLoader<Object, Object>, Serializable {
        @Override
        public Object load(Object key) throws CacheLoaderException {
            return null;
        }

        @Override
        public Map<Object, Object> loadAll(Iterable<?> keys) throws CacheLoaderException {
            return null;
        }

        public static Factory<CacheLoader<Object, Object>> factory() {
            return new FactoryBuilder.SingletonFactory(new MyCacheLoader());
        }
    }

    private static final class MyCacheWriter implements CacheWriter<Object, Object>, Serializable {
        @Override
        public void write(Cache.Entry<?, ?> entry) throws CacheWriterException {
        }

        @Override
        public void writeAll(Collection<Cache.Entry<?, ?>> entries) throws CacheWriterException {
        }

        @Override
        public void delete(Object key) throws CacheWriterException {
        }

        @Override
        public void deleteAll(Collection<?> keys) throws CacheWriterException {
        }

        public static Factory<CacheWriter<Object, Object>> factory() {
            return new FactoryBuilder.SingletonFactory(new MyCacheWriter());
        }
    }
}


text:
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// 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.

package google.registry.request.auth;

import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.appengine.api.oauth.OAuthService;
import com.google.appengine.api.oauth.OAuthServiceFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import dagger.Module;
import dagger.Provides;
import google.registry.config.RegistryConfig.Config;
import javax.inject.Singleton;

/**
 * Dagger module for authentication routines.
 */
@Module
public class AuthModule {

  /** Provides the custom authentication mechanisms (including OAuth). */
  @Provides
  ImmutableList<AuthenticationMechanism> provideApiAuthenticationMechanisms(
      OAuthAuthenticationMechanism oauthAuthenticationMechanism,
      CookieOAuth2AuthenticationMechanism cookieOAuth2AuthenticationMechanism) {
    return ImmutableList.of(oauthAuthenticationMechanism, cookieOAuth2AuthenticationMechanism);
  }

  /** Provides the OAuthService instance. */
  @Provides
  OAuthService provideOauthService() {
    return OAuthServiceFactory.getOAuthService();
  }

  @Provides
  @Singleton
  GoogleIdTokenVerifier provideGoogleIdTokenVerifier(
      @Config("allowedOauthClientIds") ImmutableSet<String> allowedOauthClientIds,
      NetHttpTransport httpTransport,
      JsonFactory jsonFactory) {
    return new GoogleIdTokenVerifier.Builder(httpTransport, jsonFactory)
        .setAudience(allowedOauthClientIds)
        .build();
  }
}


text:
function [gridResults, bestSVMParams] = performCrossValidation(...
    allFoldsData, processParams, predParams, gridParams, backupDir)
%performCrossValidation Executes the cross-validation.
% [gridResults, bestSVMParams] = performCrossValidation(allFoldsData, processParams, predParams, gridParams, backupDir)
% cross-validates the results for a given set of SVM parameters. The
% metrics are calculated from the results and all the results are saved on
% the HDD. Furthermore, the best SVM parameters are returned.

% initialize best results
bestResults = 0;
bestSVMParams = [];

% assign broadcast variables to temporary variables
numClasses  = processParams.classes;
numFolds    = processParams.folds;
kernel      = predParams.kernel;

k = 1;
paramList = cell(1,length(gridParams.C)*length(gridParams.gamma));
for l=1:length(gridParams.C)
    for m=1:length(gridParams.gamma)
        paramList{k}.C      = gridParams.C(l);
        paramList{k}.gamma  = gridParams.gamma(m);
        k = k + 1;
    end
end

% time stamp to create backup folder
dateTime = fix(clock);
timeStamp = sprintf('%04d_%02d_%02d-%02d_%02d_%02d', dateTime);
backupFolder = fullfile(backupDir, timeStamp);
mkdir(backupFolder);

gridResults = cell(1, length(paramList));
for p=1:length(paramList)
    % svm parameter values
    currentC = num2str(paramList{p}.C);
    currentG = num2str(paramList{p}.gamma);

    switch kernel
        case 'linear'
            resultLine = sprintf('Grid values: C = %s\n' , currentC);
            subStruct = struct('C', currentC);
        case {'polynomial', 'rbf'}
            resultLine = sprintf('Grid values: C = %s , gamma = %s\n', currentC, currentG);
            subStruct = struct('C', currentC, 'gamma', currentG);
    end
    % save the svm parameters in a structure
    predParamsSVM = struct('svmParameter', subStruct);
    % merge parameter structure objects and overwrite the svmParameter dummy fields in
    % predParams by the values from predParamsSVM
    updatedPredParams = setstructfields(predParams, predParamsSVM);

    cvMetrics       = zeros(1, numFolds);
    cvTanhMetrics   = zeros(1, numFolds);
    cvResults       = cell (1, numFolds);
    avgAccurracies  = zeros(1, numFolds);
    varOfAccur      = zeros(1, numFolds);

    tic
    for k=1:numFolds
        % merge all folds except k-th fold
        [trainD, testD] = mergeData(allFoldsData, k);

        % reduce dimensionality if desired
        if updatedPredParams.reduceDimensionality == true
            [trainD.features, testD.features] = reduceDimensionality(...
                trainD.features, testD.features, updatedPredParams.reducedFeatLength, ...
                updatedPredParams.reductionMode);
        end

        % learn the models
        [modelC, modelR] = ...
            trainCombClassifRegrModel(trainD, numClasses, updatedPredParams);
        % predict test data with learned models
        [prediction, probEstim, plotTitle] = ...
            predictCombClassifRegrModel(...
            modelC, modelR, testD, numClasses, updatedPredParams);
        % calculate differences between truth and prediction & confusion matrix
        [results, confMat] = calcPredictionResults(...
            prediction, testD, numClasses);

        % models can be large and do not always have to be saved
        if updatedPredParams.saveModel == false
            modelC = [];
            modelR = [];
        end

        % include fold number into plot title
        plotTitle = sprintf('%s -- cv%d', plotTitle, k);

        % calculate metric
        helpVec = cell2mat(results(:,3));
        evalMetric = 1/size(helpVec, 1) * sum(arrayfun(@(x) (1+cos(x))/2, helpVec));
        tanhMetric = 1/size(helpVec, 1) * sum(arrayfun(@(x) 1 - tanh(x), helpVec));

        cv = struct(...
            'modelC',       {modelC},...
            'modelR',       {modelR},...
            'probEstim',    {probEstim},...
            'plotTitle',    {plotTitle},...
            'results',      {results},...
            'confMat',      {confMat});

        % save metric
        cvMetrics(1,k) = evalMetric;
        cvTanhMetrics(1,k) = tanhMetric;
        cvResults{1,k} = cv;
        [avgAccurracies(1,k), varOfAccur(1,k)] = myHelperDisplayConfusionMatrix(...
            confMat, numClasses, 'absolute', true);

        % save backup file on hdd
        fileName = sprintf('fold%02d.mat', k);
        save(fullfile(backupFolder, fileName), 'cv');
    end
    t = toc;
    fprintf('%saverage cosine metric: %0.6f\naverage tanh metric: %0.6f\ncomputation time: %0.1f min\n',...
        resultLine, mean(cvMetrics), mean(cvTanhMetrics), t/60);

    gridResults{1,p} = struct(...
                        'avgMetric', {mean(cvMetrics)},...
                        'avgTanhMetric', {mean(cvTanhMetrics)},...
                        'avgVariance', {mean(varOfAccur)},...
                        'calcTime', {t},...
                        'cvMetrics', {cvMetrics},...
                        'cvTanhMetrics', {cvTanhMetrics},...
                        'cvResults', {cvResults},...
                        'avgAccuracies', {avgAccurracies},...
                        'varOfAccur', {varOfAccur},...
                        'C', {currentC},...
                        'gamma', {currentG},...
                        'params', {updatedPredParams});

    % save backup file on hdd
    currResult = gridResults{1,p};
	fileName = sprintf('gridResults%02d.mat', p);
	save(fullfile(backupFolder, fileName), 'currResult');

    % set new best parameters if results are better than previous ones
    if mean(cvMetrics) > bestResults
        bestResults = mean(cvMetrics);
        bestSVMParams = paramList{p};
    end

end

% save backup file on hdd
fileName = sprintf('allResults.mat');
save(fullfile(backupFolder, fileName), 'gridResults');

end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Home page
 */
class Home extends MY_Controller {

	public function index()
	{
		//$this->render('home');

    header('Location: '.base_url().'admin');
	}
}


text:
<?php

/**
 * This class has been auto-generated by the IPF_ORM Framework.
 * Changes to this file may cause incorrect behavior
 * and will be lost if the code is regenerated.
 */

abstract class BaseUserRole extends IPF_ORM_Record
{
  public static function setTableDefinition(IPF_ORM_Table $table)
  {
    $table->setTableName('auth_user_role');
    $table->setColumn('user_id', 'integer', null, array('type' => 'integer', 'primary' => true));
    $table->setColumn('role_id', 'integer', null, array('type' => 'integer', 'primary' => true));
    $table->setOption('type', 'INNODB');
    $table->setOption('collate', 'utf8_unicode_ci');
    $table->setOption('charset', 'utf8');

  }

  public static function setUp(IPF_ORM_Table $table)
  {
    $table->hasOne('User', '', array('local' => 'user_id', 'foreign' => 'id', 'onDelete' => 'CASCADE'));
    $table->hasOne('Role', '', array('local' => 'role_id', 'foreign' => 'id', 'onDelete' => 'CASCADE'));
  }

  public static function table()
  {
    return IPF_ORM::getTable('UserRole');
  }

  public static function query($alias='')
  {
    return IPF_ORM::getTable('UserRole')->createQuery($alias);
  }
}


text:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Drachenhorn.Xml.Sheet.Skills;

namespace Drachenhorn.Desktop.UserControls
{
    /// <summary>
    ///     Interaktionslogik für SkillListControl.xaml
    /// </summary>
    public partial class SkillListControl : UserControl
    {
        #region c'tor

        public SkillListControl()
        {
            InitializeComponent();
        }

        #endregion

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            var source = DataGrid.Resources["SkillViewSource"] as CollectionViewSource;
            if (!(source?.Source is IList<Skill>))
                return;

            var newItem = new Skill();

            ((IList<Skill>) source?.Source).Add(newItem);
            List.SelectedItem = newItem;
        }

        private void RemoveButton_Click(object sender, RoutedEventArgs e)
        {
            var source = DataGrid.Resources["SkillViewSource"] as CollectionViewSource;

            (source?.Source as IList<Skill>)?.Remove((Skill) List.SelectedItem);
        }

        private void List_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Handled || e.MouseDevice.Captured is ComboBox)
                return;

            e.Handled = true;
            var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
            eventArg.RoutedEvent = MouseWheelEvent;
            eventArg.Source = sender;
            var parent = ((Control) sender).Parent as UIElement;
            parent.RaiseEvent(eventArg);
        }
    }
}


text:
package com.cyl.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.cyl.Idao.ICommonDAO;
import com.cyl.frame.util.SessionFactoryUtil;

public class CommonDAO<T> implements ICommonDAO<T> {

	private String mapperName=null;

	public String getMapperName() {
		return mapperName;
	}

	public void setMapperName(String mapperName) {
		this.mapperName = mapperName;
	}

	public CommonDAO(String mappername){
		this.setMapperName(mappername);
	}

	/**
	 * 获得sqlsession
	 *
	 * @return
	 */
	public SqlSession getSession() {
		return SessionFactoryUtil.getSqlSession();
	}

	/**
	 * 关闭session
	 */
	public void closeSession() {
		SessionFactoryUtil.closeCurrentSession();
	}

	@Override
	public int deleteByPrimaryKey(String key) {
		int i = 0;
		SqlSession session = null;
		try {
			session = getSession();
			i = session.delete("com.cyl.Idao."+this.getMapperName()+".deleteByPrimaryKey",
					key);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.commit();
			session.close();
		}
		return i;
	}

	@Override
	public int insert(T record) {
		int i = 0;
		SqlSession session = null;
		try {
			session = getSession();
			System.out.println(this.getMapperName());
			String queryid="com.cyl.Idao."+this.getMapperName()+".insert";
			System.out.println(queryid);
			i = session.insert(queryid, record);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.commit();
			this.closeSession();
		}
		return i;
	}

	@Override
	public int insertSelective(T record) {
		int i = 0;
		SqlSession session = null;
		try {
			session = getSession();
			i = session.insert("com.cyl.Idao."+this.getMapperName()+".insertSelective",
					record);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.commit();
			this.closeSession();
		}
		return i;
	}

	@Override
	public T selectByPrimaryKey(String key) {
		T i = null;
		SqlSession session = null;
		try {
			session = getSession();
			i = (T) session.selectOne(
					"com.cyl.Idao."+this.getMapperName()+".selectByPrimaryKey", key);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// session.commit();
			this.closeSession();
		}
		return i;
	}

	@Override
	public int updateByPrimaryKeySelective(T record) {
		int i = 0;
		SqlSession session = null;
		try {
			session = getSession();
			i = session.update(
					"com.cyl.Idao."+this.getMapperName()+".updateByPrimaryKeySelective",
					record);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.commit();
			this.closeSession();
		}
		return i;
	}

	@Override
	public int updateByPrimaryKey(T record) {
		int i = 0;
		SqlSession session = null;
		try {
			session = getSession();
			i = session.update("com.cyl.Idao."+this.getMapperName()+".updateByPrimaryKey",
					record);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.commit();
			this.closeSession();
		}
		return i;
	}

	@Override
	public int selectCount(T record) {
		int i = 0;
		SqlSession session = null;
		try {
			session = getSession();
			i = (int) session.selectOne(
					"com.cyl.Idao."+this.getMapperName()+".selectCount", record);
			System.out.println("i-------------------------------"+i);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// session.commit();
			// session.commit();
			this.closeSession();
		}
		return i;
	}

	@Override
	public List<T> selectList(T record) {
		List<T> list = new ArrayList<T>();
		SqlSession session = null;
		try {
			session = getSession();
			list = session.selectList("com.cyl.Idao."+this.getMapperName()+".selectList",
					record);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// session.commit();
			// session.commit();
			this.closeSession();
		}
		return list;
	}

	@Override
	public int deleteByPrimaryKey(int key) {
		int i = 0;
		SqlSession session = null;
		try {
			session = getSession();
			i = session.delete("com.cyl.Idao."+this.getMapperName()+".deleteByPrimaryKey",
					key);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.commit();
			session.close();
		}
		return i;
	}

}


text:
import sys
import unittest
import hashlib

sys.path.append("..")

import sql_manager

class SqlManagerTests(unittest.TestCase):

    def setUp(self):
        sql_manager.create_clients_table()
        sql_manager.register('Tester', '123Ab#78', 'email@hostname.com')

    def tearDown(self):
        sql_manager.cursor.execute('DROP TABLE clients')

    def test_register(self):
        sql_manager.register('Dinko', '123aB#23123', 'email@hostname.com')
        m = hashlib.sha1()
        passw = '123aB#23123'
        m.update(passw.encode('utf-8'))
        passw = m.hexdigest()

        sql_manager.cursor.execute('''SELECT Count(*)  FROM clients
                                      WHERE username = (?)
                                      AND password = (?)''', ('Dinko', passw))
        users_count = sql_manager.cursor.fetchone()

        self.assertEqual(users_count[0], 1)

    def test_register_long_weak_password(self):
        self.assertFalse(sql_manager.register('adad', '123123123',
                                              'email@hostname.com'))

    def test_register_short_password(self):
        self.assertFalse(sql_manager.register('adad', '123',
                                              'email@hostname.com'))

    def test_login(self):
        logged_user = sql_manager.login('Tester', '123Ab#78')
        self.assertEqual(logged_user.get_username(), 'Tester')

    def test_login_wrong_password(self):
        logged_user = sql_manager.login('Tester', '123567')
        self.assertFalse(logged_user)

    def test_change_message(self):
        logged_user = sql_manager.login('Tester', '123Ab#78')
        new_message = "podaivinototam"
        sql_manager.change_message(new_message, logged_user)
        self.assertEqual(logged_user.get_message(), new_message)

    def test_get_tan(self):
        logged_user = sql_manager.login('Tester', '123Ab#78')
        self.assertEqual(10, len(sql_manager.get_tan(logged_user)))

    def test_deposit_withdraw(self):
        logged_user = sql_manager.login('Tester', '123Ab#78')
        sql_manager.deposit(10000, sql_manager.get_tan(logged_user)[0], logged_user)
        self.assertEqual(sql_manager.display_balance(logged_user), 10000.00)
        sql_manager.withdraw(1000, sql_manager.get_tan(logged_user)[1], logged_user)
        self.assertEqual(sql_manager.display_balance(logged_user), 9000.00)

    def test_change_password(self):
        logged_user = sql_manager.login('Tester', '123Ab#78')
        new_password = "12345dSfs$f"
        sql_manager.change_pass(new_password, logged_user)
        logged_user_new_password = sql_manager.login('Tester', '12345dSfs$f')
        self.assertEqual(logged_user_new_password.get_username(), 'Tester')

if __name__ == '__main__':
    unittest.main()


text:
package me.ci.BuilderTasks;

public class QBMatrix{
	public String name;
	public int xSize;
	public int ySize;
	public int zSize;
	public int xPos;
	public int yPos;
	public int zPos;
	public int[] blocks;
	public void create(){
		blocks = new int[xSize*ySize*zSize];
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 324122 $ -->

<refentry xml:id="function.eio-truncate" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>eio_truncate</refname>
  <refpurpose>Truncate a file</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>resource</type><methodname>eio_truncate</methodname>
   <methodparam><type>string</type><parameter>path</parameter></methodparam>
   <methodparam choice="opt"><type>int</type><parameter>offset</parameter><initializer>0</initializer></methodparam>
   <methodparam
   choice="opt"><type>int</type><parameter>pri</parameter><initializer>EIO_PRI_DEFAULT</initializer></methodparam>
   <methodparam
   choice="opt"><type>callable</type><parameter>callback</parameter><initializer>NULL</initializer></methodparam>
   <methodparam
   choice="opt"><type>mixed</type><parameter>data</parameter><initializer>NULL</initializer></methodparam>
  </methodsynopsis>
  <para>
  <function>eio_truncate</function> causes the regular file named by <parameter>path</parameter> to be truncated to
  a size of precisely <parameter>length</parameter> bytes
  </para>

 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <variablelist>
   <varlistentry>
    <term><parameter>path</parameter></term>
    <listitem>
     <para>
     File path
     </para>
    </listitem>
   </varlistentry>
   <varlistentry>
    <term><parameter>offset</parameter></term>
    <listitem>
     <para>
     Offset from beginning of the file.
     </para>
    </listitem>
   </varlistentry>
   <varlistentry>
    <term><parameter>pri</parameter></term>
    <listitem>
    &eio.request.pri.values;
    </listitem>
   </varlistentry>
   <varlistentry>
    <term><parameter>callback</parameter></term>
    <listitem>
     &eio.callback.proto;
    </listitem>
   </varlistentry>
   <varlistentry>
    <term><parameter>data</parameter></term>
    <listitem>
     <para>
     Arbitrary variable passed to <parameter>callback</parameter>.
     </para>
    </listitem>
   </varlistentry>
  </variablelist>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   <function>eio_busy</function> returns request resource on success or &false; on error.
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <simplelist>
   <member>eio_ftruncate</member>
  </simplelist>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package org.anodyneos.sfs.impl.translater;

public interface TranslaterResult {
    /**
     *  @return "package.class" or "class" if no package.
     */
    String getFullClassName();

    /**
     *  @return Package name or null.
     */
    String getPackageName();

    /**
     *  @return Class name or null.
     */
    String getClassName();

}


text:
// import polyfills first
import './polyfill';

// export lib
import * as accessibility from './accessibility';
import * as extract from './extract';
import * as extras from './extras';
import * as filters from './filters';
import * as interaction from './interaction';
import * as loaders from './loaders';
import * as mesh from './mesh';
import * as particles from './particles';
import * as prepare from './prepare';

export * from './core';
export {
    accessibility,
    extract,
    extras,
    filters,
    interaction,
    loaders,
    mesh,
    particles,
    prepare,
};

// Mixin the deprecations
import './deprecation';

/**
 * A premade instance of the loader that can be used to loader resources.
 *
 * @name loader
 * @memberof PIXI
 * @property {PIXI.loaders.Loader}
 */
const loader = new loaders.Loader();

export { loader };

// Always export pixi globally.
global.PIXI = exports; // eslint-disable-line


text:
class FindSecurityClassification
  class << self
    def at_or_earlier_than(security, major = nil, minor = nil, micro = nil, datestamp)
      security_classification_time_series_map = SecurityClassificationLoader.get(security, major, minor, micro)
      security_classification_time_series_map.latest_value_at_or_earlier_than(datestamp)
    end
  end
end