text:
package com.google.template.soy.tofu.internal;

import com.google.inject.Inject;
import com.google.template.soy.data.SoyData;
import com.google.template.soy.data.SoyMapData;
import com.google.template.soy.msgs.SoyMsgBundle;
import com.google.template.soy.shared.SoyCssRenamingMap;
import com.google.template.soy.soytree.TemplateRegistry;
import com.google.template.soy.tofu.restricted.SoyTofuPrintDirective;

import java.util.Deque;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nullable;
import javax.inject.Singleton;

/**
 * Implementation of RenderVisitorFactory for Tofu backend.
 *
 * @author Mark Knichel
 * @author Kai Huang
 */
@Singleton
class TofuRenderVisitorFactory {

  /** Map of all SoyTofuPrintDirectives (name to directive). */
  private final Map<String, SoyTofuPrintDirective> soyTofuDirectivesMap;

  /** Factory for creating an instance of TofuEvalVisitor. */
  private final TofuEvalVisitorFactory tofuEvalVisitorFactory;

  @Inject
  public TofuRenderVisitorFactory(
      Map<String, SoyTofuPrintDirective> soyTofuDirectivesMap,
      TofuEvalVisitorFactory tofuEvalVisitorFactory) {
    this.soyTofuDirectivesMap = soyTofuDirectivesMap;
    this.tofuEvalVisitorFactory = tofuEvalVisitorFactory;
  }

  /**
   * Creates a TofuRenderVisitor.
   *
   * @param outputBuf The Appendable to append the output to.
   * @param templateRegistry A registry of all templates.
   * @param data The current template data.
   * @param ijData The current injected data.
   * @param env The current environment, or null if this is the initial call.
   * @param activeDelPackageNames The set of active delegate package names. Allowed to be null
   *     when known to be irrelevant, i.e. when not using delegates feature.
   * @param msgBundle The bundle of translated messages, or null to use the messages from the
   *     Soy source.
   * @param cssRenamingMap The CSS renaming map, or null if not applicable.
   * @return The newly created TofuRenderVisitor instance.
   */
  public TofuRenderVisitor create(
      Appendable outputBuf, TemplateRegistry templateRegistry, SoyMapData data,
      @Nullable SoyMapData ijData, @Nullable Deque<Map<String, SoyData>> env,
      @Nullable Set<String> activeDelPackageNames, @Nullable SoyMsgBundle msgBundle,
      @Nullable SoyCssRenamingMap cssRenamingMap) {

    return new TofuRenderVisitor(
        soyTofuDirectivesMap, tofuEvalVisitorFactory, outputBuf, templateRegistry, data, ijData,
        env, activeDelPackageNames, msgBundle, cssRenamingMap);
  }

}


text:
class QueueListener
  include Ak::Client
  class Error < StandardError; end

  def perform(sqs_message, params)
    case params[:type]
      when 'update_pages', 'page:update'
        PageUpdater.run(params)

      when 'create', 'page:new'
        PageCreator.run(params[:params])

      when 'action', 'action:new'
        ActionCreator.run(action_params(params))

      when 'donation', 'donation:new'
        DonationCreator.run(params)

      when 'subscription-payment', 'subscription-payment:new'
        upsert_payment(params)

      when 'subscription-payment-failure'
        GocardlessSubscriptionTransactionUpdator.run(params[:params])

      when 'subscribe_member', 'member-subscription:new'
        subscribe_member(params)

      when 'create_campaign', 'campaign:new'
        CampaignCreator.run(params)

      when 'update_campaign', 'campaign:update'
        CampaignUpdater.run(params)

      when 'update_member', 'member:update'
        update_member(params)

      when 'cancel_subscription', 'subscription:cancel'
        cancel_subscription(params[:params])

      when 'new_survey_response', 'survey-response:new'
        SurveyResponseProcessor.run(params)

      when 'recurring_payment_update', 'recurring-payment:update'
        update_recurring_payment(params)

      when 'new_call', 'call:new'
        ActionCreator.run(params)

      when 'update_call', 'call:update'
        ActionUpdater.run(params)

      when 'payment-status-update'
        PaymentStatusUpdator.run(params)

      else
        raise ArgumentError, "Unsupported message type: #{params[:type]}"
    end
  end

  private

  def cancel_subscription(params)
    res = client.cancel_subscription(params)
    unless res.success?
      raise Error.new("Marking recurring donation cancelled failed. HTTP Response code: #{res.code}, body: #{res.body}")
    end
  end

  def upsert_payment(params)
    res = client.create_recurring_payment(params[:params])
    SubscriptionUpdator.run(params);
    unless res.success?
      raise Error.new("Managing recurring subscription payment failed with:\n #{res.inspect}")
    end
    res
  end

  def subscribe_member(params)
    language = params[:params][:locale].try(:upcase)
    page_name = ENV["AK_SUBSCRIPTION_PAGE_#{language}"] || ENV['AK_SUBSCRIPTION_PAGE_EN']
    unset_message = "Your ActionKit page for subscriptions from the home page has not been set for locales '#{language}' or 'EN'"
    raise Error.new(unset_message) if page_name.blank?
    res = client.create_action(action_params(params)[:params].merge({ page: page_name }))
    raise Error.new("Member subscription failed with #{res.parsed_response['errors']}!") unless res.success?
    res
  end

  def update_member(params)
    res = client.update_user(params[:params]["akid"], params[:params])
    unless res.success?
      raise Error.new("Member update failed with #{res.parsed_response["errors"]}!")
    end
  end

  def update_recurring_payment(params)
    res = client.update_recurring_payment(params[:params])
    unless res.success?
      raise Error.new("Updating recurring payment failed with #{res.parsed_response['errors']}")
    end
  end

  def action_params(params)
    country = params[:params][:country]
    raise Error.new("Generic action processing attempted without a country in the request.") unless country.present?
    if country == "United States" && ENV['BYPASS_ZIP_VALIDATION']
      raise Error.new("Your default US zip code has not been set!") unless ENV['DEFAULT_US_ZIP'].present?
      params[:params][:postal] = ZipFormatter.format(params[:params][:postal])
    end
    params
  end
end

redpajama_set_name: RedPajamaGithub


text:
// BlueJ project: lesson8/counting

// TODO: Provide an instance variable for counting the passengers.
// TODO: Complete the addPassenger and getPassengerCount methods.

public class Car
{
    private int numberOfSeats;
    private int passengerCount = 0;

    /**
        Constructs a car with a given number of seats
        @param numberOfSeats the number of seats in this car.
    */
    public Car(int numberOfSeats)
    {
        this.numberOfSeats = numberOfSeats;
    }

    /**
       Adds a passenger to this car, provided that there is space.
    */
    public void addPassenger()
    {
        if (passengerCount < numberOfSeats -1)
            //see if seat available and driver takes up a seat too, hence the -1
        {
            passengerCount++;
        }
    }

