text:
namespace blimp {
namespace engine {

// Blimp engine crash client. This should be available globally and should be
// long lived.
base::LazyInstance<BlimpEngineCrashReporterClient>
    g_blimp_engine_crash_reporter_client = LAZY_INSTANCE_INITIALIZER;

namespace {
void InitLogging() {
  logging::LoggingSettings settings;
  base::FilePath log_filename;
  PathService::Get(base::DIR_EXE, &log_filename);
  log_filename = log_filename.AppendASCII("blimp_engine.log");
  settings.logging_dest = logging::LOG_TO_ALL;
  settings.log_file = log_filename.value().c_str();
  settings.delete_old = logging::DELETE_OLD_LOG_FILE;
  logging::InitLogging(settings);
  logging::SetLogItems(true,    // Process ID
                       true,    // Thread ID
                       true,    // Timestamp
                       false);  // Tick count
}
}  // namespace

BlimpContentMainDelegate::BlimpContentMainDelegate() {}

BlimpContentMainDelegate::~BlimpContentMainDelegate() {}

bool BlimpContentMainDelegate::BasicStartupComplete(int* exit_code) {
  InitLogging();
  content::SetContentClient(&content_client_);
  return false;
}

void BlimpContentMainDelegate::PreSandboxStartup() {
  // Enable crash reporting for all processes, and initialize the crash
  // reporter client.
  crash_reporter::SetCrashReporterClient(
      g_blimp_engine_crash_reporter_client.Pointer());
  base::CommandLine* cmd = base::CommandLine::ForCurrentProcess();
  cmd->AppendSwitch(::switches::kEnableCrashReporter);
  breakpad::InitCrashReporter(
      cmd->GetSwitchValueASCII(::switches::kProcessType));

  InitializeResourceBundle();
}

void BlimpContentMainDelegate::InitializeResourceBundle() {
  base::FilePath pak_file;
  bool pak_file_valid = PathService::Get(base::DIR_MODULE, &pak_file);
  CHECK(pak_file_valid);
  pak_file = pak_file.Append(FILE_PATH_LITERAL("blimp_engine.pak"));
  ui::ResourceBundle::InitSharedInstanceWithPakPath(pak_file);
}

content::ContentBrowserClient*
BlimpContentMainDelegate::CreateContentBrowserClient() {
  DCHECK(!browser_client_);
  browser_client_.reset(new BlimpContentBrowserClient);
  return browser_client_.get();
}

content::ContentRendererClient*
BlimpContentMainDelegate::CreateContentRendererClient() {
  DCHECK(!renderer_client_);
  renderer_client_.reset(new BlimpContentRendererClient);
  return renderer_client_.get();
}

}  // namespace engine
}  // namespace blimp


text:
package com.totvslabs.mdm.restclient;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;
import org.glassfish.jersey.client.JerseyClientBuilder;

import com.google.gson.Gson;
import com.totvslabs.mdm.restclient.command.AuthenticationRequired;
import com.totvslabs.mdm.restclient.command.CommandPostStagingC;
import com.totvslabs.mdm.restclient.command.ICommand;
import com.totvslabs.mdm.restclient.vo.EnvelopeVO;
import com.totvslabs.mdm.restclient.vo.GenericVO;

/**
 *
 *
 */
public class MDMRestConnection {

	private static final Logger log = Logger.getLogger(MDMRestConnection.class);

	private Client client;
	private String mdmURL;

	public MDMRestConnection(String mdmURL) {
		this.client = new JerseyClientBuilder()
						.sslContext(getTrustAllSSLContext())
						.hostnameVerifier(new DefaultHostnameVerifier())
						.build();

		this.mdmURL = mdmURL;
	}

	public EnvelopeVO executeCommand(ICommand command) {
		if(command instanceof CommandPostStagingC) {
			this.client.register(GZipReaderInterceptor.class);
			this.client.register(GZipWriterInterceptor.class);
		}

		Map<String, String> parametersHeader = command.getParametersHeader();
		Map<String, String> parameterPath = command.getParameterPath();

		Set<String> keySetPath = parameterPath != null ? parameterPath.keySet() : null;
		Set<String> keySetHeader = parametersHeader != null ? parametersHeader.keySet() : null;

		WebTarget webResource = this.client.target(mdmURL + command.getCommandURL());

		if(keySetPath != null) {
			for (String string : keySetPath) {
				webResource = webResource.queryParam(string, parameterPath.get(string));
			}
		}

		Builder request = webResource.request(MediaType.APPLICATION_JSON);

		if(keySetHeader != null) {
			for (String string : keySetHeader) {
				request = request.header(string, parametersHeader.get(string));
			}
		}

		if(command instanceof AuthenticationRequired) {
			request = request.header("Authorization", MDMRestAuthentication.getInstance().getAuthVO().getAccess_token());
		}

		Response response = null;

		switch(command.getType()) {
			case GET:
				long initialTimeGet = System.currentTimeMillis();

				response = request.accept(MediaType.APPLICATION_JSON).get();

				log.info("Time to execute the GET service ('" + command.getCommandURL() + "'): " + (System.currentTimeMillis() - initialTimeGet) );
				break;

			case POST:
				String type = MediaType.APPLICATION_JSON;
				String additionalInformation = "";

				if(command instanceof CommandPostStagingC) {
					request.header(HttpHeaders.ACCEPT_ENCODING, "gzip");
					additionalInformation = " - COMPRESS";
				}

				Map<String, String> formDataCommand = command.getFormData();
				MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();

				if(formDataCommand != null && formDataCommand.size() > 0) {
					Set<String> keySet = formDataCommand.keySet();

					for (String key : keySet) {
						String value = formDataCommand.get(key);

						formData.add(key, value);
					}
				}

				long initialTimeConvertJson = System.currentTimeMillis();
				String string = command.getData() != null ? command.getData().toString() : "";
				log.info("Time to convert the OBJECT to JSON: " + (System.currentTimeMillis() - initialTimeConvertJson) );
				long initialTime = System.currentTimeMillis();

				if (formData != null && formData.size() > 0) {
					response = request.accept(type).post(Entity.form(formData));
				} else {
					response = request.accept(type).post(Entity.entity(string, type));
				}

				log.info("Time to execute the POST service ('" + command.getCommandURL() + "'" + additionalInformation + "): " + (System.currentTimeMillis() - initialTime) );
				break;
		}

		if (response.getStatus() != Response.Status.OK.getStatusCode()) {
			if(command.getData() != null) {
				log.info("Data response:" + command.getData().toString());
			}

			String readEntity = response.readEntity(String.class);

			throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + " -> " + readEntity);
		}

		Gson gson = new Gson();
		Object resultVO = gson.fromJson(response.readEntity(String.class), command.getResponseType());
		EnvelopeVO envelopeVO = null;

		if (resultVO instanceof EnvelopeVO) {
			envelopeVO = (EnvelopeVO) resultVO;
		} else {
			envelopeVO = new EnvelopeVO();

			List<GenericVO> genericVO = new ArrayList<GenericVO>();
			genericVO.add((GenericVO) resultVO);
			envelopeVO.setHits(genericVO);
		}

