text:
/*
 * Public API Surface of angular-l10n
 */

// Models
export * from './lib/models/types';
export * from './lib/models/l10n-config';
export * from './lib/models/l10n-async-pipe';
export * from './lib/models/l10n-directive';
export * from './lib/models/utils';
// Services
export * from './lib/services/l10n-resolver';
// L10nTranslationModule
export * from './lib/services/l10n-translation.service';
export * from './lib/services/l10n-cache';
export { L10nStorage } from './lib/services/l10n-storage';
export { L10nUserLanguage } from './lib/services/l10n-user-language';
export { L10nTranslationFallback } from './lib/services/l10n-translation-fallback';
export { L10nTranslationLoader } from './lib/services/l10n-translation-loader';
export { L10nTranslationHandler } from './lib/services/l10n-translation-handler';
export { L10nMissingTranslationHandler } from './lib/services/l10n-missing-translation-handler';
export { L10nLoader } from './lib/services/l10n-loader';
export * from './lib/pipes/l10n-translate.pipe';
export * from './lib/directives/l10n-translate.directive';
export * from './lib/modules/l10n-translation.module';
// L10nIntlModule
export * from './lib/services/l10n-intl.service';
export * from './lib/pipes/l10n-date.pipe';
export * from './lib/pipes/l10n-number.pipe';
export * from './lib/pipes/l10n-time-ago.pipe';
export * from './lib/pipes/l10n-plural.pipe';
export * from './lib/pipes/l10n-display-names.pipe';
export * from './lib/directives/l10n-date.directive';
export * from './lib/directives/l10n-number.directive';
export * from './lib/directives/l10n-time-ago.directive';
export * from './lib/directives/l10n-plural.directive';
export * from './lib/directives/l10n-display-names.directive';
export * from './lib/modules/l10n-intl.module';
// L10nValidationModule
export * from './lib/directives/l10n-validate-number.directive';
export * from './lib/directives/l10n-validate-date.directive';
export { L10nValidation } from './lib/services/l10n-validation';
export * from './lib/modules/l10n-validation.module';
// L10nRoutingModule
export * from './lib/services/l10n-routing.service';
export * from './lib/modules/l10n-routing.module';
export { L10nLocation } from './lib/services/l10n-location';


text:
(function (tree) {

tree.Element = function (combinator, value, index) {
    this.combinator = combinator instanceof tree.Combinator ?
                      combinator : new(tree.Combinator)(combinator);

    if (typeof(value) === 'string') {
        this.value = value.trim();
    } else if (value) {
        this.value = value;
    } else {
        this.value = "";
    }
    this.index = index;
};
tree.Element.prototype = {
    type: "Element",
    accept: function (visitor) {
        this.combinator = visitor.visit(this.combinator);
        this.value = visitor.visit(this.value);
    },
    eval: function (env) {
        return new(tree.Element)(this.combinator,
                                 this.value.eval ? this.value.eval(env) : this.value,
                                 this.index);
    },
    toCSS: function (env) {
        var value = (this.value.toCSS ? this.value.toCSS(env) : this.value);
        if (value == '' && this.combinator.value.charAt(0) == '&') {
            return '';
        } else {
            return this.combinator.toCSS(env || {}) + value;
        }
    }
};

tree.Attribute = function (key, op, value) {
    this.key = key;
    this.op = op;
    this.value = value;
};
tree.Attribute.prototype = {
    type: "Attribute",
    accept: function (visitor) {
        this.value = visitor.visit(this.value);
    },
    eval: function (env) {
        return new(tree.Attribute)(this.key.eval ? this.key.eval(env) : this.key,
            this.op, (this.value && this.value.eval) ? this.value.eval(env) : this.value);
    },
    toCSS: function (env) {
        var value = this.key.toCSS ? this.key.toCSS(env) : this.key;

        if (this.op) {
            value += this.op;
            value += (this.value.toCSS ? this.value.toCSS(env) : this.value);
        }

        return '[' + value + ']';
    }
};

tree.Combinator = function (value) {
    if (value === ' ') {
        this.value = ' ';
    } else {
        this.value = value ? value.trim() : "";
    }
};
tree.Combinator.prototype = {
    type: "Combinator",
    toCSS: function (env) {
        return {
            ''  : '',
            ' ' : ' ',
            ':' : ' :',
            '+' : env.compress ? '+' : ' + ',
            '~' : env.compress ? '~' : ' ~ ',
            '>' : env.compress ? '>' : ' > ',
            '|' : env.compress ? '|' : ' | '
        }[this.value];
    }
};

})(require('../tree'));

redpajama_set_name: RedPajamaGithub


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

/**
 * @name: User Model
 * @author: Somkit T.
 */
class User_model extends CI_Model
{

    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    // Check existing of the user given email
    public function is_exist($data){
        $this->db->where($data);
        $query = $this->db->get('user');
        if($query->num_rows() > 0){
            return true;
        } else {
            return false;
        }
    }

    // get u_id from email
    public function get_uid($data) {
        return $this->db->select('id')
                ->get_where('user', $data)
                ->row()
                ->id;
    }

    // Add new user by email
    public function add_new($data) {
        // Check urgently field
        //$this->db->set('due_date', $due_date, FALSE);
        $this->db->insert("user", $data);
        return $this->db->insert_id();
    }

    // list all currently active project
    /*
    public function list_all_active() {
        $this->db->from('project');
        $this->db->where('active', 1);
        $this->db->order_by('id', 'desc');
        $query = $this->db->get();
        return $query->result();
    }

    // change state of this ticket
    public function change_state($ticket_id, $state){
        $this->db->set('state', $state);
        $this->db->where('id', $ticket_id);
        return ($this->db->update('ticket')) ? TRUE : FALSE;
    }
*/
    // close connection
    function __destruct() {
        $this->db->close();
    }
}


text:
package com.google.idea.blaze.java.run.hotswap;

import static com.google.common.collect.ImmutableList.toImmutableList;

import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.idea.blaze.base.command.BlazeCommandName;
import com.google.idea.blaze.base.command.BlazeInvocationContext;
import com.google.idea.blaze.base.command.buildresult.BlazeArtifact;
import com.google.idea.blaze.base.command.buildresult.BuildResultHelper;
import com.google.idea.blaze.base.command.buildresult.BuildResultHelper.GetArtifactsException;
import com.google.idea.blaze.base.command.buildresult.BuildResultHelperProvider;
import com.google.idea.blaze.base.model.BlazeProjectData;
import com.google.idea.blaze.base.run.BlazeBeforeRunCommandHelper;
import com.google.idea.blaze.base.run.BlazeCommandRunConfiguration;
import com.google.idea.blaze.base.run.ExecutorType;
import com.google.idea.blaze.base.run.confighandler.BlazeCommandRunConfigurationRunner;
import com.google.idea.blaze.base.sync.aspects.BuildResult;
import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager;
import com.google.idea.blaze.base.util.SaveUtil;
import com.intellij.debugger.impl.HotSwapProgress;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.RunCanceledByUserException;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import java.io.File;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;

/** Builds a .class file manifest to support hotswapping. */
public class ClassFileManifestBuilder {

  /** Used to associate data with an {@link ExecutionEnvironment}. */
  private static final Key<AtomicReference<ClassFileManifest>> MANIFEST_KEY =
      Key.create("blaze.debug.class.manifest");

  /** Called when initializing our run profile state, to support hotswapping. */
  public static void initState(ExecutionEnvironment env) {
    if (!HotSwapUtils.canHotSwap(env)) {
      return;
    }
    if (env.getCopyableUserData(MANIFEST_KEY) == null) {
      env.putCopyableUserData(MANIFEST_KEY, new AtomicReference<>());
    }
  }

  @Nullable
  static ClassFileManifest getManifest(ExecutionEnvironment env) {
    AtomicReference<ClassFileManifest> ref = env.getCopyableUserData(MANIFEST_KEY);
    return ref != null ? ref.get() : null;
  }

  /**
   * Builds a .class file manifest, then diffs against any previously calculated manifest for this
   * debugging session.
   *
   * @return null if no diff is available (either no manifest could be calculated, or no previously
   *     calculated manifest is available.
   */
  @Nullable
  public static ClassFileManifest.Diff buildManifest(
      ExecutionEnvironment env, @Nullable HotSwapProgress progress) throws ExecutionException {
    if (!HotSwapUtils.canHotSwap(env)) {
      return null;
    }
    BlazeCommandRunConfiguration configuration =
        BlazeCommandRunConfigurationRunner.getConfiguration(env);
    Project project = configuration.getProject();
    BlazeProjectData projectData =
        BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
    if (projectData == null) {
      throw new ExecutionException("Not synced yet; please sync project");
    }
    JavaClasspathAspectStrategy aspectStrategy =
        JavaClasspathAspectStrategy.findStrategy(projectData.getBlazeVersionData());
    if (aspectStrategy == null) {
      return null;
    }

    SaveUtil.saveAllFiles();
    // Explicitly create a local build helper because the logic below assumes the JARs to be present
    // locally
    try (BuildResultHelper buildResultHelper =
        BuildResultHelperProvider.createForLocalBuild(project)) {

      ListenableFuture<BuildResult> buildOperation =
          BlazeBeforeRunCommandHelper.runBlazeCommand(
              BlazeCommandName.BUILD,
              configuration,
              buildResultHelper,
              aspectStrategy.getBuildFlags(),
              ImmutableList.of(),
              BlazeInvocationContext.runConfigContext(
                  ExecutorType.fromExecutor(env.getExecutor()), configuration.getType(), true),
              "Building debug binary");

      if (progress != null) {
        progress.setCancelWorker(() -> buildOperation.cancel(true));
      }
      try {
        BuildResult result = buildOperation.get();
        if (result.status != BuildResult.Status.SUCCESS) {
          throw new ExecutionException("Blaze failure building debug binary");
        }
      } catch (InterruptedException | CancellationException e) {
        buildOperation.cancel(true);
        throw new RunCanceledByUserException();
      } catch (java.util.concurrent.ExecutionException e) {
        throw new ExecutionException(e);
      }
      ImmutableList<File> jars;
      try {
        jars =
            BlazeArtifact.getLocalFiles(
                    buildResultHelper.getArtifactsForOutputGroup(
                        JavaClasspathAspectStrategy.OUTPUT_GROUP, file -> true))
                .stream()
                .filter(f -> f.getName().endsWith(".jar"))
                .collect(toImmutableList());
      } catch (GetArtifactsException e) {
        throw new ExecutionException("Failed to get debug binary: " + e.getMessage());
      }
      ClassFileManifest oldManifest = getManifest(env);
      ClassFileManifest newManifest = ClassFileManifest.build(jars, oldManifest);
      env.getCopyableUserData(MANIFEST_KEY).set(newManifest);
      return oldManifest != null
          ? ClassFileManifest.modifiedClasses(oldManifest, newManifest)
          : null;
    }
  }
}


text:
// Copyright (c) 2017 Brian Barto
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GPL License. See LICENSE for more details.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <time.h>
#include <sys/stat.h>

#include "main.h"
#include "modules/keyfile.h"
#include "modules/base64.h"

/*
 * MODULE DESCRIPTION
 *
 * The keyfile module manages the opening, closing, creating, and
 * reading of a key file. Creating the key file also includes creating
 * the key itself.
 */

#define MIRROR_DENSITY   20

// Static variables
static FILE *keyFile;

/*
 * The keyfile_init() function initializes any static variables.
 */
void keyfile_init(void) {
	keyFile = NULL;
}

/*
 * The keyfile_open() function attempts to open the keyfile specified in
 * the keyFileName parameter. If keyFileName does not contain an absolute
 * path, it will use $HOME/DEFAULT_KEY_PATH as the path to the directory
 * that contains the specified key file.
 *
 * If the key file is not found and the autoCreate flag is set, it will
 * call the keyfile_create() function to attempt to create a new key file
 * at the determined path.
 *
 * Upon any errors, zero is returned.
 */