    /**
       Gets the number of passengers in this car (not counting the driver).
       @return the number of passengers
    */
    public int getPassengerCount()
    {
        return passengerCount;
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Zipfel, Beer, Jacobs, Wingfield & Wingfield, Stud. Mycol. 55: 91 (2006)

#### Original name
Ophiostoma radiaticola J.J. Kim, Seifert & G.H. Kim, 2005

### Remarks
null


text:
package org.seasar.doma.internal.apt.entity;

import org.seasar.doma.Entity;

/**
 * @author taedium
 *
 */
@Entity
public class ParameterizedPropertyEntity {

    public Weight<Integer> wight;
}


text:
package org.mafagafogigante.dungeon.io;

import org.mafagafogigante.dungeon.schema.JsonRule;
import org.mafagafogigante.dungeon.schema.rules.JsonRuleFactory;

import com.eclipsesource.json.JsonObject;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class PrefaceJsonFileTest extends ResourcesTypeTest {

  private static final String FORMAT_FIELD = "format";

  @Test
  public void testIsFileHasValidStructure() {
    Map<String, JsonRule> tutorialFileRules = new HashMap<>();
    tutorialFileRules.put(FORMAT_FIELD, JsonRuleFactory.makeStringRule());
    JsonRule tutorialJsonRule = JsonRuleFactory.makeObjectRule(tutorialFileRules);
    String filename = ResourceNameResolver.resolveName(DungeonResource.PREFACE);
    JsonObject prefaceFileJsonObject = getJsonObjectByJsonFilename(filename);
    tutorialJsonRule.validate(prefaceFileJsonObject);
  }

}


text:
use serde_json;
use serde_json::value;
use serde_json::Value;
use chrono::offset::utc::UTC;

#[allow(dead_code)]
fn int_to_level(level: u64) -> String {
  match level {
    10 => "trace".to_string(),
    20 => "debug".to_string(),
    30 => "info".to_string(),
    40 => "warn".to_string(),
    50 => "error".to_string(),
    60 => "fatal".to_string(),
    _ => format!("Unknown level {}", level)
  }
}

#[allow(dead_code)]
pub fn transform(input_value: &mut Value) -> Value {
  // {"name":"stakhanov","hostname":"Quark.local","pid":65470,"level":30
  // "msg":"pushing http://fr.wikipedia.org/wiki/Giant_Sand",
  // "time":"2015-05-21T10:11:02.132Z","v":0}
  //
  // entry['@timestamp'] = entry.time;
  // entry.level = levels[entry.level];
  // entry.message = entry.msg;
  // delete entry.time;
  // delete entry.msg;
  let mut input = input_value.as_object_mut().unwrap();

  if input.contains_key("time") {
    let time = input.get("time").unwrap().clone();
    input.insert("@timestamp".to_string(), time);
    input.remove("time");
  } else {
    // Inject now timestamp.
    let tm = UTC::now();

    let format_prefix = "%Y-%m-%dT%H:%M:%S.%f";
    let format_suffix = "%Z";
    // truncate up to the third digit
    // 2015-05-21T15:27:20.994
    // 01234567890123456789012
    let mut timestamp = tm.format(format_prefix.as_ref()).to_string();
    timestamp.truncate(23);
    let timestamp_suffix =  tm.format(format_suffix.as_ref()).to_string();
    timestamp.push_str(&timestamp_suffix);

    input.insert("@timestamp".to_string(), value::to_value(&timestamp));
  }

  if input.contains_key("level") {
    let level = input.get("level").unwrap().as_u64().unwrap();
    input.insert("level".to_string(), value::to_value(&int_to_level(level)));
  }

  if input.contains_key("msg") {
    let message = input.get("msg").unwrap().clone();
    input.insert("message".to_string(), message);
    input.remove("msg");
  }
  return value::to_value(input);
}

#[allow(dead_code)]
pub fn time_to_index_name(full_timestamp: &str) -> String {
  // compatible with "2015-05-21T10:11:02.132Z"
  let mut input = full_timestamp.to_string();
  input.truncate(10);
  input = input.replace("-", ".");
  format!("logstash-{}", input)
}

#[test]
fn it_transform_ok() {
  // let src = r#"{"name":"stakhanov","hostname":"Quark.local","pid":65470,"level":30,"msg":"pushing http://fr.wikipedia.org/wiki/Giant_Sand","time":"2015-05-21T10:11:02.132Z","v":0}"#;
  let src = r#"{"level":30, "msg":"this is a test.", "time": "12"}"#;
  let mut decode = serde_json::from_str::<Value>(src).unwrap();
  let transformed = transform(&mut decode);
  let out = serde_json::to_string(&transformed).unwrap();
  assert_eq!(out, r#"{"@timestamp":"12","level":"info","message":"this is a test."}"#);
}

#[test]
fn it_prepares_index_name() {
  // let src = r#"{"name":"stakhanov","hostname":"Quark.local","pid":65470,"level":30,"msg":"pushing http://fr.wikipedia.org/wiki/Giant_Sand","time":"2015-05-21T10:11:02.132Z","v":0}"#;
  let src = r#"{"time": "2015-05-21T10:11:02.132Z"}"#;
  let decode = serde_json::from_str::<Value>(src).unwrap();
  match decode.find("time") {
    Some(time) => assert_eq!("logstash-2015.05.21", time_to_index_name(time.as_string().unwrap())),
    None => assert!(false)
  }
}


text:
using System.IO;
using Microsoft.Extensions.Configuration;

namespace MySqlConnector.Performance
{
	public static class AppConfig
	{
		public static IConfigurationRoot Config = new ConfigurationBuilder()
			.SetBasePath(Directory.GetCurrentDirectory())
			.AddJsonFile("appsettings.json")
			.AddJsonFile("config.json")
			.Build();
	}
}


text:
package org.bouncycastle.crypto.tls;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Hashtable;
import java.util.Vector;

import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.util.Arrays;

public class DTLSServerProtocol
    extends DTLSProtocol
{
    protected boolean verifyRequests = true;

    public DTLSServerProtocol(SecureRandom secureRandom)
    {
        super(secureRandom);
    }

    public boolean getVerifyRequests()
    {
        return verifyRequests;
    }

    public void setVerifyRequests(boolean verifyRequests)
    {
        this.verifyRequests = verifyRequests;
    }

    public DTLSTransport accept(TlsServer server, DatagramTransport transport)
        throws IOException
    {
        if (server == null)
        {
            throw new IllegalArgumentException("'server' cannot be null");
        }
        if (transport == null)
        {
            throw new IllegalArgumentException("'transport' cannot be null");
        }

        SecurityParameters securityParameters = new SecurityParameters();
        securityParameters.entity = ConnectionEnd.server;

        ServerHandshakeState state = new ServerHandshakeState();
        state.server = server;
        state.serverContext = new TlsServerContextImpl(secureRandom, securityParameters);

        securityParameters.serverRandom = TlsProtocol.createRandomBlock(server.shouldUseGMTUnixTime(),
            state.serverContext.getNonceRandomGenerator());

        server.init(state.serverContext);

        DTLSRecordLayer recordLayer = new DTLSRecordLayer(transport, state.serverContext, server, ContentType.handshake);

        // TODO Need to handle sending of HelloVerifyRequest without entering a full connection

        try
        {
            return serverHandshake(state, recordLayer);
        }
        catch (TlsFatalAlert fatalAlert)
        {
            recordLayer.fail(fatalAlert.getAlertDescription());
            throw fatalAlert;
        }
        catch (IOException e)
        {
            recordLayer.fail(AlertDescription.internal_error);
            throw e;
        }
        catch (RuntimeException e)
        {
            recordLayer.fail(AlertDescription.internal_error);
            throw new TlsFatalAlert(AlertDescription.internal_error, e);
        }
    }

    protected DTLSTransport serverHandshake(ServerHandshakeState state, DTLSRecordLayer recordLayer)
        throws IOException
    {
        SecurityParameters securityParameters = state.serverContext.getSecurityParameters();
        DTLSReliableHandshake handshake = new DTLSReliableHandshake(state.serverContext, recordLayer);

        DTLSReliableHandshake.Message clientMessage = handshake.receiveMessage();

        // NOTE: DTLSRecordLayer requires any DTLS version, we don't otherwise constrain this
//        ProtocolVersion recordLayerVersion = recordLayer.getReadVersion();

        if (clientMessage.getType() == HandshakeType.client_hello)
        {
            processClientHello(state, clientMessage.getBody());
        }
        else
        {
            throw new TlsFatalAlert(AlertDescription.unexpected_message);
        }

        {
            byte[] serverHelloBody = generateServerHello(state);

            applyMaxFragmentLengthExtension(recordLayer, securityParameters.maxFragmentLength);

            ProtocolVersion recordLayerVersion = state.serverContext.getServerVersion();
            recordLayer.setReadVersion(recordLayerVersion);
            recordLayer.setWriteVersion(recordLayerVersion);

            handshake.sendMessage(HandshakeType.server_hello, serverHelloBody);
        }

        handshake.notifyHelloComplete();

        Vector serverSupplementalData = state.server.getServerSupplementalData();
        if (serverSupplementalData != null)
        {
            byte[] supplementalDataBody = generateSupplementalData(serverSupplementalData);
            handshake.sendMessage(HandshakeType.supplemental_data, supplementalDataBody);
        }

        state.keyExchange = state.server.getKeyExchange();
        state.keyExchange.init(state.serverContext);

        state.serverCredentials = state.server.getCredentials();

        Certificate serverCertificate = null;

        if (state.serverCredentials == null)
        {
            state.keyExchange.skipServerCredentials();
        }
        else
        {
            state.keyExchange.processServerCredentials(state.serverCredentials);

            serverCertificate = state.serverCredentials.getCertificate();
            byte[] certificateBody = generateCertificate(serverCertificate);
            handshake.sendMessage(HandshakeType.certificate, certificateBody);
        }

        // TODO[RFC 3546] Check whether empty certificates is possible, allowed, or excludes CertificateStatus
        if (serverCertificate == null || serverCertificate.isEmpty())
        {
            state.allowCertificateStatus = false;
        }

        if (state.allowCertificateStatus)
        {
            CertificateStatus certificateStatus = state.server.getCertificateStatus();
            if (certificateStatus != null)
            {
                byte[] certificateStatusBody = generateCertificateStatus(state, certificateStatus);
                handshake.sendMessage(HandshakeType.certificate_status, certificateStatusBody);
            }
        }

        byte[] serverKeyExchange = state.keyExchange.generateServerKeyExchange();
        if (serverKeyExchange != null)
        {
            handshake.sendMessage(HandshakeType.server_key_exchange, serverKeyExchange);
        }

        if (state.serverCredentials != null)
        {
            state.certificateRequest = state.server.getCertificateRequest();
            if (state.certificateRequest != null)
            {
                if (TlsUtils.isTLSv12(state.serverContext) != (state.certificateRequest.getSupportedSignatureAlgorithms() != null))
                {
                    throw new TlsFatalAlert(AlertDescription.internal_error);
                }

                state.keyExchange.validateCertificateRequest(state.certificateRequest);

                byte[] certificateRequestBody = generateCertificateRequest(state, state.certificateRequest);
                handshake.sendMessage(HandshakeType.certificate_request, certificateRequestBody);

                TlsUtils.trackHashAlgorithms(handshake.getHandshakeHash(),
                    state.certificateRequest.getSupportedSignatureAlgorithms());
            }
        }

        handshake.sendMessage(HandshakeType.server_hello_done, TlsUtils.EMPTY_BYTES);

        handshake.getHandshakeHash().sealHashAlgorithms();

        clientMessage = handshake.receiveMessage();

        if (clientMessage.getType() == HandshakeType.supplemental_data)
        {
            processClientSupplementalData(state, clientMessage.getBody());
            clientMessage = handshake.receiveMessage();
        }
        else
        {
            state.server.processClientSupplementalData(null);
        }

        if (state.certificateRequest == null)
        {
            state.keyExchange.skipClientCredentials();
        }
        else
        {
            if (clientMessage.getType() == HandshakeType.certificate)
            {
                processClientCertificate(state, clientMessage.getBody());
                clientMessage = handshake.receiveMessage();
            }
            else
            {
                if (TlsUtils.isTLSv12(state.serverContext))
                {
                    /*
                     * RFC 5246 If no suitable certificate is available, the client MUST send a
                     * certificate message containing no certificates.
                     *
                     * NOTE: In previous RFCs, this was SHOULD instead of MUST.
                     */
                    throw new TlsFatalAlert(AlertDescription.unexpected_message);
                }

                notifyClientCertificate(state, Certificate.EMPTY_CHAIN);
            }
        }

        if (clientMessage.getType() == HandshakeType.client_key_exchange)
        {
            processClientKeyExchange(state, clientMessage.getBody());
        }
        else
        {
            throw new TlsFatalAlert(AlertDescription.unexpected_message);
        }

        TlsHandshakeHash prepareFinishHash = handshake.prepareToFinish();
        securityParameters.sessionHash = TlsProtocol.getCurrentPRFHash(state.serverContext, prepareFinishHash, null);

        TlsProtocol.establishMasterSecret(state.serverContext, state.keyExchange);
        recordLayer.initPendingEpoch(state.server.getCipher());

        /*
         * RFC 5246 7.4.8 This message is only sent following a client certificate that has signing
         * capability (i.e., all certificates except those containing fixed Diffie-Hellman
         * parameters).
         */
        if (expectCertificateVerifyMessage(state))
        {
            byte[] certificateVerifyBody = handshake.receiveMessageBody(HandshakeType.certificate_verify);
            processCertificateVerify(state, certificateVerifyBody, prepareFinishHash);
        }

        // NOTE: Calculated exclusive of the actual Finished message from the client
        byte[] expectedClientVerifyData = TlsUtils.calculateVerifyData(state.serverContext, ExporterLabel.client_finished,
            TlsProtocol.getCurrentPRFHash(state.serverContext, handshake.getHandshakeHash(), null));
        processFinished(handshake.receiveMessageBody(HandshakeType.finished), expectedClientVerifyData);

        if (state.expectSessionTicket)
        {
            NewSessionTicket newSessionTicket = state.server.getNewSessionTicket();
            byte[] newSessionTicketBody = generateNewSessionTicket(state, newSessionTicket);
            handshake.sendMessage(HandshakeType.session_ticket, newSessionTicketBody);
        }

        // NOTE: Calculated exclusive of the Finished message itself
        byte[] serverVerifyData = TlsUtils.calculateVerifyData(state.serverContext, ExporterLabel.server_finished,
            TlsProtocol.getCurrentPRFHash(state.serverContext, handshake.getHandshakeHash(), null));
        handshake.sendMessage(HandshakeType.finished, serverVerifyData);

        handshake.finish();

        state.server.notifyHandshakeComplete();

        return new DTLSTransport(recordLayer);
    }

    protected byte[] generateCertificateRequest(ServerHandshakeState state, CertificateRequest certificateRequest)
        throws IOException
    {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        certificateRequest.encode(buf);
        return buf.toByteArray();
    }

    protected byte[] generateCertificateStatus(ServerHandshakeState state, CertificateStatus certificateStatus)
        throws IOException
    {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        certificateStatus.encode(buf);
        return buf.toByteArray();
    }

    protected byte[] generateNewSessionTicket(ServerHandshakeState state, NewSessionTicket newSessionTicket)
        throws IOException
    {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        newSessionTicket.encode(buf);
        return buf.toByteArray();
    }

    protected byte[] generateServerHello(ServerHandshakeState state)
        throws IOException
    {
        SecurityParameters securityParameters = state.serverContext.getSecurityParameters();

        ByteArrayOutputStream buf = new ByteArrayOutputStream();

        {
            ProtocolVersion server_version = state.server.getServerVersion();
            if (!server_version.isEqualOrEarlierVersionOf(state.serverContext.getClientVersion()))
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            // TODO Read RFCs for guidance on the expected record layer version number
            // recordStream.setReadVersion(server_version);
            // recordStream.setWriteVersion(server_version);
            // recordStream.setRestrictReadVersion(true);
            state.serverContext.setServerVersion(server_version);

            TlsUtils.writeVersion(state.serverContext.getServerVersion(), buf);
        }

        buf.write(securityParameters.getServerRandom());

        /*
         * The server may return an empty session_id to indicate that the session will not be cached
         * and therefore cannot be resumed.
         */
        TlsUtils.writeOpaque8(TlsUtils.EMPTY_BYTES, buf);

        int selectedCipherSuite = state.server.getSelectedCipherSuite();
        if (!Arrays.contains(state.offeredCipherSuites, selectedCipherSuite)
            || selectedCipherSuite == CipherSuite.TLS_NULL_WITH_NULL_NULL
            || CipherSuite.isSCSV(selectedCipherSuite)
            || !TlsUtils.isValidCipherSuiteForVersion(selectedCipherSuite, state.serverContext.getServerVersion()))
        {
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }
        validateSelectedCipherSuite(selectedCipherSuite, AlertDescription.internal_error);
        securityParameters.cipherSuite = selectedCipherSuite;

        short selectedCompressionMethod = state.server.getSelectedCompressionMethod();
        if (!Arrays.contains(state.offeredCompressionMethods, selectedCompressionMethod))
        {
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }
        securityParameters.compressionAlgorithm = selectedCompressionMethod;

        TlsUtils.writeUint16(selectedCipherSuite, buf);
        TlsUtils.writeUint8(selectedCompressionMethod, buf);

        state.serverExtensions = state.server.getServerExtensions();

        /*
         * RFC 5746 3.6. Server Behavior: Initial Handshake
         */
        if (state.secure_renegotiation)
        {
            byte[] renegExtData = TlsUtils.getExtensionData(state.serverExtensions, TlsProtocol.EXT_RenegotiationInfo);
            boolean noRenegExt = (null == renegExtData);

            if (noRenegExt)
            {
                /*
                 * Note that sending a "renegotiation_info" extension in response to a ClientHello
                 * containing only the SCSV is an explicit exception to the prohibition in RFC 5246,
                 * Section 7.4.1.4, on the server sending unsolicited extensions and is only allowed
                 * because the client is signaling its willingness to receive the extension via the
                 * TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV.
                 */

                /*
                 * If the secure_renegotiation flag is set to TRUE, the server MUST include an empty
                 * "renegotiation_info" extension in the ServerHello message.
                 */
                state.serverExtensions = TlsExtensionsUtils.ensureExtensionsInitialised(state.serverExtensions);
                state.serverExtensions.put(TlsProtocol.EXT_RenegotiationInfo,
                    TlsProtocol.createRenegotiationInfo(TlsUtils.EMPTY_BYTES));
            }
        }

        if (securityParameters.extendedMasterSecret)
        {
            state.serverExtensions = TlsExtensionsUtils.ensureExtensionsInitialised(state.serverExtensions);
            TlsExtensionsUtils.addExtendedMasterSecretExtension(state.serverExtensions);
        }

        /*
         * TODO RFC 3546 2.3 If [...] the older session is resumed, then the server MUST ignore
         * extensions appearing in the client hello, and send a server hello containing no
         * extensions.
         */

        if (state.serverExtensions != null)
        {
            securityParameters.encryptThenMAC = TlsExtensionsUtils.hasEncryptThenMACExtension(state.serverExtensions);

            securityParameters.maxFragmentLength = evaluateMaxFragmentLengthExtension(state.resumedSession,
                state.clientExtensions, state.serverExtensions, AlertDescription.internal_error);

            securityParameters.truncatedHMac = TlsExtensionsUtils.hasTruncatedHMacExtension(state.serverExtensions);

            /*
             * TODO It's surprising that there's no provision to allow a 'fresh' CertificateStatus to be sent in
             * a session resumption handshake.
             */
            state.allowCertificateStatus = !state.resumedSession
                && TlsUtils.hasExpectedEmptyExtensionData(state.serverExtensions,
                    TlsExtensionsUtils.EXT_status_request, AlertDescription.internal_error);

            state.expectSessionTicket = !state.resumedSession
                && TlsUtils.hasExpectedEmptyExtensionData(state.serverExtensions, TlsProtocol.EXT_SessionTicket,
                    AlertDescription.internal_error);

            TlsProtocol.writeExtensions(buf, state.serverExtensions);
        }

        securityParameters.prfAlgorithm = TlsProtocol.getPRFAlgorithm(state.serverContext,
            securityParameters.getCipherSuite());

        /*
         * RFC 5264 7.4.9. Any cipher suite which does not explicitly specify verify_data_length
         * has a verify_data_length equal to 12. This includes all existing cipher suites.
         */
        securityParameters.verifyDataLength = 12;

        return buf.toByteArray();
    }

    protected void notifyClientCertificate(ServerHandshakeState state, Certificate clientCertificate)
        throws IOException
    {
        if (state.certificateRequest == null)
        {
            throw new IllegalStateException();
        }

        if (state.clientCertificate != null)
        {
            throw new TlsFatalAlert(AlertDescription.unexpected_message);
        }

        state.clientCertificate = clientCertificate;

        if (clientCertificate.isEmpty())
        {
            state.keyExchange.skipClientCredentials();
        }
        else
        {

            /*
             * TODO RFC 5246 7.4.6. If the certificate_authorities list in the certificate request
             * message was non-empty, one of the certificates in the certificate chain SHOULD be
             * issued by one of the listed CAs.
             */

            state.clientCertificateType = TlsUtils.getClientCertificateType(clientCertificate,
                state.serverCredentials.getCertificate());

            state.keyExchange.processClientCertificate(clientCertificate);
        }

        /*
         * RFC 5246 7.4.6. If the client does not send any certificates, the server MAY at its
         * discretion either continue the handshake without client authentication, or respond with a
         * fatal handshake_failure alert. Also, if some aspect of the certificate chain was
         * unacceptable (e.g., it was not signed by a known, trusted CA), the server MAY at its
         * discretion either continue the handshake (considering the client unauthenticated) or send
         * a fatal alert.
         */
        state.server.notifyClientCertificate(clientCertificate);
    }

    protected void processClientCertificate(ServerHandshakeState state, byte[] body)
        throws IOException
    {
        ByteArrayInputStream buf = new ByteArrayInputStream(body);

        Certificate clientCertificate = Certificate.parse(buf);

        TlsProtocol.assertEmpty(buf);

        notifyClientCertificate(state, clientCertificate);
    }

    protected void processCertificateVerify(ServerHandshakeState state, byte[] body, TlsHandshakeHash prepareFinishHash)
        throws IOException
    {
        if (state.certificateRequest == null)
        {
            throw new IllegalStateException();
        }

        ByteArrayInputStream buf = new ByteArrayInputStream(body);

        TlsServerContextImpl context = state.serverContext;
        DigitallySigned clientCertificateVerify = DigitallySigned.parse(context, buf);

        TlsProtocol.assertEmpty(buf);

        // Verify the CertificateVerify message contains a correct signature.
        try
        {
            SignatureAndHashAlgorithm signatureAlgorithm = clientCertificateVerify.getAlgorithm();

            byte[] hash;
            if (TlsUtils.isTLSv12(context))
            {
                TlsUtils.verifySupportedSignatureAlgorithm(state.certificateRequest.getSupportedSignatureAlgorithms(), signatureAlgorithm);
                hash = prepareFinishHash.getFinalHash(signatureAlgorithm.getHash());
            }
            else
            {
                hash = context.getSecurityParameters().getSessionHash();
            }

            org.bouncycastle.asn1.x509.Certificate x509Cert = state.clientCertificate.getCertificateAt(0);
            SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
            AsymmetricKeyParameter publicKey = PublicKeyFactory.createKey(keyInfo);

            TlsSigner tlsSigner = TlsUtils.createTlsSigner(state.clientCertificateType);
            tlsSigner.init(context);
            if (!tlsSigner.verifyRawSignature(signatureAlgorithm, clientCertificateVerify.getSignature(), publicKey, hash))
            {
                throw new TlsFatalAlert(AlertDescription.decrypt_error);
            }
        }
        catch (TlsFatalAlert e)
        {
            throw e;
        }
        catch (Exception e)
        {
            throw new TlsFatalAlert(AlertDescription.decrypt_error, e);
        }
    }

    protected void processClientHello(ServerHandshakeState state, byte[] body)
        throws IOException
    {
        ByteArrayInputStream buf = new ByteArrayInputStream(body);

        // TODO Read RFCs for guidance on the expected record layer version number
        ProtocolVersion client_version = TlsUtils.readVersion(buf);
        if (!client_version.isDTLS())
        {
            throw new TlsFatalAlert(AlertDescription.illegal_parameter);
        }

        /*
         * Read the client random
         */
        byte[] client_random = TlsUtils.readFully(32, buf);

        byte[] sessionID = TlsUtils.readOpaque8(buf);
        if (sessionID.length > 32)
        {
            throw new TlsFatalAlert(AlertDescription.illegal_parameter);
        }

        // TODO RFC 4347 has the cookie length restricted to 32, but not in RFC 6347
        byte[] cookie = TlsUtils.readOpaque8(buf);

        int cipher_suites_length = TlsUtils.readUint16(buf);
        if (cipher_suites_length < 2 || (cipher_suites_length & 1) != 0)
        {
            throw new TlsFatalAlert(AlertDescription.decode_error);
        }

        /*
         * NOTE: "If the session_id field is not empty (implying a session resumption request) this
         * vector must include at least the cipher_suite from that session."
         */
        state.offeredCipherSuites = TlsUtils.readUint16Array(cipher_suites_length / 2, buf);

        int compression_methods_length = TlsUtils.readUint8(buf);
        if (compression_methods_length < 1)
        {
            throw new TlsFatalAlert(AlertDescription.illegal_parameter);
        }

        state.offeredCompressionMethods = TlsUtils.readUint8Array(compression_methods_length, buf);

        /*
         * TODO RFC 3546 2.3 If [...] the older session is resumed, then the server MUST ignore
         * extensions appearing in the client hello, and send a server hello containing no
         * extensions.
         */
        state.clientExtensions = TlsProtocol.readExtensions(buf);

        TlsServerContextImpl context = state.serverContext;
        SecurityParameters securityParameters = context.getSecurityParameters();

        /*
         * TODO[session-hash]
         *
         * draft-ietf-tls-session-hash-04 4. Clients and servers SHOULD NOT accept handshakes
         * that do not use the extended master secret [..]. (and see 5.2, 5.3)
         */
        securityParameters.extendedMasterSecret = TlsExtensionsUtils.hasExtendedMasterSecretExtension(state.clientExtensions);

        context.setClientVersion(client_version);

        state.server.notifyClientVersion(client_version);
        state.server.notifyFallback(Arrays.contains(state.offeredCipherSuites, CipherSuite.TLS_FALLBACK_SCSV));

        securityParameters.clientRandom = client_random;

        state.server.notifyOfferedCipherSuites(state.offeredCipherSuites);
        state.server.notifyOfferedCompressionMethods(state.offeredCompressionMethods);

        /*
         * RFC 5746 3.6. Server Behavior: Initial Handshake
         */
        {
            /*
             * RFC 5746 3.4. The client MUST include either an empty "renegotiation_info" extension,
             * or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the
             * ClientHello. Including both is NOT RECOMMENDED.
             */

            /*
             * When a ClientHello is received, the server MUST check if it includes the
             * TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV. If it does, set the secure_renegotiation flag
             * to TRUE.
             */
            if (Arrays.contains(state.offeredCipherSuites, CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV))
            {
                state.secure_renegotiation = true;
            }

            /*
             * The server MUST check if the "renegotiation_info" extension is included in the
             * ClientHello.
             */
            byte[] renegExtData = TlsUtils.getExtensionData(state.clientExtensions, TlsProtocol.EXT_RenegotiationInfo);
            if (renegExtData != null)
            {
                /*
                 * If the extension is present, set secure_renegotiation flag to TRUE. The
                 * server MUST then verify that the length of the "renegotiated_connection"
                 * field is zero, and if it is not, MUST abort the handshake.
                 */
                state.secure_renegotiation = true;

                if (!Arrays.constantTimeAreEqual(renegExtData, TlsProtocol.createRenegotiationInfo(TlsUtils.EMPTY_BYTES)))
                {
                    throw new TlsFatalAlert(AlertDescription.handshake_failure);
                }
            }
        }

        state.server.notifySecureRenegotiation(state.secure_renegotiation);

        if (state.clientExtensions != null)
        {
            state.server.processClientExtensions(state.clientExtensions);
        }
    }

    protected void processClientKeyExchange(ServerHandshakeState state, byte[] body)
        throws IOException
    {
        ByteArrayInputStream buf = new ByteArrayInputStream(body);

        state.keyExchange.processClientKeyExchange(buf);

        TlsProtocol.assertEmpty(buf);
    }

    protected void processClientSupplementalData(ServerHandshakeState state, byte[] body)
        throws IOException
    {
        ByteArrayInputStream buf = new ByteArrayInputStream(body);
        Vector clientSupplementalData = TlsProtocol.readSupplementalDataMessage(buf);
        state.server.processClientSupplementalData(clientSupplementalData);
    }

    protected boolean expectCertificateVerifyMessage(ServerHandshakeState state)
    {
        return state.clientCertificateType >= 0 && TlsUtils.hasSigningCapability(state.clientCertificateType);
    }

    protected static class ServerHandshakeState
    {
        TlsServer server = null;
        TlsServerContextImpl serverContext = null;
        int[] offeredCipherSuites = null;
        short[] offeredCompressionMethods = null;
        Hashtable clientExtensions = null;
        Hashtable serverExtensions = null;
        boolean resumedSession = false;
        boolean secure_renegotiation = false;
        boolean allowCertificateStatus = false;
        boolean expectSessionTicket = false;
        TlsKeyExchange keyExchange = null;
        TlsCredentials serverCredentials = null;
        CertificateRequest certificateRequest = null;
        short clientCertificateType = -1;
        Certificate clientCertificate = null;
    }
}


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

<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<meta name="generator" content="WordPress <?php bloginfo('version'); ?>" />

<title><?php wp_title("•",true,"right"); ?> <?php if ( is_single() ) { ?> Blog Archive • <?php } ?><?php bloginfo('name'); ?></title>

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/admin/css/superfish.css" type="text/css" media="screen" />
<?php
	global $hemingwayEx, $hemingwayEx_options;
	if ($hemingwayEx->style != 'none') :
?>
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/styles/<?php echo $hemingwayEx->style ?>" type="text/css" media="screen" />
<?php endif; ?>
<link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Feed" href="<?php bloginfo('rss2_url'); ?>" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />

<?php wp_enqueue_script('textsize', get_bloginfo('template_directory') . '/admin/js/textsize.js'); ?>
<?php wp_enqueue_script('superfish', get_bloginfo('template_directory') . '/admin/js/superfish.js', array('jquery')); ?>
<?php wp_enqueue_script('initialize', get_bloginfo('template_directory') . '/admin/js/init.js'); ?>
<?php wp_head(); ?>

					<form method="get" id="sform" action="<?php bloginfo('home'); ?>/">

						<input type="text" id="q" value="<?php echo wp_specialchars($s, 1); ?>" name="s" size="15" />
					</form>

				<?php if ($hemingwayEx_options['font_resizer'] == 1) { ?>

						<?php _e('Font:','hemingwayex') ?>
							<a id="upSize" href="#" title="<?php _e('Increase size','hemingwayex') ?>">A+
							<a id="downSize" href="#" title="<?php _e('Decrease size','hemingwayex') ?>">A-
							<a id="resetSize" href="#" title="<?php _e('Revert styles to default','hemingwayex') ?>">A

				<?php } ?>

<a href="<?php echo get_option('home'); ?>/"><?php bloginfo('name'); ?>

<?php bloginfo('description'); ?>

         <?php hemingwayEx_nav() ?>
         <?php if ($hemingwayEx_options['slidebar_enabled'] == 1){ ?>

               <a id="openSlidebar" href="#" title="<?php _e('Open Navigation','hemingwayex') ?>"><?php _e('Open Navigation','hemingwayex') ?>
               <a id="closeSlidebar" href="#" title="<?php _e('Close Navigation','hemingwayex') ?>" style="display:none;"><?php _e('Close Navigation','hemingwayex') ?>

         <?php } ?>

	<?php include (TEMPLATEPATH . '/dynamic_slidebar.php'); ?>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Kydia glabrescens Mast.

### Remarks
null


text:
import logging

from cartridge.shop.checkout import CheckoutError
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import gettext_lazy as _
from mezzanine.conf import settings

logger = logging.getLogger("braintree_payment")

# Requires Braintree package -- install from pypi: pip install braintree.
try:
    import braintree
except ImportError:
    raise ImproperlyConfigured(_("Braintree package must be installed."))

if settings.DEBUG:
    BRAINTREE_ENVIROMENT = braintree.Environment.Sandbox
else:
    BRAINTREE_ENVIROMENT = braintree.Environment.Production

try:
    BRAINTREE_MERCHANT_ID = settings.BRAINTREE_MERCHANT_ID
    BRAINTREE_PUBLIC_KEY = settings.BRAINTREE_PUBLIC_KEY
    BRAINTREE_PRIVATE_KEY = settings.BRAINTREE_PRIVATE_KEY
except AttributeError:
    raise ImproperlyConfigured(
        _("You need to define BRAINTREE_MERCHANT_ID, "
        "BRAINTREE_PUBLIC_KEY and BRAINTREE_PRIVATE_KEY "
        "in your settings module to use the "
        "Braintree payment processor.")
    )

BRAINTREE_IS_CONFIGURED = False

def configure():
    global BRAINTREE_IS_CONFIGURED
    braintree.Configuration.configure(
        BRAINTREE_ENVIROMENT,
        BRAINTREE_MERCHANT_ID,
        BRAINTREE_PUBLIC_KEY,
        BRAINTREE_PRIVATE_KEY,
    )
    BRAINTREE_IS_CONFIGURED = True

def client_token():
    # verify that braintree has been configured, if not, call configure()
    if not BRAINTREE_IS_CONFIGURED:
        configure()
    token = braintree.ClientToken.generate()
    logger.info(f"Generated Braintree client token '{token[:5]}...{token[-5:]}'")
    return token

def payment_handler(request, order_form, order):
    """
    Braintree payment handler.

    See https://www.braintreepayments.com/docs/python/transactions/create

    Raise cartride.shop.checkout.CheckoutError("error message") if
    payment is unsuccessful.

    In your settings, set ``SHOP_HANDLER_PAYMENT`` to point to this function,
    'cartridge_braintree.braintree_payment.payment_handler'

    """
    # verify that braintree has been configured, if not, call configure()
    if not BRAINTREE_IS_CONFIGURED:
        configure()

    data = order_form.cleaned_data

    trans = {
        "payment_method_nonce": data["payment_method_nonce"],
        "amount": f"{order.total:.2f}",
        "order_id": str(order.id),
        "customer": {
            "first_name": data["billing_detail_first_name"],
            "last_name": data["billing_detail_last_name"],
            "email": data["billing_detail_email"],
            "phone": data["billing_detail_phone"],
        },
        "billing": {
            "first_name": data["billing_detail_first_name"],
            "last_name": data["billing_detail_last_name"],
            "street_address": data["billing_detail_street"],
            "locality": data["billing_detail_city"],
            "region": data["billing_detail_state"],
            "postal_code": data["billing_detail_postcode"],
            "country_code_alpha2": data["billing_detail_country"],
        },
        "shipping": {
            "first_name": data["shipping_detail_first_name"],
            "last_name": data["shipping_detail_last_name"],
            "street_address": data["shipping_detail_street"],
            "locality": data["shipping_detail_city"],
            "region": data["shipping_detail_state"],
            "postal_code": data["shipping_detail_postcode"],
            "country_code_alpha2": data["shipping_detail_country"],
        },
        "options": {"submit_for_settlement": True},
    }

    logger.debug("Sending order %s to Braintree ..." % order.id)
    result = braintree.Transaction.sale(trans)
    if result.is_success:
        transaction_id = result.transaction.id
        logger.debug("Transaction completed with Braintree ID: %s" % transaction_id)
        return transaction_id
    else:
        all_errors = ""
        for error in result.errors.deep_errors:
            all_errors += f" [code: {error.code}, attribute: {error.attribute}, '{error.message}']"
        logger.error(f"Order {order.id} failed with{all_errors}")

        raise CheckoutError(_("Payment error:") + " " + result.message)


text:
using System.Data.SqlClient;
using System.Linq;
using EIDSS.Reports.BaseControls.BaseDataSetTableAdapters;

namespace EIDSS.Reports.Parameterized.Veterinary.Situation {

    partial class VetSituationDataSet
    {
    }
}

namespace EIDSS.Reports.Parameterized.Veterinary.Situation.VetSituationDataSetTableAdapters
{

    public partial class sp_rep_VET_YearlyVeterinarySituationTableAdapter : global::System.ComponentModel.Component
    {
        private SqlTransaction m_Transaction;

        internal SqlTransaction Transaction
        {
            get { return m_Transaction; }
            set
            {
                m_Transaction = value;
                BaseAdapter.SetTransaction(Adapter, CommandCollection, value);
            }
        }

        internal int CommandTimeout
        {
            get { return CommandCollection.Select(c => c.CommandTimeout).FirstOrDefault(); }
            set
            {
                foreach (SqlCommand command in CommandCollection)
                {
                    command.CommandTimeout = value;
                }
            }
        }
    }

}


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

<title>I-Index</title>
<meta name="date" content="2014-09-15">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I K L M N O P R S T U V W _

I

IDLEN - Variable in class com.aleozlx.pacswitch.types.FutureTracker

IDRANGE - Variable in class com.aleozlx.pacswitch.types.FutureTracker

IEventListener - Interface in com.aleozlx.pacswitch.types

IEventListener.Args - Class in com.aleozlx.pacswitch.types

IEventListener.Args() - Constructor for class com.aleozlx.pacswitch.types.IEventListener.Args

IEventListener.Type - Enum in com.aleozlx.pacswitch.types

inbox - Variable in class com.aleozlx.pacswitch.GatewayMessager

Message inbox for messages not read immediately

INTERVAL_DEFAULT - Static variable in class com.aleozlx.pacswitch.types.FutureObject

isAuthenticated() - Method in class com.aleozlx.pacswitch.PacswitchMessager

Authentication state.

isAvailable() - Method in class com.aleozlx.pacswitch.types.FutureObject

isCancelled() - Method in class com.aleozlx.pacswitch.types.FutureObject

isDone() - Method in class com.aleozlx.pacswitch.types.FutureObject

ISignalHandler - Interface in com.aleozlx.pacswitch.types

isResponse() - Method in enum com.aleozlx.pacswitch.PacswitchMessager.MessageProtocol.Type

isTracked() - Method in enum com.aleozlx.pacswitch.PacswitchMessager.MessageProtocol.Type

A B C D E F G H I K L M N O P R S T U V W _

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
'use strict';

var sopracovoitControllers = angular.module('sopracovoitControllers', []);

sopracovoitControllers.controller('MainController', ["appConfig", "$scope", "$rootScope", "$cookieStore", "$mdSidenav", "$location",
    function(appConfig, $scope, $rootScope, $cookieStore, $mdSidenav, $location){

    $scope.menu = [
        {"nom": appConfig.routes.stats.name, "url": appConfig.routes.stats.path},
        {"nom": appConfig.routes.users.name, "url": appConfig.routes.users.path},
        {"nom": appConfig.routes.workplaces.name, "url": appConfig.routes.workplaces.path},
    ];

    if($cookieStore.get("loggedUser") != undefined)
    {
        // TODO check token
        $rootScope.loggedUser = $cookieStore.get("loggedUser");
    } else {
        $rootScope.loggedUser = {"connected": false};
    }

    $scope.isLoggedUser = function()
    {
        return $rootScope.loggedUser.connected == true;
    };

    $scope.toggleMenu = function()
    {
        $mdSidenav('left').toggle();
    };

    $scope.closeMenu = function()
    {
        $mdSidenav('left').close();
    };

    $scope.isLoading = function()
    {
        return $rootScope.isLoading;
    };

        $scope.setLoading = function(what)
        {
            $rootScope.isLoading = what;
        };

    $scope.loadPage = function(page)
    {
        $location.path(page);
        $scope.closeMenu();
    };

    $scope.loadedPage = function(name)
    {
        $scope.page = name;
        $scope.closeMenu();
    };

}]);

sopracovoitControllers.controller('LogoutCtrl', ["$scope",
    "$rootScope",
    "$location",
    "Utils",
    "$cookieStore", function($scope, $rootScope, $location, Utils, $cookieStore){

        $rootScope.loggedUser = {"connected": false};
        $cookieStore.put("loggedUser", $rootScope.loggedUser);
        Utils.toast("Goodbye !")

        $location.path("/");

}]);

sopracovoitControllers.controller('LoginCtrl', ["appConfig", "$scope",
    "$rootScope",
    "$location",
    "Utils",
    "$cookieStore", function(appConfig, $scope, $rootScope, $location, Utils, $cookieStore){

    $scope.$parent.loadedPage(appConfig.routes.login.name);

    $scope.submit = function(user)
    {
        if(user == undefined || user.email == undefined || user.password == undefined)
        {
            Utils.toast("Please fill all fields !");
            return;
        }

        if(user.email == "admin" && user.password == "admin") // TODO : add good check ...
        {
            $rootScope.loggedUser = {
                "email" : user.email,
                "connected": true
            };

            if(user.remember)
            {
                $cookieStore.put("loggedUser", $rootScope.loggedUser);
            }

            Utils.toast("Welcome !");

            $location.path("#/stats");
        } else {
            Utils.toast("Bad user or password");
        }
    }

}]);

sopracovoitControllers.controller("StatsCtrl", ["appConfig", "$scope", "User", "Workplace", function(appConfig, $scope, User, Workplace){
    $scope.$parent.loadedPage(appConfig.routes.stats.name);

    $scope.users = User.query();
    $scope.workplaces = Workplace.query();

}]);

sopracovoitControllers.controller("UsersCtrl", ["appConfig", "$scope", "User", "Workplace", "Utils", "$mdDialog",
    function(appConfig, $scope, User, Workplace, Utils, $mdDialog){
    $scope.$parent.loadedPage(appConfig.routes.users.name);
    $scope.$parent.setLoading(true);

    $scope.users = User.query(function(){
        $scope.$parent.setLoading(false);
    });
    $scope.workplaces = Workplace.query();

    $scope.add = function()
    {
        $mdDialog.show({
            title:"Add user",
            controller: "UserAddCtrl",
            templateUrl: "partials/user_add.html"
        }).then(function(user){
            user = new User(user);
            user.$save(function(data){ // success
                data.tmp = {};
                data.tmp.expanded = false;
                $scope.users = [data].concat($scope.users);
                Utils.toast("User added");

            }, function(err){ // error
                Utils.toast("Unable to create user");
            });
        });
    }

    $scope.save = function(user)
    {
        user.$save(function(data){ // success
            Utils.toast("User saved");
            user.tmp.expanded = false;
        }, function(err){ // error
            Utils.toast("User not saved - internal error");
        });
    };

    $scope.delete = function(user)
    {
        Utils.dialogConfirm("This user will be lost ...",
            function(){
                user.$remove(function(data){
                    Utils.toast("User deleted.");
                    $scope.users = User.query();
                }, function(err){
                    Utils.toast("User not deleted - internal error.");
                });
            },
            function(){
                Utils.toast("Action canceled");
            }
        );
    };

}]);

sopracovoitControllers.controller("UserAddCtrl", ["$scope", "$mdDialog", "Workplace", function($scope, $mdDialog, Workplace){

    $scope.workplaces = Workplace.query();
    $scope.user = {};
    $scope.user.workplace = {};

    $scope.cancel = function()
    {
        $mdDialog.cancel();
    };

    $scope.save = function()
    {
        $scope.user.password = new Hashes.SHA1().b64($scope.user.password);
        $mdDialog.hide($scope.user);
    };

}]);

sopracovoitControllers.controller("WorkplacesCtrl", ["appConfig", "$scope", "Workplace", "$mdDialog", "Utils",
    function(appConfig, $scope, Workplace, $mdDialog, Utils){

    $scope.$parent.loadedPage(appConfig.routes.workplaces.name);
    $scope.$parent.setLoading(true);

    $scope.markerOptions = {draggable: true};
    $scope.workplaces = Workplace.query(function(){
        $scope.$parent.setLoading(false);
    });

    $scope.add = function()
    {
        $mdDialog.show({
            title:"Add workplace",
            controller: "WorkplaceAddCtrl",
            templateUrl: "partials/workplace_add.html"
        }).then(function(workplace){
            workplace = new Workplace(workplace);
            $scope.$parent.setLoading(true);
            workplace.$save(function(data){ // success

                data.tmp = {};
                data.tmp.expanded = true;
                $scope.workplaces = [data].concat($scope.workplaces);
                Utils.toast("Workplace added");
                $scope.$parent.setLoading(false);

            }, function(err){ // error
                Utils.toast("Unable to create workplace");
                $scope.$parent.setLoading(false);
            });
        });
    };

    $scope.save = function(workplace)
    {
        $scope.$parent.setLoading(true);
        workplace.$save(function(data){ // success
            Utils.toast("Workplace saved");
            workplace.tmp.expanded = false;
            $scope.$parent.setLoading(false);
        }, function(err){ // error
            Utils.toast("Workplace not saved !!!");
            $scope.$parent.setLoading(false);
        });

    };

    $scope.delete = function(workplace)
    {

        Utils.dialogConfirm("This workplace will be lost ...",
            function(){
                $scope.$parent.setLoading(true);
                workplace.$remove(function(data){
                    Utils.toast("Workplace deleted.");
                    $scope.workplaces = Workplace.query(function(){
                        $scope.$parent.setLoading(false);
                    });
                }, function(err){
                    Utils.toast("Workplace not deleted - internal error.");
                    $scope.$parent.setLoading(false);
                });
            },
            function(){
                Utils.toast("Action canceled");
            }
        );

    };

}]);

sopracovoitControllers.controller("WorkplaceAddCtrl", ["$scope", "$mdDialog", function($scope, $mdDialog){

    $scope.markerOptions = { draggable: true};

    $scope.workplace = {
        location: {latitude:43.570900885989744, longitude:1.466313457965839},
    };

    $scope.cancel = function()
    {
        $mdDialog.cancel();
    };

    $scope.save = function()
    {
      $mdDialog.hide($scope.workplace);
    };

}]);

sopracovoitControllers.controller("PathsCtrl", ["appConfig", "$scope", function(appConfig, $scope){
    $scope.$parent.loadedPage(appConfig.routes.paths.name);
}]);


text:
namespace Utils {
#define max(a, b) (a > b) ? a : b
#define min(a, b) (a < b) ? a : b
    bool isNumber(char *number);
    unsigned int countDigits(unsigned int number);

    inline bool isNumberPowerOfTwo(unsigned int number) {
        return (number & (number-1)) == 0;
    }
}

#endif // UTIL_H


text:
/**
 * CSS files with the .module.css suffix will be treated as CSS modules
 * and scoped locally.
 */

.heroBanner {
    padding: 4rem 0;
    text-align: center;
    position: relative;
    overflow: hidden;
}

@media screen and (max-width: 966px) {
    .heroBanner {
        padding: 2rem;
    }
}

.buttons {
    display: flex;
    align-items: center;
    justify-content: center;
}

.features {
    display: flex;
    align-items: center;
    padding: 2rem 0;
    width: 100%;
}

.featureImage {
    height: 120px;
    width: 200px;
    background-color: white;
}

.featureDescription {
    max-width: 300px;
    margin: 0 auto;
}

.starIframe {
    border: none;
    margin-bottom: 30px;
}

.descriptions {
}

.descriptionRow {
    width: 100%;
    margin: 0;
}

.description {
    width: 100%;
    min-height: 300px;
}

.descriptionContent {
    display: flex;
    align-items: center;
    max-width: var(--ifm-container-width);
    margin: 0 auto;
    padding: 0 var(--ifm-spacing-horizontal);
    width: 100%;
    height: 100%;
}

.descriptionImage {
    height: auto;
    width: 280px;
}

.lightBackground {
    background-color: #f6f6f6;
}

.rightImage {
    flex-direction: row-reverse;
}

.deployByYourself {
    width: 100%;
    min-height: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.deployTitle {
    color: var(--ifm-color-primary);
}

.heroButton {
    margin: 0 10px;
}


text:
package jodd.proxetta.fixtures.data;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface PetiteInject {

	String value() default "";

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia, Beih. 29: 342 (1969)

#### Original name
Rhodophyllus dissimilis Singer

### Remarks
null


text:
class ShowTypes(object):
    SIMULCAST = 'simulcasts'
    BROADCAST_DUBS = 'broadcast-dubs'
    SEARCH = 'search'
    SHOWS = 'shows'

class SortBy(object):
    TITLE = 'slug_exact'
    DATE = 'start_timestamp'

class SortOrder(object):
    ASC = 'asc'
    DESC = 'desc'

class AudioType(object):
    SUB = 'ja'
    DUB = 'en'


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Console\Command;

use Psr\Container\ContainerInterface;
use Spiral\Console\Config\ConsoleConfig;

final class UpdateCommand extends SequenceCommand
{
    protected const NAME        = 'update';
    protected const DESCRIPTION = 'Update project state';

    /**
     * @param ConsoleConfig      $config
     * @param ContainerInterface $container
     * @return int
     */
    public function perform(ConsoleConfig $config, ContainerInterface $container): int
    {
        $this->writeln("<info>Updating project state:</info>\n");

        return $this->runSequence($config->updateSequence(), $container);
    }
}


text:
package org.apache.camel.component.aws2.eventbridge.localstack;

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

import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws2.eventbridge.EventbridgeConstants;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.eventbridge.model.RemoveTargetsResponse;
import software.amazon.awssdk.services.eventbridge.model.Target;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

public class EventbridgeRemoveTargetsLocalstackTest extends Aws2EventbridgeBaseTest {

    @EndpointInject
    private ProducerTemplate template;

    @EndpointInject("mock:result")
    private MockEndpoint result;

    @Test
    public void sendIn() throws Exception {
        result.expectedMessageCount(1);

        template.send("direct:evs", new Processor() {

            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(EventbridgeConstants.RULE_NAME, "firstrule");
            }
        });

        template.send("direct:evs-targets", new Processor() {

            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(EventbridgeConstants.RULE_NAME, "firstrule");
                Target target = Target.builder().id("sqs-queue").arn("arn:aws:sqs:eu-west-1:780410022472:camel-connector-test")
                        .build();
                List<Target> targets = new ArrayList<Target>();
                targets.add(target);
                exchange.getIn().setHeader(EventbridgeConstants.TARGETS, targets);
            }
        });

        template.send("direct:evs-remove-targets", new Processor() {

            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(EventbridgeConstants.RULE_NAME, "firstrule");
                List<String> targets = new ArrayList<String>();
                targets.add("sqs-queue");
                exchange.getIn().setHeader(EventbridgeConstants.TARGETS_IDS, targets);
            }
        });
        assertMockEndpointsSatisfied();
        assertEquals(1, result.getExchanges().size());
        assertFalse(result.getExchanges().get(0).getIn().getBody(RemoveTargetsResponse.class).hasFailedEntries());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                String awsEndpoint
                        = "aws2-eventbridge://default?operation=putRule&eventPatternFile=file:src/test/resources/eventpattern.json";
                String target = "aws2-eventbridge://default?operation=putTargets";
                String removeTargets = "aws2-eventbridge://default?operation=removeTargets";
                from("direct:evs").to(awsEndpoint);
                from("direct:evs-targets").to(target);
                from("direct:evs-remove-targets").to(removeTargets).to("mock:result");
            }
        };
    }
}