		return envelopeVO;
	}

	/**
	 * Instantiates and initializes a trust-all SSL Context
	 * @return
	 */
	protected SSLContext getTrustAllSSLContext() {
		SSLContext sc = null;

		try {
			sc = SSLContext.getInstance("SSL");
		} catch (NoSuchAlgorithmException e) {
			log.error("Error registering SSLContext", e);
		}
		try {
			sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
		} catch (KeyManagementException e) {
			log.error("Error initializing SSLContext", e);
		}

		return sc;
	}

	public static class DefaultTrustManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[0];
		}

	}

	public static class DefaultHostnameVerifier implements HostnameVerifier {

		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'podunk/app/router/route'

module Podunk
  class App
    module Router
      def self.included(base)
        base.extend ClassMethods
      end

      def method_for_path
        route = Route.for(request.verb, request.path)
        request.params.merge! route.params
        route.method
      end

      def body_method_for_route
        method_for_path
      end

      def render_body_for_route
        body = self.send body_method_for_route
      end

      module ClassMethods
        def route(&block)
          yield
        end

      private
        def root(opts={})
          method = opts[:to]
          Route.root = method
        end

        def get(opts)
          register_route('GET', opts)
        end

        def register_route(verb, opts)
          check_verb!(verb) and check_route!(opts)

          path   = opts.keys.first
          method = opts.values.first

          Route.new verb, path, method
        end

        def check_verb!(verb)
          fail ArgumentError.new('not a valid HTTP verb') unless %w[GET POST PUT PATCH DELETE HEAD].include? verb
        end

        def check_route!(opts)
          fail ArgumentError.new('not a single element Hash') unless opts.is_a?(Hash) && opts.count == 1
        end
      end
    end
  end
end


text:
<xml>
  <error>0</error>
  <status>success</status>
  <campaignCnt>1</campaignCnt>
  <campaign>
    <campaignID>1234</campaignID>
    <campaignName>Sample Campaign</campaignName>
    <dateCreated>2014-06-01T11:00:00</dateCreated>
    <sentFrom>Test User</sentFrom>
    <subject>My Sample Campaign</subject>
    <startDate>2014-06-02T12:00:00</startDate>
    <status>4</status>
    <groupID>1314</groupID>
    <emailFrom>my@emailaddress.com</emailFrom>
    <totalRecipients>12</totalRecipients>
    <opened>3</opened>
      <clicks>2</clicks>
      <unsubscribers>1</unsubscribers>
      <bounced>2</bounced>
      <newsletterID>2131</newsletterID>
      <newsletter><![CDATA[21asvasvasv7as*V&VSA*V&ASVcsacascasc31]]></newsletter>
    </campaign>
</xml>


text:
function varargout = grabadora(varargin)

gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @grabadora_OpeningFcn, ...
                   'gui_OutputFcn',  @grabadora_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before grabadora is made visible.
function grabadora_OpeningFcn(hObject, eventdata, handles, varargin)
a=imread('play.png');
set(handles.Play,'CData',a);
rec_img=imread('rec.png');
set(handles.Rec,'CData',rec_img);
c=imread('pause.png');
set(handles.StopRec,'CData',c);

% --- %
set(handles.playOtra,'CData',a);
set(handles.grabarOtra,'CData',rec_img);
set(handles.pausaOtra,'CData',c);
% Choose default command line output for grabadora
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes grabadora wait for user response (see UIRESUME)
% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.
function varargout = grabadora_OutputFcn(hObject, eventdata, handles)

varargout{1} = handles.output;

% --- Executes on button press in Rec.
function Rec_Callback(hObject, eventdata, handles)

global r
r=audiorecorder;
record(r);

% --- Executes on button press in Play.
function Play_Callback(hObject, eventdata, handles)
% hObject    handle to Play (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global voz Fs
%[voz Fs] =wavread('grabacion1');
sound(voz,Fs);
% Ts=1/Fs;
% tam=length(voz);
% t=(0:tam-1)*Ts;
% stem(handles.modificada,t,voz);
% title(handles.modificada,'Audio Modificado');
% xlabel(handles.modificada,'Tiempo (segundos)');
% ylabel(handles.modificada,'Amplitud');

% --- Executes on button press in StopRec.
function StopRec_Callback(hObject, eventdata, handles)
% hObject    handle to StopRec (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global r voz Fs t
stop(r);
voz=getaudiodata(r);
Fs=r.SampleRate;
Ts=1/Fs;
tam=length(voz);
t=(0:tam-1)*Ts;
plot(handles.original,t,voz);
title(handles.original,'Audio');
xlabel(handles.original,'Tiempo (segundos)');
ylabel(handles.original,'Amplitud');

% --- Executes on button press in habilitar.
function habilitar_Callback(hObject, eventdata, handles)
% hObject    handle to habilitar (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
bandera = get(hObject,'Value');
if bandera == 0
    set(handles.playOtra,'enable','off');
    set(handles.grabarOtra,'enable','off');
    set(handles.pausaOtra,'enable','off');
else
    set(handles.playOtra,'enable','on');
    set(handles.grabarOtra,'enable','on');
    set(handles.pausaOtra,'enable','on');
end

% --- Executes on button press in grabarOtra.
function grabarOtra_Callback(hObject, eventdata, handles)
% hObject    handle to grabarOtra (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global r
r=audiorecorder;
record(r);

% --- Executes on button press in playOtra.
function playOtra_Callback(hObject, eventdata, handles)
% hObject    handle to playOtra (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global otra Fs
%[voz Fs] =wavread('grabacion1');
sound(otra,Fs);

% --- Executes on button press in pausaOtra.
function pausaOtra_Callback(hObject, eventdata, handles)
% hObject    handle to pausaOtra (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global r otra Fs t
stop(r);
otra=getaudiodata(r);
Fs=r.SampleRate;
Ts=1/Fs;
tam=length(otra);
t=(0:tam-1)*Ts;
plot(handles.otra,t,otra);
title(handles.otra,'Audio');
xlabel(handles.otra,'Tiempo (segundos)');
ylabel(handles.otra,'Amplitud');

% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function popupmenu3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes during object creation, after setting all properties.
function factor_CreateFcn(hObject, eventdata, handles)
% hObject    handle to factor (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
global voz Fs
opc=get(handles.popupmenu3,'Value');
f=get(handles.factor,'String');
factor=str2double(f);
Ts=1/Fs;
tam=length(voz);
t=(0:tam-1)*Ts;
switch opc
    case 1
        resultado=AmplificarAtenuar(voz,factor);
        stem(handles.modificada,t,resultado);
        title(handles.modificada,'Audio Modificado');
        xlabel(handles.modificada,'Tiempo (segundos)');
        ylabel(handles.modificada,'Amplitud');
        sound(resultado,Fs);

    case 2
        if(factor>0)
            resultado=voz(factor:+1:end);
            tam=length(resultado);
            t=(0:tam-1)*Ts;
            stem(handles.modificada,t,resultado);
            title(handles.modificada,'Audio Modificado');
            xlabel(handles.modificada,'Tiempo (segundos)');
            ylabel(handles.modificada,'Amplitud');
            sound(resultado,Fs);

        else
            r=-factor;
            p=zeros(r,1);
            resultado=vertcat(p,voz);
            tam=length(resultado);
            t=(0:tam-1)*Ts;
            stem(handles.modificada,t,resultado);
            title(handles.modificada,'Audio Modificado');
            xlabel(handles.modificada,'Tiempo (segundos)');
            ylabel(handles.modificada,'Amplitud');
            sound(resultado,Fs);

        end

    case 3
         resultado=Reflejo(voz);
         stem(handles.modificada,t,resultado);
         title(handles.modificada,'Audio Modificado');
        xlabel(handles.modificada,'Tiempo (segundos)');
        ylabel(handles.modificada,'Amplitud');
        sound(resultado,Fs);

    case 4

        tiem=tam/Fs;
        resultado=Diezmacion(voz,factor);
        t=downsample(t,factor);
        tam=length(resultado);
        stem(handles.modificada,t,resultado);
        title(handles.modificada,'Audio Modificado');
        xlabel(handles.modificada,'Tiempo (segundos)');
        ylabel(handles.modificada,'Amplitud');
        FsD=tam/tiem
        sound(resultado,FsD);

    case 5

        tiem=tam/Fs;
        resultado=Interpolacion(voz,factor);
        t=upsample(t,factor);
        tam=length(resultado);
        stem(handles.modificada,t,resultado);
        title(handles.modificada,'Audio Modificado');
        xlabel(handles.modificada,'Tiempo (segundos)');
        ylabel(handles.modificada,'Amplitud');
        FsD=tam/tiem
        sound(resultado,FsD);

end

% --- Executes on button press in Convolucion.
function Convolucion_Callback(hObject, eventdata, handles)
% hObject    handle to Convolucion (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global r voz otra Fs t
funcion = get(handles.funcion,'String');
if isempty(funcion)
    convolucion = conv(voz, otra, 'full');
    Fs=r.SampleRate;
    Ts=1/Fs;
    tam = length(convolucion);
    t=(0:tam-1)*Ts;
    stem(handles.modificada,t,convolucion);
    title(handles.modificada,'Audio Convolucion');
    xlabel(handles.modificada,'Tiempo (segundos)');
    ylabel(handles.modificada,'Amplitud');
    tiem=tam/Fs;
    FsD=tam/tiem;
    sound(convolucion,FsD);
else
    x = linspace(0,100,1000);
    size(x)
    evaluada = eval(funcion);
    size(evaluada)
    plot(evaluada)
    title(handles.otra,'Audio Otra');
    xlabel(handles.otra,'Tiempo (ms)');
    ylabel(handles.otra,'Amplitud');
    %
    convolucion = conv(voz, evaluada, 'full');
    Fs=r.SampleRate;
    Ts=1/Fs;
    tam = length(convolucion);
    t=(0:tam-1)*Ts;
    stem(handles.modificada,t,convolucion);
    title(handles.modificada,'Audio Convolucion');
    xlabel(handles.modificada,'Tiempo (segundos)');
    ylabel(handles.modificada,'Amplitud');
    tiem=tam/Fs;
    FsD=tam/tiem;
    sound(convolucion,FsD);
end

function funcion_Callback(hObject, eventdata, handles)
% hObject    handle to funcion (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of funcion as text
%        str2double(get(hObject,'String')) returns contents of funcion as a double

% --- Executes during object creation, after setting all properties.
function funcion_CreateFcn(hObject, eventdata, handles)
% hObject    handle to funcion (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


text:
import superimport

import spacy
import numpy as np
import pandas as pd
from scipy import spatial

nlp = spacy.load('en_core_web_md', disable=['tagger','parser','ner']) # Just tokenize

cosine_similarity = lambda x, y: 1 - spatial.distance.cosine(x, y)

# Pairwise similarity
tokens = nlp(u'dog cat banana') # type spacy.tokens.doc.Doc
N = len(tokens)
S = np.empty((N,N))
S2 = np.empty((N,N))
for i in range(N):
  for j in range(N):
    t1 = tokens[i]
    t2 = tokens[j]
    S[i,j] = t1.similarity(t2)
    S2[i,j] = cosine_similarity(t1.vector, t2.vector)

assert np.isclose(S, S2).all()
df=pd.DataFrame(data=S,columns=tokens,index=tokens)
print(df)
"""
             dog       cat    banana
dog     1.000000  0.801686  0.243276
cat     0.801686  1.000000  0.281544
banana  0.243276  0.281544  1.000000
"""

# The vector embedding of a doc is the average of the vectors of each token
# Each token has a D=300 dimensional embedding
tokens = nlp(u"The cat sat on the mat.")
token_embeds = np.array([t.vector for t in tokens]) # N*D
assert np.isclose(tokens.vector, np.mean(token_embeds,axis=0)).all()

# we can use this for document retrieval

target = nlp("Cats are beautiful animals.")
doc1 = nlp("Dogs are awesome.")
doc2 = nlp("Some gorgeous creatures are felines.")
doc3 = nlp("Dolphins are swimming mammals.")
print(target.similarity(doc1))  # 0.8901765218466683
print(target.similarity(doc2))  # 0.9115828449161616
print(target.similarity(doc3))  # 0.7822956752876101

# Vector space arithmetic

man = nlp.vocab['man'].vector
woman = nlp.vocab['woman'].vector
queen = nlp.vocab['queen'].vector
king = nlp.vocab['king'].vector

# We now need to find the closest vector in the vocabulary to the result of "man" - "woman" + "queen"
maybe_king = man - woman + queen
computed_similarities = []
from time import time
time_start = time() #  slow to search through 1,344,233 words
print("searching through {} words for nearest neighbors".format(len(nlp.vocab)))
for word in nlp.vocab:
    if not word.has_vector:
        continue
    similarity = cosine_similarity(maybe_king, word.vector)
    computed_similarities.append((word, similarity))
print('time spent training {:0.3f}'.format(time() - time_start))

computed_similarities = sorted(computed_similarities, key=lambda item: -item[1])
print([w[0].text for w in computed_similarities[:10]])

# ['Queen', 'QUEEN', 'queen', 'King', 'KING', 'king', 'KIng', 'KINGS', 'kings', 'Kings']

"""
X = [word.vector for word in nlp.vocab if word.has_vector]
print(np.shape(X)) # (684 755, 300)
N = 10000; D = 300;
X = np.random.rand(N,D)
# datascience book p89 - correct, but gets memory error if N is too large
time_start = time()
sqdst = np.sum((X[:,np.newaxis,:] - X[np.newaxis,:,:]) ** 2, axis=-1)
print(time() - time_start)
i=10;j=200;assert np.isclose(sqdst[i,j], np.sum((X[i,:]-X[j,:])**2))
"""


text:
package io.fabric8.runtime.container.spi;

import io.fabric8.runtime.container.ContainerConfiguration;
import io.fabric8.runtime.container.LifecycleException;
import io.fabric8.runtime.container.ManagedContainer;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import org.jboss.gravia.resource.MavenCoordinates;
import org.jboss.shrinkwrap.api.GenericArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.exporter.ExplodedExporter;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;

/**
 * The managed root container
 *
 * @since 26-Feb-2014
 */
public abstract class AbstractManagedContainer<T extends ContainerConfiguration> implements ManagedContainer<T> {

    private T configuration;
    private File containerHome;
    private State state;
    private Process process;

    @Override
    public final synchronized void create(T configuration) throws LifecycleException {
        if (state != null)
            throw new IllegalStateException("Cannot create container in state: " + state);

        this.configuration = configuration;

        // [TODO] [FABRIC-929] No connector available to access repository jboss-public-repository-group
        // Remove this hack. It shouldbe possible to use the shrinkwrap maven resolver
        boolean useShrinkwrap = System.getProperty("shrinkwrap.resolver") != null;

        for (MavenCoordinates artefact : configuration.getMavenCoordinates()) {
            File zipfile = useShrinkwrap ? shrinkwrapResolve(artefact) : localResolve(artefact);
            GenericArchive archive = ShrinkWrap.createFromZipFile(GenericArchive.class, zipfile);
            ExplodedExporter exporter = archive.as(ExplodedExporter.class);
            File targetdir = configuration.getTargetDirectory();
            if (!targetdir.isDirectory() && !targetdir.mkdirs())
                throw new IllegalStateException("Cannot create target dir: " + targetdir);

            if (containerHome == null) {
                exporter.exportExploded(targetdir, "");
                File[] childDirs = targetdir.listFiles();
                if (childDirs.length != 1)
                    throw new IllegalStateException("Expected one child directory, but was: " + Arrays.asList(childDirs));
                containerHome = childDirs[0];
            } else {
                exporter.exportExploded(containerHome, "");
            }
        }

        state = State.CREATED;

        try {
            doConfigure(configuration);
        } catch (Exception ex) {
            throw new LifecycleException("Cannot configure container", ex);
        }
    }

    private File localResolve(MavenCoordinates artefact) {
        File userHome = new File(System.getProperty("user.home"));
        File repodir = new File(userHome, ".m2/repository");
        File artefactPath = new File(repodir, artefact.getArtifactPath());
        if (!artefactPath.isFile())
            throw new IllegalStateException("Cannot obtain maven artefact: " + artefact);

        return artefactPath;
    }

    private File shrinkwrapResolve(MavenCoordinates artefact) {
        File[] resolved = Maven.resolver().resolve(artefact.toString()).withoutTransitivity().asFile();
        if (resolved == null || resolved.length == 0)
            throw new IllegalStateException("Cannot obtain maven artefact: " + artefact);
        if (resolved.length > 1)
            throw new IllegalStateException("Multiple maven artefacts for: " + artefact);

        return resolved[0];
    }

    @Override
    public File getContainerHome() {
        return containerHome;
    }

    @Override
    public State getState() {
        return state;
    }

    @Override
    public final synchronized void start() throws LifecycleException {
        assertNotDestroyed();
        try {
            if (state == State.CREATED || state == State.STOPPED) {
                doStart(configuration);
                state = State.STARTED;
            }
        } catch (Exception ex) {
            throw new LifecycleException("Cannot start container", ex);
        }
    }

    @Override
    public final synchronized void stop() throws LifecycleException {
        assertNotDestroyed();
        try {
            if (state == State.STARTED) {
                doStop(configuration);
                state = State.STOPPED;
            }
        } catch (Exception ex) {
            throw new LifecycleException("Cannot stop container", ex);
        }
    }

    @Override
    public final synchronized void destroy() throws LifecycleException {
        assertNotDestroyed();
        if (state == State.STARTED) {
            try {
                stop();
            } catch (Exception ex) {
                // ignore
            }
        }
        try {
            doDestroy(configuration);
        } catch (Exception ex) {
            throw new LifecycleException("Cannot destroy container", ex);
        } finally {
            state = State.DESTROYED;
        }
    }

    private void assertNotDestroyed() {
        if (state == State.DESTROYED)
            throw new IllegalStateException("Cannot start container in state: " + state);
    }

    protected void doConfigure(T configuration) throws Exception {
    }

    protected void doStart(T configuration) throws Exception {
    }

    protected void doStop(T configuration) throws Exception {
    }

    protected void doDestroy(T configuration) throws Exception {
        destroyProcess();
    }

    protected void startProcess(ProcessBuilder processBuilder, ContainerConfiguration config) throws IOException {
        process = processBuilder.start();
        new Thread(new ConsoleConsumer(process, config)).start();
    }

    protected void destroyProcess() throws Exception {
        if (process != null) {
            process.destroy();
            process.waitFor();
        }
    }

    /**
     * Runnable that consumes the output of the process. If nothing consumes the output the AS will hang on some platforms
     */
    public static class ConsoleConsumer implements Runnable {

        private final Process process;
        private final ContainerConfiguration config;

        public ConsoleConsumer(Process process, ContainerConfiguration config) {
            this.process = process;
            this.config = config;
        }

        @Override
        public void run() {
            final InputStream stream = process.getInputStream();
            try {
                byte[] buf = new byte[32];
                int num;
                // Do not try reading a line cos it considers '\r' end of line
                while ((num = stream.read(buf)) != -1) {
                    if (config.isOutputToConsole())
                        System.out.write(buf, 0, num);
                }
            } catch (IOException e) {
            }
        }
    }
}


text:
package nl.uva.multimedia.camera;
/*
 * Framework for camera processing and visualisation
 *
 * For the Multimedia course in the BSc Computer Science
 * at the University of Amsterdam
 *
 * I.M.J. Kamps, S.J.R. van Schaik, R. de Vries (2013)
 */

/* XXX Yes, you should change stuff here */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class CanvasView extends View {
    public int[] argb;
    public int image_width;
    public int image_height;
    float[] percentages;
    float[] pixelarray;
    float optimuspixel;
    static int average;
    static int median;
    static double standardDev;

    Bitmap m_image = null;

    public CanvasView(Context context) {
        super(context);
    }

    public CanvasView(Context context, AttributeSet attributes) {
        super(context, attributes);
    }

    public CanvasView(Context context, AttributeSet attributes, int style) {
        super(context, attributes, style);
    }

    /* Called whenever the canvas is dirty and needs redrawing. */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawColor(Color.BLACK);

		/* Define the basic paint. */
        Paint paint = new Paint();
        paint.setColor(Color.rgb(0xa0, 0xa0, 0xb0));
        paint.setAntiAlias(true);

		/* text inherits from the basic paint and adds text properties. */
        Paint text = new Paint(paint);
        text.setColor(Color.WHITE);
        text.setShadowLayer(3.0F, 3.0F, 3.0F, Color.rgb(0x20, 0x20, 0x20));
        text.setTextSize(getHeight() * 0.1F);

        /* To draw histogram */
        Paint hist = new Paint(paint);
        hist.setColor(Color.WHITE);
        hist.setAntiAlias(true);

        /*Colors for bins*/
        Paint bin = new Paint(paint);
        bin.setColor(Color.GREEN);
        bin.setAntiAlias(true);

        /* Colours for average bin */
        Paint aver = new Paint(paint);
        aver.setColor(Color.RED);
        aver.setAntiAlias(true);

        /* Colours for median bin*/
        Paint paintMedian = new Paint(paint);
        paintMedian.setColor(Color.BLACK);
        paintMedian.setAntiAlias(true);

        /*Colours for standard deviation*/
        Paint paintDev = new Paint(paint);
        paintDev.setColor(Color.YELLOW);
        paintDev.setAntiAlias(true);

		/* Save state */
        canvas.save();
        canvas.translate(getWidth() * 0.1F, getHeight() * 0.1F);
        canvas.drawRect(0.0F,20.0F,850.0F,600.0F,hist);

        if(pixelarray != null) {
            int width = 850/pixelarray.length;
            float perbin = 256/pixelarray.length;
            int counter = 0;
            for (float i : pixelarray) {
                int left = counter * width;
                int right = left + width;
                int top = 600 - (int) i;
                int bottom = 600;

                /*Print values*/
                String averageString = Integer.toString(average);
                String medString = Integer.toString(median);
                String standardString = Integer.toString((int) standardDev);
                canvas.drawText(averageString + "," + medString + "," + standardString, 0.0F, 0.0F, text);

                /*Calculate average bin*/
                int averagebin = (int)Math.ceil(average/perbin);

                /*Calculate median bin*/
                int medianbin = (int) Math.ceil(median/perbin);

                /* Calculate standard deviation bins */
                int standardDevBin1 = (int) Math.ceil(((average + standardDev)/perbin));
                int standardDevBin2 = (int) Math.ceil(((average - standardDev)/perbin));

                /*If counter equals average paint bin red
                * If counter equals median paint bin yellow
                * Else paint bin green*/
                if(counter + 1 == averagebin){
                    canvas.drawRect(left,top,right,bottom,aver);
                }
                else if(counter + 1 == medianbin){
                    canvas.drawRect(left,top,right,bottom,paintMedian);
                }
                else if(counter + 1 == standardDevBin1 || counter + 1 == standardDevBin2){
                    canvas.drawRect(left,top,right,bottom,paintDev);
                }
                else{
                    canvas.drawRect(left, top, right, bottom, bin);
                }
                counter++;
            }
        }
        canvas.restore();

		/* Paint a image if we have it, just a demo, clean this up so it works
		 * your way, or remove it if you don't need it
		 */
        if (m_image != null) {
            Rect rect = new Rect(
                    (int) (getWidth() * 0.25F), (int) (getHeight() * 0.25F),
                    (int) (getWidth() * 0.75F), (int) (getHeight() * 0.75F)
            );
            Paint bmp = new Paint();
            bmp.setAntiAlias(true);
            bmp.setFilterBitmap(true);
            bmp.setDither(true);

            canvas.drawBitmap(m_image, null, rect, paint);
        }
    }

    public void setPercentage(Histogram hist){
        percentages = hist.binpercentage;

        /* Function to get heighest number */
        float heighest = 0;
        for(float i : percentages){
            if(i > heighest){
                heighest = i;
            }
        }

        optimuspixel = 580/heighest;

        pixelarray = new float[percentages.length];
        int optimuscounter = 0;
        for(float i : percentages){
            float newPixel = i * optimuspixel;
            pixelarray[optimuscounter] = newPixel;
            optimuscounter++;

        }

    }

    /* Accessors */
    public Bitmap getSelectedImage() {
        return m_image;
    }

    public void setSelectedImage(Bitmap image) {
        m_image = image;
    }

    public static void aver(int gem) {
        average = gem;
    }

    public static void median(int med) {
        median = med;
    }

    public static void standardDeviation(double standardDeviation) {
        standardDev = standardDeviation;
    }
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Trash Day Help</title>

Introduction

Thank you for being a Trash Day user.  Since the Alexa service only provides
voice and (small) cards to provide help for using the application, I have created
this document for users that may need additional information.

Updated 2017-02-12: Trash Day now supports weekly, biweekly, and monthly pickups!
Thanks to the users who took the time to read this document and email their request.
I hope this change makes the skill more useful to a lot of people.

Setup

To use Trash Day, you have to tell the application your time zone and make a
pickup schedule.  This is the most difficult part of using the Trash Day
application.  As an example, here's how I setup to use the application in
my house:

Alexa, tell Trash Day, to change schedule.

Set time zone to Eastern.

Add weekly trash pickup on Tuesday at seven-thirty A.M.

Add weekly trash pickup on Friday at seven-thirty A.M.

Add biweekly recycling pickup on this Wednesday at four P.M.

Add biweekly lawn waste pickup on Wednesday after next at four P.M.

Add monthly scrap metal pickup on the fifteenth at four P.M.

Add monthly scrap metal pickup on the last day of the month at four P.M.

Add monthly rent pickup five days before the end of the month at four P.M.

Add monthly hockey team pickup on the first Saturday of the month at nine A.M.

Add monthly hockey team pickup on the third Saturday of the month at nine A.M.

Add monthly little league pickup on the last Saturday of the month at ten A.M.

Tell me the schedule.

Stop.

NOTE:The Trash Day application keeps listening (the blue ring is lit on the Echo)
while you give commands.  If you mess up or get delayed, the blue ring will turn off.
If that happens, just say "Alexa, tell Trash Day, to change schedule" and continue where you left
off with your setup.

Usage

Once you have setup your time zone and pickup schedule, using Trash Day is easy.  Here
are the common commands:

Alexa, ask Trash Day, what's next?

Alexa, ask Trash Day, is it trash day?

Alexa, ask Trash Day, when is the next recycling pickup?

Alexa, ask Trash Day, what is the schedule?

Schedule Updates

If you need to make changes to your pickup schedule, use commands like the following
to set your time zone, delete old pickups, and add new pickups.  You can use any combination
of these commands, depending on what you need for your schedule.

Alexa, open Trash Day.

Set time zone to Pacific.

Add weekly trash pickup on Tuesday at seven-thirty A.M.

Add weekly trash pickup on Friday at seven-thirty A.M.

Add biweekly recycling pickup on this Wednesday at four P.M.

Add biweekly lawn waste pickup on Wednesday after next at four P.M.

Add monthly scrap metal pickup on the fifteenth at four P.M.

Add monthly scrap metal pickup on the last day of the month at four P.M.

Add monthly rent pickup five days before the end of the month at four P.M.

Add monthly hockey team pickup on the first Saturday of the month at nine A.M.

Add monthly hockey team pickup on the third Saturday of the month at nine A.M.

Add monthly little league pickup on the last Saturday of the month at ten A.M.

Delete all lawn waste pickups.

Delete weekly trash pickup on Tuesday at seven-thirty A.M.

Delete weekly trash pickup on Friday at seven-thirty A.M.

Delete biweekly recycling pickup on this Wednesday at four P.M.

Delete biweekly lawn waste pickup on Wednesday after next at four P.M.

Delete monthly scrap metal pickup on the fifteenth at four P.M.

Delete monthly scrap metal pickup on the last day of the month at four P.M.

Delete monthly rent pickup five days before the end of the month at four P.M.

Delete monthly hockey team pickup on the first Saturday of the month at nine A.M.

Delete monthly hockey team pickup on the third Saturday of the month at nine A.M.

Delete monthly little league pickup on the last Saturday of the month at ten A.M.

Tell me the schedule.

Stop.

If you need to make more extensive changes, you may want to delete the entire
schedule.  To do this:

Alexa, tell Trash Day, to delete the entire schedule.

Yes

You will need to answer "Yes" to confirm the schedule deletion.  Once the schedule
is deleted, rebuild a new schedule by using the commands given in the Setup section
at the top of this page.

Further Help

If you need further help, you may send EMail to me at J. Todd Baldwin


text:
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Din.Service.Clients.Abstractions;
using Din.Service.Clients.Interfaces;
using Din.Service.Clients.RequestObjects;
using Din.Service.Clients.ResponseObjects;
using Din.Service.Config.Interfaces;
using Newtonsoft.Json;

namespace Din.Service.Clients.Concrete
{
    public class TvShowClient : BaseClient, ITvShowClient
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ITvShowClientConfig _config;

        public TvShowClient(IHttpClientFactory httpClientFactory, ITvShowClientConfig config)
        {
            _httpClientFactory = httpClientFactory;
            _config = config;
        }

        public async Task<IEnumerable<TcTvShow>> GetCurrentTvShowsAsync()
        {
            var client = _httpClientFactory.CreateClient();

            return JsonConvert.DeserializeObject<IEnumerable<TcTvShow>>(
                await client.GetStringAsync(BuildUrl(_config.Url, "series", $"?apikey={_config.Key}")));
        }

        public async Task<TcTvShow> GetTvShowByIdAsync(int id)
        {
            var client = _httpClientFactory.CreateClient();

            return JsonConvert.DeserializeObject<TcTvShow>(
                await client.GetStringAsync(BuildUrl(_config.Url, $"series/{id}", $"?apikey={_config.Key}")));
        }

        public async Task<(bool status, int systemId)> AddTvShowAsync(TcRequest tvShow)
        {
            tvShow.RootFolderPath = _config.SaveLocation;
            var client = _httpClientFactory.CreateClient();

            var response = await client.PostAsync(BuildUrl(_config.Url, "series", $"?apikey={_config.Key}"),
                new StringContent(JsonConvert.SerializeObject(tvShow)));

            return (response.StatusCode.Equals(HttpStatusCode.Created),
                JsonConvert.DeserializeObject<TcTvShow>(await response.Content.ReadAsStringAsync()).SystemId);
        }

        public async Task<IEnumerable<TcCalendar>> GetCalendarAsync()
        {
            var client = _httpClientFactory.CreateClient();

            return JsonConvert.DeserializeObject<IEnumerable<TcCalendar>>(
                await client.GetStringAsync(BuildUrl(_config.Url, "calendar", $"?apikey={_config.Key}",
                    GetCalendarTimeSpan())));
        }

        public async Task<IEnumerable<TcQueueItem>> GetQueue()
        {
            var client = _httpClientFactory.CreateClient();

            return JsonConvert.DeserializeObject<IEnumerable<TcQueueItem>>(
                await client.GetStringAsync(BuildUrl(_config.Url, "queue", $"?apikey={_config.Key}")));
        }
    }
}


text:
export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO';
export const EDIT_TODO = 'EDIT_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';
export const COMPLETE_ALL = 'COMPLETE_ALL';
export const CLEAR_COMPLETED = 'CLEAR_COMPLETED';

// todo types
export const SHOW_ALL = 'show_all'
export const SHOW_COMPLETED = 'show_completed'
export const SHOW_ACTIVE = 'show_active'


text:
namespace Tadpole::GC {

GC::GC() noexcept : gc_(std::make_unique<MarkSweep>()) {}
GC::~GC() noexcept {}

BaseGC& GC::get_instance() noexcept {
  static GC ins;
  return *ins.gc_;
}

}


text:
Это коллекция из 22 популярных паттернов проектирования с примерами кода на языке Go и кратким описанием паттерна.

В кратких описаниях будут употребляться классические термины, такие как Класс, Объект, Абстрактный Класс. Применимо к языку Go, это Тип, Значение этого типа и Интерфейс (где это возможно).

Умение правильно использовать шаблоны проектирования, так сказать, в нужном месте и в нужное время, помогут сохранить ваши нервные клетки.

## Установка

Вы можете скачать этот репозиторий и запустить тесты

```bash
$ go get github.com/alexandergrom/go-patterns
```

## Паттерны

### [Порождающие (Creational)](Creational)

* [Абстрактная фабрика (Abstract Factory)](Creational/AbstractFactory)
* [Строитель (Builder)](Creational/Builder)
* [Фабричный метод (Factory Method)](Creational/FactoryMethod)
* [Прототип (Prototype)](Creational/Prototype)
* [Одиночка (Singleton)](Creational/Singleton)

### [Структурные (Structural)](Structural)

* [Адаптер (Adapter)](Structural/Adapter)
* [Мост (Bridge)](Structural/Bridge)
* [Компоновщик (Composite)](Structural/Composite)
* [Декоратор (Decorator)](Structural/Decorator)
* [Фасад (Facade)](Structural/Facade)
* [Приспособленец (Flyweight)](Structural/Flyweight)
* [Заместитель (Proxy)](Structural/Proxy)

### [Поведенческие (Behavioral)](Behavioral)

* [Цепочка ответственности (Chain Of Responsibility)](Behavioral/ChainOfResponsibility)
* [Команда (Command)](Behavioral/Command)
* [Итератор (Iterator)](Behavioral/Iterator)
* [Посредник (Mediator)](Behavioral/Mediator)
* [Хранитель (Memento)](Behavioral/Memento)
* [Наблюдатель (Observer)](Behavioral/Observer)
* [Состояние (State)](Behavioral/State)
* [Стратегия (Strategy)](Behavioral/Strategy)
* [Шаблонный метод (Template Method)](Behavioral/TemplateMethod)
* [Посетитель (Visitor)](Behavioral/Visitor)

## -~- THE END -~-


text:
package org.esnm.server.data.jpa.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import org.esnm.server.data.jpa.SampleDataRestApplication;
import org.esnm.server.data.jpa.domain.Person;

import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

/**
 * Integration tests for {@link PersonRepository}.
 *
 * @author Oliver Gierke
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleDataRestApplication.class)
public class CityRepositoryIntegrationTests {

	@Autowired
	PersonRepository repository;

	@Test
	public void findsFirstPageOfCities() {

		Page<Person> cities = this.repository.findAll(new PageRequest(0, 10));
		assertThat(cities.getTotalElements(), is(greaterThan(20L)));
	}
}


text:
import $ from 'jquery';
import Cookies from 'js-cookie';

export default class UserCallout {
  constructor(options = {}) {
    this.options = options;

    const className = this.options.className || 'user-callout';

    this.userCalloutBody = $(`.${className}`);
    this.cookieName = this.userCalloutBody.data('uid');
    this.isCalloutDismissed = Cookies.get(this.cookieName);
    this.init();
  }

  init() {
    if (!this.isCalloutDismissed || this.isCalloutDismissed === 'false') {
      this.userCalloutBody.find('.js-close-callout').on('click', e => this.dismissCallout(e));
    }
  }

  dismissCallout(e) {
    const $currentTarget = $(e.currentTarget);
    const cookieOptions = {};

    if (!$currentTarget.hasClass('js-close-session')) {
      cookieOptions.expires = 365;
    }
    if (this.options.setCalloutPerProject) {
      cookieOptions.path = this.userCalloutBody.data('projectPath');
    }

    Cookies.set(this.cookieName, 'true', cookieOptions);

    if ($currentTarget.hasClass('close') || $currentTarget.hasClass('js-close')) {
      this.userCalloutBody.remove();
    }
  }
}


text:
package de.tudarmstadt.informatik.tk.assistance.sdk.sensing.impl.periodic.incomplete;

import android.Manifest.permission;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;

import java.util.Date;
import java.util.Locale;

import de.tudarmstadt.informatik.tk.assistance.sdk.db.DbAccountReaderSensor;
import de.tudarmstadt.informatik.tk.assistance.sdk.model.api.sensing.SensorApiType;
import de.tudarmstadt.informatik.tk.assistance.sdk.sensing.impl.AbstractPeriodicSensor;
import de.tudarmstadt.informatik.tk.assistance.sdk.util.DateUtils;
import de.tudarmstadt.informatik.tk.assistance.sdk.util.logger.Log;

/**
 * @author Unknown
 * @edited by Wladimir Schmidt (wlsc.dev@gmail.com)
 * @date 24.11.2015
 */
public class AccountsReaderSensor extends AbstractPeriodicSensor {

    private static final String TAG = AccountsReaderSensor.class.getSimpleName();

    public static final int INTERVAL_IN_SEC = 3600;
    public static final char SEMICOLON = ';';

    private AccountManager mAccountManager;

    private String currentAccountValue;

    public AccountsReaderSensor(Context context) {
        super(context);

        mAccountManager = AccountManager.get(context);
    }

    @Override
    public void dumpData() {

        if (currentAccountValue == null || currentAccountValue.isEmpty()) {
            return;
        }

        DbAccountReaderSensor accountReaderEvent = new DbAccountReaderSensor();

        accountReaderEvent.setTypes(currentAccountValue);
        accountReaderEvent.setCreated(DateUtils.dateToISO8601String(new Date(), Locale.getDefault()));

        Log.d(TAG, "Insert entry");

        daoProvider.getAccountReaderSensorDao().insert(accountReaderEvent);

        Log.d(TAG, "Finished");
    }

    @Override
    public void updateSensorInterval(Double collectionInterval) {

    }

    @Override
    public int getType() {
        return SensorApiType.ACCOUNT_READER;
    }

    @Override
    public void reset() {

        currentAccountValue = "";
    }

    @Override
    protected void getData() {

        if (mAccountManager == null) {
            return;
        }

        if (ActivityCompat.checkSelfPermission(context,
                permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        Account[] accounts = mAccountManager.getAccounts();

        if (accounts == null) {
            return;
        }

        int accountsLength = accounts.length;

        String[] strAccountTypes = new String[accountsLength];

        for (int i = 0; i < accountsLength; i++) {
            strAccountTypes[i] = accounts[i].type;
        }

        // for (Account acc : accounts) {
        // System.out.println("Account-Type: " + acc.type);
        // try {
        // String pass = mAccountManager.getPassword(acc);
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        // }

        if (accountsLength > 0) {

            StringBuilder sb = new StringBuilder();

            int accountsLengthMinusOne = accountsLength - 1;

            for (int i = 0; i < accountsLengthMinusOne; i++) {
                sb.append(accounts[i].type).append(SEMICOLON);
            }

            sb.append(accounts[accountsLengthMinusOne]);

            currentAccountValue = sb.toString();

            dumpData();
        }
    }

    @Override
    protected int getDataIntervalInSec() {
        return INTERVAL_IN_SEC;
    }

}


text:
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\CS\Fixer\PSR2;

use Symfony\CS\AbstractFixer;
use Symfony\CS\Tokenizer\Tokens;

/**
 * Fixer for rules defined in PSR2 ¶5.2.
 *
 * @author SpacePossum
 */
final class SwitchCaseSemicolonToColonFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function fix(\SplFileInfo $file, $content)
    {
        $tokens = Tokens::fromCode($content);

        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind(array(T_CASE, T_DEFAULT))) {
                continue;
            }

            $ternariesCount = 0;
            for ($colonIndex = $index + 1; ; ++$colonIndex) {
                // We have to skip ternary case for colons.
                if ($tokens[$colonIndex]->equals('?')) {
                    ++$ternariesCount;
                }

                if ($tokens[$colonIndex]->equalsAny(array(':', ';'))) {
                    if (0 === $ternariesCount) {
                        break;
                    }

                    --$ternariesCount;
                }
            }

            if ($tokens[$colonIndex]->equals(';')) {
                $tokens[$colonIndex]->setContent(':');
            }
        }

        return $tokens->generateCode();
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'A case should be followed by a colon and not a semicolon.';
    }
}


text:
/* printk.h - low-level debug output */

/*
 * Copyright (c) 2010-2012, 2014 Wind River Systems, Inc.
 *
 * 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.
 */
#ifndef _PRINTK_H_
#define _PRINTK_H_

#include <toolchain.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 *
 * @brief Print kernel debugging message.
 *
 * This routine prints a kernel debugging message to the system console.
 * Output is send immediately, without any mutual exclusion or buffering.
 *
 * A basic set of conversion specifier characters are supported:
 *   - signed decimal: \%d, \%i
 *   - unsigned decimal: \%u
 *   - unsigned hexadecimal: \%x (\%X is treated as \%x)
 *   - pointer: \%p
 *   - string: \%s
 *   - character: \%c
 *   - percent: \%\%
 *
 * No other conversion specification capabilities are supported, such as flags,
 * field width, precision, or length attributes.
 *
 * @param fmt Format string.
 * @param ... Optional list of format arguments.
 *
 * @return N/A
 */
#ifdef CONFIG_PRINTK
extern void printk(const char *fmt, ...);
#else
static inline void printk(const char *fmt, ...)
{
	ARG_UNUSED(fmt);
}
#endif

#ifdef __cplusplus
}
#endif

#endif


text:
namespace blink {
class WebInputEvent;
class WebMouseEvent;
class WebMouseWheelEvent;
class WebKeyboardEvent;
struct WebDeviceEmulationParams;
struct WebFloatPoint;
struct WebPoint;
struct WebSize;
}

namespace content {
struct NativeWebKeyboardEvent;
}

namespace mate {

int GetWebInputEventType(v8::Isolate* isolate, v8::Local<v8::Value> val);

template<>
struct Converter<blink::WebInputEvent> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     blink::WebInputEvent* out);
};

template<>
struct Converter<blink::WebKeyboardEvent> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     blink::WebKeyboardEvent* out);
};

template<>
struct Converter<content::NativeWebKeyboardEvent> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     content::NativeWebKeyboardEvent* out);
};

template<>
struct Converter<blink::WebMouseEvent> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     blink::WebMouseEvent* out);
};

template<>
struct Converter<blink::WebMouseWheelEvent> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     blink::WebMouseWheelEvent* out);
};