int keyfile_open(char *keyFileName, int autoCreate) {
	char *homeDir              = getenv("HOME");
	char *keyFilePath          = DEFAULT_KEY_PATH;
	char *keyFilePathName;
	char *keyFileFullPathName;

	// Return if we don't have a home directory
	if (homeDir == NULL)
		return 0;

	// Check if we have an absolute path
	if (*keyFileName == '/') {

		// Assign to full path variable
		keyFileFullPathName = keyFileName;

	} else {

		// Combine default file path and name in to one string.
		keyFilePathName = malloc(strlen(keyFilePath) + strlen(keyFileName) + 1);
		sprintf(keyFilePathName, "%s%s", keyFilePath, keyFileName);

		// Build key file path
		keyFileFullPathName = malloc(strlen(keyFilePathName) + strlen(homeDir) + 2);
		sprintf(keyFileFullPathName, "%s/%s", homeDir, keyFilePathName);

		// Build key file path
		keyFileFullPathName = malloc(strlen(keyFilePathName) + strlen(homeDir) + 2);
		sprintf(keyFileFullPathName, "%s/%s", homeDir, keyFilePathName);
	}

	// Open key file
	while ((keyFile = fopen(keyFileFullPathName, "r")) == NULL) {
		if (autoCreate) {
			if (keyfile_create(keyFileFullPathName)) {
				continue;
			}
		}
		break;
	}

	// Return zero if we can't open the key file
	if (keyFile == NULL)
		return 0;

	return 1;
}

/*
 * The keyfile_create() function creates a new key file at the given path.
 * A full absolute path and name must be provided as a single character
 * string. It will attempt to create any missing directories in the path
 * if necessary.
 *
 * Upon successfully creating the key file, it will also populate the file
 * with a new randomized key.
 *
 * Upon any errors, zero is returned.
 */
int keyfile_create(char *keyFileFullPathName) {
	int i, r, c;
	int w = 0;
	struct stat sb;
	FILE *keyfile;
	FILE *urandom;
	unsigned char perimeterChars[GRID_SIZE * 4];
	base64 contents = { .index = 0 };

	// Check subdirs and create them if needed
	if (strchr(keyFileFullPathName, '/') != NULL) {
		for (i = 1; keyFileFullPathName[i] != '\0'; ++i) {
			if (keyFileFullPathName[i] == '/') {
				keyFileFullPathName[i] = '\0';
				if (stat(keyFileFullPathName, &sb) != 0)
					if (mkdir(keyFileFullPathName, 0700) == -1)
						return 0;
				keyFileFullPathName[i] = '/';
			}
		}
	}

	// Open the key file
	if ((keyfile = fopen(keyFileFullPathName, "w")) == NULL)
		return 0;

	// Open the urandom resource
	if ((urandom = fopen("/dev/urandom", "r")) == NULL)
		return 0;

	// Write mirror data to file
	for (r = 0; r < GRID_SIZE; ++r) {
		for (c = 0; c < GRID_SIZE; ++c) {

			// Randomly generate mirror char
			switch (fgetc(urandom) % MIRROR_DENSITY) {
				case 1:
					contents.decoded[contents.index++] = '/';
					break;
				case 2:
					contents.decoded[contents.index++] = '\\';
					break;
				default:
					contents.decoded[contents.index++] = ' ';
					break;
			}

			// If we have max input for the base64 encoder, encode it
			if (contents.index == BASE64_DECODED_COUNT) {
				contents = base64_encode(contents);
				fprintf(keyfile, "%c%c%c%c", contents.encoded[0], contents.encoded[1], contents.encoded[2], contents.encoded[3]);
				contents.index = 0;

				// Newline after every 72 chars (18 * 4)
				if (++w % 18 == 0)
					fprintf(keyfile, "\n");
			}
		}
	}

	// init all perimeter chars to zero
	memset(perimeterChars, 0, GRID_SIZE * 4);

	// Generate perimeter characters in random placements
	for (i = 1; i < GRID_SIZE * 4; i++) {
		r = fgetc(urandom) % (GRID_SIZE * 4);
		if (r % 2 == 0) {
			while (perimeterChars[r] > 0) {
				r = (r + 1) % (GRID_SIZE * 4);
			}
		} else {
			while (perimeterChars[r] > 0) {
				r = (r + (GRID_SIZE * 4) - 1) % (GRID_SIZE * 4);
			}
		}
		perimeterChars[r] = i;
	}

	// Close urandom resource
	fclose(urandom);

	// Encode perimeter chars to base64 and write to key file
	for (i = 0; i < GRID_SIZE * 4; ++i) {
		contents.decoded[contents.index++] = perimeterChars[i];
		if (contents.index == BASE64_DECODED_COUNT) {
			contents = base64_encode(contents);
			fprintf(keyfile, "%c%c%c%c", contents.encoded[0], contents.encoded[1], contents.encoded[2], contents.encoded[3]);
			contents.index = 0;

			// Newline after every 72 chars (18 * 4)
			if (++w % 18 == 0)
				fprintf(keyfile, "\n");
		}
	}
	if (contents.index > 0) {
		contents = base64_encode(contents);
		fprintf(keyfile, "%c%c%c%c", contents.encoded[0], contents.encoded[1], contents.encoded[2], contents.encoded[3]);

		// Newline after every 72 chars (18 * 4)
		if (++w % 18 == 0)
			fprintf(keyfile, "\n");
	}

	// Close mirror file
	fclose(keyfile);

	return 1;
}

/*
 * The keyfile_next_char() function is responsible for reading and decoding
 * the contents of the key file. It returns a single unsigned char cast
 * as an integer for each call.
 */
int keyfile_next_char(void) {
	static base64 contents = { .index = BASE64_DECODED_COUNT, .error = 0 };

	if (contents.index == BASE64_DECODED_COUNT) {
		contents.index = 0;

		while (contents.index < BASE64_ENCODED_COUNT) {
			contents.encoded[contents.index] = fgetc(keyFile);
			if (contents.encoded[contents.index] == EOF)
				return EOF;
			else if (contents.encoded[contents.index] == '\n')
				continue;
			else
				++contents.index;
		}

		contents = base64_decode(contents);
		if (contents.error)
			return EOF;
		else
			contents.index = 0;
	}

	return (int)contents.decoded[contents.index++];
}

/*
 * The keyfile_close() function closes the key file pointer if it has
 * been opened.
 */
void keyfile_close(void) {
	if (keyFile != NULL) {
		fclose(keyFile);
		keyFile = NULL;
	}
}


text:
{% if site.data.bio.work %}

Professional Experience

{% for entry in site.data.bio.work %}

{{ entry.position }}, {{ entry.company }}

{{ entry.website | remove: "http://" | remove: "https://" }}

      {% if entry.startDate %}
        {{ entry.startDate | slice: 0,4 }}
      {% endif %}
      {% if entry.startDate and entry.endDate %}
        -
      {% endif %}
      {% if entry.endDate %}
        {% if entry.endDate != "Present" %}
          {{ entry.endDate | slice: 0,4 }}
         {% else %}
          {{ entry.endDate }}
        {% endif %}
      {% endif %}

{{ entry.summary }}

    {% if entry.highlights %}

        {% for highlight in entry.highlights %}

{{ highlight }}

        {% endfor %}

    {% endif %}

{% endfor %}

{% endif %}


text:
package com.thinkaurelius.titan.hadoop.mapreduce.util;

import com.thinkaurelius.titan.hadoop.Tokens;
import com.thinkaurelius.titan.hadoop.compat.HadoopCompiler;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;

import java.io.IOException;