text:
class MyRegistrationsController < Devise::RegistrationsController
    include Learnery::AuthenticationHelper

    before_filter :user_only,  :only => [ :edit, :index]
    before_filter :admin_only,  :only => [ :update, :destroy]
    before_filter :configure_permitted_parameters

    def sign_up_params
      params.require(:user).permit(:nickname, :email, :password, :password_confirmation)
    end
    def user_params
      params.require(:user).permit(:nickname, :email, :password, :password_confirmation, :admin)
    end

protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:nickname, :email, :password, :password_confirmation) }
    devise_parameter_sanitizer.for(:account_update) do |u|
      if  Learnery::User.can_become_admin? or ( current_user and current_user.admin? )
        u.permit(:email, :nickname, :firstname, :lastname, :password, :password_confirmation, :current_password, :admin )
      else
        u.permit(:email, :nickname, :firstname, :lastname, :password, :password_confirmation, :current_password )
      end
    end
  end
end


text:
'use strict';

/**
 * New node file
 */
var deepAssign = require('deep-assign');
//var Promise = require("bluebird");
var dbService = require('@colabo-knalledge/b-knalledge-storage-mongo');

var mockup = { fb: { authenticate: false }, db: { data: false } };
var accessId = 0;

function resSendJsonProtected(res, data) {
    // http://tobyho.com/2011/01/28/checking-types-in-javascript/
    if (data !== null && typeof data === 'object') { // http://stackoverflow.com/questions/8511281/check-if-a-variable-is-an-object-in-javascript
        res.set('Content-Type', 'application/json');
        // JSON Vulnerability Protection
        // http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/
        // https://docs.angularjs.org/api/ng/service/$http#description_security-considerations_cross-site-request-forgery-protection
        res.send(")]}',\n" + JSON.stringify(data));
    } else if (typeof data === 'string') { // http://stackoverflow.com/questions/4059147/check-if-a-variable-is-a-string
        res.send(data);
    } else {
        res.send(data);
    }
};