template<>
struct Converter<blink::WebFloatPoint> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     blink::WebFloatPoint* out);
};

template<>
struct Converter<blink::WebPoint> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     blink::WebPoint* out);
};

template<>
struct Converter<blink::WebSize> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     blink::WebSize* out);
};

template<>
struct Converter<blink::WebDeviceEmulationParams> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     blink::WebDeviceEmulationParams* out);
};

}  // namespace mate

#endif  // ATOM_COMMON_NATIVE_MATE_CONVERTERS_BLINK_CONVERTER_H_


text:
function Properties(listbox, metadata, element_info, on_property_change) {
  var this_ = this;
  this.listbox_ = listbox;
  listbox.removeAllElements();
  this.metadata_ = metadata;
  this.element_info_ = element_info;
  this.element_ = element_info.element;
  this.on_property_change_ = on_property_change;
  this.get_value_funcs_ = [ ];
  this.set_value_funcs_ = [ ];
  this.setting_value_ = [ ];
  this.name_to_index_ = { };
  var i = 0;
  for (var name in metadata) {
    var item = listbox.appendElement("<item>" +
      "
" +
      "</item>");
    item.children.item(1).tooltip = name;
    item.children.item(1).innerText = name;
    this.name_to_index_[name] = i;
    CreateEditControl(i, item, name);
    i++;
  }
  this.SyncFromElement();

  function CreateEditControl(index, item, name) {
    var default_value = metadata[name].default_value;
    var metainfo = metadata[name].extra_info;
    // The edit control of the property item, may be a combobox or an edit.
    var edit_control;

    if (metainfo instanceof Array) {
      // Enumerated values.
      edit_control = AddCombobox(metainfo);
      this_.get_value_funcs_[index] = function() {
        return metainfo[edit_control.selectedIndex];
      };
      this_.set_value_funcs_[index] = function(value) {
        var value = GetElementProperty(this_.element_info_, name);
        for (var i in metainfo) {
          if (value == metainfo[i]) {
            edit_control.selectedIndex = i;
            return;
          }
        }
        edit_control.selectedIndex = -1;
      };
    } else if (typeof default_value == "boolean") {
      edit_control = AddCombobox([ false, true ]);
      this_.get_value_funcs_[index] = function() {
        return edit_control.selectedIndex == 1;
      };
      this_.set_value_funcs_[index] = function(value) {
        edit_control.selectedIndex = value ? 1 : 0;
      };
    } else {
      // Normal property editor.
      edit_control = item.appendElement(
        "<edit width='60%' x='40%' height='100%' size='9'/>");
      edit_control.onkeypress = function() {
        if (event.keyCode == 10 || event.keyCode == 13)
          SyncOut();
      };
      edit_control.onfocusout = function() {
        SyncOut();
      };
      this_.get_value_funcs_[index] = function() {
        return edit_control.value;
      };
      this_.set_value_funcs_[index] = function(value) {
        edit_control.value = value;
      };

      if (typeof metainfo == "function") {
        var button = item.appendElement(
          "<button x='100%' pinX='14' width='14' height='17' " +
          "defaultRendering='true' caption='...' size='7' align='center'/>");
        button.onclick = function() {
          edit_control.value = metainfo(edit_control.value);
          SyncOut();
        };
      }
    }

    edit_control.onfocusin = function() {
      this_.listbox_.selectedIndex = index;
    };

    function AddCombobox(values) {
      var combobox = item.appendElement(
          "<combobox width='60%' x='40%' height='144' type='droplist'" +
          " itemWidth='100%' itemHeight='16' background='#FFFFFF'/>");
      for (var i in values) {
        combobox.appendElement("<item>" + values[i] +
                               "</item>");
      }
      combobox.onchange = function() {
        if (!this_.setting_value_[index])
          SyncOut();
      };
      combobox.onsize = function() {
        this_.UpdateComboboxBorder(combobox);
      };
      return combobox;
    }

    function SyncOut() {
      var value = this_.get_value_funcs_[index]();
      var old_value = GetElementProperty(this_.element_info_, name);
      if (value != old_value) {
        SetElementProperty(this_.element_info_, name, value);
        if (this_.on_property_change_) {
          // Delay the callback after the layout.
          view.setTimeout(this_.on_property_change_, 0);
        }
      }
    }
  }
}