import static com.thinkaurelius.titan.hadoop.compat.HadoopCompatLoader.DEFAULT_COMPAT;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class SafeReducerOutputs {

    private final MultipleOutputs outputs;
    private final Reducer.Context context;
    private final boolean testing;

    public SafeReducerOutputs(final Reducer.Context context) {
        this.context = context;
        this.outputs = new MultipleOutputs(this.context);
        this.testing = DEFAULT_COMPAT.getContextConfiguration(context).getBoolean(HadoopCompiler.TESTING, false);
    }

    public void write(final String type, final Writable key, final Writable value) throws IOException, InterruptedException {
        if (this.testing) {
            if (type.equals(Tokens.SIDEEFFECT))
                this.context.write(key, value);
        } else
            this.outputs.write(type, key, value);
    }

    public void close() throws IOException, InterruptedException {
        this.outputs.close();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bothalia 4: 828 (1948)

#### Original name
Pestalotia pterocelastri Laughton

### Remarks
null


text:
package jfskora;

import com.sun.management.UnixOperatingSystemMXBean;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.PlatformManagedObject;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;

public class JvmStatus {

    private static final int NUM_FILES = 100;

    public static void main( String[] args ) {
        File[] files = new File[NUM_FILES];
        FileOutputStream[] fout = new FileOutputStream[NUM_FILES];

        dumpOperatingSystemInfo();

        System.out.println("Number of open fd - start      : " + getOpenFileCount());
        for (int i = 0; i < NUM_FILES; i++) {
            files[i] = new File("/tmp/fout" + i);
        }
        System.out.println("Number of open fd - before open: " + getOpenFileCount());
        try {
            for (int x = 0; x < NUM_FILES; x++) {
                fout[x] = new FileOutputStream(files[x]);
            }
            System.out.println("Number of open fd - after open : " + getOpenFileCount());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            for (int x = 0; x < NUM_FILES; x++) {
                fout[x].close();
            }
            System.out.println("Number of open fd - after close: " + getOpenFileCount());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Number of open fd - done       : " + getOpenFileCount());
    }

    private static long getOpenFileCount() {
        OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
        if (os instanceof UnixOperatingSystemMXBean) {
            return ((UnixOperatingSystemMXBean) os).getOpenFileDescriptorCount();
        } else {
            return 0;
        }
    }

    private static void dumpOperatingSystemInfo() {
        OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
        dumpMxBeanInfo(OperatingSystemMXBean.class, os);
        if (os instanceof UnixOperatingSystemMXBean) {
            dumpMxBeanInfo(UnixOperatingSystemMXBean.class, os);
        }

        RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
        dumpMxBeanInfo(RuntimeMXBean.class, rt);
    }

    private static void dumpMxBeanInfo(Class klass, PlatformManagedObject bean) {
        System.out.println(klass.getCanonicalName());
        System.out.println("----------------------------------------");
        HashMap<String, Method> methods = new HashMap<>();
        for (Method method : klass.getMethods()) {
            if (method.getName().startsWith("get")) {
                methods.put(method.getName(), method);
            }
        }
        String[] keys = methods.keySet().toArray(new String[methods.size()]);
        Arrays.sort(keys);
        for (String method : keys) {
            try {
                System.out.println(klass.getSimpleName() + "." + methods.get(method).getName() + " = " + methods.get(method).invoke(bean));
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        System.out.println("----------------------------------------");
        System.out.println("");
    }

}


text:
CONCEPT_FUNCTION(LFQueue)
CONCEPT_FUNCTION(LFQueueEnqueue)
CONCEPT_FUNCTION(LFQueueDequeue)
CONCEPT_FUNCTION(LFQueueDestroy)

#endif // __LIBRARY_H


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HealthyTargetReference</title>
<meta name="date" content="2017-08-19">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

registry

Class HealthyTargetReference

java.lang.Object

registry.HealthyTargetReference

All Implemented Interfaces:

java.io.Serializable

public class HealthyTargetReference
extends java.lang.Object
implements java.io.Serializable

This class holds the references for healthy target ranges.

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

HealthyTargetReference()

Default constructor

<a href="../registry/HealthyTargetReference.html#HealthyTargetReference-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-registry.HealthyTarget-">HealthyTargetReference(HealthyTarget a1c,
                      HealthyTarget alt,
                      HealthyTarget ast,
                      HealthyTarget bloodPressureDiastole,
                      HealthyTarget bloodPressureSystole,
                      HealthyTarget bmi,
                      HealthyTarget creatinine,
                      HealthyTarget egfr,
                      HealthyTarget glucoseAc,
                      HealthyTarget hdlFemale,
                      HealthyTarget hdlMale,
                      HealthyTarget ldl,
                      HealthyTarget physicalActivity,
                      HealthyTarget psa,
                      HealthyTarget t4,
                      HealthyTarget triglycerides,
                      HealthyTarget tsh,
                      HealthyTarget uacr,
                      HealthyTarget waistFemale,
                      HealthyTarget waistMale)

Parameterized constructor

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

HealthyTarget
getA1c()

Get the value of a1c

HealthyTarget
getAlt()

Get the value of alt

HealthyTarget
getAst()

Get the value of ast

HealthyTarget
getBloodPressureDiastole()

Get the value of bloodPressureDiastole

HealthyTarget
getBloodPressureSystole()

Get the value of bloodPressureSystole

HealthyTarget
getBmi()

Get the value of bmi

HealthyTarget
getCreatinine()

Get the value of creatinine

HealthyTarget
getEgfr()

Get the value of egfr

HealthyTarget
getGlucoseAc()

Get the value of glucoseAc

HealthyTarget
getHdlFemale()

Get the value of hdlFemale

HealthyTarget
getHdlMale()

Get the value of hdlMale

HealthyTarget
getLdl()

Get the value of ldl

HealthyTarget
getPhysicalActivity()

Get the value of physicalActivity

HealthyTarget
getPsa()

Get the value of psa

HealthyTarget
getT4()

Get the value of t4

HealthyTarget
getTriglycerides()

Get the value of triglycerides

HealthyTarget
getTsh()

Get the value of tsh

HealthyTarget
getUacr()

Get the value of uacr

HealthyTarget
getWaistFemale()

Get the value of waistFemale

HealthyTarget
getWaistMale()

Get the value of waistMale

void
setA1c(HealthyTarget a1c)

Set the value of a1c

void
setAlt(HealthyTarget alt)

Set the value of alt

void
setAst(HealthyTarget ast)

Set the value of ast

void
setBloodPressureDiastole(HealthyTarget bloodPressureDiastole)

Set the value of bloodPressureDiastole

void
setBloodPressureSystole(HealthyTarget bloodPressureSystole)

Set the value of bloodPressureSystole

void
setBmi(HealthyTarget bmi)

Set the value of bmi

void
setCreatinine(HealthyTarget creatinine)

Set the value of creatinine

void
setEgfr(HealthyTarget egfr)

Set the value of egfr

void
setGlucoseAc(HealthyTarget glucoseAc)

Set the value of glucoseAc

void
setHdlFemale(HealthyTarget hdlFemale)

Set the value of hdlFemale

void
setHdlMale(HealthyTarget hdlMale)

Set the value of hdlMale

void
setLdl(HealthyTarget ldl)

Set the value of ldl

void
setPhysicalActivity(HealthyTarget physicalActivity)

Set the value of physicalActivity

void
setPsa(HealthyTarget psa)

Set the value of psa

void
setT4(HealthyTarget t4)

Set the value of t4

void
setTriglycerides(HealthyTarget triglycerides)

Set the value of triglycerides

void
setTsh(HealthyTarget tsh)

Set the value of tsh

void
setUacr(HealthyTarget uacr)

Set the value of uacr

void
setWaistFemale(HealthyTarget waistFemale)

Set the value of waistFemale

void
setWaistMale(HealthyTarget waistMale)

Set the value of waistMale

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HealthyTargetReference

public HealthyTargetReference()

Default constructor

HealthyTargetReference

public HealthyTargetReference(HealthyTarget a1c,
                              HealthyTarget alt,
                              HealthyTarget ast,
                              HealthyTarget bloodPressureDiastole,
                              HealthyTarget bloodPressureSystole,
                              HealthyTarget bmi,
                              HealthyTarget creatinine,
                              HealthyTarget egfr,
                              HealthyTarget glucoseAc,
                              HealthyTarget hdlFemale,
                              HealthyTarget hdlMale,
                              HealthyTarget ldl,
                              HealthyTarget physicalActivity,
                              HealthyTarget psa,
                              HealthyTarget t4,
                              HealthyTarget triglycerides,
                              HealthyTarget tsh,
                              HealthyTarget uacr,
                              HealthyTarget waistFemale,
                              HealthyTarget waistMale)

Parameterized constructor

Parameters:

a1c - the target A1C

alt - the target ALT

ast - the target AST

bloodPressureDiastole - the target diastolic blood pressure

bloodPressureSystole - the target systolic blood pressure

bmi - the target BMI

creatinine - the target creatinine

egfr - the target eGFR

glucoseAc - the target glucose AC

hdlFemale - the target HDL for females

hdlMale - the target HDL for males

ldl - the target LDL

physicalActivity - the target physical activity in weekly minutes

psa - the target PSA

t4 - the target T4

triglycerides - the target triglycerides

tsh - the target TSH

uacr - the target UACR

waistFemale - the target waist measurement for females

waistMale - the target waist measurement for males

Method Detail

getWaistMale

public HealthyTarget getWaistMale()

Get the value of waistMale

Returns:

the value of waistMale

setWaistMale

public void setWaistMale(HealthyTarget waistMale)

Set the value of waistMale

Parameters:

waistMale - new value of waistMale

getWaistFemale

public HealthyTarget getWaistFemale()

Get the value of waistFemale

Returns:

the value of waistFemale

setWaistFemale

public void setWaistFemale(HealthyTarget waistFemale)

Set the value of waistFemale

Parameters:

waistFemale - new value of waistFemale

getUacr

public HealthyTarget getUacr()

Get the value of uacr

Returns:

the value of uacr

setUacr

public void setUacr(HealthyTarget uacr)

Set the value of uacr

Parameters:

uacr - new value of uacr

getTsh

public HealthyTarget getTsh()

Get the value of tsh

Returns:

the value of tsh

setTsh

public void setTsh(HealthyTarget tsh)

Set the value of tsh

Parameters:

tsh - new value of tsh

getTriglycerides

public HealthyTarget getTriglycerides()

Get the value of triglycerides

Returns:

the value of triglycerides

setTriglycerides

public void setTriglycerides(HealthyTarget triglycerides)

Set the value of triglycerides

Parameters:

triglycerides - new value of triglycerides

getT4

public HealthyTarget getT4()

Get the value of t4

Returns:

the value of t4

setT4

public void setT4(HealthyTarget t4)

Set the value of t4

Parameters:

t4 - new value of t4

getPsa

public HealthyTarget getPsa()

Get the value of psa

Returns:

the value of psa

setPsa

public void setPsa(HealthyTarget psa)

Set the value of psa

Parameters:

psa - new value of psa

getPhysicalActivity

public HealthyTarget getPhysicalActivity()

Get the value of physicalActivity

Returns:

the value of physicalActivity

setPhysicalActivity

public void setPhysicalActivity(HealthyTarget physicalActivity)

Set the value of physicalActivity

Parameters:

physicalActivity - new value of physicalActivity

getLdl

public HealthyTarget getLdl()

Get the value of ldl

Returns:

the value of ldl

setLdl

public void setLdl(HealthyTarget ldl)

Set the value of ldl

Parameters:

ldl - new value of ldl

getHdlMale

public HealthyTarget getHdlMale()

Get the value of hdlMale

Returns:

the value of hdlMale

setHdlMale

public void setHdlMale(HealthyTarget hdlMale)

Set the value of hdlMale

Parameters:

hdlMale - new value of hdlMale

getHdlFemale

public HealthyTarget getHdlFemale()

Get the value of hdlFemale

Returns:

the value of hdlFemale

setHdlFemale

public void setHdlFemale(HealthyTarget hdlFemale)

Set the value of hdlFemale

Parameters:

hdlFemale - new value of hdlFemale

getGlucoseAc

public HealthyTarget getGlucoseAc()

Get the value of glucoseAc

Returns:

the value of glucoseAc

setGlucoseAc

public void setGlucoseAc(HealthyTarget glucoseAc)

Set the value of glucoseAc

Parameters:

glucoseAc - new value of glucoseAc

getEgfr

public HealthyTarget getEgfr()

Get the value of egfr

Returns:

the value of egfr

setEgfr

public void setEgfr(HealthyTarget egfr)

Set the value of egfr

Parameters:

egfr - new value of egfr

getCreatinine

public HealthyTarget getCreatinine()

Get the value of creatinine

Returns:

the value of creatinine

setCreatinine

public void setCreatinine(HealthyTarget creatinine)

Set the value of creatinine

Parameters:

creatinine - new value of creatinine

getBmi

public HealthyTarget getBmi()

Get the value of bmi

Returns:

the value of bmi

setBmi

public void setBmi(HealthyTarget bmi)

Set the value of bmi

Parameters:

bmi - new value of bmi

getBloodPressureSystole

public HealthyTarget getBloodPressureSystole()

Get the value of bloodPressureSystole

Returns:

the value of bloodPressureSystole

setBloodPressureSystole

public void setBloodPressureSystole(HealthyTarget bloodPressureSystole)

Set the value of bloodPressureSystole

Parameters:

bloodPressureSystole - new value of bloodPressureSystole

getBloodPressureDiastole

public HealthyTarget getBloodPressureDiastole()

Get the value of bloodPressureDiastole

Returns:

the value of bloodPressureDiastole

setBloodPressureDiastole

public void setBloodPressureDiastole(HealthyTarget bloodPressureDiastole)

Set the value of bloodPressureDiastole

Parameters:

bloodPressureDiastole - new value of bloodPressureDiastole

getAst

public HealthyTarget getAst()

Get the value of ast

Returns:

the value of ast

setAst

public void setAst(HealthyTarget ast)

Set the value of ast

Parameters:

ast - new value of ast

getAlt

public HealthyTarget getAlt()

Get the value of alt

Returns:

the value of alt

setAlt

public void setAlt(HealthyTarget alt)

Set the value of alt

Parameters:

alt - new value of alt

getA1c

public HealthyTarget getA1c()

Get the value of a1c

Returns:

the value of a1c

setA1c

public void setA1c(HealthyTarget a1c)

Set the value of a1c

Parameters:

a1c - new value of a1c

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Background Parallax Video</title>
  <link href="../css/normalize.css" rel="stylesheet" />
  <link href="../css/styles.css" rel="stylesheet" />
</head>
<body>
  <main style="height: 1500px">
    <video class="bv-video"></video>
  </main>
  <script src="../dist/backgroundVideo.js"></script>
  <script>
    const backgroundVideo = new BackgroundVideo('.bv-video', {
      src: [
        '../videos/sample.mp4',
        '../videos/sample.webm'
      ],
      onReady: function () {
        // Use onReady() to prevent flickers or force loading state
        const vidParent = document.querySelector(`.${this.bvVideoWrapClass}`);
        vidParent.classList.add('bv-video-wrap--ready');
      }
    });
  </script>
</body>
</html>


text:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class cameraFocus : MonoBehaviour
{
	public float _speed;
	public Vector3 Offset;
	private Vector3 _target = new Vector3 ();

	private bool _activeFocus;

	// Use this for initialization
	void Start ()
	{
		_target = transform.position;
	}

	// Update is called once per frame
	void Update ()
	{
		if (Input.GetMouseButtonDown (0)) {
			if (!EventSystem.current.IsPointerOverGameObject ()) {
				RaycastHit hit;
				Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
				if (Physics.Raycast (ray, out hit)) {
					if (hit.rigidbody != null) {
						StopAllCoroutines ();
						StartCoroutine (FocusOn (hit.transform));
					}
				}
			}
		}
	}

	IEnumerator FocusOn (Transform target)
	{
		Vector3 targetVect = target.position;
		targetVect.y = transform.position.y;
		while (targetVect != transform.position) {
			transform.position = Vector3.MoveTowards (transform.position, targetVect, _speed * Time.deltaTime);
			yield return null;
		}
		Debug.Log ("End!");
		yield return null;
	}
}


text:
using DataModel;
using Newtonsoft.Json;

namespace AddisCode.SolidPrinciple.Dip
{
    public interface IDocumentSerializer
    {
        string Serilize(Student[] doc);
    }

    public class JsonDocumentSerializer : IDocumentSerializer
    {
        public string Serilize(Student[] doc)
        {
            return JsonConvert.SerializeObject(doc);
        }
    }

    public class CamleCaseJsonSerializer : IDocumentSerializer
    {
        public string Serilize(Student[] doc)
        {
            return new CamleCaseJsonSerializer().Serilize(doc);
        }
    }
}


text:
import { editorUrl } from '../../utils/constants';
import { credentials, login } from '../../utils/auth-utils';
import { getLocation } from '../../utils/location-utils';
import { dataField } from '../../utils/selector-utils';
import { createAlias, waitForKeyToBeDeleted } from '../../clients/authoring-client';
import { tweekManagementClient } from '../../clients/tweek-clients';
import EditKey from '../../pages/Keys/EditKey';
import Alert from '../../pages/Alert';
import KeysPage from '../../pages/Keys';

const originalKeyPath = 'behavior_tests/key_aliases/regular_key';
const aliasKeyPath = 'behavior_tests/key_aliases/alias_key';
const aliasToAliasKeyPath = 'behavior_tests/key_aliases/alias_to_alias';
const newAliasKeyPath = 'behavior_tests/key_aliases/new_alias';
const deleteAliasKeyPath = 'behavior_tests/key_aliases/delete_alias';

const alert = new Alert();
const keysPage = new KeysPage();

fixture`Key Aliases`.page`${editorUrl}/keys`.httpAuth(credentials).beforeEach(login);

test('add alias', async (t) => {
  const editKey = await EditKey.open(originalKeyPath);

  await t
    .click(editKey.addAliasButton)
    .expect(alert.okButton.visible)
    .ok()
    .typeText(alert.section.find(dataField('new-key-name-input')), newAliasKeyPath, {
      replace: true,
    })
    .click(alert.okButton)
    .click(editKey.aliases.toggleButton)
    .expect(editKey.aliases.alias(newAliasKeyPath).container.visible)
    .ok();

  const link = await keysPage.navigateToLink(newAliasKeyPath);

  await t.expect(link.visible).ok();
}).before(async (t) => {
  await tweekManagementClient.deleteKey(newAliasKeyPath);
  await login(t);
});

test('should delete alias', async (t) => {
  const editKey = await EditKey.open(deleteAliasKeyPath); // should redirect to original key

  const alias = editKey.aliases.alias(deleteAliasKeyPath);

  await t
    .click(editKey.aliases.toggleButton)
    .expect(alias.container.visible)
    .ok()
    .click(alias.deleteButton)
    .click(alert.okButton)
    .expect(alias.container.exists)
    .notOk();

  const link = await keysPage.navigateToLink(deleteAliasKeyPath);

  await t.expect(link.exists).notOk();

  await waitForKeyToBeDeleted(deleteAliasKeyPath);
}).before(async (t) => {
  await createAlias(originalKeyPath, deleteAliasKeyPath);
  await login(t);
});

test('should redirect to key when navigating to alias', async (t) => {
  const editKey = await keysPage.openKey(aliasKeyPath);

  await t
    .expect(getLocation())
    .eql(`${editorUrl}/keys/${originalKeyPath}`)
    .click(editKey.aliases.toggleButton)
    .expect(editKey.aliases.alias(aliasKeyPath).container.visible)
    .ok()
    .expect(editKey.aliases.alias(aliasToAliasKeyPath).container.visible)
    .ok();
});


text:
jQuery( document ).ready( function( $ ) {
var map, geocoder, markersArray = [];

if ( $( "#wpsl-gmap-wrap" ).length ) {
	initializeGmap();
}

/*
 * If we're on the settings page, then check for returned
 * browser key errors from the autocomplete field
 * and validate the server key when necessary.
 */
if ( $( "#wpsl-map-settings").length ) {
	observeBrowserKeyErrors();

    /**
	 * Check if we need to validate the server key, and if no
	 * error message is already visible after saving the setting page.
     */
    if ( $( "#wpsl-api-server-key" ).hasClass( "wpsl-validate-me" ) && !$( "#setting-error-server-key" ).length ) {
    	validateServerKey();
	}
}

/**
 * Initialize the map with the correct settings.
 *
 * @since	1.0.0
 * @returns {void}
 */
function initializeGmap() {
	var defaultLatLng = wpslSettings.defaultLatLng.split( "," ),
		latLng = new google.maps.LatLng( defaultLatLng[0], defaultLatLng[1] ),
		mapOptions = {};

	mapOptions = {
		zoom: parseInt( wpslSettings.defaultZoom ),
		center: latLng,
		mapTypeId: google.maps.MapTypeId[ wpslSettings.mapType.toUpperCase() ],
		mapTypeControl: false,
		streetViewControl: false,
		zoomControlOptions: {
			position: google.maps.ControlPosition.RIGHT_TOP
		}
	};

	geocoder = new google.maps.Geocoder();
	map		 = new google.maps.Map( document.getElementById( "wpsl-gmap-wrap" ), mapOptions );

	checkEditStoreMarker();
}

/**
 * Check if we have an existing latlng value.
 *
 * If there is an latlng value, then we add a marker to the map.
 * This can only happen on the edit store page.
 *
 * @since	1.0.0
 * @returns {void}
 */
function checkEditStoreMarker() {
	var location,
		lat = $( "#wpsl-lat" ).val(),
		lng = $( "#wpsl-lng" ).val();

	if ( ( lat ) && ( lng ) ) {
		location = new google.maps.LatLng( lat, lng );

		map.setCenter( location );
		map.setZoom( 16 );
		addMarker( location );
	}
}

// If we have a city/country input field enable the autocomplete.
if ( $( "#wpsl-start-name" ).length ) {
	activateAutoComplete();
}

/**
 * Activate the autocomplete function for the city/country field.
 *
 * @since	1.0.0
 * @returns {void}
 */
function activateAutoComplete() {
	var latlng,
		input = document.getElementById( "wpsl-start-name" ),
		options = {
		  types: ['geocode']
		},
		autocomplete = new google.maps.places.Autocomplete( input, options );

	google.maps.event.addListener( autocomplete, "place_changed", function() {
		latlng = autocomplete.getPlace().geometry.location;
		setLatlng( latlng, "zoom" );
	});
}

/**
 * Add a new marker to the map based on the provided location (latlng).
 *
 * @since	1.0.0
 * @param   {object} location The latlng value
 * @returns {void}
 */
function addMarker( location ) {
	var marker = new google.maps.Marker({
		position: location,
		map: map,
		draggable: true
	});

	markersArray.push( marker );

	// If the marker is dragged on the map, make sure the latlng values are updated.
	google.maps.event.addListener( marker, "dragend", function() {
		setLatlng( marker.getPosition(), "store" );
	});
}

// Lookup the provided location with the Google Maps API.
$( "#wpsl-lookup-location" ).on( "click", function( e ) {
	e.preventDefault();
	codeAddress();
});

/**
 * Update the hidden input field with the current latlng values.
 *
 * @since	1.0.0
 * @param   {object} latLng The latLng values
 * @param   {string} target The location where we need to set the latLng
 * @returns {void}
 */
function setLatlng( latLng, target ) {
	var coordinates = stripCoordinates( latLng ),
		lat			= roundCoordinate( coordinates[0] ),
		lng			= roundCoordinate( coordinates[1] );

	if ( target == "store" ) {
		$( "#wpsl-lat" ).val( lat );
		$( "#wpsl-lng" ).val( lng );
	} else if ( target == "zoom" ) {
		$( "#wpsl-latlng" ).val( lat + ',' + lng );
	}
}

/**
 * Geocode the user input.
 *
 * @since	1.0.0
 * @returns {void}
 */
function codeAddress() {
    var filteredResponse, geocodeAddress;

	// Check if we have all the required data before attempting to geocode the address.
	if ( !validatePreviewFields() ) {
		geocodeAddress = createGeocodeAddress();

		geocoder.geocode( { 'address': geocodeAddress }, function( response, status ) {
			if ( status === google.maps.GeocoderStatus.OK ) {

				// If we have a previous marker on the map we remove it.
				if ( typeof( markersArray[0] ) !== "undefined" ) {
					if ( markersArray[0].draggable ) {
						markersArray[0].setMap( null );
						markersArray.splice(0, 1);
					}
				}

				// Center and zoom to the searched location.
				map.setCenter( response[0].geometry.location );
				map.setZoom( 16 );

				addMarker( response[0].geometry.location );
				setLatlng( response[0].geometry.location, "store" );

				filteredResponse = filterApiResponse( response );

				$( "#wpsl-country" ).val( filteredResponse.country.long_name );
				$( "#wpsl-country_iso" ).val( filteredResponse.country.short_name );
			} else {
				alert( wpslL10n.geocodeFail + ": " + status );
			}
		});

		return false;
	} else {
		activateStoreTab( "first" );

		alert( wpslL10n.missingGeoData );

		return true;
	}
}

/**
 * Check that all required fields for the map preview are there.
 *
 * @since	1.0.0
 * @returns {boolean} error  Whether all the required fields contained data.
 */
function validatePreviewFields() {
	var i, fieldData, requiredFields,
		error = false;

	$( ".wpsl-store-meta input" ).removeClass( "wpsl-error" );

	// Check which fields are required.
    if ( typeof wpslSettings.requiredFields !== "undefined" && _.isArray( wpslSettings.requiredFields ) ) {
        requiredFields = wpslSettings.requiredFields;

        // Check if all the required fields contain data.
        for ( i = 0; i < requiredFields.length; i++ ) {
            fieldData = $.trim( $( "#wpsl-" + requiredFields[i] ).val() );

            if ( !fieldData ) {
                $( "#wpsl-" + requiredFields[i] ).addClass( "wpsl-error" );
                error = true;
            }

            fieldData = '';
        }
    }

	return error;
}

/**
 * Build the address that's send to the Geocode API.
 *
 * @since	2.1.0
 * @returns {string} geocodeAddress The address separated by , that's send to the Geocoder.
 */
function createGeocodeAddress() {
	var i, part,
		address      = [],
		addressParts = [ "address", "city", "state", "zip", "country" ];

	for ( i = 0; i < addressParts.length; i++ ) {
		part = $.trim( $( "#wpsl-" + addressParts[i] ).val() );

		/*
		 * At this point we already know the address, city and country fields contain data.
		 * But no need to include the zip and state if they are empty.
		 */
		if ( part ) {
			address.push( part );
		}

		part = "";
	}

	return address.join();
}

/**
 * Filter out the country name from the API response.
 *
 * @since	1.0.0
 * @param   {object} response	   The response of the geocode API
 * @returns {object} collectedData The short and long country name
 */
function filterApiResponse( response ) {
	var i, responseType,
		country		  = {},
		collectedData = {},
		addressLength = response[0].address_components.length;

	// Loop over the API response.
	for ( i = 0; i < addressLength; i++ ) {
		responseType = response[0].address_components[i].types;

		// Filter out the country name.
		if ( /^country,political$/.test( responseType ) ) {
			country = {
				long_name: response[0].address_components[i].long_name,
				short_name: response[0].address_components[i].short_name
			};
		}
	}

	collectedData = {
		country: country
	};

	return collectedData;
}

/**
 * Round the coordinate to 6 digits after the comma.
 *
 * @since	1.0.0
 * @param   {string} coordinate   The coordinate
 * @returns {number} roundedCoord The rounded coordinate
 */
function roundCoordinate( coordinate ) {
	var roundedCoord, decimals = 6;

	roundedCoord = Math.round( coordinate * Math.pow( 10, decimals ) ) / Math.pow( 10, decimals );

	return roundedCoord;
}

/**
 * Strip the '(' and ')' from the captured coordinates and split them.
 *
 * @since	1.0.0
 * @param   {string} coordinates The coordinates
 * @returns {object} latLng      The latlng coordinates
 */
function stripCoordinates( coordinates ) {
	var latLng    = [],
		selected  = coordinates.toString(),
		latLngStr = selected.split( ",", 2 );

	latLng[0] = latLngStr[0].replace( "(", "" );
	latLng[1] = latLngStr[1].replace( ")", "" );

	return latLng;
}

$( ".wpsl-marker-list input[type=radio]" ).click( function() {
	$( this ).parents( ".wpsl-marker-list" ).find( "li" ).removeClass();
	$( this ).parent( "li" ).addClass( "wpsl-active-marker" );
});

$( ".wpsl-marker-list li" ).click( function() {
	$( this ).parents( ".wpsl-marker-list" ).find( "input" ).prop( "checked", false );
	$( this ).find( "input" ).prop( "checked", true );
	$( this ).siblings().removeClass();
	$( this ).addClass( "wpsl-active-marker" );
});

// Handle a click on the dismiss button. So that the warning msg that no starting point is set is disabled.
$( ".wpsl-dismiss" ).click( function() {
	var $link = $( this ),
		data = {
			action: "disable_location_warning",
			_ajax_nonce: $link.attr( "data-nonce" )
		};

	$.post( ajaxurl, data );

	$( ".wpsl-dismiss" ).parents( ".error" ).remove();

	return false;
});

// Detect changes in checkboxes that have a conditional option.
$( ".wpsl-has-conditional-option" ).on( "change", function() {
	$( this ).parent().next( ".wpsl-conditional-option" ).toggle();
});

/*
 * Detect changes to the store template dropdown. If the template is selected to
 * show the store list under the map then we show the option to hide the scrollbar.
 */
$( "#wpsl-store-template" ).on( "change", function() {
	var $scrollOption = $( "#wpsl-listing-below-no-scroll" );

	if ( $( this ).val() == "below_map" ) {
		$scrollOption.show();
	} else {
		$scrollOption.hide();
	}
});

$( "#wpsl-api-region" ).on( "change", function() {
	var $geocodeComponent = $( "#wpsl-geocode-component" );

	if ( $( this ).val() ) {
		$geocodeComponent.show();
	} else {
		$geocodeComponent.hide();
	}
});

// Make sure the correct hour input format is visible.
$( "#wpsl-editor-hour-input" ).on( "change", function() {
	$( ".wpsl-" + $( this ).val() + "-hours" ).show().siblings( "div" ).hide();
	$( ".wpsl-hour-notice" ).toggle();
});

// Set the correct tab to active and show the correct content block.
$( "#wpsl-meta-nav li" ).on( "click", function( e ) {
	var activeClass = $( this ).attr( "class" );
		activeClass = activeClass.split( "-tab" );

	e.stopPropagation();

	// Set the correct tab and metabox to active.
	$( this ).addClass( "wpsl-active" ).siblings().removeClass( "wpsl-active" );
	$( ".wpsl-store-meta ." + activeClass[0] + "" ).show().addClass( "wpsl-active" ).siblings( "div" ).hide().removeClass( "wpsl-active" );
});

// Make sure the required store fields contain data.
if ( $( "#wpsl-store-details" ).length ) {
	$( "#publish" ).click( function() {
		var firstErrorElem, currentTabClass, elemClass,
			errorMsg	= '

' + wpslL10n.requiredFields + '

',
			missingData = false;

		// Remove error messages and css classes from previous submissions.
		$( "#wpbody-content .wrap #message" ).remove();
		$( ".wpsl-required" ).removeClass( "wpsl-error" );

		// Loop over the required fields and check for a value.
		$( ".wpsl-required" ).each( function() {
			if ( $( this ).val() == "" ) {
				$( this ).addClass( "wpsl-error" );

				if ( typeof firstErrorElem === "undefined" ) {
					firstErrorElem = getFirstErrorElemAttr( $( this ) );
				}

				missingData = true;
			}
		});

		// If one of the required fields are empty, then show the error msg and make sure the correct tab is visible.
		if ( missingData ) {
			$( "#wpbody-content .wrap > h2" ).after( errorMsg );

			if ( typeof firstErrorElem.val !== "undefined" ) {
				if ( firstErrorElem.type == "id" ) {
					currentTabClass = $( "#" + firstErrorElem.val + "" ).parents( ".wpsl-tab" ).attr( "class" );
					$( "html, body" ).scrollTop( Math.round( $( "#" + firstErrorElem.val + "" ).offset().top - 100 ) );
				} else if ( firstErrorElem.type == "class" ) {
					elemClass		= firstErrorElem.val.replace( /wpsl-required|wpsl-error/g, "" );
					currentTabClass = $( "." + elemClass + "" ).parents( ".wpsl-tab" ).attr( "class" );
					$( "html, body" ).scrollTop( Math.round( $( "." + elemClass + "" ).offset().top - 100 ) );
				}

				currentTabClass = $.trim( currentTabClass.replace( /wpsl-tab|wpsl-active/g, "" ) );
			}

			// If we don't have a class of the tab that should be set to visible, we just show the first one.
			if ( !currentTabClass ) {
				activateStoreTab( 'first' );
			} else {
				activateStoreTab( currentTabClass );
			}

			/*
			 * If not all required fields contains data, and the user has
			 * clicked the submit button. Then an extra css class is added to the
			 * button that will disabled it. This only happens in WP 3.8 or earlier.
			 *
			 * We need to make sure this css class doesn't exist otherwise
			 * the user can never resubmit the page.
			 */
			$( "#publish" ).removeClass( "button-primary-disabled" );
			$( ".spinner" ).hide();

			return false;
		} else {
			return true;
		}
	});
}

/**
 * Set the correct tab to visible, and hide all other metaboxes
 *
 * @since	2.0.0
 * @param   {string} $target The name of the tab to show
 * @returns {void}
 */
function activateStoreTab( $target ) {
	if ( $target == 'first' ) {
		$target = ':first-child';
	} else {
		$target = '.' + $target;
	}

	if ( !$( "#wpsl-meta-nav li" + $target + "-tab" ).hasClass( "wpsl-active" ) ) {
		$( "#wpsl-meta-nav li" + $target + "-tab" ).addClass( "wpsl-active" ).siblings().removeClass( "wpsl-active" );
		$( ".wpsl-store-meta > div" + $target + "" ).show().addClass( "wpsl-active" ).siblings( "div" ).hide().removeClass( "wpsl-active" );
	}
}

/**
 * Get the id or class of the first element that's an required field, but is empty.
 *
 * We need this to determine which tab we need to set active,
 * which will be the tab were the first error occured.
 *
 * @since	2.0.0
 * @param   {object} elem			The element the error occured on
 * @returns {object} firstErrorElem The id/class set on the first elem that an error occured on and the attr value
 */
function getFirstErrorElemAttr( elem ) {
	var firstErrorElem = { "type": "id", "val" : elem.attr( "id" ) };

	// If no ID value exists, then check if we can get the class name.
	if ( typeof firstErrorElem.val === "undefined" ) {
		firstErrorElem = { "type": "class", "val" : elem.attr( "class" ) };
	}

	return firstErrorElem;
}

// If we have a store hours dropdown, init the event handler.
if ( $( "#wpsl-store-hours" ).length ) {
	initHourEvents();
}

/**
 * Assign an event handler to the button that enables
 * users to remove an opening hour period.
 *
 * @since	2.0.0
 * @returns {void}
 */
function initHourEvents() {
	$( "#wpsl-store-hours .wpsl-icon-cancel-circled" ).off();
	$( "#wpsl-store-hours .wpsl-icon-cancel-circled" ).on( "click", function() {
		removePeriod( $( this ) );
	});
}

// Add new openings period to the openings hours table.
$( ".wpsl-add-period" ).on( "click", function( e ) {
	var newPeriod,
		hours		= {},
		returnList  = true,
		$tr			= $( this ).parents( "tr" ),
		periodCount = currentPeriodCount( $( this ) ),
		periodCss   = ( periodCount >= 1 ) ? "wpsl-current-period wpsl-multiple-periods" : "wpsl-current-period",
		day 	    = $tr.find( ".wpsl-opening-hours" ).attr( "data-day" ),
		selectName  = ( $( "#wpsl-settings-form" ).length ) ? "wpsl_editor[dropdown]" : "wpsl[hours]";

	newPeriod = '
';
	newPeriod += '<select autocomplete="off" name="' + selectName + '[' + day + '_open][]" class="wpsl-open-hour">' + createHourOptionList( returnList ) + '</select>';
	newPeriod += ' - ';
	newPeriod += '<select autocomplete="off" name="' + selectName + '[' + day + '_close][]" class="wpsl-close-hour">' + createHourOptionList( returnList ) + '</select>';
	newPeriod += '

';
	newPeriod += '
';

	$tr.find( ".wpsl-store-closed" ).remove();
	$( "#wpsl-hours-" + day + "" ).append( newPeriod ).end();

	initHourEvents();

	if ( $( "#wpsl-editor-hour-format" ).val() == 24 ) {
		hours = {
			"open": "09:00",
			"close": "17:00"
		};
	} else {
		hours = {
			"open": "9:00 AM",
			"close": "5:00 PM"
		};
	}

	$tr.find( ".wpsl-open-hour:last option[value='" + hours.open + "']" ).attr( "selected", "selected" );
	$tr.find( ".wpsl-close-hour:last option[value='" + hours.close + "']" ).attr( "selected", "selected" );

	e.preventDefault();
});

/**
 * Remove an openings period
 *
 * @since  2.0.0
 * @param  {object} elem The clicked element
 * @return {void}
 */
function removePeriod( elem ) {
	var periodsLeft	= currentPeriodCount( elem ),
		$tr			= elem.parents( "tr" ),
		day 	    = $tr.find( ".wpsl-opening-hours" ).attr( "data-day" );

	// If there was 1 opening hour left then we add the 'Closed' text.
	if ( periodsLeft == 1 ) {
		$tr.find( ".wpsl-opening-hours" ).html( "
" + wpslL10n.closedDate + "<input type='hidden' name='wpsl[hours][" + day + "_open]' value='' />
" );
	}

	// Remove the selected openings period.
	elem.parent().closest( ".wpsl-current-period" ).remove();

	// If the first element has the multiple class, then we need to remove it.
	if ( $tr.find( ".wpsl-opening-hours div:first-child" ).hasClass( "wpsl-multiple-periods" ) ) {
		$tr.find( ".wpsl-opening-hours div:first-child" ).removeClass( "wpsl-multiple-periods" );
	}
}

/**
 * Count the current opening periods in a day block
 *
 * @since  2.0.0
 * @param  {object} elem		   The clicked element
 * @return {string} currentPeriods The ammount of period divs found
 */
function currentPeriodCount( elem ) {
	var currentPeriods = elem.parents( "tr" ).find( ".wpsl-current-period" ).length;

	return currentPeriods;
}

/**
 * Create an option list with the correct opening hour format and interval
 *
 * @since  2.0.0
 * @param  {string} returnList Whether to return the option list or call the setSelectedOpeningHours function
 * @return {mixed}  optionList The html for the option list of or void
 */
function createHourOptionList( returnList ) {
	var openingHours, openingHourInterval, hour, hrFormat,
		pm   			   = false,
        twelveHrsAfternoon = false,
		pmOrAm			   = "",
		optionList		   = "",
		openingTimes 	   = [],
		openingHourOptions = {
			"hours": {
				"hr12": [ 12, 1, 2, 3 ,4 ,5 ,6, 7, 8, 9, 10, 11, 12, 1, 2, 3 , 4, 5, 6, 7, 8, 9, 10, 11 ],
				"hr24": [ 0, 1, 2, 3 ,4 ,5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ,16, 17, 18, 19, 20, 21, 22, 23 ]
			},
			"interval": [ '00', '15', '30', '45' ]
		};

	if ( $( "#wpsl-editor-hour-format" ).length ) {
		hrFormat = $( "#wpsl-editor-hour-format" ).val();
	} else {
		hrFormat = wpslSettings.hourFormat;
	}

	$( "#wpsl-store-hours td" ).removeAttr( "style" );

	if ( hrFormat == 12 ) {
		$( "#wpsl-store-hours" ).removeClass().addClass( "wpsl-twelve-format" );
		openingHours = openingHourOptions.hours.hr12;
	} else {
		$( "#wpsl-store-hours" ).removeClass().addClass( "wpsl-twentyfour-format" );
		openingHours = openingHourOptions.hours.hr24;
	}

	openingHourInterval = openingHourOptions.interval;

	for ( var i = 0; i < openingHours.length; i++ ) {
		hour = openingHours[i];

		/*
		 * If the 12hr format is selected, then check if we need to show AM or PM.
		 *
		 * If the 24hr format is selected and the hour is a single digit
		 * then we add a 0 to the start so 5:00 becomes 05:00.
		 */
		if ( hrFormat == 12 ) {
			if ( hour >= 12 ) {
				pm = ( twelveHrsAfternoon ) ? true : false;

                twelveHrsAfternoon = true;
			}

			pmOrAm = ( pm ) ? "PM" : "AM";
		} else if ( ( hrFormat == 24 ) && ( hour.toString().length == 1 ) ) {
			hour = "0" + hour;
		}

		// Collect the new opening hour format and interval.
		for ( var j = 0; j < openingHourInterval.length; j++ ) {
			openingTimes.push( hour + ":" + openingHourInterval[j] + " " + pmOrAm );
		}
	}

	// Create the <option> list.
	for ( var i = 0; i < openingTimes.length; i++ ) {
		optionList = optionList + '<option value="' + $.trim( openingTimes[i] ) + '">' + $.trim( openingTimes[i] ) + '</option>';
	}

	if ( returnList ) {
		return optionList;
	} else {
		setSelectedOpeningHours( optionList, hrFormat );
	}
}

/**
 * Set the correct selected opening hour in the dropdown
 *
 * @since  2.0.0
 * @param  {string} optionList The html for the option list
 * @param  {string} hrFormat   The html for the option list
 * @return {void}
 */
function setSelectedOpeningHours( optionList, hrFormat ) {
	var splitHour, hourType, periodBlock,
		hours = {};

	/*
	 * Loop over each open/close block and make sure the selected
	 * value is still set as selected after changing the hr format.
	 */
	$( ".wpsl-current-period" ).each( function() {
		periodBlock = $( this ),
		hours 		= {
			"open": $( this ).find( ".wpsl-open-hour" ).val(),
			"close": $( this ).find( ".wpsl-close-hour" ).val()
		};

		// Set the new hour format for both dropdowns.
		$( this ).find( "select" ).html( optionList ).promise().done( function() {

			// Select the correct start/end hours as selected.
			for ( var key in hours ) {
				if ( hours.hasOwnProperty( key ) ) {

					// Breakup the hour, so we can check the part before and after the : separately.
					splitHour = hours[key].split( ":" );

					if ( hrFormat == 12 ) {
						hourType = "";

						// Change the hours to a 12hr format and add the correct AM or PM.
						if ( hours[key].charAt( 0 ) == 0 ) {
							hours[key] = hours[key].substr( 1 );
							hourType   = " AM";
						} else if ( ( splitHour[0].length == 2 ) && ( splitHour[0] > 12 ) ) {
							hours[key] = ( splitHour[0] - 12 ) + ":" + splitHour[1];
							hourType   = " PM";
						} else if ( splitHour[0] < 12 ) {
							hours[key] = splitHour[0] + ":" + splitHour[1];
							hourType   = " AM";
						} else if ( splitHour[0] == 12 ) {
							hours[key] = splitHour[0] + ":" + splitHour[1];
							hourType   = " PM";
						}

						// Add either AM or PM behind the time.
						if ( ( splitHour[1].indexOf( "PM" ) == -1 ) && ( splitHour[1].indexOf( "AM" ) == -1 ) ) {
							hours[key] = hours[key] + hourType;
						}

					} else if ( hrFormat == 24 ) {

						// Change the hours to a 24hr format and remove the AM or PM.
						if ( splitHour[1].indexOf( "PM" ) != -1 ) {
							if ( splitHour[0] == 12 ) {
								hours[key] = "12:" + splitHour[1].replace( " PM", "" );
							} else {
								hours[key] = ( + splitHour[0] + 12 ) + ":" + splitHour[1].replace( " PM", "" );
							}
						} else if ( splitHour[1].indexOf( "AM" ) != -1 ) {
							if ( splitHour[0].toString().length == 1 ) {
								hours[key] = "0" + splitHour[0] + ":" + splitHour[1].replace( " AM", "" );
							} else {
								hours[key] = splitHour[0] + ":" + splitHour[1].replace( " AM", "" );
							}
						} else {
							hours[key] = splitHour[0] + ":" + splitHour[1]; // When the interval is changed
						}
					}

					// Set the correct value as the selected one.
					periodBlock.find( ".wpsl-" + key + "-hour option[value='" + $.trim( hours[key] ) + "']" ).attr( "selected", "selected" );
				}
			}

		});
	});
}

// Update the opening hours format if one of the dropdown values change.
$( "#wpsl-editor-hour-format, #wpsl-editor-hour-interval" ).on( "change", function() {
	createHourOptionList();
});

// Show the tooltips.
$( ".wpsl-info" ).on( "mouseover", function() {
	$( this ).find( ".wpsl-info-text" ).show();
});

$( ".wpsl-info" ).on( "mouseout", function() {
	$( this ).find( ".wpsl-info-text" ).hide();
});

// If the start location is empty, then we color the info icon red instead of black.
if ( $( "#wpsl-latlng" ).length && !$( "#wpsl-latlng" ).val() ) {
	$( "#wpsl-latlng" ).siblings( "label" ).find( ".wpsl-info" ).addClass( "wpsl-required-setting" );
}

/**
 * Try to apply the custom style data to the map.
 *
 * If the style data is invalid json we show an error.
 *
 * @since  2.0.0
 * @return {void}
 */
function tryCustomMapStyle() {
	var validStyle = "",
		mapStyle   = $.trim( $( "#wpsl-map-style" ).val() );

	$( ".wpsl-style-preview-error" ).remove();

	if ( mapStyle ) {

		// Make sure the data is valid json.
		validStyle = tryParseJSON( mapStyle );

		if ( !validStyle ) {
			$( "#wpsl-style-preview" ).after( "
" + wpslL10n.styleError + "
" );
		}
	}

	map.setOptions({ styles: validStyle });
}

// Handle the map style changes on the settings page.
if ( $( "#wpsl-map-style" ).val() ) {
	tryCustomMapStyle();
}

// Handle clicks on the map style preview button.
$( "#wpsl-style-preview" ).on( "click", function() {
	tryCustomMapStyle();

	return false;
});

/**
 * Make sure the JSON is valid.
 *
 * @link   http://stackoverflow.com/a/20392392/1065294
 * @since  2.0.0
 * @param  {string} jsonString The JSON data
 * @return {object|boolean}	   The JSON string or false if it's invalid json.
 */
function tryParseJSON( jsonString ) {

    try {
        var o = JSON.parse( jsonString );

        /*
		 * Handle non-exception-throwing cases:
		 * Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
		 * but... JSON.parse(null) returns 'null', and typeof null === "object",
		 * so we must check for that, too.
		 */
        if ( o && typeof o === "object" && o !== null ) {
            return o;
        }
    }
    catch ( e ) { }

    return false;
}

/**
 * Look for changes on the start location input field.
 *
 * If there's a problem with the browser API key,
 * then a 'gm-err-autocomplete' class is added to the input field.
 *
 * When this happens we create a notice explaining how to fix the issue.
 *
 * @since 2.2.10
 * @return void
 */
function observeBrowserKeyErrors() {
    var observer,
		attributeValue 	 = '',
		MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
		$startName 		 = $( "#wpsl-start-name" );

	if ( typeof MutationObserver !== "undefined" ) {
		observer = new MutationObserver( function( mutations ) {

			// Loop over the mutations.
			mutations.forEach( function( mutation ) {
				if ( mutation.attributeName === "class" ) {
					attributeValue = $( mutation.target ).prop( mutation.attributeName );

					// Look for a specific class that's added when there's a problem with the browser API key
					if ( ( attributeValue.indexOf( "gm-err-autocomplete" ) !== -1 ) ) {
                        createErrorNotice( wpslL10n.browserKeyError, "browser-key" );
					}
				}
			});
		});

		observer.observe( $startName[0], {
			attributes: true
		});
	}
}

/**
 * Make a request to the geocode API with the
 * provided server key to check for any errors.
 *
 * @since 2.2.10
 * @return void
 */
function validateServerKey() {
    var ajaxData = {
        action: "validate_server_key",
        server_key: $( "#wpsl-api-server-key" ).val()
    };

    $.get( wpslSettings.ajaxurl, ajaxData, function( response ) {
        if ( !response.valid && typeof response.msg !== "undefined" ) {
            createErrorNotice( response.msg, "server-key" );
		} else {
            $( "#wpsl-api-server-key" ).removeClass( "wpsl-error" );
        }
    });
}

/**
 * Create the error notice.
 *
 * @since 2.2.10
 * @param {string} errorMsg The error message to show
 * @param {string} type 	The type of API key we need to show the notice for
 * @return void
 */
function createErrorNotice( errorMsg, type ) {
	var errorNotice, noticeLocation;

	errorNotice = '
';
	errorNotice += '
' + errorMsg + '
';
	errorNotice += '<button type="button" class="notice-dismiss">' + wpslL10n.dismissNotice + '</button>';
	errorNotice += '
';

	noticeLocation = ( $( "#wpsl-tabs" ).length ) ? 'wpsl-tabs' : 'wpsl-settings-form';

	$( "#" + noticeLocation + "" ).before( errorNotice );
	$( "#wpsl-api-" + type + "").addClass( "wpsl-error" );
}

// Make sure the custom error notices can be removed
$( "#wpsl-wrap" ).on( "click", "button.notice-dismiss", function() {
    $( this ).closest( 'div.notice' ).remove();
})

});


text:
package amu.roboclub.notification;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import androidx.core.app.NotificationCompat;
import androidx.core.content.res.ResourcesCompat;
import android.util.Log;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import amu.roboclub.R;
import amu.roboclub.ui.MainActivity;

import static amu.roboclub.BuildConfig.DEBUG;

public class NotificationService extends FirebaseMessagingService {
    private static final String TAG = "AMURoboClub";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        boolean toShow = DEBUG || remoteMessage.getFrom().equals("/topics/news");

        if (remoteMessage.getNotification() != null && toShow) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification());
        }

    }

    private void sendNotification(RemoteMessage.Notification notification) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String title = notification.getTitle() != null ? notification.getTitle() : getString(R.string.app_name);
        int color = notification.getColor() != null ? Color.parseColor(notification.getColor()) : ResourcesCompat.getColor(getResources(), R.color.colorAccent, null);
        String messageBody = notification.getBody();

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, TAG)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setColor(color)
                .setAutoCancel(true)
                .setStyle(new NotificationCompat.BigTextStyle())
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  ~cDeviceDriver
  cDeviceDriver

  ~cDriver
  cDriver

  ~cEvent
  cEvent

  ~cMutex
  cMutex

  ~cRegAccess
  cRegAccess

  ~cThread
  cThread

  ~cUsbDetect
  cUsbDetect

  ~TThread
  TThread

Searching...

No Matches


text:
package db.dao.simple;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by igor on 22.10.2015.
 */
public class Run {

    public static void main(String[] args) {

        try(TestDAO test = new TestDAO()) {

//            List<TestEntity> entities = test.getAll();
//
//            for(TestEntity entity :entities) {
//                System.out.println(entity);
//            }

            TestEntity entity =test.get(5);
            entity.setName("QQQQQ");
            entity.setNumber(1111111);
            test.update(entity);
            //test.remove(entity);

            List<TestEntity> entities = test.getAll();

            for(TestEntity e :entities) {
                System.out.println(e);
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
}


text:
layout:     post
title:      "设计模式(12)——状态模式"
subtitle:   ""
date:       2017-07-21 22:30:00
author:     "Crow"
#header-img: "img/post-bg-nextgen-web-pwa.jpg"
header-mask: 0.3
catalog:    true
tags:
    - 设计模式
    - 读书笔记
---

**状态模式**允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。

直接看定义好像有些晦涩,我们先看例子,待会儿再回到定义来。

我们现在模拟一个糖果机的工作状态,它的状态变化图如下所示
![](https://pic.yupoo.com/crowhawk/12a0e9a4/740a76ec.png)
找出所有的状态:
+ 没有25分钱
+ 有25分钱
+ 糖果售罄
+ 售出糖果

现在我们需要用代码来实现这些状态。我们可以创建一个实例变量来持有目前的状态,然后定义每个状态的值:
```java
final static int SOLD_OUT=0;
final static int NO_QUARTER=1;
final static int HAS_QUARTER=2;
final static int SOLD=3;

int state =SOLD_OUT;
```
但是显然可以预见的是,这种做法会带来一个弊端,当你需要扩展状态时,修改代码会变得非常困难。比如说,我们需要为糖果机新增一个功能,"售出糖果"状态有10%的几率会导致掉下两颗糖果,而不是一颗,这显然需要增加一个状态,用原有的实现方式会让我们陷入混乱的状态中无法脱身。

为此,我们应该试着局部化每个状态的行为,遵守**"封装变化"**原则,将每个状态的行为都放在各自的类中,那么每个状态只要实现它自己的动作就可以了。我们要做的事情是
+ 我们可以定义一个State接口,在这个接口内,糖果机的每个动作都有一个对应的方法。
+ 然后为机器中的每个状态实现状态类。这些类将负责在对应的状态下进行机器的行为。
+ 最后,将动作委托到状态类。

State接口
```java
public interface State {

	public void insertQuarter();
	public void ejectQuarter();
	public void turnCrank();
	public void dispense();
}
```
每个状态对应的状态类
```java
import java.util.Random;

public class HasQuarterState implements State {
	Random randomWinner = new Random(System.currentTimeMillis());
	GumballMachine gumballMachine;

	public HasQuarterState(GumballMachine gumballMachine) {
		this.gumballMachine = gumballMachine;
	}

	public void insertQuarter() {
		System.out.println("You can't insert another quarter");
	}

	public void ejectQuarter() {
		System.out.println("Quarter returned");
		gumballMachine.setState(gumballMachine.getNoQuarterState());
	}

	public void turnCrank() {
		System.out.println("You turned...");
		int winner = randomWinner.nextInt(10);
		if ((winner == 0) && (gumballMachine.getCount() > 1)) {
			gumballMachine.setState(gumballMachine.getWinnerState());
		} else {
			gumballMachine.setState(gumballMachine.getSoldState());
		}
	}

    public void dispense() {
        System.out.println("No gumball dispensed");
    }

	public String toString() {
		return "waiting for turn of crank";
	}
}
```
```java
public class NoQuarterState implements State {
    GumballMachine gumballMachine;

    public NoQuarterState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

	public void insertQuarter() {
		System.out.println("You inserted a quarter");
		gumballMachine.setState(gumballMachine.getHasQuarterState());
	}

	public void ejectQuarter() {
		System.out.println("You haven't inserted a quarter");
	}

	public void turnCrank() {
		System.out.println("You turned, but there's no quarter");
	 }

	public void dispense() {
		System.out.println("You need to pay first");
	}

	public String toString() {
		return "waiting for quarter";
	}
}
```
```java
public class SoldOutState implements State {
    GumballMachine gumballMachine;

    public SoldOutState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

	public void insertQuarter() {
		System.out.println("You can't insert a quarter, the machine is sold out");
	}

	public void ejectQuarter() {
		System.out.println("You can't eject, you haven't inserted a quarter yet");
	}

	public void turnCrank() {
		System.out.println("You turned, but there are no gumballs");
	}

	public void dispense() {
		System.out.println("No gumball dispensed");
	}

	public String toString() {
		return "sold out";
	}
}
```
```java
public class SoldState implements State {
    GumballMachine gumballMachine;

    public SoldState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

	public void insertQuarter() {
		System.out.println("Please wait, we're already giving you a gumball");
	}

	public void ejectQuarter() {
		System.out.println("Sorry, you already turned the crank");
	}

	public void turnCrank() {
		System.out.println("Turning twice doesn't get you another gumball!");
	}

	public void dispense() {
		gumballMachine.releaseBall();
		if (gumballMachine.getCount() > 0) {
			gumballMachine.setState(gumballMachine.getNoQuarterState());
		} else {
			System.out.println("Oops, out of gumballs!");
			gumballMachine.setState(gumballMachine.getSoldOutState());
		}
	}

	public String toString() {
		return "dispensing a gumball";
	}
}
```
```java
public class WinnerState implements State {
    GumballMachine gumballMachine;

    public WinnerState(GumballMachine gumballMachine) {
        this.gumballMachine = gumballMachine;
    }

	public void insertQuarter() {
		System.out.println("Please wait, we're already giving you a Gumball");
	}

	public void ejectQuarter() {
		System.out.println("Please wait, we're already giving you a Gumball");
	}

	public void turnCrank() {
		System.out.println("Turning again doesn't get you another gumball!");
	}

	public void dispense() {
		System.out.println("YOU'RE A WINNER! You get two gumballs for your quarter");
		gumballMachine.releaseBall();
		if (gumballMachine.getCount() == 0) {
			gumballMachine.setState(gumballMachine.getSoldOutState());
		} else {
			gumballMachine.releaseBall();
			if (gumballMachine.getCount() > 0) {
				gumballMachine.setState(gumballMachine.getNoQuarterState());
			} else {
            	System.out.println("Oops, out of gumballs!");
				gumballMachine.setState(gumballMachine.getSoldOutState());
			}
		}
	}

	public String toString() {
		return "despensing two gumballs for your quarter, because YOU'RE A WINNER!";
	}
}
```
下面是我们的糖果机代码
```java
public class GumballMachine {

	State soldOutState;
	State noQuarterState;
	State hasQuarterState;
	State soldState;
	State winnerState;

	State state = soldOutState;
	int count = 0;

	public GumballMachine(int numberGumballs) {
		soldOutState = new SoldOutState(this);
		noQuarterState = new NoQuarterState(this);
		hasQuarterState = new HasQuarterState(this);
		soldState = new SoldState(this);
		winnerState = new WinnerState(this);

		this.count = numberGumballs;
 		if (numberGumballs > 0) {
			state = noQuarterState;
		}
	}

	public void insertQuarter() {
		state.insertQuarter();
	}

	public void ejectQuarter() {
		state.ejectQuarter();
	}

	public void turnCrank() {
		state.turnCrank();
		state.dispense();
	}

	void setState(State state) {
		this.state = state;
	}

	void releaseBall() {
		System.out.println("A gumball comes rolling out the slot...");
		if (count != 0) {
			count = count - 1;
		}
	}

	int getCount() {
		return count;
	}

	void refill(int count) {
		this.count = count;
		state = noQuarterState;
	}

    public State getState() {
        return state;
    }

    public State getSoldOutState() {
        return soldOutState;
    }

    public State getNoQuarterState() {
        return noQuarterState;
    }

    public State getHasQuarterState() {
        return hasQuarterState;
    }

    public State getSoldState() {
        return soldState;
    }

    public State getWinnerState() {
        return winnerState;
    }

	public String toString() {
		StringBuffer result = new StringBuffer();
		result.append("\nMighty Gumball, Inc.");
		result.append("\nJava-enabled Standing Gumball Model #2004");
		result.append("\nInventory: " + count + " gumball");
		if (count != 1) {
			result.append("s");
		}
		result.append("\n");
		result.append("Machine is " + state + "\n");
		return result.toString();
	}
}
```
测试代码如下
```java
public class GumballMachineTestDrive {

	public static void main(String[] args) {
		GumballMachine gumballMachine =
			new GumballMachine(10);

		System.out.println(gumballMachine);

		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();
		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();

		System.out.println(gumballMachine);

		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();
		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();

		System.out.println(gumballMachine);

		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();
		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();

		System.out.println(gumballMachine);

		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();
		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();

		System.out.println(gumballMachine);

		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();
		gumballMachine.insertQuarter();
		gumballMachine.turnCrank();

		System.out.println(gumballMachine);
	}
}
```
测试结果为
![](https://pic.yupoo.com/crowhawk/2436b792/e9b19892.png)
![](https://pic.yupoo.com/crowhawk/c537aad7/f331a39f.png)

现在我们回到文章开头状态模式的定义,这个描述的第一部分**"状态模式允许对象在内部状态改变时改变它的行为"**附有相当多的涵义,因为这个模式将状态封装成独立的类,并将动作委托到代表当前状态的对象,行为会随着内部的状态改变而改变。

定义的第二部分**"对象看起来好像修改了它的类"**是什么意思呢?从客户的视角看:如果你使用的对象能够完全改变它的行为,那么你会觉得,这个对象实际上是从别的类实例化而来的。然而,实际上,我们是在使用组合通过简单引用不同的状态对象来造成类改变的假象。

状态模式的类图为
![](https://pic.yupoo.com/crowhawk/32ed23fd/6e0339f1.png)

###  状态模式和策略模式

我们把策略模式想成是除了继承之外的一种弹性替代方案。如果你继承定义了一个类的行为,你将被这个行为困住,甚至要修改它都很难。有了策略模式,你可以通过组合不同的对象来改变行为。

我们把状态模式想成是不用再context中放置许多条件判断的替代方案。通过将行为包装进状态对象中,你可以通过在context内简单地改变状态对象来改变context的行为。


text:
package com.wayfair.brickkit.brick;

import android.view.View;

/**
 * Interface defining a brick that can be clicked in two places.
 */
public interface MultiTouchableBrick {
    /**
     * {@link android.view.View.OnClickListener} to be called when primary hit target on brick is clicked.
     *
     * @return {@link android.view.View.OnClickListener}
     */
    View.OnClickListener onTouch();

    /**
     * {@link android.view.View.OnClickListener} to be called when second hit target on brick is clicked.
     *
     * @return {@link android.view.View.OnClickListener}
     */
    View.OnClickListener onSecondaryTouch();

    /**
     * Whether or not the brick is currently handling click events.
     *
     * @return true if the brick is currently handling click events, false otherwise
     */
    boolean isEnabled();

    /**
     * Whether or not the brick is currently handling click events on the secondary touch target.
     *
     * @return true if the brick is currently handling click events on the secondary touch target, false otherwise
     */
    boolean isSecondaryEnabled();
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>{{ $page_title or "" }} {{Config::get('system.sys_name').'@'.Config::get('system.sys_version')}}</title>
    <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>

    <link href="{{ asset("/bower_components/adminLTE/bootstrap/css/bootstrap.min.css") }}" rel="stylesheet" type="text/css" />

    <link href="{{ asset("/css/font-awesome.min.css")}}" rel="stylesheet" type="text/css" />

    <link href="{{ asset("/css/ionicons.min.css")}}" rel="stylesheet" type="text/css" />

    <link href="{{ asset("/bower_components/adminLTE/dist/css/AdminLTE.min.css")}}" rel="stylesheet" type="text/css" />

    <link href="{{ asset("/bower_components/adminLTE/dist/css/skins/skin-blue.min.css")}}" rel="stylesheet" type="text/css" />
@stack('cssFiles')

    @include('layouts.header')

    @include('layouts.sidebar')

                {{ $page_title or "" }}
                {{ $page_description or null }}

            @yield('content')

    @include('layouts.footer')

@stack('scriptFiles')
@stack('runningScripts')


text:
layout: page
title: Hopkins - Gates Wedding
date: 2016-05-24
author: Alice Hooper
tags: weekly links, java
status: published
summary: Vivamus mattis tincidunt ultrices. Duis a.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 06/12/2018
  endDate: 06/13/2018
  ctyhocn: YLLYDHX
  groupCode: HGW
published: true
---
In congue vitae ante eu dictum. Fusce ornare luctus interdum. Sed sed tincidunt nisl, non cursus nulla. Nullam dapibus maximus efficitur. Mauris at ultricies justo. Duis et lorem at ligula commodo mattis. Integer faucibus accumsan augue quis commodo. In vitae dignissim lacus. In dolor leo, interdum efficitur ornare in, finibus non urna. Sed tristique vulputate scelerisque. Quisque bibendum, est eu laoreet gravida, risus lacus malesuada purus, a viverra nisl ligula eu elit.

1 Nullam vel arcu lobortis, venenatis sem nec, rhoncus nulla.

Fusce lacinia finibus neque ac scelerisque. Sed eget varius massa, eu vehicula ex. Donec elementum, neque sit amet ultrices gravida, enim lectus varius tellus, at aliquam nisl erat sed nisl. Duis et ligula vitae erat aliquet consequat. Praesent at turpis dui. Ut rutrum facilisis lacus malesuada consectetur. Donec malesuada a ex ut vehicula. Vestibulum et orci at velit cursus consectetur. Cras rhoncus eros vel urna cursus, vel elementum risus iaculis. In hac habitasse platea dictumst. Donec eget ante sed diam pharetra semper. Curabitur bibendum et libero non bibendum.


text:
"""Support for devices connected to UniFi POE."""
from homeassistant.const import CONF_HOST
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC

from .const import CONF_CONTROLLER, CONF_SITE_ID, CONTROLLER_ID, DOMAIN
from .controller import UniFiController

async def async_setup(hass, config):
    """Component doesn't support configuration through configuration.yaml."""
    return True

async def async_setup_entry(hass, config_entry):
    """Set up the UniFi component."""
    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {}

    controller = UniFiController(hass, config_entry)

    controller_id = CONTROLLER_ID.format(
        host=config_entry.data[CONF_CONTROLLER][CONF_HOST],
        site=config_entry.data[CONF_CONTROLLER][CONF_SITE_ID]
    )

    hass.data[DOMAIN][controller_id] = controller

    if not await controller.async_setup():
        return False

    if controller.mac is None:
        return True

    device_registry = await \
        hass.helpers.device_registry.async_get_registry()
    device_registry.async_get_or_create(
        config_entry_id=config_entry.entry_id,
        connections={(CONNECTION_NETWORK_MAC, controller.mac)},
        manufacturer='Ubiquiti',
        model="UniFi Controller",
        name="UniFi Controller",
        # sw_version=config.raw['swversion'],
    )

    return True

async def async_unload_entry(hass, config_entry):
    """Unload a config entry."""
    controller_id = CONTROLLER_ID.format(
        host=config_entry.data[CONF_CONTROLLER][CONF_HOST],
        site=config_entry.data[CONF_CONTROLLER][CONF_SITE_ID]
    )
    controller = hass.data[DOMAIN].pop(controller_id)
    return await controller.async_reset()


text:
from django.core import urlresolvers
from django.conf import settings
from django.utils import translation

def reverse(viewname, urlconf=None, args=[], kwargs={}, prefix=None):
    locale = kwargs.pop('locale', translation.get_language())
    path = django_reverse(viewname, urlconf, args, kwargs, prefix)
    script_prefix = urlresolvers.get_script_prefix()
    if settings.USE_I18N:
        path = script_prefix + locale + '/' + path.partition(script_prefix)[2]
    return path

django_reverse = urlresolvers.reverse
urlresolvers.reverse = reverse


text:
brooklyn-tosca - karaf/init
===

[![Build Status](https://travis-ci.org/cloudsoft/brooklyn-tosca.svg?branch=master)](https://travis-ci.org/cloudsoft/brooklyn-tosca)

## Overview

This project builds a plugin to [Apache Brooklyn](http://brooklyn.io)
to understand [OASIS TOSCA](https://www.oasis-open.org/committees/tosca/) plans,
using [Alien4Cloud](http://alien4cloud.github.io).

It can be run as a standalone file, launching Brooklyn, or the JAR dropped in to your own Brooklyn.

## Build Notes

Consult the instructions in the root ancestor project for build instructions.

## Running

Once the project is built:

**Note:** As the Alien4Cloud code uses AWT, the full JRE or JDK is required as `headless` distributions
do not include AWT classes.

1. Install the `jar` bundle from the `target/` of this project to the Apache Brooklyn Karaf server

2. Add the [Alien4Cloud configuration file](../../brooklyn-tosca-dist/src/main/assembly/files/conf/alien4cloud-config.yml)
   to the Apache Brooklyn Karaf `etc/` folder.

3. Add the following to the Apache Brooklyn Karaf `system.properties` file (also in `etc/`):

```
brooklyn.experimental.feature.tosca=true
alien4cloud-config.file=file:///${karaf.etc}/alien4cloud-config.yml
```

4. Start (or restart) Apache Brooklyn. The Tosca code bundle initializes only when necessary, so visit the Brooklyn server in a browser to trigger ahead of time. Initialization may take a couple minutes.

That's it.  You can now run TOSCA files from Apache Brooklyn!


text:
% smssr_detector_many.m- script for applying the SMSSR detector on many images
%**************************************************************************
%
% author: Elena Ranguelova, NLeSc
% date created: 30 June 2015
% last modification date:
% modification details:
%**************************************************************************
% NOTES: if masked image is to be processed use the mask from separate file!!
%**************************************************************************
% EXAMPLES USAGE:
% simply type
%
% smssr_detector_many
%
% and follow questions.
%%
%**************************************************************************
clc;
disp('-------------------------------------------------------------------------');
disp('    Smart Morphology-based Stable Salient Regions (SMSSR) Detection      ');
disp('-------------------------------------------------------------------------');
disp('                                                                         ');

%% parameters
interactive = false;
verbose = false;
visualise_major = false;
visualise_minor = false;
execution_params = [verbose visualise_major visualise_minor];

preproc_types = [0 0];
%saliency_types = [1 1 0 0];
SE_size_factor = 0.05;
SE_size_factor_preproc = 0.002;
Area_factor = 0.25;
num_levels = 20;
thresh_type = 'h';
saliency_thresh = 0.75;
region_params = [SE_size_factor Area_factor saliency_thresh];

% saliency type
sal = input('Default saliency types [holes-Yes islands-Yes indent.-Yes protr.-Yes]? Y/N: ','s');

if (lower(sal)=='n')
     hol = input('Holes (Isolated dark on bright BG)? Y/N: ','s');
     if (lower(hol) == 'n')
         holes = 0;
     else
         holes = 1;
     end
     isl = input('Islands (Isolated bright on dark BG)? Y/N: ','s');
     if (lower(isl) == 'n')
         islands = 0;
     else
         islands = 1;
     end
     ind = input('Indentations (Border dark on bright BG)? Y/N: ','s');
     if (lower(ind) == 'n')
         indentations = 0;
     else
         indentations = 1;
     end
     pro = input('Protrusions (Border bright on dark BG)? Y/N: ','s');
     if (lower(pro) == 'n')
         protrusions = 0;
     else
         protrusions = 1;
     end
 end

saliency_types = [holes islands indentations protrusions];

disp('------------------------------------------------------------------');
disp('                                                                  ');

%% input paths
%input image directory
input_dir = input('Enter the full path to the input image directory: ','s');

fnames_struct = dir([input_dir '*.png']);

if isempty(fnames_struct)
    fnames_struct = dir([input_dir '*.pgm']);
end
if isempty(fnames_struct)
    fnames_struct = dir([input_dir '*.ppm']);
end
if isempty(fnames_struct)
    disp('The input directory must contain images in one of these formats: PNG/PPM/PGM!');
    return;
else
    num_images = length(fnames_struct);
end

for i = 1:num_images
    fnames{i} = fnames_struct(i).name;
end

% all images?
all = input(['Process all ' num2str(num_images) ' input images [y/n]? '],'s');
if strcmpi(all,'n')
    ind = input('Specify part (P) of images with beginning and end indicies or list (L) [P/L]?: ','s');
    if strcmpi(ind,'p')
        ind_beg = input('Enter the beginning image number: ');
        ind_end = input('Enter the ending image number: ');
        indicies = ind_beg:ind_end;
    else
        indicies = input('Enter the list of image indicies: ');
    end
else
    indicies = 1:num_images;
end

% output (feature) directory
features_dir = input('Enter the full path to the output features directory: ','s');

%% run for the selected images
for i = indicies
    base_fname = fnames{i};
    image_fname = [input_dir base_fname];
    k = find(base_fname =='.');
    l = k(end);
    if isempty(l)
        features_fname = [features_dir base_fname '.smssr'];
        regions_fname = [features_dir base_fname '_smartregions.mat'];

    else
        features_fname = [features_dir base_fname(1:l-1) '.smssr'];
        regions_fname = [features_dir base_fname(1:l-1) '_smartregions.mat'];
    end

    disp([' Processing image index # ' num2str(i) ' out of total ' num2str(length(indicies)) ' images...']);

    %% load the image & convert to gray-scale if  color
    image_data = imread(image_fname);
    if ndims(image_data) > 2
        image_data = rgb2gray(image_data);
    end

%     %% load & apply the mask, if any
     ROI = [];
%     if ~isempty(mask_filename)
%         s = load(ROI_mask_fname);
%         s_cell = struct2cell(s);
%         for k = 1:size(s_cell)
%             field = s_cell{k};
%             if islogical(field)
%                 ROI = field;
%             end
%         end
%         if isempty(ROI)
%            error('ROI_mask_fname does not contain binary mask!');
%         end
%     end

    %% SMSSR detector
    tic;
    if find(preproc_types)
        image_data = smssr_preproc(image_data, preproc_types);
    end
    [num_smartregions, features, saliency_masks] = smssr(image_data, ROI, ...
        num_levels, saliency_types, thresh_type, region_params, execution_params);
    toc
    % save the features
    disp('Saving ...');
    smssr_save(features_fname, regions_fname, num_smartregions, features, saliency_masks);

    disp('------------------------------------------------------------------');

end


text:
"""\
================================
Processing Parsed DVB PSI Tables
================================

Components for filtering and processing parsed Programme Status Information
(PSI) tables - that is the output from components in
Kamaelia.Device.DVB.Parse

Selecting 'currently' valid tables
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

FilterOutNotCurrent takes in parsed DVB PSI tables, but only outputs the
ones that are marked as being currently-valid. Tables that are not yet
valid are simply dropped.

NOTE: whether a table is currently-valid or not is *different* from concepts
such as present-following (now & next) used for event/programme information.
See DVB specification documents for a more detailed explanation.

Example Usage
-------------

Tuning to a particular broadcast multiplex and displaying the current selection
of services (channels) in the multiplex (as opposed to any future descriptions
of services that may be appearing later)::

    frequency = 505833330.0/1000000.0
    feparams = {
        "inversion" : dvb3.frontend.INVERSION_AUTO,
        "constellation" : dvb3.frontend.QAM_16,
        "code_rate_HP" : dvb3.frontend.FEC_3_4,
        "code_rate_LP" : dvb3.frontend.FEC_3_4,
    }

    PAT_PID=0

    Pipeline( DVB_Multiplex([PAT_PID], feparams),
              DVB_Demuxer({ PAT_PID:["outbox"]}),
              ReassemblePSITables(),
              ParseProgramAssociationTable(),
              FilterOutNotCurrent(),
              PrettifyProgramAssociationTable(),
              ConsoleEchoer(),
            ).run()

Behaviour
---------

Send parsed DVB PSI tables to this component's "inbox" inbox. If the
table is a currently-valid one it will immediately be sent on out of the
"outbox" outbox.

Tables that are not-yet-valid will be ignored.

If a shutdownMicroprocess or producerFinished message is received on this
component's "control" inbox, it will be immediately sent on out of the
"signal" outbox and the component will terminate.

How does it work?
-----------------

The parsed tables you send to this component are dictionaries. This component
simply checks the value of the 'current' key in the dictionary.
"""
from Axon.Component import component
from Axon.Ipc import producerFinished,shutdownMicroprocess

class FilterOutNotCurrent(component):
    """Filters out any parsed tables not labelled as currently valid"""

    def shutdown(self):
        while self.dataReady("control"):
            msg = self.recv("control")
            self.send(msg,"signal")
            if isinstance(msg, (shutdownMicroprocess, producerFinished)):
                return True
        return False

    def main(self):
        while not self.shutdown():

            while self.dataReady("inbox"):
                table = self.recv("inbox")
                if table['current']:
                    self.send(table,"outbox")

            self.pause()
            yield 1

__kamaelia_components__ = ( FilterOutNotCurrent, )