function isPrmNull(val){
  return val == null ||  val == '' || val == 'undefined' || val == 'null';
}

var dbConnection = dbService.DBConnect();

var KNodeModel = dbConnection.model('KNode', global.db.kNode.Schema);

// module.exports = KNodeModel; //then we can use it by: var User = require('./app/models/KNodeModel');

// curl -v -H "Content-Type: application/json" -X GET http://127.0.0.1:8888/knodes/one/551bdcda1763e3f0eb749bd4
// curl -v -H "Content-Type: application/json" -X GET http://127.0.0.1:8888/knodes/in_map/552678e69ad190a642ad461c
exports.index = function(req, res) {
    var id = req.params.searchParam;
    var id2 = req.params.searchParam2;
    var id3 = req.params.searchParam3;
    var id4 = req.params.searchParam4;
    var type = req.params.type;
    exports._index(id, id2, id3, id4, type, res, function(err, kNodes) {
        resSendJsonProtected(res, { data: kNodes, accessId: accessId, success: true });
    });
}

exports._index = function(id, id2, id3, id4, type, res, callback) {
  //TODO: fix if NULL is received for any parameter etc: https://github.com/Cha-OS/colabo/issues/341
    var found = function(err, kNodes) {
        console.log("[modules/kNode.js:index] in 'found'", kNodes);
        if (err) {
            throw err;
            var msg = JSON.stringify(err);
            if (callback) callback(err, null);
        } else {
            if (callback) callback(null, kNodes);
        }
    }

    //console.log("[modules/kNode.js:index] id: %s. id2: %s id3: %s; id4: %s", id, id2, id3, id4);
    switch (type) {
        case 'one': //by id:
            console.log("findById:\n id: %s.\n", id);
            KNodeModel.findById(id, found);
            break;
        case 'in_map': //all nodes in specific map
            console.log("find:\n mapId: %s.\n", id);
            KNodeModel.find({ 'mapId': id }, found);
            break;
        case 'in_map_of_type': //all nodes of particular type in specific map
            //hack: id2 = id2 + '.sdg';
            console.log("find: mapId: %s, type: %s", id, id2);
            KNodeModel.find({ $and: [{ mapId: id }, { type: id2 }] }, found);
            break;
        case 'in_map_of_type_for_user': //all nodes of particular type in specific map for that user
            console.log("find 'in_map_of_type_for_user': mapId: %s, type: %s, iAmId: %s", id, id2, id3);
            if(isPrmNull(id) || isPrmNull(id2) || isPrmNull(id3)){
              console.log('unallowed parameter');
              resSendJsonProtected(res, { data: [], accessId: accessId, message: 'unallowed parameter', success: false });
            }
            else{
              //  console.log('all parameters allowed');
                KNodeModel.find({ $and: [{ mapId: id }, { type: id2 }, { iAmId: id3 }] }, found);
            }
            //hack: id2 = id2 + '.sdg';

            break;
        case 'in_content_data':
            console.log("find: in_content_data:: name: %s, value: %s", id, id2);
            var searchObj = {};
            searchObj['dataContent.' + id] = id2;
            KNodeModel.find(searchObj, found);
            //KNodeModel.find({ 'dataContent.phoneNo': "+385989813852" }, found);
            break;
        case 'in_map_of_type_and_content_data':
            console.log("find: in_map_of_type_and_content_data: map: %s, type: %s, contentDataPath: %s, data: %s", id, id2, id3, id4);
            if(isPrmNull(id) || isPrmNull(id2) || isPrmNull(id3)  || isPrmNull(id4)){
              console.log('unallowed parameter');
              resSendJsonProtected(res, { data: [], accessId: accessId, message: 'unallowed parameter', success: false });
            }
            else{
                //console.log('all parameters allowed');

                var searchObj1 = {};
                //searchObj1[id3] = id4;
                searchObj1['dataContent.' + id3] = parseInt(id4);
                //'dataContent.dialoGameReponse.playRound'
              //  searchObj1 = { id3 : parseInt(id4) }
                // KNodeModel.find(searchObj, found);
                var searchObj = { $and: [{ mapId: id }, { type: id2 }, searchObj1 ] };
                console.log('searchObj:', searchObj);
                KNodeModel.find(searchObj, found);
            }
            break;
        case 'max_val':
            //TODO: make it to work for any parameter instead of the fixed one 'dataContent.humanID':
            console.log("find: max_val: name: %s", id);
            //KNodeModel.findOne().where({id: 1}).sort('-LAST_MOD').exec(function(err, doc)
            KNodeModel.findOne().sort('-dataContent.humanID').exec(function(err, doc) {
                if (err) {
                    console.console.error('max_val:error', err);
                    throw err;
                } else {
                    if (doc) {
                        //var max = doc.LAST_MOD;
                        console.log("find: max_val - found:", doc.dataContent.humanID);
                        found(err, doc.dataContent.humanID);
                    } else {
                        console.log("find: max_val - not found, returning null");
                        found(err, null);
                    }
                }

            });
            KNodeModel.find().sort({ id: -1 }).limit(1)
            break;
        case 'id_in':
          console.log("_index ::find 'id_in': ids: %s", id);
          var ids = id.split(',');
          console.log('ids',ids);

          //mongoose.Types.ObjectId('4ed3ede8844f0f351100000c')
          KNodeModel.find({ '_id': { $in: ids} }, found);
          break;
        default:
            console.log("[modules/kNode.js:index] unsuported req.params.type: %s", type);
            resSendJsonProtected(res, { data: [], accessId: accessId, message: 'unsuported req type \'' + type + '\'', success: false });
    }
}