Properties.prototype = {
  SyncFromElement: function() {
    var i = 0;
    for (var name in this.metadata_) {
      var value = GetElementProperty(this.element_info_, name);
      this.setting_value_[i] = true;
      this.set_value_funcs_[i](value);
      this.setting_value_[i] = false;
      i++;
    }
  },

  SyncPropertyFromElement: function(name) {
    var value = GetElementProperty(this.element_info_, name);
    var index = this.name_to_index_[name];
    if (index !== undefined) {
      this.setting_value_[index] = true;
      this.set_value_funcs_[index](value);
      this.setting_value_[index] = false;
    }
  },

  OnSelectionChange: function() {
    var item = this.listbox_.selectedItem;
    if (item) {
      var edit_control = item.children.item(2);
      edit_control.focus();
    }
  },

  SelectProperty: function(name) {
    var index = this.name_to_index_[name];
    if (index !== undefined) {
      if (this.listbox_.selectedIndex != index) {
        this.listbox_.selectedIndex = index;
      } else {
        this.OnSelectionChange();
      }
    }
  },

  UpdateComboboxBorder: function(combobox) {
    if (combobox.offsetHeight > 20) {
      var pos = designerUtils.elementCoordToAncestor(combobox, e_tool_views,
                                                     0, 0);
      e_combobox_border.x = pos.x - 1;
      e_combobox_border.y = pos.y + 18;
      e_combobox_border.width = combobox.offsetWidth + 2;
      e_combobox_border.height = combobox.offsetHeight - 17;
      e_combobox_border.visible = true;
    } else {
      e_combobox_border.visible = false;
    }
  }

};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class GlobalExpressionConfigStore
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class GlobalExpressionConfigStore
   ">
    <meta name="generator" content="docfx 2.56.6.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class GlobalExpressionConfigStore