// curl -v -H "Content-Type: application/json" -X POST -d '{"_id":"5548038779743f2504b8941f", "mapId":"5548038779743f2504b89420", "name":"Collective Intelligence", "iAmId":5, "visual": {"isOpen": true}}' http://127.0.0.1:8888/knodes
// curl -v -H "Content-Type: application/json" -X POST -d '{"name":"Hello World Pl", "iAmId":5, "visual": {"isOpen": true}}' http://127.0.0.1:8888/knodes
// curl -v -H "Content-Type: application/json" -X POST -d '{"_id":"551bdcda1763e3f0eb749bd4", "name":"Hello World ID", "iAmId":5, "visual": {"isOpen": true}}' http://127.0.0.1:8888/knodes
exports.create = function(req, res) {
    console.log("[modules/kNode.js:create] req.body: %s", JSON.stringify(req.body));

    var data = req.body;

    exports._create(data, function(knode, err) {
        if (err) throw err;
        console.log("[modules/KNode.js:create] id:%s, knode data: %s", knode._id, JSON.stringify(knode));
        resSendJsonProtected(res, { success: true, data: knode, accessId: accessId });
    });
}

exports._create = function(data, callback) {
    console.log("[modules/kNode.js:_create] data: ", data);
    try { //TODO: to catch errors when unpropriate data is sent for creation, including missing or inapropriate reference keys (iAmId, mapId), etc that are uncaught so far:
        //console.log("Before create data: %s", data.toString());
        var knode = new KNodeModel(data);
        //console.log("After create data: %s", data.toString());

        knode.save(function(err) {
            console.log('knode.save', err);
            if (err) throw err;
            if (callback) callback(knode, err);
        });
    } catch (ex) {
        console.log("create exception: %s", ex);
    }
}

// curl -v -H "Content-Type: application/json" -X PUT -d '{"name": "Hello World Pt23", "iAmId": 5, "visual": {"isOpen": false}}' http://127.0.0.1:8888/knodes/one/55266618cce5af993fe8675f
exports.update = function(req, res) {
    //console.log("[modules/KNode.js:update] req.body: %s", JSON.stringify(req.body));

    var data = req.body;
    var id = req.params.searchParam;
    var actionType = req.params.actionType;

    exports._update(data, id, actionType, function(err, old_data) {
        resSendJsonProtected(res, { success: true, data: old_data, accessId: accessId });
    });
}

exports._update = function(data, id, actionType, callback) {

    /* here, we started logics if RIMA-whats are integrated in kNode.dataContent.rima.whats and
    some of them are newly created on frontend so should be first created in whatAmI collection.
    But now we do this logic on frontend, so this code is just for possible usage in other usecases (btw, this code is not finished, just started)

    if((knode.dataContent !== null && typeof knode.dataContent !== 'undefined') &&  (knode.dataContent.rima !== null && typeof knode.dataContent.rima !== 'undefined') && (knode.dataContent.rima.whats !== null && typeof knode.dataContent.rima.whats !== 'undefined'){
    	for(var i in kNode.dataContent.rima.whats){
    		var what = kNode.dataContent.rima.whats[i];
    		if(typeof what !== 'string'){ //it is newly created RIMA-what
    			//console.log('howAmI:' + JSON.stringify(data));
    			WhatAmIModel.findOneByName(what.name, function(err, whatAmI){ // Nevertheless, we check, for its existence:
    				if (err) throw err;
    				if(whatAmI === null || typeof whatAmI === 'undefined'){
    					console.log("whatAmI '%s' not found", what.name);
    					var  whatAmI = new WhatAmIModel({name:what.name});
    					whatAmI.save(function (err) {
    						if (err) return handleError(err);
    						//console.log("whatAmI._id: "+whatAmI._id);
    						knode.whatAmI = whatAmI._id;
    						save(knode);
    					});
    				}
    				else{
    					console.log("whatAmI '%s' is found", whatAmIName);
    					//console.log('findByName:: whatAmI: ' + JSON.stringify(whatAmI));
    					knode.whatAmI = whatAmI._id;
    					save(knode);
    				}
    			});
    		}else{ //it is whatAmi._id. we don't have anything to do:
    			console.log("it is whatAmi._id: " + what);
    		}
    	}
    }
    else
    {
    	save(knode);
    }
    $q.all([nodes.$promise, edges.$promise])
    				.then(nodesEdgesReceived.bind(this));
    */

    /* this is wrong because it creates default-values populated object (including id) first and then populate it with paremeter object:
     * var knode = new KNodeModel(req.body);
     */
    console.log("[modules/KNode.js:update/%s/] id : %s", actionType, id);
    console.log("[modules/KNode.js] actionType = ", actionType);
    console.log("[modules/KNode.js:update] data, : %s", JSON.stringify(data));
    // console.log("[modules/KNode.js:update] knode.toObject(), : %s", JSON.stringify(knode.toObject());
    delete data._id;
    //TODO: check this: multi (boolean) whether multiple documents should be updated (false)
    //TODO: fix: numberAffected vraca 0, a raw vraca undefined. pitanje je da li su ispravni parametri callback f-je
    // KNodeModel.findByIdAndUpdate(id , data, { /* multi: true */ }, function (err, numberAffected, raw) {
    // 	  if (err) throw err;
    // 	  console.log('The number of updated documents was %d', numberAffected);
    // 	  console.log('The raw response from Mongo was ', raw);
    // 	  resSendJsonProtected(res, {success: true, data: data, accessId : accessId});
    // });

    var found = function found(err, old_data) {
        if (err) {
            throw err;
            var msg = JSON.stringify(err);
            if (callback) callback(err);
        } else {
            //console.log('old_data', JSON.stringify(old_data));

            //TODO: required because deepAssign could only work on shallow level, so overwriting votes,
            //when it received a deeper object like `{"dataContent":{"ibis":{"votes":{"556760847125996dc1a4a21c":3}}}};`
            old_data = JSON.parse(JSON.stringify(old_data));
            // console.log('old_data', JSON.stringify(old_data));
            // console.log('patch data', JSON.stringify(data));
            switch (actionType) {
                case 'DATA_CONTENT_RIMA_WHATS_DELETING':
                    //TODO: this is very specific treatment (almost a HACK) - we need more general action:
                    // this could be other approach: http://stackoverflow.com/questions/5059951/deleting-js-object-properties-a-few-levels-deep
                    var whatId = data.dataContent.rima.whats._id;
                    //console.log('whatId: ', whatId);
                    if (old_data.dataContent && old_data.dataContent.rima && old_data.dataContent.rima.whats) {
                        var whats = old_data.dataContent.rima.whats;
                        for (var i = 0; i < whats.length; i++) {
                            if (whats[i]._id === whatId) {
                                whats.splice(i, 1);
                            }
                        }
                    }
                    break;
                case 'DATA_CONTENT_RIMA_WHATS_ADDING':
                    if (!old_data.dataContent) {
                        old_data.dataContent = { rima: { whats: [] } };
                    } else {
                        if (!old_data.dataContent.rima) {
                            old_data.dataContent.rima = { whats: [] };
                        } else {
                            if (!old_data.dataContent.rima.whats) { old_data.dataContent.rima.whats = []; }
                        }
                    }
                    old_data.dataContent.rima.whats.push(data.dataContent.rima.whats[0]);
                    break;
                default:
                    deepAssign(old_data, data);
            }

            console.log('after patching', JSON.stringify(old_data));

            /* test
            let a = {"_id":"555d9b8fca6170de0e069f5f","name":"helo 3","type":"type_knowledge",
            "mapId":"555d9774b53940a00d4e72b7",
            "iAmId":"55268521fb9a901e442172f8","ideaId":0,"__v":0,
            "dataContent":{"ibis":{"votes":{"556760847125996dc1a4a241":2}}},
            "updatedAt":"2016-05-08T23:02:48.125Z","createdAt":"2015-05-21T08:47:11.449Z",
            "visual":{"yM":518,"xM":251.5,"isOpen":false},"isPublic":true,"version":1,"activeVersion":1};
            console.log('a before patch', JSON.stringify(a));
            let d = {"dataContent":{"ibis":{"votes":{"556760847125996dc1a4a21c":3}}}};
            deepAssign(a,d);
            console.log('a after patch', JSON.stringify(a)); */

            KNodeModel.update({ _id: id }, old_data, function(err, raw) {
                if (err) throw err;
                //console.log('The raw response from Mongo was ', raw);
                data._id = id; //TODO: when we completly transfer to differential updates we won't need this
                if (callback) callback(err, old_data);
            });
        }
    }

    data.updatedAt = new Date(); //TODO: workaround for hook "schema.pre('update',...)" not working
    KNodeModel.findById(id, found);
}