A singleton object which holds the global configuration for C# expression evaluation.

Inheritance

System.Object

GlobalExpressionConfigStore

Implements

IConfiguresCSharpExpressionGlobals

Inherited Members

      System.Object.Equals(System.Object)

      System.Object.Equals(System.Object, System.Object)

      System.Object.GetHashCode()

      System.Object.GetType()

      System.Object.MemberwiseClone()

      System.Object.ReferenceEquals(System.Object, System.Object)

      System.Object.ToString()

Namespace: ZptSharp.Expressions.CSharpExpressions

Assembly: ZptSharp.CSharpExpressions.dll

Syntax

public class GlobalExpressionConfigStore : IConfiguresCSharpExpressionGlobals

Properties

    |
    Improve this Doc

    View Source

GlobalAssemblyReferences

Gets a collection of globally-available assembly references which are
added to all C# expressions and which do not need an 'assemblyref' expression
in-scope.

Declaration

public ICollection<AssemblyReference> GlobalAssemblyReferences { get; }

Property Value

        Type
        Description

        System.Collections.Generic.ICollection<AssemblyReference>

The global assembly references.

    |
    Improve this Doc

    View Source

GlobalUsingNamespaces

Gets a collection of globally-available using namespaces which are
added to all C# expressions and which do not need an 'using' expression
in-scope.