// curl -v -H "Content-Type: application/json" -X DELETE http://127.0.0.1:8888/knodes/one/551bdcda1763e3f0eb749bd4
// for type `one`: In the server's response, the ServerData.data is equal to the _id of the deleted VO.  ServerData.data will be equal to null, if there is no data we intended to delete. In both cases `ServerData.success` will be eq `true`
exports.destroy = function(req, res) {
    //TODO: should we destroy edges connected to this node? or is it done automatically? or error is risen?
    var type = req.params.type;
    console.log('kNode::destroy::req.params', req.params);
    var searchParam = req.params.searchParam;
    console.log("[modules/KNode.js:destroy] searchParam:%s, type:%s, req.body: %s", searchParam, type, JSON.stringify(req.body));

    switch (type) {
        case 'one':
            exports._destroyOne(searchParam, function(err, removedItem) {
                //console.log("[modules/kNode.js:destroy] removedItem:" + JSON.stringify(removedItem));
                var data = removedItem ? removedItem._id : null; // if removedItem is null it means that there is no data we intended to delete
                console.log("[modules/kNode.js:destroy] data:" + JSON.stringify(data));
                resSendJsonProtected(res, { success: true, data: data, accessId: accessId });
            });
            break;
        case 'in-map': //all nodes in the map
            exports._destroyInMap(searchParam, function(err) {
                var data = { id: searchParam };
                console.log("[modules/kNode.js:destroy] data:" + JSON.stringify(data));
                resSendJsonProtected(res, { success: true, data: data, accessId: accessId });
            });
            break;
            // TODO: this currently delete all nodes that belongs to the provided mapId
        case 'by-modification-source': // by source (manual/computer) of modification
            exports._destroyByModificationSource(searchParam, function(err) {
                var data = { mapId: searchParam };
                console.log("[modules/kNode.js:destroy] data:" + JSON.stringify(data));
                resSendJsonProtected(res, { success: true, data: data, accessId: accessId });
            });
            break;
        case 'by-type-n-user': // by type and user
            //TODO: we must also filter by `mapId` but so far we are sending only 2 parameters!
            var node_type = req.params.actionType;
            var iAmId = req.params.searchParam;
            console.log("[modules/kNode.js:destroy] deleting all Nodes of type %s by user %s", node_type, iAmId);
            exports._destroyByTypenUser(node_type, iAmId, function(err) {
                var data = { iAmId: iAmId };
                console.log("[modules/kNode.js:destroy] data:" + JSON.stringify(data));
                resSendJsonProtected(res, { success: true, data: data, accessId: accessId });
            });
            break;
    }
};

exports._destroyOne = function(searchParam, callback) {
    KNodeModel.findByIdAndRemove(searchParam, function(err, countOfRemoved) {
        if (err) {
            console.log("[modules/kNode.js:destroy] error:" + err);
            throw err;
        }
        if (callback) callback(err, countOfRemoved);
    });
}

//all nodes in the map
exports._destroyInMap = function(searchParam, callback) {
    console.log("[modules/kNode.js:destroy] deleting nodes in map %s", searchParam);
    KNodeModel.remove({ 'mapId': searchParam }, function(err) {
        if (err) {
            console.log("[modules/kNode.js:destroy] error:" + err);
            throw err;
        }
        if (callback) callback(err);
    });
}

// TODO: this currently delete all nodes that belongs to the provided mapId
// by source (manual/computer) of modification
exports._destroyByModificationSource = function(searchParam, callback) {
    console.log("[modules/kNode.js:destroy] deleting nodes in map %s", searchParam);
    KNodeModel.remove({ 'mapId': searchParam }, function(err) {
        if (err) {
            console.log("[modules/kNode.js:destroy] error:" + err);
            throw err;
        }
        if (callback) callback(err);
    });
}

//TODO: we must also filter by `mapId` but so far we are sending only 2 parameters!
exports._destroyByTypenUser = function(type, iAmId, callback) {
    console.log("[modules/kNode.js:_destroyByTypenUser] deleting all Nodes of type %s by user %s", type, iAmId);

    KNodeModel.remove({ $and: [{ 'type': type }, { 'iAmId': iAmId }] }, function(err) {
        if (err) {
            console.log("[modules/kNode.js:destroy] error:" + err);
            throw err;
        }
        if (callback) callback(err);
    });
}


text:
@interface OFHttpCredentialsCreateController : OFAccountSetupBaseController
@end


text:
/*
 * Project: interviewtask-react
 * File: client/routes/App.js
 *
 * Author: Alexander Missa
 *
 * Description:
 */

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as actionCreators from './../actions/actionCreators';
import RectanglesPlaceholder from './views/Rectangles/RectanglesPlaceholder';

// actions mapping
function mapStateToProps(state) {
  return {
    rectangles: state.rectangles
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

// connect actual data
const App = connect(mapStateToProps, mapDispatchToProps)(RectanglesPlaceholder);
export default App;


text:
export const BUFFER = Symbol('buffer');
const TYPE = Symbol('type');

export default class Blob {
	constructor() {
		this[TYPE] = '';

		const blobParts = arguments[0];
		const options = arguments[1];

		const buffers = [];

		if (blobParts) {
			const a = blobParts;
			const length = Number(a.length);
			for (let i = 0; i < length; i++) {
				const element = a[i];
				let buffer;
				if (element instanceof Buffer) {
					buffer = element;
				} else if (ArrayBuffer.isView(element)) {
					buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
				} else if (element instanceof ArrayBuffer) {
					buffer = Buffer.from(element);
				} else if (element instanceof Blob) {
					buffer = element[BUFFER];
				} else {
					buffer = Buffer.from(typeof element === 'string' ? element : String(element));
				}
				buffers.push(buffer);
			}
		}

		this[BUFFER] = Buffer.concat(buffers);

		let type = options && options.type !== undefined && String(options.type).toLowerCase();
		if (type && !/[^\u0020-\u007E]/.test(type)) {
			this[TYPE] = type;
		}
	}
	get size() {
		return this[BUFFER].length;
	}
	get type() {
		return this[TYPE];
	}
	slice() {
		const size = this.size;

		const start = arguments[0];
		const end = arguments[1];
		let relativeStart, relativeEnd;
		if (start === undefined) {
			relativeStart = 0;
		} else if (start < 0) {
			relativeStart = Math.max(size + start, 0);
		} else {
			relativeStart = Math.min(start, size);
		}
		if (end === undefined) {
			relativeEnd = size;
		} else if (end < 0) {
			relativeEnd = Math.max(size + end, 0);
		} else {
			relativeEnd = Math.min(end, size);
		}
		const span = Math.max(relativeEnd - relativeStart, 0);

		const buffer = this[BUFFER];
		const slicedBuffer = buffer.slice(
			relativeStart,
			relativeStart + span
		);
		const blob = new Blob([], { type: arguments[2] });
		blob[BUFFER] = slicedBuffer;
		return blob;
	}
}

Object.defineProperties(Blob.prototype, {
	size: { enumerable: true },
	type: { enumerable: true },
	slice: { enumerable: true }
});

Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
	value: 'Blob',
	writable: false,
	enumerable: false,
	configurable: true
});


text:
import { createStore, applyMiddleware, compose } from 'redux';
import rootReducer from '../reducers';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
import promiseMiddleware from '../promiseMiddleware';
import callAPIMiddleware from '../callAPIMiddleware';

/**
 * Entirely optional, this tiny library adds some functionality to
 * your DevTools, by logging actions/state to your console. Used in
 * conjunction with your standard DevTools monitor gives you great
 * flexibility!
 */
const logger = createLogger({
  predicate: (/* getState, action */) => true, // log all actions
  level: `info`,
  duration: true,
  actionTransformer: (action) => {
    return {
      ...action,
      type: String(action.type || action.types)
    };
  }
});

const finalCreateStore = compose(
  // Middleware you want to use in development:
  applyMiddleware(logger, thunk, promiseMiddleware,
    callAPIMiddleware
  ),

  // Setup dev tools - start
  // vanilla Redux DevTools
  // DevTools.instrument();

  // zalmoxisus Redux DevTools Extension
  typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f
  // Setup dev tools - end
)(createStore);

module.exports = function configureStore(initialState) {
  const store = finalCreateStore(rootReducer, initialState);

  // Hot reload reducers (requires Webpack or Browserify HMR to be enabled)
  if (module.hot) {
    module.hot.accept('../reducers', () =>
      store.replaceReducer(require('../reducers'))
    );
  }

  return store;
};


text:
using System.Linq;

namespace Eventualize.Interfaces.Domain
{
    public interface IEventData
    {

    }
}


text:
void ExpressionFunCall::setFunction(Expression *e) {
	this->function = e;
}

void ExpressionFunCall::addExpression(Expression *e) {
	argList.push_front(e);
}

string ExpressionFunCall::toString(void) {
	string s = function->toString() + " ";

	list<Expression *>::iterator it;
	for(it = argList.begin(); it != argList.end(); it++) {
		s += (*it)->toString();
		s += " ";
	}
	return s;
}


text:
layout: page
title: About this blog
excerpt: "Data Science: Best Approaches Review."
modified: 2016-04-26T23:44:38.564948-04:00
image:
  feature: bar_color_2.jpg
  credit: Sean Davis
  creditlink: https://www.flickr.com/photos/seandavis/
---

Data Science bar is a place where you can get a shot of useful information on data science, data analytics and machine learning. We are planning to review interesting data science competitions, such as Kaggle, explore different exciting datasets and problems. We intend this blog to be a dive into approaches and techniques that work best for different types of problems. If you have an interesting problem to solve, feel free to  contact us.

 Give me a "drink"


text:
set -o errexit
set -o pipefail
set -o nounset

celery -A awesome_app.taskapp beat -l INFO


text:
'use strict';

module.exports = function(io, socket){
	io.emit('chatMessage', {
		type: 'status',
		text: 'connected',
		created: Date.now()
	});

	socket.on('chatMessage', function(message) {
		message.type = 'message';
		message.created = Date.now();
		io.emit('chatMessage', message);
	});

	socket.on('disconnect', function(){
		io.emit('chatMessage', {
			type: 'status',
			text: 'disconnected',
			created: Date.now()
		});
	});
};


text:
module Azure::Dns::Mgmt::V2016_04_01
  module Models
    #
    # Defines values for OperationStatus
    #
    module OperationStatus
      InProgress = "InProgress"
      Succeeded = "Succeeded"
      Failed = "Failed"
    end
  end
end


text:
from __future__ import unicode_literals

from django.db import models, migrations
import autoslug.fields
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Page',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=255)),
                ('slug', autoslug.fields.AutoSlugField(populate_from=b'title', unique_with=[b'id'], editable=False, blank=True)),
                ('visible', models.BooleanField(default=False)),
                ('text', models.TextField()),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('modified', models.DateTimeField(auto_now=True)),
                ('views', models.IntegerField(default=0)),
                ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL, blank=True)),
            ],
        ),
    ]


text:
module Rules.Library (
    buildPackageLibrary, buildPackageGhciLibrary, buildDynamicLib
    ) where

import Hadrian.Haskell.Cabal
import qualified System.Directory as IO

import Base
import Context
import Expression hiding (way, package)
import Flavour
import GHC
import Oracles.ModuleFiles
import Oracles.PackageData
import Oracles.Setting
import Rules.Gmp
import Settings
import Target
import Utilities

libraryObjects :: Context -> Action [FilePath]
libraryObjects context@Context{..} = do
    hsObjs   <- hsObjects    context
    noHsObjs <- nonHsObjects context

    -- This will create split objects if required (we don't track them
    -- explicitly as this would needlessly bloat the Shake database).
    need $ noHsObjs ++ hsObjs

    split <- interpretInContext context =<< splitObjects <$> flavour
    let getSplitObjs = concatForM hsObjs $ \obj -> do
            let dir = dropExtension obj ++ "_" ++ osuf way ++ "_split"
            contents <- liftIO $ IO.getDirectoryContents dir
            return . map (dir -/-) $ filter (not . all (== '.')) contents

    (noHsObjs ++) <$> if split then getSplitObjs else return hsObjs

buildDynamicLib :: Context -> Rules ()
buildDynamicLib context@Context{..} = do
    let libPrefix = "//" ++ contextDir context -/- "libHS" ++ pkgName package
    -- OS X
    libPrefix ++ "*.dylib" %> buildDynamicLibUnix
    -- Linux
    libPrefix ++ "*.so"    %> buildDynamicLibUnix
    -- TODO: Windows
  where
    buildDynamicLibUnix lib = do
        deps <- contextDependencies context
        need =<< mapM pkgLibraryFile deps
        objs <- libraryObjects context
        build $ target context (Ghc LinkHs stage) objs [lib]

buildPackageLibrary :: Context -> Rules ()
buildPackageLibrary context@Context {..} = do
    let libPrefix = "//" ++ contextDir context -/- "libHS" ++ pkgName package
    libPrefix ++ "*" ++ (waySuffix way <.> "a") %%> \a -> do
        objs <- libraryObjects context
        asuf <- libsuf way
        let isLib0 = ("//*-0" ++ asuf) ?== a
        removeFile a
        if isLib0 then build $ target context (Ar stage) []   [a] -- TODO: Scan for dlls
                  else build $ target context (Ar stage) objs [a]

        synopsis <- pkgSynopsis package
        unless isLib0 . putSuccess $ renderLibrary
            (quote (pkgName package) ++ " (" ++ show stage ++ ", way "
            ++ show way ++ ").") a synopsis

buildPackageGhciLibrary :: Context -> Rules ()
buildPackageGhciLibrary context@Context {..} = priority 2 $ do
    let libPrefix = "//" ++ contextDir context -/- "HS" ++ pkgName package
    libPrefix ++ "*" ++ (waySuffix way <.> "o") %> \obj -> do
        objs <- allObjects context
        need objs
        build $ target context Ld objs [obj]

allObjects :: Context -> Action [FilePath]
allObjects context = (++) <$> nonHsObjects context <*> hsObjects context

nonHsObjects :: Context -> Action [FilePath]
nonHsObjects context = do
    path    <- buildPath context
    cObjs   <- cObjects context
    cmmSrcs <- pkgDataList (CmmSrcs path)
    cmmObjs <- mapM (objectPath context) cmmSrcs
    eObjs   <- extraObjects context
    return $ cObjs ++ cmmObjs ++ eObjs

cObjects :: Context -> Action [FilePath]
cObjects context = do
    path <- buildPath context
    srcs <- pkgDataList (CSrcs path)
    objs <- mapM (objectPath context) srcs
    return $ if way context == threaded
        then objs
        else filter ((`notElem` ["Evac_thr", "Scav_thr"]) . takeBaseName) objs

extraObjects :: Context -> Action [FilePath]
extraObjects context
    | package context == integerGmp = do
        gmpPath <- gmpBuildPath
        need [gmpPath -/- gmpLibraryH]
        map unifyPath <$> getDirectoryFiles "" [gmpPath -/- gmpObjectsDir -/- "*.o"]
    | otherwise         = return []