Declaration

public ICollection<UsingNamespace> GlobalUsingNamespaces { get; }

Property Value

        Type
        Description

        System.Collections.Generic.ICollection<UsingNamespace>

The global using namespaces.

Implements

      IConfiguresCSharpExpressionGlobals

                    Improve this Doc

                    View Source

In This Article

              Back to top

            Generated by DocFX


text:
@interface PAQRCodeViewController : UIViewController

- (id)initWithCompletion:(void(^)(BOOL succeeded, NSString * result))completion;

- (void)start;
- (void)stop;
- (void)cancel;

- (UIImage *)generateQRCode:(NSString *)code width:(CGFloat)width height:(CGFloat)height;

@end


text:
from lldbsuite.test import decorators
from lldbsuite.test import lldbinline

lldbinline.MakeInlineTest(
    __file__, globals(), [
        decorators.skipIfFreeBSD, decorators.skipIfLinux,
        decorators.skipIfWindows, decorators.skipIfNetBSD])


text:
.colorsdemoBasicUsage .card-media {
  margin-right: 16px;
  border-radius: 50%;
  overflow: hidden; }

.colorsdemoBasicUsage .md-subhead.description {
  color: rgba(255, 255, 255, 0.7); }

.colorsdemoBasicUsage .card-media md-icon {
  width: 40px;
  height: 40px;
  color: rgba(255, 255, 255, 0.87); }

.colorsdemoBasicUsage h4.card-title {
  margin: 24px 8px 0; }

.colorsdemoBasicUsage code.css {
  background-color: #fffcc2; }

.colorsdemoBasicUsage p.footnote code {
  font-size: 0.85em; }

.colorsdemoBasicUsage p.footnote {
  font-size: 0.85em;
  margin: 30px 8px;
  padding: 16px;
  background-color: rgba(205, 205, 205, 0.45); }


text:
<!DOCTYPE html>

	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Simplex Method Demo</title>

			Type your linear programming problem below. (Press "Examples" to cycle through some problems already set up.) Then press "Solve".

			<textarea rows="15" cols="15" id="inputarea" style="width:95%"></textarea>

				Solution:

				An optimal solution (or message) will appear here.

				<input type="button" value="Solve"
				onClick="clearOutput();
					adjustAccuracy();setMode();setShowTabl();
					var Q = new lpProblem( document.getElementById('inputarea').value );
					lp_verboseLevel=lp_demo_verboseLevel;
					Q.mode=lp_demo_mode;
					Q.sigDigits=lp_demo_accuracy;
					try{Q.solve()}
					finally{showOutput( lp_trace_string );showSolution( Q.solutionToString() );}
				">

				<input type="button" value="Examples" onClick="showExamples();">

				<input type="button" value="Erase everything" onClick="clearAll();">

					<input type="radio" name="displaytabl" id="noTabl"> Hide tableaus.

					<input type="radio" checked="true" name="displaytabl" id="yesTabl"> Show tableaus (slower).

					<input type="radio" name="displaytabl" id="andSolns"> Show tableaus and intermediate solutions.

				Tableau mode:

					<input type="radio" checked="true" name="modepicker" id="3" value="decimal"> decimal

					<input type="radio" name="modepicker" id="2" value="fraction"> fraction

					<input type="radio" name="modepicker" id="1" value="integer"> integer

				Rounding: <input type="text" id="accuracyDig" size="1" value="6"> significant digits

				The tableaus will appear here if desired.


text:
package org.jogl.ceylon;

import com.redhat.ceylon.compiler.java.metadata.Import;
import com.redhat.ceylon.compiler.java.metadata.Module;

/**
 * @author Ales Justin
 */
@Module(
    name = "org.jogl.ceylon", version = "1.0.0",
    dependencies = {@Import(name = "org.jogamp.jogl:jogl-all", version = "2.1.2")})
public class $module_ {
    public static void run() throws Throwable {
        run_.main(new String[0]);
    }
}


text:
MongoDB::getDBRef() returns null if reference parameter is invalid
--SKIPIF--
<?php require_once dirname(__FILE__) . "/skipif.inc";?>
--FILE--
<?php
require_once dirname(__FILE__) . "/../utils.inc";
$mongo = mongo();
$db = $mongo->selectDB('test');

var_dump($db->getDBRef(array()));
var_dump($db->getDBRef(array('$ref' => 'dbref')));
var_dump($db->getDBRef(array('$id' => 123)));
?>
--EXPECT--
NULL
NULL
NULL


text:
import * as React from "react"
import {StoreContainer} from "./StoreContainer"
import {ArgumentPositions, checkValidDependency, metadataKey, throwError} from "./utils"

function propertyDecorator(target: any, propertyName: string) {
    if (!(target instanceof React.Component)) {
        throwError("Injection store can implement only in React.Component", target)
    }
    const targetConstructor = target.constructor
    const storeConstructor = Reflect.getMetadata("design:type", target, propertyName)

    checkValidDependency(target, storeConstructor)

    if (targetConstructor.contextTypes == null) {
        targetConstructor.contextTypes = {}
    }

    if (targetConstructor.contextTypes.storeContainer == null) {
        targetConstructor.contextTypes.storeContainer = React.PropTypes.instanceOf(StoreContainer).isRequired
    }

    Object.defineProperty(target, propertyName, {
        get() {
            return this.context.storeContainer.get(storeConstructor)
        },
    })
}

function parameterDecorator(target: any, parameterIndex: number) {
    const injectParameters: ArgumentPositions = Reflect.getMetadata(metadataKey, target) || []
    const parametersTypes = Reflect.getMetadata("design:paramtypes", target)
    checkValidDependency(target, parametersTypes[parameterIndex])
    injectParameters.push(parameterIndex)
    Reflect.defineMetadata(metadataKey, injectParameters, target)
}

export function inject(target: any, propertyName: string, propertyIndex?: number): any {
    if (propertyName && propertyIndex === void 0) {
        return propertyDecorator(target, propertyName)
    } else if (!propertyName && propertyIndex !== void 0) {
        return parameterDecorator(target, propertyIndex)
    }
    throwError("Decorator is to be applied to property in React.Component, or to a store constructor argument", target)
}


text:
/**
 * Created by Nightpaws on 26/02/2016.
 */
var express = require('express'),
    responseFactory = require('./../response/response');

var account = function () {
    var accountRouter = express.Router();

    accountRouter.route('/account')
        .post(function (req, res) {

        });

    return accountRouter;
};

module.exports = account;


text:
title: Subclusters in oVirt 4.0 - Label-Based VM to Host Affinity
author: msivak
tags: community, documentation, infrastructure
date: 2016-07-25 15:00:00 CEST
comments: true
published: true
---

Before I start discussing the feature itself I have to explain a bit about the use cases that we were trying to solve.

* Let us imagine you have a special piece of software with a node-licensing model that only cares about physical machines when counting the number of licenses needed. This specifically allows you to run that software in virtual machines, but you need to control the physical host on which the VMs are running.

* The other case is basically related to hardware capabilities. Some NICs might be faster than others and you want to place all high traffic VMs on hosts that have them. Or a special custom device is needed and VMs that need it won't run on a host that does not have it.

READMORE

Both cases follow the same basic scenario: There is a small subset of VMs that need a special capability (license, device), but there are not enough of them to fully utilize a separate cluster. To achieve efficient utilization of your cluster, you need to add many common VMs with no special needs and some hosts to handle the full load. But… how do you keep the special VMs from migrating to the hosts without the special capabilities?

We already had [VM to host pinning](/documentation/admin-guide/administration-guide/#affinity-groups) that allowed limiting VM placement to [single or multiple hosts](/develop/release-management/features/vmpinningtomultiplehosts/), but with no migration enabled for that VM. Our team also just implemented a new feature that allows you to define pinning and still keep migration enabled. Affinity labels allow you to take a subset of hosts and attach a label to them. Any VM with the same affinity label will be then constrained to the labeled hosts. Standard VMs with no labels won't notice anything and will still happily run anywhere according to the normal oVirt scheduling rules.

Now the bad news, there is no edit enabled user interface for now and all changes need to be done using the oVirt engine REST API. We have a development version of read only view for host and VM to affinity label assignments for getting a quick overview of the configuration and we plan to have full fledged UI in the future.

The rest of this post will show you how to implement an example setup with three groups of hosts: webserver, storage and applications:

![Example affinity groups layout](/images/affinity-label-example-diagram.png)

I will be using my local server `localhost:8080`, `curl`, `jq`, and a specially crafted shell alias to avoid repeating the login and content type parameters in every example call. Tweak the admin@internal user and letmein password to match the user you will be using. Please note that if you are not using the admin account then you need to make sure the user has the *TagManager* permissions.

```
alias cengine='curl -s -u admin@internal:letmein -H "Content-Type: application/json" -H "Accept: application/json"'
```

## Creating and Updating a Label

Creating a new affinity label is a straightforward operation, just send a POST request to the right endpoint while saving the ID to a variable:

```
$ STORAGELABEL=$(cengine -f -X POST -d '{"name": "test"}' http://localhost:8080/ovirt-engine/api/affinitylabels | jq -r '.id'); echo $STORAGELABEL

cc8bcf08-bc78-40e9-a01a-38a0fe99ea26
```

Operations for listing all labels and updating a label's name are also supported, of course:

```
cengine -f http://localhost:8080/ovirt-engine/api/affinitylabels | jq -r '.affinity_label[] | {id, name}'

{
  "id": "cc8bcf08-bc78-40e9-a01a-38a0fe99ea26",
  "name": "test"
}

cengine -X PUT -d '{"name": "storage_subcluster"}' http://localhost:8080/ovirt-engine/api/affinitylabels/$STORAGELABEL | jq -r '{id, name}'

{
  "id": "cc8bcf08-bc78-40e9-a01a-38a0fe99ea26",
  "name": "storage_subcluster"
}
```

## Attaching Hosts and VMs to a Label

Affinity labels reference all labeled objects using their id, although the API accepts the full object representation. It will ignore all fields except id, though. There are two ways to manipulate affinity label assignments to hosts and VMs:

- Posting the host or VM to the proper affinity label subcollection
- Posting the affinity label to the host's or VM's affinitylabels subcollection

We need some VMs and Hosts for the following examples so create hosts red, green, and blue as well as some VMs: webserver, storage, application1, and application2.

I will now show you how to express the following rules using the affinity labels:

- Webserver VM should be allowed to run anywhere
- Storage VM should be restricted to host red (special HBA card maybe?)
- Application VMs should be restricted to hosts red and blue (as you have license for two physical nodes, for example)

We will first attach the storage VM and the red host to the already created storage_subcluster affinity label:

```
$ cengine -f -X POST -d "{\"id\": \"$REDHOSTID\"}" http://localhost:8080/ovirt-engine/api/affinitylabels/$STORAGELABEL/hosts | jq -r '.status'

complete

$ cengine -f -X POST -d "{\"id\": \"$STORAGEVMID\"}" http://localhost:8080/ovirt-engine/api/affinitylabels/$STORAGELABEL/vms | jq -r '.status'

complete
```

Now we can create the application affinity group and attach the necessary hosts and VMs:

```
$ APPLABEL=$(cengine -f -X POST -d '{"name": "app_subcluster"}' http://localhost:8080/ovirt-engine/api/affinitylabels | jq -r '.id'); echo $APPLABEL

d7d91849-262d-4274-bb47-3ad711566fc7

$ for host in $REDHOSTID $BLUEHOSTID; do cengine -f -X POST -d "{\"id\": \"$APPLABEL\"}" http://localhost:8080/ovirt-engine/api/hosts/$host/affinitylabels | jq -r '.status'; done

completed
completed

$ for vm in $APP1VMID $APP2VMID; do cengine -f -X POST -d "{\"id\": \"$APPLABEL\"}" http://localhost:8080/ovirt-engine/api/vms/$vm/affinitylabels | jq -r '.status'; done

completed
completed
```

## Deleting Labels or Assignments

That concludes the setup. You can use a standard REST DELETE call in case you need to remove a label to host assignment (just replace hosts with VMs to make it work for label to VM assignments):

```
cengine -f -X DELETE http://localhost:8080/ovirt-engine/api/hosts/$hostid/affinitylabels/$labelid | jq -r '.status'
```

or

```
cengine -f -X DELETE http://localhost:8080/ovirt-engine/api/affinitylabels/$labelid/hosts/$hostid | jq -r '.status'
```

## The Result

The situation now is as described at the beginning, and will be obeyed during VM startups and VM migrations.

```
$ cengine -f http://localhost:8080/ovirt-engine/api/affinitylabels | jq -r '.affinity_label[] | {id, name, vms, hosts}'

{
  "id": "cc8bcf08-bc78-40e9-a01a-38a0fe99ea26",
  "name": "storage_subcluster",
  "vms": {
    "vm": [
      {"id": "bd6e32cd-1df5-4c5c-a44e-371371e44168"}
    ]
  },
  "hosts": {
    "host": [
      {"id": "4d711089-a3e3-45b7-935a-dc66c4c4ccef"}
    ]
  }
}
{
  "id": "d7d91849-262d-4274-bb47-3ad711566fc7",
  "name": "app_subcluster",
  "vms": {
    "vm": [
      {"id": "a98d58ee-73e4-40be-95f8-bf360e646473"},
      {"id": "7506d8f9-7b40-4ee2-85be-6a7b02024729"}
    ]
  },
  "hosts": {
    "host": [
      {"id": "e2715dfc-5e21-45c1-9e9e-c2d316dc51dd"},
      {"id": "4d711089-a3e3-45b7-935a-dc66c4c4ccef"}
    ]
  }
}
```

I hope this new feature will be useful for you, and should you have any questions, do not hesitate to ask on [users@ovirt.org](mailto:users@ovirt.org).


text:
#include "barrier.h"

int main(int argc, char *argv[])
{
	return barrier_main(argc, argv);
}


text:
id: writing-tests
title: "Writing Tests"
---

Playwright assertions are created specifically for the dynamic web. Checks are automatically retried until the necessary conditions are met. Playwright comes with [auto-wait](./actionability.md) built in meaning it waits for elements to be actionable prior to performing actions. Playwright provides [assertThat](./test-assertions.md) overloads to write assertions.

Take a look at the example test below to see how to write a test using web first assertions, locators and selectors.

```java
package org.example;

import java.util.regex.Pattern;
import com.microsoft.playwright.*;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

public class App {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch();
            Page page = browser.newPage();
            page.navigate("http://playwright.dev");

            // Expect a title "to contain" a substring.
            assertThat(page).hasTitle(Pattern.compile("Playwright"));

            // create a locator
            Locator getStarted = page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Get Started"))

            // Expect an attribute "to be strictly equal" to the value.
            assertThat(getStarted).hasAttribute("href", "/docs/intro");

            // Click the get started link.
            getStarted.click();

            // Expects the URL to contain intro.
            assertThat(page).hasURL(Pattern.compile(".*intro"));
        }
    }
}
```

### Assertions

Playwright provides [`assertThat`](./test-assertions.md) overloads which will wait until the expected condition is met.

```java
import java.util.regex.Pattern;
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

assertThat(page).hasTitle(Pattern.compile("Playwright"));
```

### Locators

[Locators](./locators.md) are the central piece of Playwright's auto-waiting and retry-ability. Locators represent a way to find element(s) on the page at any moment and are used to perform actions on elements such as `.click` `.fill` etc. Custom locators can be created with the [`method: Page.locator`] method.

```java
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

Locator getStarted = page.locator("text=Get Started");

assertThat(getStarted).hasAttribute("href", "/docs/intro");
getStarted.click();
```

[Selectors](./selectors.md) are strings that are used to create Locators. Playwright supports many different selectors like [Text](./selectors.md#text-selector), [CSS](./selectors.md#css-selector), [XPath](./selectors.md#xpath-selectors) and many more. Learn more about available selectors and how to pick one in this [in-depth guide](./selectors.md).

```java
import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

assertThat(page.locator("text=Installation")).isVisible();
```

### Test Isolation

Playwright has the concept of a [BrowserContext] which is an in-memory isolated browser profile. It's recommended to create a new [BrowserContext] for each test to ensure they don't interfere with each other.

```java
Browser browser = playwright.chromium().launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();
```

## What's Next

- [Run single test, multiple tests, headed mode](./running-tests.md)
- [Generate tests with Codegen](./codegen.md)
- [See a trace of your tests](./trace-viewer-intro.md)


text:
package net.vz.mongodb.jackson.internal.stream;

import java.io.IOException;
import java.io.InputStream;

import net.vz.mongodb.jackson.JacksonDBCollection;
import net.vz.mongodb.jackson.internal.JacksonDBCollectionProvider;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import de.undercouch.bson4jackson.BsonParser;
import de.undercouch.bson4jackson.types.ObjectId;

/**
 * Parser that wraps BSONParser to convert bson4jackson ObjectIds to org.bson ObjectIds, and stores error codes
 *
 * @author James Roper
 * @since 1.1.2
 */
public class DBDecoderBsonParser extends BsonParser implements JacksonDBCollectionProvider{

    private final JacksonDBObject<?> dbObject;
    private final JacksonDBCollection dbCollection;

    public DBDecoderBsonParser(int jsonFeatures, InputStream in, JacksonDBObject<?> dbObject, JacksonDBCollection dbCollection) {
        // Honor document length must be true
        super(jsonFeatures, Feature.HONOR_DOCUMENT_LENGTH.getMask(), in);
        this.dbObject = dbObject;
        this.dbCollection = dbCollection;
    }

    @Override
    public Object getEmbeddedObject() throws IOException, JsonParseException {
        Object object = super.getEmbeddedObject();
        if (object instanceof ObjectId) {
            return ObjectIdConvertor.convert((ObjectId) object);
        } else {
            return object;
        }
    }

    public boolean handleUnknownProperty(DeserializationContext ctxt, JsonDeserializer<?> deserializer,
                                         Object beanOrClass, String propertyName) throws IOException {
        if (propertyName.startsWith("$") || propertyName.equals("code")) {
            // It's a special server response
            JsonToken token = getCurrentToken();
            if (token == JsonToken.FIELD_NAME) {
                 token = nextToken();
            }
            if (token == JsonToken.START_ARRAY || token == JsonToken.START_OBJECT) {
                // The server shouldn't be returning arrays or objects as the response, skip all children
                skipChildren();
            }
            // Store the value, whatever type it happens to be
            dbObject.put(propertyName, getEmbeddedObject());
            return true;
        }
        return false;
    }

    public JacksonDBCollection getDBCollection() {
        return dbCollection;
    }
}


text:
package com.github.sdd330;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * Utility class for file related operations
 */
public class FileUtil {
    /**
     * Get the first part of a file path, which is the root directory
     * or the file name if the path contains no directory
     *
     * @param path
     * @return The first part of a file path
     */
    public static String getFirstPart(File path) {
        String first = "";
        File tmp = path;
        while (tmp != null) {
            first = tmp.getName();
            tmp = tmp.getParentFile();
        }
        return first;
    }

    /**
     * Get everything but the first part of a file path
     *
     * @param path
     * @return Everything but the first part of the file path
     */
    public static File getTail(File path) {
        if (path.getParentFile() == null) {
            return null;
        } else {
            String first = getFirstPart(path);
            return new File(path.getPath().substring(first.length() + 1));
        }
    }

    /**
     * Calculates the relative path of one path relative to another
     *
     * @param path The target path
     * @param relativeTo The path that the target path should be
     *            relative to
     * @return A path that is pointing to the target path but is
     *         relative to the relativeTo path
     */
    public static File relativePath(File path, File relativeTo) {
        File tmpPath = path;
        File tmpRelativeTo = relativeTo;

        if (tmpRelativeTo != null) {
            String t1 = getFirstPart(tmpPath);
            String t2 = getFirstPart(tmpRelativeTo);
            while (t2.equals(t1)) {
                tmpPath = getTail(tmpPath);
                tmpRelativeTo = getTail(tmpRelativeTo);
                t1 = getFirstPart(tmpPath);
                t2 = getFirstPart(tmpRelativeTo);
            }
        }
        while (tmpRelativeTo != null) {
            tmpPath = new File("..", tmpPath.getPath());
            tmpRelativeTo = tmpRelativeTo.getParentFile();
        }

        return tmpPath;
    }

    private static File remove(File path, int n) throws IOException {
        if (path == null) {
            throw new IOException();
        } else if (n == 0) {
            return path;
        } else if (!"..".equals(path.getName())) {
            return remove(path.getParentFile(), n - 1);
        } else {
            return remove(path.getParentFile(), n + 1);
        }
    }

    /**
     * Make a file path canonical by removing and resolving all ".."
     * directory references
     *
     * @param path
     * @return A canonical path
     * @throws IOException
     */
    public static File canonical(File path) throws IOException {
        if ("..".equals(path.getName())) {
            return canonical(remove(path.getParentFile(), 1));
        } else if (path.getParentFile() != null) {
            return new File(canonical(path.getParentFile()), path.getName());
        } else {
            return path;
        }
    }

    /**
     * Copy a file
     *
     * @param in Input file
     * @param out Output file
     * @param overwrite If false, only overwrite if in is newer than
     *            out
     * @throws IOException
     */
    public static void copy(File in, File out, boolean overwrite) throws IOException {
        if (overwrite || !out.exists() || (out.lastModified() < in.lastModified())) {
            FileChannel inChannel = new FileInputStream(in).getChannel();
            FileChannel outChannel = new FileOutputStream(out).getChannel();
            try {
                inChannel.transferTo(0, inChannel.size(), outChannel);
            } finally {
                if (inChannel != null) {
                    inChannel.close();
                }
                if (outChannel != null) {
                    outChannel.close();
                }
            }
        }
    }

    /**
     * Touch a file, setting its last modified timestamp to current
     * time
     *
     * @param file
     * @throws IOException
     */
    public static void touch(File file) throws IOException {
        if (file.exists()) {
            if (!file.setLastModified(System.currentTimeMillis())) {
                throw new IOException("Could not touch file " + file.getAbsolutePath());
            }
        } else {
            try {
                File directory = file.getParentFile();
                if (!directory.exists()) {
                    directory.mkdirs();
                }
                file.createNewFile();
            } catch (IOException e) {
                throw new IOException("Could not create file " + file.getAbsolutePath(), e);
            }
        }
    }
}


text:
define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var HighlightRules = require("./json_highlight_rules").JsonHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;

var Mode = function() {
    this.$tokenizer = new Tokenizer(new HighlightRules().getRules());
    this.$outdent = new MatchingBraceOutdent();
    this.$behaviour = new CstyleBehaviour();
    this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);

(function() {

    this.getNextLineIndent = function(state, line, tab) {
        var indent = this.$getIndent(line);

        if (state == "start") {
            var match = line.match(/^.*[\{\(\[]\s*$/);
            if (match) {
                indent += tab;
            }
        }

        return indent;
    };

    this.checkOutdent = function(state, line, input) {
        return this.$outdent.checkOutdent(line, input);
    };

    this.autoOutdent = function(state, doc, row) {
        this.$outdent.autoOutdent(doc, row);
    };

}).call(Mode.prototype);

exports.Mode = Mode;
});