repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
khy/baler
|
spec/url_mapping_spec.rb
|
require File.dirname(__FILE__) + '/spec_helper'
class UrlMappingGame
include Baler
attr_accessor :league, :season
set_remote_source(ASSET_BASE + '/parser/|filename|.html') do |source|
source.set_context 'html > body > ol > li'
source.map :league => 'h1.global.league', :use_context => false
source.map :season => 'h1.global.season', :use_context => false
end
end
describe 'A class that mixes-in Baler' do
before(:each) do
@game = UrlMappingGame.new
end
context 'upon #gather' do
it 'should resolve the url against the supplied pattern' do
@game.gather :url_mapping => {'|filename|' => 'game'}
@game.league.should == "National Basketball Association"
@game.season.should == "2008-09"
@game.gather :url_mapping => {'|filename|' => 'alternate'}
@game.league.should == "Major League Baseball"
@game.season.should == "1996"
end
end
end
|
ashishbh/dropwizard
|
dropwizard-util/src/test/java/io/dropwizard/util/DataSizeUnitTest.java
|
<filename>dropwizard-util/src/test/java/io/dropwizard/util/DataSizeUnitTest.java
package io.dropwizard.util;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.function.Function;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.params.provider.Arguments.arguments;
class DataSizeUnitTest {
private static class Converter {
private Function<Long, Long> f;
Converter(Function<Long, Long> f) {
this.f = f;
}
long toOneDst() {
return f.apply(1L);
}
}
static Stream<Arguments> parameters() {
return Stream.of(
// bytes
arguments(DataSizeUnit.BYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.BYTES::toBytes), 1L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.BYTES::toKilobytes), 0L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.BYTES::toMegabytes), 0L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.BYTES::toGigabytes), 0L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.BYTES::toTerabytes), 0L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.BYTES::toPetabytes), 0L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.BYTES::toKibibytes), 0L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.BYTES::toMebibytes), 0L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.BYTES::toGibibytes), 0L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.BYTES::toTebibytes), 0L),
arguments(DataSizeUnit.BYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.BYTES::toPebibytes), 0L),
// kilobytes
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.KILOBYTES::toBytes), 1000L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.KILOBYTES::toKilobytes), 1L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.KILOBYTES::toMegabytes), 0L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.KILOBYTES::toGigabytes), 0L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.KILOBYTES::toTerabytes), 0L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.KILOBYTES::toPetabytes), 0L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.KILOBYTES::toKibibytes), 0L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.KILOBYTES::toMebibytes), 0L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.KILOBYTES::toGibibytes), 0L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.KILOBYTES::toTebibytes), 0L),
arguments(DataSizeUnit.KILOBYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.KILOBYTES::toPebibytes), 0L),
// megabytes
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.MEGABYTES::toBytes), 1000L * 1000L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.MEGABYTES::toKilobytes), 1000L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.MEGABYTES::toMegabytes), 1L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.MEGABYTES::toGigabytes), 0L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.MEGABYTES::toTerabytes), 0L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.MEGABYTES::toPetabytes), 0L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.MEGABYTES::toKibibytes), 1000L * 1000L / 1024L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.MEGABYTES::toMebibytes), 0L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.MEGABYTES::toGibibytes), 0L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.MEGABYTES::toTebibytes), 0L),
arguments(DataSizeUnit.MEGABYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.MEGABYTES::toPebibytes), 0L),
// gigabytes
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.GIGABYTES::toBytes), 1000L * 1000L * 1000L),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.GIGABYTES::toKilobytes), 1000L * 1000L),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.GIGABYTES::toMegabytes), 1000L),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.GIGABYTES::toGigabytes), 1L),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.GIGABYTES::toTerabytes), 0L),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.GIGABYTES::toPetabytes), 0L),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.GIGABYTES::toKibibytes), 1000L * 1000L * 1000L / 1024L),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.GIGABYTES::toMebibytes), 1000L * 1000L * 1000L / (1024L * 1024L)),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.GIGABYTES::toGibibytes), 0L),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.GIGABYTES::toTebibytes), 0L),
arguments(DataSizeUnit.GIGABYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.GIGABYTES::toPebibytes), 0L),
// terabytes
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.TERABYTES::toBytes), 1000L * 1000L * 1000L * 1000L),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.TERABYTES::toKilobytes), 1000L * 1000L * 1000L),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.TERABYTES::toMegabytes), 1000L * 1000L),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.TERABYTES::toGigabytes), 1000L),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.TERABYTES::toTerabytes), 1L),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.TERABYTES::toPetabytes), 0L),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.TERABYTES::toKibibytes), 1000L * 1000L * 1000L * 1000L / 1024L),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.TERABYTES::toMebibytes), 1000L * 1000L * 1000L * 1000L / (1024L * 1024L)),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.TERABYTES::toGibibytes), 1000L * 1000L * 1000L * 1000L / (1024L * 1024L * 1024L)),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.TERABYTES::toTebibytes), 0L),
arguments(DataSizeUnit.TERABYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.TERABYTES::toPebibytes), 0L),
// petabytes
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.PETABYTES::toBytes), 1000L * 1000L * 1000L * 1000L * 1000L),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.PETABYTES::toKilobytes), 1000L * 1000L * 1000L * 1000L),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.PETABYTES::toMegabytes), 1000L * 1000L * 1000L),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.PETABYTES::toGigabytes), 1000L * 1000L),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.PETABYTES::toTerabytes), 1000L),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.PETABYTES::toPetabytes), 1L),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.PETABYTES::toKibibytes), 1000L * 1000L * 1000L * 1000L * 1000L / 1024L),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.PETABYTES::toMebibytes), 1000L * 1000L * 1000L * 1000L * 1000L / (1024L * 1024L)),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.PETABYTES::toGibibytes), 1000L * 1000L * 1000L * 1000L * 1000L / (1024L * 1024L * 1024L)),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.PETABYTES::toTebibytes), 1000L * 1000L * 1000L * 1000L * 1000L / (1024L * 1024L * 1024L * 1024L)),
arguments(DataSizeUnit.PETABYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.PETABYTES::toPebibytes), 0L),
// kibibytes
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.KIBIBYTES::toBytes), 1024L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.KIBIBYTES::toKilobytes), 1L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.KIBIBYTES::toMegabytes), 0L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.KIBIBYTES::toGigabytes), 0L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.KIBIBYTES::toTerabytes), 0L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.KIBIBYTES::toPetabytes), 0L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.KIBIBYTES::toKibibytes), 1L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.KIBIBYTES::toMebibytes), 0L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.KIBIBYTES::toGibibytes), 0L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.KIBIBYTES::toTebibytes), 0L),
arguments(DataSizeUnit.KIBIBYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.KIBIBYTES::toPebibytes), 0L),
// mebibytes
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.MEBIBYTES::toBytes), 1024L * 1024L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.MEBIBYTES::toKilobytes), 1024L * 1024L / 1000L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.MEBIBYTES::toMegabytes), 1L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.MEBIBYTES::toGigabytes), 0L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.MEBIBYTES::toTerabytes), 0L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.MEBIBYTES::toPetabytes), 0L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.MEBIBYTES::toKibibytes), 1024L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.MEBIBYTES::toMebibytes), 1L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.MEBIBYTES::toGibibytes), 0L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.MEBIBYTES::toTebibytes), 0L),
arguments(DataSizeUnit.MEBIBYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.MEBIBYTES::toPebibytes), 0L),
// gibibytes
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.GIBIBYTES::toBytes), 1024L * 1024L * 1024L),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.GIBIBYTES::toKilobytes), 1024L * 1024L * 1024L / 1000L),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.GIBIBYTES::toMegabytes), 1024L * 1024L * 1024L / (1000L * 1000L)),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.GIBIBYTES::toGigabytes), 1L),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.GIBIBYTES::toTerabytes), 0L),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.GIBIBYTES::toPetabytes), 0L),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.GIBIBYTES::toKibibytes), 1024L * 1024L),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.GIBIBYTES::toMebibytes), 1024L),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.GIBIBYTES::toGibibytes), 1L),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.GIBIBYTES::toTebibytes), 0L),
arguments(DataSizeUnit.GIBIBYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.GIBIBYTES::toPebibytes), 0L),
// tebibytes
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.TEBIBYTES::toBytes), 1024L * 1024L * 1024L * 1024L),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.TEBIBYTES::toKilobytes), 1024L * 1024L * 1024L * 1024L / 1000L),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.TEBIBYTES::toMegabytes), 1024L * 1024L * 1024L * 1024L / (1000L * 1000L)),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.TEBIBYTES::toGigabytes), 1024L * 1024L * 1024L * 1024L / (1000L * 1000L * 1000L)),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.TEBIBYTES::toTerabytes), 1L),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.TEBIBYTES::toPetabytes), 0L),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.TEBIBYTES::toKibibytes), 1024L * 1024L * 1024L),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.TEBIBYTES::toMebibytes), 1024L * 1024L),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.TEBIBYTES::toGibibytes), 1024L),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.TEBIBYTES::toTebibytes), 1L),
arguments(DataSizeUnit.TEBIBYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.TEBIBYTES::toPebibytes), 0L),
// pebibytes
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.BYTES, new Converter(DataSizeUnit.PEBIBYTES::toBytes), 1024L * 1024L * 1024L * 1024L * 1024L),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.KILOBYTES, new Converter(DataSizeUnit.PEBIBYTES::toKilobytes), 1024L * 1024L * 1024L * 1024L * 1024L / 1000L),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.MEGABYTES, new Converter(DataSizeUnit.PEBIBYTES::toMegabytes), 1024L * 1024L * 1024L * 1024L * 1024L / (1000L * 1000L)),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.GIGABYTES, new Converter(DataSizeUnit.PEBIBYTES::toGigabytes), 1024L * 1024L * 1024L * 1024L * 1024L / (1000L * 1000L * 1000L)),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.TERABYTES, new Converter(DataSizeUnit.PEBIBYTES::toTerabytes), 1024L * 1024L * 1024L * 1024L * 1024L / (1000L * 1000L * 1000L * 1000L)),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.PETABYTES, new Converter(DataSizeUnit.PEBIBYTES::toPetabytes), 1L),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.KIBIBYTES, new Converter(DataSizeUnit.PEBIBYTES::toKibibytes), 1024L * 1024L * 1024L * 1024L),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.MEBIBYTES, new Converter(DataSizeUnit.PEBIBYTES::toMebibytes), 1024L * 1024L * 1024L),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.GIBIBYTES, new Converter(DataSizeUnit.PEBIBYTES::toGibibytes), 1024L * 1024L),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.TEBIBYTES, new Converter(DataSizeUnit.PEBIBYTES::toTebibytes), 1024L),
arguments(DataSizeUnit.PEBIBYTES, DataSizeUnit.PEBIBYTES, new Converter(DataSizeUnit.PEBIBYTES::toPebibytes), 1L));
}
@ParameterizedTest(name = "{0} => {1}")
@MethodSource("parameters")
void oneSrcUnitInDstUnits(DataSizeUnit src, DataSizeUnit dst, Converter c, long value) {
assertThat(dst.convert(1, src)).isEqualTo(value);
assertThat(c.toOneDst()).isEqualTo(value);
}
}
|
lta-disco-unimib-it/KLFA
|
src-bct-porting/file/JFLAP3Codec.java
|
<reponame>lta-disco-unimib-it/KLFA
/*******************************************************************************
* Copyright 2019 <NAME>, <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import regular.RegularExpression;
import automata.Automaton;
import automata.State;
import automata.Transition;
import grammar.Grammar;
import grammar.Production;
import grammar.UnboundGrammar;
/**
* This is the codec for reading JFLAP structures in the JFLAP 3 saved
* file format.
*
* @author <NAME>
*/
public class JFLAP3Codec extends Codec {
/**
* Given a file, this will return a JFLAP structure associated
* with that file. This method should always return a structure,
* or throw a {@link ParseException} in the event of failure with
* a message detailing the nature of why the decoder failed.
* @param file the file to decode into a structure
* @param parameters this decoder ignores all parameters
* @return a JFLAP structure resulting from the interpretation of
* the JFLAP 3 saved file
* @throws ParseException if there was a problem reading the file
*/
public Serializable decode(File file, Map parameters) {
if (file.getName().endsWith(GRAMMAR_SUFFIX))
return readGrammar(file);
if (file.getName().endsWith(REGULAR_EXPRESSION_SUFFIX))
return readRE(file);
return readAutomaton(file);
}
/**
* Reads the file as a regular expression.
* @param file the file to read
* @return the regular expression associated with this document
*/
private RegularExpression readRE(File file) {
String rstring = ""; // If nothing found, RE is blank.
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.startsWith("#")) continue;
if (line.length()==0) continue;
rstring = line;
}
} catch (FileNotFoundException e) {
throw new ParseException("Could not find file "
+file.getName()+"!");
} catch (IOException e) {
throw new ParseException("Error accessing file to write!");
}
return new RegularExpression(rstring);
}
/**
* Reads the file as a grammar.
* @param file the file to read
* @return the grammar associated with this document
*/
private Grammar readGrammar(File file) {
Grammar g = new UnboundGrammar();
int lineNum = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
line = line.trim();
lineNum++;
if (line.length()==0) continue;
if (line.startsWith("#")) continue;
String[] elems = line.split("\\s+");
int len = elems.length;
if (len > 3 || len < 2 || !elems[1].equals("->")) {
throw new ParseException
("Line "+lineNum+" is not formatted properly!");
}
g.addProduction(new Production(elems[0], len==3?elems[2]:""));
}
} catch (FileNotFoundException e) {
throw new ParseException("Could not find file "
+file.getName()+"!");
} catch (IOException e) {
throw new ParseException("Error accessing file to write!");
}
return g;
}
/**
* Reads the file as an automaton.
* @param file the file to read
* @return the automaton associated with this document
*/
private Automaton readAutomaton(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
// Read the automaton type.
String line = reader.readLine().trim();
if (line.equals(FINITE_AUTOMATON_CODE))
return readFA(reader);
if (line.equals(PUSHDOWN_AUTOMATON_CODE))
return readPDA(reader);
if (line.equals(TURING_MACHINE_CODE))
return readTM(reader);
throw new ParseException("Unknown machine type "+line+"!");
} catch (NullPointerException e) {
throw new ParseException("Unexpected end of file!");
} catch (FileNotFoundException e) {
throw new ParseException("Could not find file "
+file.getName()+"!");
} catch (IOException e) {
throw new ParseException("Error accessing file to write!");
}
}
/**
* Reads the lines in the reader as a finite automaton.
* @param reader the source of lines in the file
*/
private automata.fsa.FiniteStateAutomaton readFA(BufferedReader reader)
throws IOException {
automata.fsa.FiniteStateAutomaton fa =
new automata.fsa.FiniteStateAutomaton();
// Generic states.
State[] states = readStateCreate(fa, reader);
String[][][] groups = readTransitionGroups
(2, 1, states.length, reader);
for (int s=0; s<groups.length; s++) {
for (int g=0; g<groups[s].length; g++) {
String[] group = groups[s][g];
State to=states[Integer.parseInt(group[1])-1], from=states[s];
if (group[0].equals("null")) group[0]="";
Transition t = new automata.fsa.FSATransition
(from, to, group[0]);
fa.addTransition(t);
}
}
readStateMove(states, reader);
return fa;
}
/**
* Reads the lines in the reader as a pushdown automaton.
* @param reader the source of lines in the file
*/
private automata.pda.PushdownAutomaton readPDA(BufferedReader reader)
throws IOException {
String ender = reader.readLine().trim();
if (!(ender.equals("FINAL") || ender.equals("EMPTY") ||
ender.equals("FINAL+EMPTY")))
throw new ParseException
(ender+" is a bad finishing type for PDA!");
automata.pda.PushdownAutomaton pda =
new automata.pda.PushdownAutomaton();
// Generic states.
State[] states = readStateCreate(pda, reader);
String[][][] groups = readTransitionGroups
(5, 3, states.length, reader);
for (int s=0; s<groups.length; s++) {
for (int g=0; g<groups[s].length; g++) {
String[] group = groups[s][g];
State to=states[Integer.parseInt(group[3])-1], from=states[s];
try {
Transition t;
// Take care of lambda symbols.
int[] check = {0,1,4};
for (int i=0; i<check.length; i++)
if (group[check[i]].equals("null"))
group[check[i]] = "";
// Create the transition.
t = new automata.pda.PDATransition
(from, to, group[0], group[1], group[4]);
pda.addTransition(t);
} catch (IllegalArgumentException e) {
throw new ParseException(e.getMessage());
}
}
}
readStateMove(states, reader);
return pda;
}
/**
* Reads the lines in the reader as a Turing machine.
* @param reader the source of lines in the file
*/
private automata.turing.TuringMachine readTM(BufferedReader reader)
throws IOException {
if (!reader.readLine().trim().equals("TAPE"))
throw new ParseException("Expected TAPE line absent!");
// Try to read the number of tapes.
int tapes = 0;
try {
tapes = Integer.parseInt(reader.readLine());
if (tapes != 1 && tapes != 2)
throw new ParseException("May only have 1 or 2 tapes!");
} catch (NumberFormatException e) {
throw new ParseException("Bad format for number of tapes!");
}
automata.turing.TuringMachine tm =
new automata.turing.TuringMachine(tapes);
// Generic states.
State[] states = readStateCreate(tm, reader);
String[][][] groups = readTransitionGroups
(1+3*tm.tapes(), 1, states.length, reader);
for (int s=0; s<groups.length; s++) {
for (int g=0; g<groups[s].length; g++) {
String[] group = groups[s][g];
State to=states[Integer.parseInt(group[1])-1], from=states[s];
try {
Transition t;
// Take care of blank tape symbols.
int[] check = tm.tapes()==1?new int[]{0,2}
:new int[]{0,2,4,5};
for (int i=0; i<check.length; i++)
if (group[check[i]].equals("B"))
group[check[i]] = "";
// Create the transition.
if (tm.tapes() == 1)
t = new automata.turing.TMTransition
(from, to, group[0], group[2],
group[3].toUpperCase());
else
t = new automata.turing.TMTransition
(from, to,
new String[]{group[0], group[4]},
new String[]{group[2], group[5]},
new String[]{group[3].toUpperCase(),
group[6].toUpperCase()});
tm.addTransition(t);
} catch (IllegalArgumentException e) {
throw new ParseException(e.getMessage());
}
}
}
readStateMove(states, reader);
return tm;
}
/**
* Reads the number of states for the automaton.
* @param automaton the automaton
* @param reader the buffered reader
* @return an array of the states created
*/
private State[] readStateCreate(Automaton automaton, BufferedReader reader)
throws IOException {
// Read the number of states.
State[] states = null;
try {
int numStates = Integer.parseInt(reader.readLine());
if (numStates < 0)
throw new ParseException
("Number of states cannot be "+numStates+"!");
states = new State[numStates];
} catch (NumberFormatException e) {
throw new ParseException("Bad format for number of states!");
}
for (int i=0; i<states.length; i++)
states[i] = automaton.createState(new java.awt.Point(0,0));
// Next possibly two lines have something to do with alphabet.
reader.readLine();
if (!(automaton instanceof automata.fsa.FiniteStateAutomaton))
reader.readLine();
// Read the ID of the initial state.
try {
int initStateID = Integer.parseInt(reader.readLine());
if (initStateID < 1 || initStateID > states.length)
throw new ParseException("Initial state cannot be "
+initStateID+".");
automaton.setInitialState(states[initStateID-1]);
} catch (NumberFormatException e) {
throw new ParseException("Bad format for initial state ID!");
}
// Read the IDs of the final states.
String line = reader.readLine();
String[] lineTokens = line.split("\\s+");
if (lineTokens.length == 0)
throw new ParseException("Final state list is empty line!");
try {
int last = Integer.parseInt(lineTokens[lineTokens.length-1]);
if (last != 0)
throw new ParseException
("Final state list not terminated with 0!");
try {
for (int i=0; i<lineTokens.length-1; i++) {
automaton.addFinalState
(states[Integer.parseInt(lineTokens[i])-1]);
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException("Bad final state ID read!");
}
} catch (NumberFormatException e) {
throw new ParseException("Bad format in final state list!");
}
return states;
}
/**
* Reads the state positions and moves the states.
* @param states the array of states
* @param reader the buffered reader
*/
private void readStateMove(State[] states, BufferedReader reader)
throws IOException {
for (int i=0; i<states.length; i++) {
int x, y;
String[] tokens=reader.readLine().split("\\s+");
try {
x = Integer.parseInt(tokens[1]);
y = Integer.parseInt(tokens[2]);
} catch (NumberFormatException e) {
throw new ParseException
("State "+(i+1)+"'s position badly formatted.");
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException
("State "+(i+1)+"'s position string too short.");
}
states[i].getPoint().setLocation(x,y);
}
}
/**
* Read the string sequences for each transition.
* @param groupSize the number of tokens for each transition
* @param idPosition the position in each group of the state ID
* @param numStates the number of states
* @param reader the buffered reader
* @return an array of size number of states, with each entry an
* array of size number of transitions for a given state, with
* each entry of that an array of size "groupSize"
*/
private String[][][] readTransitionGroups
(int groupSize, int idPosition, int numStates, BufferedReader reader)
throws IOException {
String[][][] groups = new String[numStates][][];
for (int s=0; s<numStates; s++) {
ParseException p = new ParseException("Transition line "+(s+1)+
" badly formatted.");
String[] tokens = reader.readLine().split("\\s+");
if ((tokens.length % groupSize) != 1 ||
!tokens[tokens.length-1].equals("EOL"))
throw p;
groups[s] = new String[tokens.length / groupSize][];
for (int g=0; g<groups[s].length; g++) {
groups[s][g] = new String[groupSize];
for (int i=0; i<groupSize; i++)
groups[s][g][i] = tokens[groupSize*g+i];
try {
int i=Integer.parseInt(groups[s][g][idPosition]);
if (i<1 || i>numStates) throw p;
} catch (NumberFormatException e) {
throw p;
}
}
}
return groups;
}
/**
* Given a structure, this will attempt to write the structure as
* a JFLAP 3 saved file.
* @param structure the structure to encode
* @param file
* @param parameters implementors have the option of accepting
* custom parameters in the form of a map
* @return the file to which the structure was written
* @throws EncodeException if there was a problem writing the file
*/
public File encode(Serializable structure, File file,
Map parameters) {
return file;
}
/**
* Returns if this type of structure can be encoded with this
* encoder. This should not perform a detailed check of the
* structure, since the user will have no idea why it will not be
* encoded correctly if the {@link #encode} method does not throw
* a {@link ParseException}.
* @param structure the structure to check
* @return if the structure, perhaps with minor changes, could
* possibly be written to a file
*/
public boolean canEncode(Serializable structure) {
return false;
/*return (structure instanceof Automaton &&
(!(structure instanceof TuringMachine) ||
((TuringMachine)structure).tapes() <= 2))
|| structure instanceof Grammar;*/
}
/**
* Returns the description of this codec.
* @return the description of this codec
*/
public String getDescription() {
return "JFLAP 3 File";
}
/** The JFLAP 3 file suffixes. */
public static final String FINITE_AUTOMATON_SUFFIX = ".FA",
PUSHDOWN_AUTOMATON_SUFFIX = ".PDA",
TURING_MACHINE_SUFFIX = ".TM",
TWO_TAPE_TURING_MACHINE_SUFFIX = ".TTM",
GRAMMAR_SUFFIX = ".GRM",
REGULAR_EXPRESSION_SUFFIX = ".REX";
/** Automaton type codes internal to the file. */
private static final String FINITE_AUTOMATON_CODE = "One-Way-FSA",
PUSHDOWN_AUTOMATON_CODE = "PDAP",
TURING_MACHINE_CODE = "REGTM";
}
|
flydzen/ITMO_algo
|
course1/Laba2/L/main.cpp
|
<filename>course1/Laba2/L/main.cpp
#include <iostream>
#include <vector>
#include <map>
using namespace std;
template<typename T>
void merge(vector<T> &v, int left, int right, int mid) {
int u1 = left;
int u2 = mid;
vector<T> res((int) right - left);
while (u1 < mid && u2 < right) {
if (v[u1] < v[u2]) {
res[u1 + u2 - left - mid] = v[u1];
u1++;
} else {
res[u1 + u2 - left - mid] = v[u2];
u2++;
}
}
while (u1 < mid) {
res[u1 + u2 - left - mid] = v[u1];
u1++;
}
while (u2 < right) {
res[u1 + u2 - left - mid] = v[u2];
u2++;
}
for (int i = 0; i < right - left; i++) {
v[left + i] = res[i];
}
}
template<typename T>
void sort(vector<T> &v, int l, int r) {
if (r - l <= 1) {
return;
}
int mid = (l + r) / 2;
sort(v, l, mid);
sort(v, mid, r);
merge(v, l, r, mid);
}
int part(vector<pair<double, int>> &v, int l, int r) {
int m = l;
for (int i = l; i < r; i++) {
if (v[i].first < v[r].first) {
swap(v[m++], v[i]);
}
}
swap(v[m], v[r]);
return m;
}
void kt(vector<pair<double, int>> &v, int k) {
int l = 0;
int r = (int) v.size() - 1;
while (true) {
int m = part(v, l, r);
if (m == k) {
return;
} else if (m < k) {
l = m + 1;
} else {
r = m - 1;
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
vector<pair<int, int>> v(n);
for (int i = 0; i < n; i++) {
double t1, t2;
cin >> t1 >> t2;
v[i] = make_pair(t1, t2);
}
vector<pair<double, int>> a(n);
double l = 0;
double r = 10000002;
while (r - l > 0.000000003) {
double x = l + (r - l) / 2;
for (int i = 0; i < n; i++) {
a[i] = make_pair(v[i].first - x * v[i].second, i);
}
kt(a, n - k);
long double sum = 0;
for (int i = n - k; i < n; i++) {
sum += a[i].first;
}
if (sum < 0) {
r = x;
} else {
l = x;
}
}
vector<int> answer;
for (int i = n - k; i < n; i++) {
answer.push_back(a[i].second);
}
sort(answer, 0, k);
for (int el : answer) {
cout << el + 1 << " ";
}
return 0;
}
|
RahulGera/RWRider
|
RWRider.xcframework/ios-x86_64-simulator/RWRider.framework/Headers/UIAlertController+Show.h
|
//
// UIAlertController+Show.h
// RideDriver
//
// Created by Kitos on 11/7/16.
// Copyright © 2016 FuelMe LLC. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIAlertController (Show)
@property (nonatomic, strong) UIWindow *alertWindow;
- (void)show;
- (void)show:(BOOL)animated;
@end
|
StoriCapstone/storio
|
client/socket.js
|
import io from 'socket.io-client'
import store, {getNewComment, } from './store';
const socket = io(window.location.origin)
socket.on('new-comment', comment => {
store.dispatch(getNewComment(comment))
})
socket.on('connect', () => {
console.log('Connected!')
})
export default socket
|
myoukaku/bksge
|
libs/core/render/src/bksge_core_render_frame_buffer.cpp
|
/**
* @file bksge_core_render_frame_buffer.cpp
*
* @brief FrameBuffer の実装
*
* @author myoukaku
*/
#include <bksge/fnd/config.hpp>
#if !defined(BKSGE_HEADER_ONLY)
#include <bksge/core/render/inl/frame_buffer_inl.hpp>
#endif
|
c-core-labs/Sherlock-Frontend
|
src/components/ItemKeywords.js
|
import { Box, makeStyles } from '@material-ui/core';
import Chip from '@material-ui/core/Chip'
import { secondary, themeVariables } from '../theme'
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
justifyContent: 'left',
flexWrap: 'wrap',
listStyle: 'none',
padding: theme.spacing(0)
},
chip: {
margin: '2px',
backgroundColor: secondary,
radius: themeVariables.borderRadius
}
}));
const ItemKeywords = (props) => {
const classes = useStyles()
if (!props.data) {
return (
<Box></Box>
)
} else {
return (
<Box component="ul" className={classes.root}>
{props.data.map((keyword, index) => {
return (
<li key={index}>
<Chip
className={classes.chip}
label={keyword}
clickable
/>
</li>
)}
)}
</Box>
)
}
}
export default ItemKeywords
|
weekend27/Thinking-in-Java
|
code/concurrency/BasicThreads.java
|
<reponame>weekend27/Thinking-in-Java
package concurrency;
public class BasicThreads {
public static void main(String[] args) {
Thread t = new Thread(new LiftOff());
t.start();
System.out.println("Waiting for Liftoff");
}
}
|
rachitananda/ProblemSolvingProblems
|
src/com/problem/solving/ds/tree/problem/SpiralTraversalTree.java
|
package com.problem.solving.ds.tree.problem;
import com.problem.solving.ds.tree.BinaryTree;
import com.problem.solving.ds.tree.Node;
import java.util.Stack;
/**
* https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/
* //TODO recursive method
*/
public class SpiralTraversalTree {
BinaryTree tree = new BinaryTree();
public static void main(String args[]) {
SpiralTraversalTree problem = new SpiralTraversalTree();
problem.createTree();
problem.spiralTraversal(problem.tree);
}
/*
1
/ \
2 3
/ \ / \
7 6 5 4
/ \ / \
8 9 10 11
*/
private void createTree() {
tree = new BinaryTree();
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
Node n7 = new Node(7);
Node n8 = new Node(8);
Node n9 = new Node(9);
Node n10 = new Node(10);
Node n11 = new Node(11);
tree.root = n1;
n1.left = n2;
n1.right = n3;
n2.left = n7;
n2.right = n6;
n3.left = n5;
n3.right = n4;
n7.left = n8;
n7.right = n9;
n5.left = n10;
n5.right = n11;
}
private void spiralTraversal(BinaryTree tree) {
if (tree.root == null) {
return;
}
System.out.print("----- Level Order Spiral Traversal--- ");
boolean isReverse = true;//for root node
//when isRevere= true add to stack as S0 child RL
//else add to stack as S1 child LR
Stack<Node> s0 = new Stack<>();// push LR , reverse=true
Stack<Node> s1 = new Stack<>();// push RL reverse=false
s0.push(tree.root);
//until both stacks are empty
while (!s0.isEmpty() || !s1.isEmpty()) {
while (!s0.isEmpty()) {
//reverse order RL
Node node = s0.pop();
System.out.print(" " + node.data);
if (node.right != null) {
s1.push(node.right);
}
if (node.left != null) {
s1.push(node.left);
}
}
while (!s1.isEmpty()) {
//correct order LR
Node node = s1.pop();
System.out.print(" " + node.data);
if (node.left != null) {
s0.push(node.left);
}
if (node.right != null) {
s0.push(node.right);
}
}
}
}
}
|
antkar/syn
|
syn/src/main/java/org/antkar/syn/internal/bnf/BnfElement.java
|
<filename>syn/src/main/java/org/antkar/syn/internal/bnf/BnfElement.java<gh_stars>1-10
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.antkar.syn.internal.bnf;
import org.antkar.syn.internal.Checks;
/**
* An element of a BNF grammar. Can be either a terminal or a nonterminal element.
*/
public abstract class BnfElement {
private final int elementIndex;
BnfElement(int elementIndex) {
Checks.argument(elementIndex >= 0);
this.elementIndex = elementIndex;
}
/**
* Returns the index of this element in the grammar.
*/
public final int getElementIndex() {
return elementIndex;
}
}
|
YangChengTeam/english_study
|
base/src/main/java/yc/com/base/CommonInfoHelper.java
|
package yc.com.base;
import android.content.Context;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.vondear.rxtools.RxLogTool;
import java.lang.reflect.Type;
/**
* Created by wanglin on 2018/2/9 11:34.
*/
public class CommonInfoHelper {
public static <T> void getO(Context context, String key, final Type type, final onParseListener<T> listener) {
try {
CacheUtils.readCache(context, key, new CacheUtils.SubmitRunable() {
@Override
public void run() {
final String json = this.getJson();
UIUtils.post(new Runnable() {
@Override
public void run() {
T t = parseData(json, type);
if (listener != null) {
listener.onParse(t);
}
}
});
}
}, new CacheUtils.SubmitRunable() {
@Override
public void run() {
if (listener != null) {
listener.onFail(getJson());
}
}
});
} catch (Exception e) {
RxLogTool.e(CommonInfoHelper.class.getClass().getName(), "error:->>" + e.getMessage());
}
}
public static <T> void setO(Context context, T t, String key) {
try {
CacheUtils.writeCache(context, key, JSON.toJSONString(t));
} catch (Exception e) {
RxLogTool.e(CommonInfoHelper.class.getClass().getName(), "error:->>" + e.getMessage());
}
}
private static <T> T parseData(String result, Type type) {
if (type.toString().equals("java.lang.String")) {
return (T) result;
}
T resultInfo;
if (type != null) {
resultInfo = JSON.parseObject(result, type);
} else {
resultInfo = JSON.parseObject(result, new TypeReference<T>() {
}.getType());
}
return resultInfo;
}
public interface onParseListener<T> {
void onParse(T o);
void onFail(String json);
}
}
|
ajitkhaparde/trex-core
|
src/dpdk/drivers/net/octeontx_ep/otx_ep_ethdev.c
|
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright(C) 2021 Marvell.
*/
#include <ethdev_pci.h>
#include "otx2_common.h"
#include "otx_ep_common.h"
#include "otx_ep_vf.h"
#include "otx2_ep_vf.h"
#include "otx_ep_rxtx.h"
#define OTX_EP_DEV(_eth_dev) \
((struct otx_ep_device *)(_eth_dev)->data->dev_private)
static const struct rte_eth_desc_lim otx_ep_rx_desc_lim = {
.nb_max = OTX_EP_MAX_OQ_DESCRIPTORS,
.nb_min = OTX_EP_MIN_OQ_DESCRIPTORS,
.nb_align = OTX_EP_RXD_ALIGN,
};
static const struct rte_eth_desc_lim otx_ep_tx_desc_lim = {
.nb_max = OTX_EP_MAX_IQ_DESCRIPTORS,
.nb_min = OTX_EP_MIN_IQ_DESCRIPTORS,
.nb_align = OTX_EP_TXD_ALIGN,
};
static int
otx_ep_dev_info_get(struct rte_eth_dev *eth_dev,
struct rte_eth_dev_info *devinfo)
{
struct otx_ep_device *otx_epvf;
otx_epvf = OTX_EP_DEV(eth_dev);
devinfo->speed_capa = ETH_LINK_SPEED_10G;
devinfo->max_rx_queues = otx_epvf->max_rx_queues;
devinfo->max_tx_queues = otx_epvf->max_tx_queues;
devinfo->min_rx_bufsize = OTX_EP_MIN_RX_BUF_SIZE;
devinfo->max_rx_pktlen = OTX_EP_MAX_PKT_SZ;
devinfo->rx_offload_capa = DEV_RX_OFFLOAD_JUMBO_FRAME;
devinfo->rx_offload_capa |= DEV_RX_OFFLOAD_SCATTER;
devinfo->tx_offload_capa = DEV_TX_OFFLOAD_MULTI_SEGS;
devinfo->max_mac_addrs = OTX_EP_MAX_MAC_ADDRS;
devinfo->rx_desc_lim = otx_ep_rx_desc_lim;
devinfo->tx_desc_lim = otx_ep_tx_desc_lim;
return 0;
}
static int
otx_ep_dev_start(struct rte_eth_dev *eth_dev)
{
struct otx_ep_device *otx_epvf;
unsigned int q;
int ret;
otx_epvf = (struct otx_ep_device *)OTX_EP_DEV(eth_dev);
/* Enable IQ/OQ for this device */
ret = otx_epvf->fn_list.enable_io_queues(otx_epvf);
if (ret) {
otx_ep_err("IOQ enable failed\n");
return ret;
}
for (q = 0; q < otx_epvf->nb_rx_queues; q++) {
rte_write32(otx_epvf->droq[q]->nb_desc,
otx_epvf->droq[q]->pkts_credit_reg);
rte_wmb();
otx_ep_info("OQ[%d] dbells [%d]\n", q,
rte_read32(otx_epvf->droq[q]->pkts_credit_reg));
}
otx_ep_info("dev started\n");
return 0;
}
/* Stop device and disable input/output functions */
static int
otx_ep_dev_stop(struct rte_eth_dev *eth_dev)
{
struct otx_ep_device *otx_epvf = OTX_EP_DEV(eth_dev);
otx_epvf->fn_list.disable_io_queues(otx_epvf);
return 0;
}
static int
otx_ep_chip_specific_setup(struct otx_ep_device *otx_epvf)
{
struct rte_pci_device *pdev = otx_epvf->pdev;
uint32_t dev_id = pdev->id.device_id;
int ret = 0;
switch (dev_id) {
case PCI_DEVID_OCTEONTX_EP_VF:
otx_epvf->chip_id = dev_id;
ret = otx_ep_vf_setup_device(otx_epvf);
otx_epvf->fn_list.disable_io_queues(otx_epvf);
break;
case PCI_DEVID_OCTEONTX2_EP_NET_VF:
case PCI_DEVID_CN98XX_EP_NET_VF:
otx_epvf->chip_id = dev_id;
ret = otx2_ep_vf_setup_device(otx_epvf);
otx_epvf->fn_list.disable_io_queues(otx_epvf);
break;
default:
otx_ep_err("Unsupported device\n");
ret = -EINVAL;
}
if (!ret)
otx_ep_info("OTX_EP dev_id[%d]\n", dev_id);
return ret;
}
/* OTX_EP VF device initialization */
static int
otx_epdev_init(struct otx_ep_device *otx_epvf)
{
uint32_t ethdev_queues;
int ret = 0;
ret = otx_ep_chip_specific_setup(otx_epvf);
if (ret) {
otx_ep_err("Chip specific setup failed\n");
goto setup_fail;
}
otx_epvf->fn_list.setup_device_regs(otx_epvf);
otx_epvf->eth_dev->rx_pkt_burst = &otx_ep_recv_pkts;
if (otx_epvf->chip_id == PCI_DEVID_OCTEONTX_EP_VF)
otx_epvf->eth_dev->tx_pkt_burst = &otx_ep_xmit_pkts;
else if (otx_epvf->chip_id == PCI_DEVID_OCTEONTX2_EP_NET_VF ||
otx_epvf->chip_id == PCI_DEVID_CN98XX_EP_NET_VF)
otx_epvf->eth_dev->tx_pkt_burst = &otx2_ep_xmit_pkts;
ethdev_queues = (uint32_t)(otx_epvf->sriov_info.rings_per_vf);
otx_epvf->max_rx_queues = ethdev_queues;
otx_epvf->max_tx_queues = ethdev_queues;
otx_ep_info("OTX_EP Device is Ready\n");
setup_fail:
return ret;
}
static int
otx_ep_dev_configure(struct rte_eth_dev *eth_dev)
{
struct otx_ep_device *otx_epvf = OTX_EP_DEV(eth_dev);
struct rte_eth_dev_data *data = eth_dev->data;
struct rte_eth_rxmode *rxmode;
struct rte_eth_txmode *txmode;
struct rte_eth_conf *conf;
conf = &data->dev_conf;
rxmode = &conf->rxmode;
txmode = &conf->txmode;
if (eth_dev->data->nb_rx_queues > otx_epvf->max_rx_queues ||
eth_dev->data->nb_tx_queues > otx_epvf->max_tx_queues) {
otx_ep_err("invalid num queues\n");
return -EINVAL;
}
otx_ep_info("OTX_EP Device is configured with num_txq %d num_rxq %d\n",
eth_dev->data->nb_rx_queues, eth_dev->data->nb_tx_queues);
otx_epvf->rx_offloads = rxmode->offloads;
otx_epvf->tx_offloads = txmode->offloads;
return 0;
}
/**
* Setup our receive queue/ringbuffer. This is the
* queue the Octeon uses to send us packets and
* responses. We are given a memory pool for our
* packet buffers that are used to populate the receive
* queue.
*
* @param eth_dev
* Pointer to the structure rte_eth_dev
* @param q_no
* Queue number
* @param num_rx_descs
* Number of entries in the queue
* @param socket_id
* Where to allocate memory
* @param rx_conf
* Pointer to the struction rte_eth_rxconf
* @param mp
* Pointer to the packet pool
*
* @return
* - On success, return 0
* - On failure, return -1
*/
static int
otx_ep_rx_queue_setup(struct rte_eth_dev *eth_dev, uint16_t q_no,
uint16_t num_rx_descs, unsigned int socket_id,
const struct rte_eth_rxconf *rx_conf __rte_unused,
struct rte_mempool *mp)
{
struct otx_ep_device *otx_epvf = OTX_EP_DEV(eth_dev);
struct rte_pktmbuf_pool_private *mbp_priv;
uint16_t buf_size;
if (q_no >= otx_epvf->max_rx_queues) {
otx_ep_err("Invalid rx queue number %u\n", q_no);
return -EINVAL;
}
if (num_rx_descs & (num_rx_descs - 1)) {
otx_ep_err("Invalid rx desc number should be pow 2 %u\n",
num_rx_descs);
return -EINVAL;
}
if (num_rx_descs < (SDP_GBL_WMARK * 8)) {
otx_ep_err("Invalid rx desc number should at least be greater than 8xwmark %u\n",
num_rx_descs);
return -EINVAL;
}
otx_ep_dbg("setting up rx queue %u\n", q_no);
mbp_priv = rte_mempool_get_priv(mp);
buf_size = mbp_priv->mbuf_data_room_size - RTE_PKTMBUF_HEADROOM;
if (otx_ep_setup_oqs(otx_epvf, q_no, num_rx_descs, buf_size, mp,
socket_id)) {
otx_ep_err("droq allocation failed\n");
return -1;
}
eth_dev->data->rx_queues[q_no] = otx_epvf->droq[q_no];
return 0;
}
/**
* Release the receive queue/ringbuffer. Called by
* the upper layers.
*
* @param rxq
* Opaque pointer to the receive queue to release
*
* @return
* - nothing
*/
static void
otx_ep_rx_queue_release(void *rxq)
{
struct otx_ep_droq *rq = (struct otx_ep_droq *)rxq;
struct otx_ep_device *otx_epvf = rq->otx_ep_dev;
int q_id = rq->q_no;
if (otx_ep_delete_oqs(otx_epvf, q_id))
otx_ep_err("Failed to delete OQ:%d\n", q_id);
}
/**
* Allocate and initialize SW ring. Initialize associated HW registers.
*
* @param eth_dev
* Pointer to structure rte_eth_dev
*
* @param q_no
* Queue number
*
* @param num_tx_descs
* Number of ringbuffer descriptors
*
* @param socket_id
* NUMA socket id, used for memory allocations
*
* @param tx_conf
* Pointer to the structure rte_eth_txconf
*
* @return
* - On success, return 0
* - On failure, return -errno value
*/
static int
otx_ep_tx_queue_setup(struct rte_eth_dev *eth_dev, uint16_t q_no,
uint16_t num_tx_descs, unsigned int socket_id,
const struct rte_eth_txconf *tx_conf __rte_unused)
{
struct otx_ep_device *otx_epvf = OTX_EP_DEV(eth_dev);
int retval;
if (q_no >= otx_epvf->max_tx_queues) {
otx_ep_err("Invalid tx queue number %u\n", q_no);
return -EINVAL;
}
if (num_tx_descs & (num_tx_descs - 1)) {
otx_ep_err("Invalid tx desc number should be pow 2 %u\n",
num_tx_descs);
return -EINVAL;
}
retval = otx_ep_setup_iqs(otx_epvf, q_no, num_tx_descs, socket_id);
if (retval) {
otx_ep_err("IQ(TxQ) creation failed.\n");
return retval;
}
eth_dev->data->tx_queues[q_no] = otx_epvf->instr_queue[q_no];
otx_ep_dbg("tx queue[%d] setup\n", q_no);
return 0;
}
/**
* Release the transmit queue/ringbuffer. Called by
* the upper layers.
*
* @param txq
* Opaque pointer to the transmit queue to release
*
* @return
* - nothing
*/
static void
otx_ep_tx_queue_release(void *txq)
{
struct otx_ep_instr_queue *tq = (struct otx_ep_instr_queue *)txq;
otx_ep_delete_iqs(tq->otx_ep_dev, tq->q_no);
}
/* Define our ethernet definitions */
static const struct eth_dev_ops otx_ep_eth_dev_ops = {
.dev_configure = otx_ep_dev_configure,
.dev_start = otx_ep_dev_start,
.dev_stop = otx_ep_dev_stop,
.rx_queue_setup = otx_ep_rx_queue_setup,
.rx_queue_release = otx_ep_rx_queue_release,
.tx_queue_setup = otx_ep_tx_queue_setup,
.tx_queue_release = otx_ep_tx_queue_release,
.dev_infos_get = otx_ep_dev_info_get,
};
static int
otx_epdev_exit(struct rte_eth_dev *eth_dev)
{
struct otx_ep_device *otx_epvf;
uint32_t num_queues, q;
otx_ep_info("%s:\n", __func__);
otx_epvf = OTX_EP_DEV(eth_dev);
otx_epvf->fn_list.disable_io_queues(otx_epvf);
num_queues = otx_epvf->nb_rx_queues;
for (q = 0; q < num_queues; q++) {
if (otx_ep_delete_oqs(otx_epvf, q)) {
otx_ep_err("Failed to delete OQ:%d\n", q);
return -EINVAL;
}
}
otx_ep_info("Num OQs:%d freed\n", otx_epvf->nb_rx_queues);
num_queues = otx_epvf->nb_tx_queues;
for (q = 0; q < num_queues; q++) {
if (otx_ep_delete_iqs(otx_epvf, q)) {
otx_ep_err("Failed to delete IQ:%d\n", q);
return -EINVAL;
}
}
otx_ep_dbg("Num IQs:%d freed\n", otx_epvf->nb_tx_queues);
return 0;
}
static int
otx_ep_eth_dev_uninit(struct rte_eth_dev *eth_dev)
{
if (rte_eal_process_type() != RTE_PROC_PRIMARY)
return 0;
otx_epdev_exit(eth_dev);
eth_dev->dev_ops = NULL;
eth_dev->rx_pkt_burst = NULL;
eth_dev->tx_pkt_burst = NULL;
return 0;
}
static int
otx_ep_eth_dev_init(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pdev = RTE_ETH_DEV_TO_PCI(eth_dev);
struct otx_ep_device *otx_epvf = OTX_EP_DEV(eth_dev);
struct rte_ether_addr vf_mac_addr;
/* Single process support */
if (rte_eal_process_type() != RTE_PROC_PRIMARY)
return 0;
otx_epvf->eth_dev = eth_dev;
otx_epvf->port_id = eth_dev->data->port_id;
eth_dev->dev_ops = &otx_ep_eth_dev_ops;
eth_dev->data->mac_addrs = rte_zmalloc("otx_ep", RTE_ETHER_ADDR_LEN, 0);
if (eth_dev->data->mac_addrs == NULL) {
otx_ep_err("MAC addresses memory allocation failed\n");
eth_dev->dev_ops = NULL;
return -ENOMEM;
}
rte_eth_random_addr(vf_mac_addr.addr_bytes);
rte_ether_addr_copy(&vf_mac_addr, eth_dev->data->mac_addrs);
otx_epvf->hw_addr = pdev->mem_resource[0].addr;
otx_epvf->pdev = pdev;
otx_epdev_init(otx_epvf);
if (pdev->id.device_id == PCI_DEVID_OCTEONTX2_EP_NET_VF)
otx_epvf->pkind = SDP_OTX2_PKIND;
else
otx_epvf->pkind = SDP_PKIND;
otx_ep_info("using pkind %d\n", otx_epvf->pkind);
return 0;
}
static int
otx_ep_eth_dev_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
struct rte_pci_device *pci_dev)
{
return rte_eth_dev_pci_generic_probe(pci_dev,
sizeof(struct otx_ep_device),
otx_ep_eth_dev_init);
}
static int
otx_ep_eth_dev_pci_remove(struct rte_pci_device *pci_dev)
{
return rte_eth_dev_pci_generic_remove(pci_dev,
otx_ep_eth_dev_uninit);
}
/* Set of PCI devices this driver supports */
static const struct rte_pci_id pci_id_otx_ep_map[] = {
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_CAVIUM, PCI_DEVID_OCTEONTX_EP_VF) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_CAVIUM, PCI_DEVID_OCTEONTX2_EP_NET_VF) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_CAVIUM, PCI_DEVID_CN98XX_EP_NET_VF) },
{ .vendor_id = 0, /* sentinel */ }
};
static struct rte_pci_driver rte_otx_ep_pmd = {
.id_table = pci_id_otx_ep_map,
.drv_flags = RTE_PCI_DRV_NEED_MAPPING,
.probe = otx_ep_eth_dev_pci_probe,
.remove = otx_ep_eth_dev_pci_remove,
};
RTE_PMD_REGISTER_PCI(net_otx_ep, rte_otx_ep_pmd);
RTE_PMD_REGISTER_PCI_TABLE(net_otx_ep, pci_id_otx_ep_map);
RTE_PMD_REGISTER_KMOD_DEP(net_otx_ep, "* igb_uio | vfio-pci");
RTE_LOG_REGISTER(otx_net_ep_logtype, pmd.net.octeontx_ep, NOTICE);
|
cwsteinbach/schedoscope
|
schedoscope-transformation-pig/src/test/scala/org/schedoscope/scheduler/driver/PigDriverTest.scala
|
<gh_stars>100-1000
/**
* Copyright 2015 Otto (GmbH & Co KG)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.schedoscope.scheduler.driver
import org.scalatest.{FlatSpec, Matchers}
import org.schedoscope.dsl.transformations.PigTransformation
import org.schedoscope.test.resources.LocalTestResources
import org.schedoscope.test.resources.TestDriverRunCompletionHandlerCallCounter._
class PigDriverTest extends FlatSpec with Matchers {
lazy val testResources = new LocalTestResources()
lazy val driver = testResources.driverFor[PigTransformation]("pig")
lazy val okTransformation = driver.rigTransformationForTest(PigTransformation("/* a comment */"), testResources)
lazy val badTransformation = driver.rigTransformationForTest(PigTransformation("FAIL ME"), testResources)
"PigDriver" should "have transformation name pig" in {
driver.transformationName shouldBe "pig"
}
it should "execute pig transformations synchronously" in {
val driverRunState = driver.runAndWait(okTransformation)
driverRunState shouldBe a[DriverRunSucceeded[_]]
}
it should "execute another pig transformations synchronously" in {
val driverRunState = driver.runAndWait(okTransformation)
driverRunState shouldBe a[DriverRunSucceeded[_]]
}
it should "execute pig transformations and return errors when running synchronously" in {
val driverRunState = driver.runAndWait(badTransformation)
driverRunState shouldBe a[DriverRunFailed[_]]
}
it should "execute pig transformations asynchronously" in {
val driverRunHandle = driver.run(okTransformation)
var runWasAsynchronous = false
while (driver.getDriverRunState(driverRunHandle).isInstanceOf[DriverRunOngoing[_]])
runWasAsynchronous = true
runWasAsynchronous shouldBe true
driver.getDriverRunState(driverRunHandle) shouldBe a[DriverRunSucceeded[_]]
}
it should "execute pig transformations and return errors when running asynchronously" in {
val driverRunHandle = driver.run(badTransformation)
var runWasAsynchronous = false
while (driver.getDriverRunState(driverRunHandle).isInstanceOf[DriverRunOngoing[_]])
runWasAsynchronous = true
runWasAsynchronous shouldBe true
driver.getDriverRunState(driverRunHandle) shouldBe a[DriverRunFailed[_]]
}
it should "call its DriverRunCompletitionHandlers' driverRunCompleted upon request" in {
val runHandle = driver.run(okTransformation)
while (driver.getDriverRunState(runHandle).isInstanceOf[DriverRunOngoing[_]]) {}
driver.driverRunCompleted(runHandle)
driverRunCompletedCalled(runHandle, driver.getDriverRunState(runHandle)) shouldBe true
}
it should "call its DriverRunCompletitionHandlers' driverRunStarted upon request" in {
val runHandle = driver.run(okTransformation)
driver.driverRunStarted(runHandle)
driverRunStartedCalled(runHandle) shouldBe true
}
}
|
rolandosborne/coredb
|
app/src/main/java/org/coredb/service/UserService.java
|
package org.coredb.service;
import java.security.*;
import java.security.spec.*;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.*;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.coredb.model.Amigo;
import org.coredb.model.UserEntry;
import org.coredb.jpa.entity.EmigoEntity;
import org.coredb.jpa.entity.Account;
import org.coredb.jpa.entity.AccountUser;
import org.coredb.jpa.repository.AccountRepository;
import org.coredb.jpa.repository.AccountUserRepository;
import org.coredb.jpa.repository.EmigoEntityRepository;
import org.coredb.api.NotFoundException;
import javax.ws.rs.NotAcceptableException;
import org.springframework.dao.DataIntegrityViolationException;
import java.nio.file.AccessDeniedException;
@Service
public class UserService {
@Autowired
private AccountRepository accountRepository;
@Autowired
private AccountUserRepository accountUserRepository;
@Autowired
private EmigoEntityRepository emigoEntityRepository;
private final Logger log = LoggerFactory.getLogger(this.getClass());
public AccountUser getUser(Account account, String id) throws NotFoundException {
AccountUser user = accountUserRepository.findOneByAccountAndEmigoId(account, id);
if(user == null) {
throw new NotFoundException(404, "account user not found");
}
return user;
}
@Transactional
public void deleteEmigo(Account account, String emigoId) throws NotFoundException {
// increment revision
account.setUserRevision(account.getUserRevision() + 1);
accountRepository.save(account);
// delete referenced emigo
AccountUser user = getUser(account, emigoId);
accountUserRepository.delete(user);
}
public Amigo getIdentity(String id) throws NotFoundException {
EmigoEntity entity = emigoEntityRepository.findOneByEmigoId(id);
if(entity == null) {
throw new NotFoundException(404, "identity not found");
}
return entity;
}
public List<UserEntry> getEmigos(Account account) {
List<AccountUser> users = accountUserRepository.findAll();
// return list as base class
@SuppressWarnings("unchecked")
List<UserEntry> entries = (List<UserEntry>)(List<?>)users;
return entries;
}
}
|
iot-block/iotchain
|
common/jvm/src/main/scala/jbok/common/FileUtil.scala
|
package jbok.common
import java.io.InputStream
import java.nio.channels.{FileLock, OverlappingFileLockException}
import java.nio.charset.{Charset, StandardCharsets}
import java.nio.file.{Path, StandardOpenOption}
import better.files.File
import cats.effect.{Resource, Sync}
import cats.implicits._
import jbok.common.log.Logger
trait FileUtil[F[_]] {
def read(path: Path): F[String]
def readResource(path: String): F[String]
def open(path: Path, create: Boolean = true, asDirectory: Boolean = false): F[File]
def inputStream(path: Path): Resource[F, InputStream]
def dump(text: String, path: Path, create: Boolean = true): F[Unit]
def append(text: String, path: Path, create: Boolean = true): F[Unit]
def lock(path: Path, content: String = ""): Resource[F, FileLock]
def remove(path: Path): F[Unit]
def temporaryFile(prefix: String = "", suffix: String = ""): Resource[F, File]
def temporaryDir(prefix: String = ""): Resource[F, File]
}
object FileUtil {
implicit val defaultCharset: Charset = StandardCharsets.UTF_8
final case class FileLockErr(path: Path) extends Exception(s"path=${path.toAbsolutePath} is already locked")
def apply[F[_]](implicit ev: FileUtil[F]): FileUtil[F] = ev
implicit def instance[F[_]](implicit F: Sync[F]): FileUtil[F] = new FileUtil[F] {
private[this] val log = Logger[F]
override def read(path: Path): F[String] =
log.i(s"reading text from path=${path.toAbsolutePath}") >>
F.delay(File(path).lines.mkString("\n"))
override def readResource(path: String) =
log.i(s"reading text from resource=${path}") >>
F.delay(better.files.Resource.getAsString(path))
override def open(path: Path, create: Boolean, asDirectory: Boolean): F[File] =
if (create) {
F.delay(File(path).createIfNotExists(createParents = true, asDirectory = asDirectory))
} else {
F.delay(File(path))
}
override def inputStream(path: Path): Resource[F, InputStream] =
Resource.fromAutoCloseable(open(path, create = false).map(_.newInputStream))
override def dump(text: String, path: Path, create: Boolean): F[Unit] =
log.i(s"writing text to path=${path.toAbsolutePath}") >>
open(path, create, asDirectory = false).flatMap(file => F.delay(file.overwrite(text)).void)
override def append(text: String, path: Path, create: Boolean): F[Unit] =
log.i(s"append text to path=${path.toAbsolutePath}") >>
open(path, create, asDirectory = false).flatMap(file => F.delay(file.append(text)).void)
override def lock(path: Path, content: String): Resource[F, FileLock] =
Resource
.make[F, FileLock] {
for {
_ <- log.i(s"acquiring file lock at path=${path.toAbsolutePath}")
file <- F.delay(File(path).createIfNotExists(createParents = true))
channel <- F.delay(file.newFileChannel(StandardOpenOption.WRITE :: Nil))
lock <- F.delay(channel.tryLock()).adaptError {
case _: OverlappingFileLockException => FileLockErr(path)
}
_ <- if (lock == null) F.raiseError(FileLockErr(path)) else F.unit
_ <- F.delay(file.deleteOnExit())
} yield lock
} { lock =>
F.delay(File(path).delete(swallowIOExceptions = true)) >> F.delay(lock.release()) >>
log.i(s"released file lock at path=${path.toAbsolutePath}")
}
override def remove(path: Path): F[Unit] =
log.i(s"removing file at path=${path.toAbsolutePath}") >> F.delay(File(path).delete()).void
override def temporaryFile(prefix: String, suffix: String): Resource[F, File] = Resource {
for {
file <- F.delay(File.newTemporaryFile(prefix, suffix))
_ <- F.delay(file.deleteOnExit())
_ <- log.i(s"creating temporary file path=${file.path}")
} yield file -> (F.delay(file.delete()) >> log.i(s"deleted temporary file path=${file.path}"))
}
override def temporaryDir(prefix: String): Resource[F, File] = Resource {
for {
file <- F.delay(File.newTemporaryDirectory(prefix))
_ <- F.delay(file.deleteOnExit())
_ <- log.i(s"creating temporary dir path=${file.path}")
} yield file -> (F.delay(file.delete()) >> log.i(s"deleted temporary dir path=${file.path}"))
}
}
}
|
dcos/dcos-installer-ui
|
src/js/components/icons/IconDownload.js
|
<reponame>dcos/dcos-installer-ui
import React from 'react';
module.exports = class IconDownload extends React.Component {
render() {
return (
<svg
className="icon icon-download"
height="16px"
viewBox="0 0 16 16"
width="16px"
{...this.props}>
<polygon points="15.22 11.79 13.07 13.94 13.07 7.15 12.07 7.15 12.07 13.94 9.93 11.79 9.22 12.5 12.57 15.85 15.93 12.5 15.22 11.79"/>
<path d="M3.07,4.15h7v1h-7v-1Zm0,3h7v1h-7v-1Zm0,3h5v1h-5v-1Zm10,5-13,0v-15h13v5h-1v-4h-11v13h7v1m5,0" fill-rule="evenodd"/>
</svg>
);
}
}
|
mantamusica/java_cic_grupos
|
grupo2.ejercicio027-master-55488720b7727e1119dc0c903221207dc74e5212/src/main/java/es/cic/curso/grupo2/ejercicio027/ui/VentanaContenidoCampos.java
|
package es.cic.curso.grupo2.ejercicio027.ui;
import java.util.ArrayList;
import java.util.List;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Page;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import es.cic.curso.grupo2.ejercicio027.modelo.Campo;
public class VentanaContenidoCampos extends Window {
private static final String NUMERICO = "Numérico";
String totalNombres = "";
String mostrarEnNotificacion = "";
public VentanaContenidoCampos(List<Campo> listaCampos) {
super("Añade el valor a los campos");
center();
setHeight("600px");
setWidth("600px");
setClosable(false);
setModal(true);
ArrayList<String> campos = new ArrayList<>();
ArrayList<String> tipos = new ArrayList<>();
ArrayList<String> nombres = new ArrayList<>();
ArrayList<TextField> totalCampos = new ArrayList<>();
VerticalLayout verticalLayout = new VerticalLayout();
HorizontalLayout toolbar = new HorizontalLayout();
toolbar.setMargin(true);
toolbar.setSpacing(true);
verticalLayout.setMargin(true);
verticalLayout.setSpacing(true);
int size = listaCampos.size();
TextField campoRellenar;
for(int i = 0; i < size; i++){
campoRellenar = new TextField("Campo " + listaCampos.get(i).getNombreCampo() +
" de tipo " + listaCampos.get(i).getTipoCampo());
totalCampos.add(campoRellenar);
campos.add(listaCampos.get(i).getNombreCampo());
tipos.add(listaCampos.get(i).getTipoCampo());
verticalLayout.addComponent(campoRellenar);
verticalLayout.setComponentAlignment(campoRellenar, Alignment.TOP_CENTER);
}
Notification aviso = new Notification("Campos: "+campos+" añadidos correctamente" +
" con los valores: "+nombres+"." + " Total nombres: " + totalNombres
);
aviso.setDelayMsec(5000);
Button aceptar = new Button("Aceptar");
aceptar.setWidth("230px");
aceptar.setIcon(FontAwesome.CHECK);
Button cancelar = new Button("Cancelar", event -> close());
cancelar.setIcon(FontAwesome.CLOSE);
cancelar.setWidth("230px");
aceptar.addClickListener(e->{
String nombreCampoString = "";
String tipoCampoString = "";
mostrarEnNotificacion = "";
mostrarEnNotificacion = "";
boolean confirma = true;
for (int i= 0; i<size;i++){
nombreCampoString = totalCampos.get(i).getValue().trim();
tipoCampoString = listaCampos.get(i).getTipoCampo();
if(comprobarCampos(tipoCampoString, nombreCampoString)){
nombres.add(totalCampos.get(i).getValue());
totalNombres = totalNombres + totalCampos.get(i).getValue();
mostrarEnNotificacion += "Campo " + listaCampos.get(i).getNombreCampo() + " . Valor: " +
totalCampos.get(i).getValue() + "\n";
if(i != (size - 1)){
totalNombres += ";";
}
} else {
confirma = false;
break;
}
}
if(!confirma){
Notification.show("Introduzca todos los campos correctamente.");
} else {
Notification.show(mostrarEnNotificacion);
close();
}
});
toolbar.addComponents(cancelar,aceptar);
toolbar.setComponentAlignment(aceptar, Alignment.BOTTOM_RIGHT);
toolbar.setComponentAlignment(cancelar, Alignment.BOTTOM_LEFT);
verticalLayout.addComponent(toolbar);
verticalLayout.setComponentAlignment(toolbar, Alignment.BOTTOM_CENTER);
setContent(verticalLayout);
}
private boolean comprobarCampos(String tipoCampo, String nombreCampoString){
boolean comprueba = true;
if(nombreCampoString.isEmpty()){
comprueba = false;
} else if (tipoCampo.equals(NUMERICO)) {
try{
Double.parseDouble(nombreCampoString);
}catch(Exception e){
comprueba = false;
}
}
return comprueba;
}
}
|
yingjieg/jiveapps
|
examples/opensocial/activity/petting-zoo/js/activitydata.js
|
<gh_stars>10-100
/*
* Copyright 2011 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var objects = {
"bessie": {
key: "bessie",
id: "urn:activtiyTest:animal/101",
title: "Bessie the cow",
image: "http://venaglia-z800:8000/bessie.jpg",
mediaLink: {
mediaType: "photo",
url: "http://venaglia-z800:8000/bessie.jpg"
},
objectType: "urn:activityTest:animal",
summary: "All about <i>${object.title}</i><br/><a style=\"color:#ff0; font-size:32px; font-weight:bold;\" href=\"http://www.lipsum.com/\" onclick=\"alert('pwnzd');\">Lorem ipsum</a> dolor sit amit..."
},
"lucky": {
key: "lucky",
id: "urn:activtiyTest:animal/102",
title: "Lucky the goat",
image: "http://venaglia-z800:8000/lucky.jpg",
mediaLink: {
mediaType: "blog",
url: "http://venaglia-z800:8080/people/admin/blog/2010/11/03/lucky-the-goat"
},
objectType: "urn:activityTest:animal",
summary: "All about <i>${object.title}</i><br/><a style=\"color:#ff0; font-size:32px; font-weight:bold;\" href=\"http://www.lipsum.com/\" onclick=\"alert('pwnzd');\">Lorem ipsum</a> dolor sit amit..."
},
"molly": {
key: "molly",
id: "urn:activtiyTest:animal/103",
title: "Molly the pig",
image: "http://venaglia-z800:8000/molly.jpg",
mediaLink: {
mediaType: "video",
url: "http://www.youtube.com/watch?v=F26H5n7tRFw"
},
objectType: "urn:activityTest:animal",
summary: "All about <i>${object.title}</i><br/><a style=\"color:#ff0; font-size:32px; font-weight:bold;\" href=\"http://www.lipsum.com/\" onclick=\"alert('pwnzd');\">Lorem ipsum</a> dolor sit amit..."
},
"rex": {
key: "rex",
id: "urn:activtiyTest:animal/104",
title: "Rex the chicken",
image: "http://venaglia-z800:8000/rex.jpg",
mediaLink: {
mediaType: "document",
url: "http://venaglia-z800:8000/chicken-pot-pie.pdf"
},
objectType: "urn:activityTest:animal",
summary: "All about <i><a href=\'jive:app://canvas.rex?params={\"chicken\":\"1234\"}\'>${object.title}</a></i><br/><a style=\"color:#ff0; font-size:32px; font-weight:bold;\" href=\"http://www.lipsum.com/\" onclick=\"alert('pwnzd');\">Lorem ipsum</a> dolor sit amit..."
}
};
var verbs = {
"feed": {
key: "feed",
uri: "urn:activityTest:feed",
label: "fed",
icon: "http://venaglia-z800:8000/feed.16x16.png",
jiveDisplay: "grouped",
actionLinks: [
{title:"corn",url:"http://venaglia-z800:8000/food/corn"},
{title:"alfalfa",url:"http://venaglia-z800:8000/food/alfalfa"},
{title:"ignore"}
]
},
"groom": {
key: "groom",
uri: "urn:activityTest:groom",
label: "groomed",
icon: "http://venaglia-z800:8000/brush.16x16.png",
jiveDisplay: "grouped",
actionLinks: [
{title:"brush",url:"http://venaglia-z800:8000/washrack/brush"},
{title:"bathe",url:"http://venaglia-z800:8000/washrack/bathe"},
{title:"ignore"}
]
},
"buy": {
key: "buy",
uri: "urn:activityTest:buy",
label: "bought",
icon: "http://venaglia-z800:8000/money.16x16.png",
jiveDisplay: "update",
actionLinks: [
{title:"approve",url:"http://venaglia-z800:8000/auction/buy"},
{title:"reject",url:"http://venaglia-z800:8000/auction/pass"}
]
},
"sell": {
key: "sell",
uri: "urn:activityTest:sell",
label: "sold",
icon: "http://venaglia-z800:8000/money.16x16.png",
jiveDisplay: "update",
actionLinks: [
{title:"approve",url:"http://venaglia-z800:8000/auction/sell"},
{title:"reject",url:"http://venaglia-z800:8000/auction/pass"}
]
}
};
var targets = {
"neighbor": {
id: "urn:activtiyTest:person/201",
title: "a neighbor",
objectType: "urn:activityTest:person"
},
"friend": {
id: "urn:activtiyTest:person/202",
title: "a friend",
objectType: "urn:activityTest:person"
},
"flintstone": {
id: "urn:jiveObject:user/2002",
title: "<NAME>",
objectType: "urn:activityTest:person"
}
};
|
gwdg/openproject-revisions_git
|
db/migrate/20140530204954_add_fingerprint_to_gitolite_public_keys.rb
|
<filename>db/migrate/20140530204954_add_fingerprint_to_gitolite_public_keys.rb
class AddFingerprintToGitolitePublicKeys < ActiveRecord::Migration
def self.up
add_column :gitolite_public_keys, :fingerprint, :string, null: false
add_index :gitolite_public_keys, :fingerprint
end
def self.down
remove_index :gitolite_public_keys, :fingerprint
remove_column :gitolite_public_keys, :fingerprint
end
end
|
ikatun/nnode
|
build/decorating-helpers-template.js
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.decoratingHelpersTemplate = void 0;
const decoratingHelpersTemplate = `
var akessrfljlrgqgd_decorate = function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var akessrfljlrgqgd_metadata = function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var akessrfljlrgqgd_param = function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var akessrfljlrgqgd_determineType = function(t) {
if (t === undefined) {
return Object;
}
if (typeof t === 'function') {
return t;
}
if (typeof t === 'object') {
var values = Object.values(t);
if (!values.length) {
console.log('Undetermined enum', t);
return Object;
}
if (values.filter(function(value) { return typeof value === 'string'; }).length === values.length) {
return String;
}
if (values.filter(function(value) { return typeof value === 'number'; }).length === values.length) {
return Number;
}
console.log('Undetermined enum', t);
return Object;
}
}
`;
exports.decoratingHelpersTemplate = decoratingHelpersTemplate;
|
taylorgorman/intervention
|
resources/scripts/user-interface/components/Page/ImportRowEmpty.js
|
import { __ } from '../../utils/wp';
/**
* Import Row Empty
*/
const ImportRowEmpty = () => {
return (
<div
className="
h-[44px]
lg:h-[40px]
px-16
flex
items-center
text-14
leading-none
text-gray-50
last:border-0"
>
{__('Nothing found')}.
</div>
);
};
export default ImportRowEmpty;
|
ctwardy/jacobs-vault
|
ais-analytics/aisanalytics/utilities.py
|
<gh_stars>1-10
from argparse import ArgumentParser
def cli_arguments():
parser = ArgumentParser()
parser.add_argument(
"--ais-input-table",
dest="AIS_INPUT_TABLE",
)
parser.add_argument(
"--velocities-output-table",
dest="VELOCITIES_OUTPUT_TABLE",
)
args = parser.parse_args()
return args
|
adobe/reactor-extension-alloy
|
test/functional/dataElements/xdmObject/helpers/editor.js
|
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import { t } from "testcafe";
import { createTestIdSelector } from "../../../helpers/dataTestIdSelectors";
const editor = createTestIdSelector("editor");
export default {
expectExists: async () => {
await t
.expect(editor.exists)
.ok("Editor exists when it is expected to not exist.");
},
expectNotExists: async () => {
await t
.expect(editor.exists)
.notOk("Editor does not exist when it is expected to exist.");
}
};
|
jasonwang1109/react-bootstrap-v4
|
src/InputGroup.js
|
<gh_stars>1-10
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames/bind';
class InputGroup extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
label: this.props.label,
value: this.props.data,
disabled: this.props.disabled
};
}
componentWillReceiveProps(nextProp) {
this.setState({
value:nextProp.data
});
}
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.disabled !== this.props.disabled) {
return true
}
return nextState.value !== this.state.value;
}
getValue() {
return this.state.value;
}
setValue(val) {
this.setState({value:val});
}
/*********************
* Event
*********************/
changeHandler = (e) => {
this.setState({
value:e.target.value
});
if (this.props.onChange && typeof this.props.onChange === 'function') {
this.props.onChange(e.target.value,this);
}
};
/*********************
* render method
*********************/
renderSummary() {
if (this.props.summary === '') {
return null
}
return (
<small className="form-text text-muted text-truncate">
{this.props.summary}
</small>
)
}
render() {
//default style
let def_style = {
"width": this.props.width + "px"
};
//input size
let size = null;
switch (this.props.size) {
case "sm":
size = {
main : "input-group-sm",
label: "inputGroup-sizing-sm",
input: "inputGroup-sizing-sm",
};
break;
case "lg":
size = {
main : "input-group-lg",
label: "inputGroup-sizing-lg",
input: "inputGroup-sizing-lg",
};
break;
default:
size = {
main : "",
label: "inputGroup-sizing-default",
input: "inputGroup-sizing-default",
};
}
//merge class name
let cls_name = "input-group";
cls_name = classNames(cls_name, size.main, this.props.className);
return (
<div className={cls_name} style={def_style}>
<div className="input-group-prepend">
<div className="input-group-text">{this.state.label}</div>
</div>
<input type="text" {...this.props} onChange={this.changeHandler} value={this.state.value} className="form-control"/>
{this.renderSummary()}
</div>
)
}
}
InputGroup.propTypes = {
label : PropTypes.string,
data : PropTypes.any,
size : PropTypes.string,
summary : PropTypes.string,
placeholder: PropTypes.string,
width: PropTypes.number,
disabled: PropTypes.bool,
};
InputGroup.defaultProps = {
label : "",
data : null,
size : "",
summary : '',
disabled:false
};
export default InputGroup;
|
htbkoo/weight-tracker
|
scripts/view/dialentry.js
|
<filename>scripts/view/dialentry.js
/**
* Wraps around the dial component. Essentially manages the user interactions
* and passes the appropriate values to the dial. It also dispatches custom
* events when the user taps on the value in the middle.
*
* Typically the users of this are WeightEntry and HeightEntry components, which
* configure the DialEntry with the min / max values, colors and event names.
* @license see /LICENSE
*/
WT.View.DialEntry = function(elementId) {
var dial = new WT.View.Dial(elementId);
var dialElement = document.getElementById(elementId);
var dialElementX = dialElement.offsetLeft;
var dialElementY = dialElement.offsetTop;
var user = WT.App.getUser();
var interactionStartEvent = null;
var capturingValue = false;
var changedValue = false;
var startCaptureTimeout = 0;
var startedCapture = false;
var trackColor = false;
var eventNameComplete = 'dialvaluecomplete';
var callbacks = {
startInteraction: function(evt) {
evt.preventDefault();
interactionStartEvent = evt;
capturingValue = true;
startedCapture = false;
clearTimeout(startCaptureTimeout);
startCaptureTimeout = setTimeout(callbacks.startValueEntry, 300);
},
startValueEntry: function() {
dial.startTrackTo();
startedCapture = true;
callbacks.updateInteraction(interactionStartEvent, true);
},
updateInteraction: function(evt, ignoreForUserValue) {
evt.preventDefault();
if (capturingValue) {
if (!startedCapture) {
dial.startTrackTo();
startedCapture = true;
ignoreForUserValue = true;
}
var angle = getDialAngle(evt);
var newAngle = angle / (Math.PI * 2);
var newValue = dial.trackTo(newAngle, ignoreForUserValue);
if (trackColor) {
newValue = WT.App.convertToMetricIfNeeded('weight', newValue);
dial.setDrawColor(WT.App.getWeightColor(newValue, user.height));
}
changedValue = true;
clearTimeout(startCaptureTimeout);
}
},
endInteraction: function(evt) {
if (!!evt) {
evt.preventDefault();
}
if (changedValue) {
dial.stopTrackTo();
} else {
var newValue = dial.getValue();
WT.App.dispatchEvent(dialElement, eventNameComplete, newValue);
}
clearTimeout(startCaptureTimeout);
capturingValue = false;
changedValue = false;
}
};
function getDialAngle (evt) {
var x = evt.offsetX;
var y = evt.offsetY;
var touches = evt.touches;
if (typeof x === "undefined" && typeof touches === "undefined") {
touches = [evt];
}
if (touches) {
x = touches[0].pageX - dialElementX;
y = touches[0].pageY - dialElementY;
}
var xDiff = x - 126;
var yDiff = y - 126;
return Math.atan2(yDiff, xDiff) + Math.PI * 2.5;
}
function addEventListeners () {
dial.addEventListener('touchstart', callbacks.startInteraction, false);
dial.addEventListener('touchmove', callbacks.updateInteraction, false);
dial.addEventListener('touchend', callbacks.endInteraction, false);
dial.addEventListener('mousedown', callbacks.startInteraction, false);
dial.addEventListener('mousemove', callbacks.updateInteraction, false);
dial.addEventListener('mouseup', callbacks.endInteraction, false);
}
function removeEventListeners () {
dial.removeEventListener('touchstart', callbacks.startInteraction, false);
dial.removeEventListener('touchmove', callbacks.updateInteraction, false);
dial.removeEventListener('touchend', callbacks.endInteraction, false);
dial.removeEventListener('mousedown', callbacks.startInteraction, false);
dial.removeEventListener('mousemove', callbacks.updateInteraction, false);
dial.removeEventListener('mouseup', callbacks.endInteraction, false);
}
this.show = function() {
dialElement.classList.add('active');
addEventListeners();
};
this.hide = function() {
dialElement.classList.remove('active');
removeEventListeners();
};
this.hideAndDispatch = function() {
callbacks.endInteraction();
};
this.setup = function(options) {
var rawValue = options.value;
var value = options.value;
var max = options.max;
var label = options.label;
var color = options.color;
var eventName = options.eventName;
var decimalPlaces = options.decimalPlaces;
var ratio = options.ratio;
var shouldTrackColor = options.trackColor;
dial.setDecimalPlaces(decimalPlaces);
dial.setRatio(ratio);
dial.setMax(max);
dial.setLabel(label);
dial.setDrawColor(color);
dial.animateTo(value);
eventNameComplete = eventName;
trackColor = shouldTrackColor;
if (trackColor) {
dial.setDrawColor(WT.App.getWeightColor(rawValue, user.height));
}
};
this.clear = function() {
dial.clear();
};
};
WT.View.DialEntry.prototype = new WT.View.Base();
|
power-electro/phantomjs-Gohstdriver-DIY-openshift
|
src/qt/qtbase/src/plugins/platforms/directfb/qdirectfbwindow.cpp
|
<filename>src/qt/qtbase/src/plugins/platforms/directfb/qdirectfbwindow.cpp
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdirectfbwindow.h"
#include "qdirectfbbackingstore.h"
#include "qdirectfbinput.h"
#include "qdirectfbscreen.h"
#include <qpa/qwindowsysteminterface.h>
#include <directfb.h>
QT_BEGIN_NAMESPACE
QDirectFbWindow::QDirectFbWindow(QWindow *tlw, QDirectFbInput *inputhandler)
: QPlatformWindow(tlw), m_inputHandler(inputhandler)
{
}
void QDirectFbWindow::createDirectFBWindow()
{
Q_ASSERT(!m_dfbWindow.data());
DFBDisplayLayerConfig layerConfig;
IDirectFBDisplayLayer *layer;
layer = toDfbScreen(window())->dfbLayer();
layer->GetConfiguration(layer, &layerConfig);
DFBWindowDescription description;
memset(&description,0,sizeof(DFBWindowDescription));
if (window()->type() == Qt::Desktop) {
QRect fullscreenRect(QPoint(), screen()->availableGeometry().size());
window()->setGeometry(fullscreenRect);
DFBResult result = layer->CreateWindow(layer, &description, m_dfbWindow.outPtr());
if (result != DFB_OK)
DirectFBError("QDirectFbWindow: failed to create window", result);
} else {
description.flags = DFBWindowDescriptionFlags(DWDESC_WIDTH|DWDESC_HEIGHT|DWDESC_POSX|DWDESC_POSY|DWDESC_SURFACE_CAPS
|DWDESC_OPTIONS
|DWDESC_CAPS);
description.width = qMax(1, window()->width());
description.height = qMax(1, window()->height());
description.posx = window()->x();
description.posy = window()->y();
if (layerConfig.surface_caps & DSCAPS_PREMULTIPLIED)
description.surface_caps = DSCAPS_PREMULTIPLIED;
description.pixelformat = layerConfig.pixelformat;
description.options = DFBWindowOptions(DWOP_ALPHACHANNEL);
description.caps = DFBWindowCapabilities(DWCAPS_DOUBLEBUFFER|DWCAPS_ALPHACHANNEL);
DFBResult result = layer->CreateWindow(layer, &description, m_dfbWindow.outPtr());
if (result != DFB_OK)
DirectFBError("QDirectFbWindow: failed to create window", result);
m_dfbWindow->SetOpacity(m_dfbWindow.data(), 0xff);
m_inputHandler->addWindow(m_dfbWindow.data(), window());
}
}
QDirectFbWindow::~QDirectFbWindow()
{
m_inputHandler->removeWindow(m_dfbWindow.data());
m_dfbWindow->Destroy(m_dfbWindow.data());
}
void QDirectFbWindow::setGeometry(const QRect &rect)
{
QPlatformWindow::setGeometry(rect);
m_dfbWindow->SetBounds(m_dfbWindow.data(), rect.x(),rect.y(),
rect.width(), rect.height());
}
void QDirectFbWindow::setOpacity(qreal level)
{
const quint8 windowOpacity = quint8(level * 0xff);
m_dfbWindow->SetOpacity(m_dfbWindow.data(), windowOpacity);
}
void QDirectFbWindow::setVisible(bool visible)
{
if (window()->type() != Qt::Desktop) {
if (visible) {
int x = geometry().x();
int y = geometry().y();
m_dfbWindow->MoveTo(m_dfbWindow.data(), x, y);
} else {
QDirectFBPointer<IDirectFBDisplayLayer> displayLayer;
QDirectFbConvenience::dfbInterface()->GetDisplayLayer(QDirectFbConvenience::dfbInterface(), DLID_PRIMARY, displayLayer.outPtr());
DFBDisplayLayerConfig config;
displayLayer->GetConfiguration(displayLayer.data(), &config);
m_dfbWindow->MoveTo(m_dfbWindow.data(), config. width + 1, config.height + 1);
}
if (window()->isTopLevel() && visible)
QPlatformWindow::setVisible(visible);
}
}
void QDirectFbWindow::setWindowFlags(Qt::WindowFlags flags)
{
switch (flags & Qt::WindowType_Mask) {
case Qt::ToolTip: {
DFBWindowOptions options;
m_dfbWindow->GetOptions(m_dfbWindow.data(), &options);
options = DFBWindowOptions(options | DWOP_GHOST);
m_dfbWindow->SetOptions(m_dfbWindow.data(), options);
break; }
default:
break;
}
m_dfbWindow->SetStackingClass(m_dfbWindow.data(), flags & Qt::WindowStaysOnTopHint ? DWSC_UPPER : DWSC_MIDDLE);
}
void QDirectFbWindow::raise()
{
if (window()->type() != Qt::Desktop)
m_dfbWindow->RaiseToTop(m_dfbWindow.data());
}
void QDirectFbWindow::lower()
{
if (window()->type() != Qt::Desktop)
m_dfbWindow->LowerToBottom(m_dfbWindow.data());
}
WId QDirectFbWindow::winId() const
{
DFBWindowID id;
m_dfbWindow->GetID(m_dfbWindow.data(), &id);
return WId(id);
}
bool QDirectFbWindow::setKeyboardGrabEnabled(bool grab)
{
DFBResult res;
if (grab)
res = m_dfbWindow->GrabKeyboard(m_dfbWindow.data());
else
res = m_dfbWindow->UngrabKeyboard(m_dfbWindow.data());
return res == DFB_OK;
}
bool QDirectFbWindow::setMouseGrabEnabled(bool grab)
{
DFBResult res;
if (grab)
res = m_dfbWindow->GrabPointer(m_dfbWindow.data());
else
res = m_dfbWindow->UngrabPointer(m_dfbWindow.data());
return res == DFB_OK;
}
IDirectFBWindow *QDirectFbWindow::dfbWindow() const
{
return m_dfbWindow.data();
}
IDirectFBSurface *QDirectFbWindow::dfbSurface()
{
if (!m_dfbSurface) {
DFBResult res = m_dfbWindow->GetSurface(m_dfbWindow.data(), m_dfbSurface.outPtr());
if (res != DFB_OK)
DirectFBError(QDFB_PRETTY, res);
}
return m_dfbSurface.data();
}
QT_END_NAMESPACE
|
hlick14/URL-OC
|
serverstats/node_modules/autobahn/lib/serializer.js
|
<reponame>hlick14/URL-OC
///////////////////////////////////////////////////////////////////////////////
//
// AutobahnJS - http://autobahn.ws, http://wamp.ws
//
// A JavaScript library for WAMP ("The Web Application Messaging Protocol").
//
// Copyright (c) <EMAIL> Technologies GmbH and contributors
//
// Licensed under the MIT License.
// http://www.opensource.org/licenses/mit-license.php
//
///////////////////////////////////////////////////////////////////////////////
var log = require('./log.js');
// generate a WAMP ID: this might be serializer specific, as
// we need to enforce encoding into an integer, not float
// eg we need to do some extra stuff for msgpack (json and
// cbor are fine "as is")
function newid () {
return Math.floor(Math.random() * 9007199254740992);
}
function JSONSerializer(replacer, reviver) {
this.replacer = replacer;
this.reviver = reviver;
this.SERIALIZER_ID = 'json';
this.BINARY = false;
// JSON encoder does not need anything special here
this.newid = newid;
}
JSONSerializer.prototype.serialize = function (obj) {
try {
var payload = JSON.stringify(obj, this.replacer);
return payload;
} catch (e) {
log.warn('JSON encoding error', e);
throw e;
}
};
JSONSerializer.prototype.unserialize = function (payload) {
try {
var obj = JSON.parse(payload, this.reviver);
return obj;
} catch (e) {
log.warn('JSON decoding error', e);
throw e;
}
};
exports.JSONSerializer = JSONSerializer;
// https://github.com/kawanet/msgpack-lite/
// https://github.com/kawanet/int64-buffer
var msgpack = require('msgpack-lite');
// this is needed for correct msgpack serialization of WAMP session IDs
var Uint64BE = require('int64-buffer').Uint64BE;
function MsgpackSerializer() {
this.SERIALIZER_ID = 'msgpack';
this.BINARY = true;
this.codec = msgpack.createCodec();
// msgpack: Uint64BE ensures that ID is encoded as int instead of double
this.newid = function () { return new Uint64BE(newid()); };
}
MsgpackSerializer.prototype.serialize = function (obj) {
try {
var payload = msgpack.encode(obj, {codec: this.codec});
return payload;
} catch (e) {
log.warn('MessagePack encoding error', e);
throw e;
}
};
MsgpackSerializer.prototype.unserialize = function (payload) {
try {
// need to encapsulate ArrayBuffer into Uint8Array for msgpack decoding
// https://github.com/kawanet/msgpack-lite/issues/44
var obj = msgpack.decode(new Uint8Array(payload), {codec: this.codec});
return obj;
} catch (e) {
log.warn('MessagePack decoding error', e);
throw e;
}
};
/**
* Register a packer and/or unpacker functions for a given type.
*
* The msgpack specification allows applications to register up to 128 extension
* types.
*
* @param code numeric extension code (between 0-127)
* @param type constructor for the given type (only required when packer is defined)
* @param packer a function that takes an object and returns a Buffer
* @param unpacker a function that takes a Buffer and returns an instance of the given type
*/
MsgpackSerializer.prototype.registerExtType = function (code, type, packer, unpacker) {
if (packer && type) {
this.codec.addExtPacker(code, type, packer);
}
if (unpacker) {
this.codec.addExtUnpacker(code, unpacker);
}
};
exports.MsgpackSerializer = MsgpackSerializer;
// http://hildjj.github.io/node-cbor/
var cbor = require('cbor');
function CBORSerializer() {
this.SERIALIZER_ID = 'cbor';
this.BINARY = true;
// CBOR encoder does not need anything special here
this.newid = newid;
}
CBORSerializer.prototype.serialize = function (obj) {
try {
var payload = cbor.encode(obj);
return payload;
} catch (e) {
log.warn('CBOR encoding error', e);
throw e;
}
};
CBORSerializer.prototype.unserialize = function (payload) {
try {
//var obj = cbor.decodeAllSync(payload)[0];
var obj = cbor.decodeFirstSync(payload);
return obj;
} catch (e) {
log.warn('CBOR decoding error', e);
throw e;
}
};
exports.CBORSerializer = CBORSerializer;
|
egregors/leetgo
|
solutions/s0713_subarray_product_less_than_k.go
|
<filename>solutions/s0713_subarray_product_less_than_k.go
/*
https://leetcode.com/problems/subarray-product-less-than-k/
Given an array of integers nums and an integer k, return the number of contiguous subarrays
where the product of all the elements in the subarray is strictly less than k.
*/
package solutions
func numSubarrayProductLessThanK(nums []int, k int) int {
if k <= 1 {
return 0
}
prod, res, l := 1, 0, 0
for r := 0; r < len(nums); r++ {
prod *= nums[r]
for prod >= k {
prod /= nums[l]
l++
}
res += r - l + 1
}
return res
}
|
scala-steward/bitcoin-s
|
wallet/src/main/scala/org/bitcoins/wallet/internal/AccountHandling.scala
|
package org.bitcoins.wallet.internal
import org.bitcoins.core.api.wallet.db.AccountDb
import org.bitcoins.core.hd.AddressType._
import org.bitcoins.core.hd._
import org.bitcoins.core.protocol.blockchain.{
MainNetChainParams,
RegTestNetChainParams,
SigNetChainParams,
TestNetChainParams
}
import org.bitcoins.wallet.Wallet
import scala.concurrent.Future
/** Provides functionality related enumerating accounts. Account
* creation does not happen here, as that requires an unlocked wallet.
*/
private[wallet] trait AccountHandling { self: Wallet =>
/** @inheritdoc */
override def listAccounts(): Future[Vector[AccountDb]] =
accountDAO.findAll()
private def getOrThrowAccount(account: Option[AccountDb]): AccountDb =
account.getOrElse(
throw new RuntimeException(
s"Could not find account with ${DEFAULT_HD_COIN.purpose.constant} " +
s"purpose field and ${DEFAULT_HD_COIN.coinType.toInt} coin field"))
/** @inheritdoc */
override def getDefaultAccount(): Future[AccountDb] = {
for {
account <- accountDAO.read((DEFAULT_HD_COIN, 0))
} yield {
val acct = getOrThrowAccount(account)
require(
acct.hdAccount == walletConfig.defaultAccount,
s"Divergence between configured default account and " +
s"database default account walletConfig=${walletConfig.defaultAccount} database=${acct.hdAccount}"
)
acct
}
}
/** @inheritdoc */
override def getDefaultAccountForType(
addressType: AddressType): Future[AccountDb] = {
val hdCoin = addressType match {
case Legacy => HDCoin(HDPurposes.Legacy, DEFAULT_HD_COIN_TYPE)
case NestedSegWit => HDCoin(HDPurposes.NestedSegWit, DEFAULT_HD_COIN_TYPE)
case SegWit => HDCoin(HDPurposes.SegWit, DEFAULT_HD_COIN_TYPE)
}
for {
account <- accountDAO.read((hdCoin, 0))
} yield getOrThrowAccount(account)
}
/** The default HD coin for this wallet, read from config */
protected[wallet] lazy val DEFAULT_HD_COIN: HDCoin = {
val coinType = DEFAULT_HD_COIN_TYPE
HDCoin(walletConfig.defaultAccountKind, coinType)
}
/** The default HD coin type for this wallet, derived from
* the network we're on
*/
protected[wallet] lazy val DEFAULT_HD_COIN_TYPE: HDCoinType = {
chainParams match {
case MainNetChainParams => HDCoinType.Bitcoin
case RegTestNetChainParams | TestNetChainParams | SigNetChainParams(_) =>
HDCoinType.Testnet
}
}
/** The default HD purpose for this wallet, read from config */
protected[wallet] lazy val DEFAULT_HD_PURPOSE: HDPurpose =
walletConfig.defaultAccountKind
}
|
zubairabid/Semester6
|
subjects/LData/Assignment/shallow-parser-ben-3.0.fc8/src/sl/morph/ben/analyser/my_blk_bsrch.c
|
/**
* File Name : my_blk_bsrch.c.c
*/
/** Fuction : my_blk_bsrch
* This function returns the ptr to the location of the key in the table, if it is present
* else returns a null
* It takes arguments: key of char type ,base of char type ,nel of int type
* width of int type and compar is function with integer return type
* Return : void
*/
void *my_blk_bsearch(key,base,nel,width,compar)
char *base,*key;
int nel,width;
int (* compar)();
{
/* Given the table start address - base,
the table size - nel,
the table width - width,
the comparison function - compar,
this function returns the ptr to the location of the key
in the table, if it is present else returns a null
*/
int low,high,mid,ans,pos;
low = 0;
high = nel-1;
while (low <= high) /* executes only when low < = high */
{
mid = (low + high)/2;
ans = (* compar)(key,(char *)(base+mid*width));
/* printf("The string being tested is %s\n",(char *)(base+mid*width)); */
if (ans < 0) /* checks for ans is <0 */
high = mid -1;
else if (ans > 0)
low = mid +1;
else
{
pos=mid;
ans = (* compar)(key,(char *)(base+pos*width));
while((!ans)&&(pos>0))
{
pos--;
ans = (* compar)(key,(char *)(base+pos*width));
}
if(ans!=0) pos++;
return((void *) (base + pos*width));
}
}
return ((void *) '\0');
}
|
mudchina/es2-mudlib-utf8
|
mudlib/d/green/house3.c
|
<filename>mudlib/d/green/house3.c<gh_stars>10-100
// Room: /d/green/house3.c
inherit ROOM;
int num_of_spider;
string call_spider();
void create()
{
set("short", "民宅");
set("long", @LONG
这是一间民宅, 屋内除了一张石床外其他一无所有. 昏暗的屋
内看来死气沉沉的, 似乎这屋子的主人很久没回来了. 屋角有一个
形状很奇怪的蜘蛛网(web).
LONG
);
set("exits", ([ /* sizeof() == 1 */
"south" : "/d/green/field1",
]));
set("no_clean_up", 0);
set("item_desc", ([
"web" : (: call_spider :),
]) );
setup();
reset();
}
void reset()
{
::reset();
num_of_spider = 3;
}
string call_spider()
{
object ob;
if (num_of_spider == 0) return "一个很大的蜘蛛网.\n";
num_of_spider --;
ob = new("/d/green/npc/spider");
ob->move("/d/green/house3");
return "突然你觉得头上有个阴影, 不自觉的抬起头来一看 ............"+
"好大的 ..... 蜘蛛..... \n";
}
|
sysidos/gollvm
|
unittests/TestUtils/DiffUtils.h
|
//===- llvm/tools/gollvm/unittests/TestUtils/DiffUtils.h --------------===//
//
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
//===----------------------------------------------------------------------===//
#ifndef GOLLVM_UNITTESTS_TESTUTILS_DIFFUTILS_H
#define GOLLVM_UNITTESTS_TESTUTILS_DIFFUTILS_H
#include <string>
#include <vector>
#define RAW_RESULT(x) #x
namespace goBackendUnitTests {
// Trim leading and trailing spaces
std::string trimsp(const std::string &s);
// Split specified string into tokens (with whitespace as delimiter)
std::vector<std::string> tokenize(const std::string &s);
// Join together vector of strings to single string, separate with spaces
std::string vectostr(const std::vector<std::string> &tv);
// Tokenize the two strings, then diff the resulting token vectors,
// returning TRUE if they are identical or FALSE if different (and
// setting 'diffreason' to explanation of diff)
bool difftokens(const std::string &expected,
const std::string &result,
std::string &diffreason);
// Return TRUE if string 'text' contains instead of string 'pat'.
// Tokenizes both strings to avoid whitespace differences
bool containstokens(const std::string &text, const std::string &pat);
// Return the number of instances of 'pat' within 'text'. Both the pattern
// and the text are tokenized prior to the search. Search is brute-force.
unsigned countinstances(const std::string &text, const std::string &pat);
// Issue an error message to std:cerr to report the fact that
// 'expected' does not match 'actual'; emit actual/expected debug dump
// files if 'emitDump' is true.
void complainOnNequal(const std::string &reason,
const std::string &expected,
const std::string &actual,
bool emitDump);
}
#endif // GOLLVM_UNITTESTS_TESTUTILS_DIFFUTILS_H
|
rubytomato/demo-java12-javalin3
|
src/main/java/com/example/demo/config/DslConfigure.java
|
<gh_stars>0
package com.example.demo.config;
import org.jooq.Configuration;
import org.jooq.ConnectionProvider;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.TransactionProvider;
import org.jooq.conf.Settings;
import org.jooq.impl.DefaultConfiguration;
import javax.sql.DataSource;
import java.util.Optional;
public interface DslConfigure {
DSLContext getDslContext();
DataSource getDataSource();
SQLDialect getSqlDialect();
Settings getSettings();
// optional settings
Optional<ConnectionProvider> getConnectionProvider();
Optional<TransactionProvider> getTransactionProvider();
default Configuration configuration() {
Configuration config = new DefaultConfiguration();
config
.set(getSqlDialect())
.set(getSettings());
getConnectionProvider().ifPresentOrElse(cp -> {
config.set(cp);
getTransactionProvider().ifPresent(tp -> {
config.set(tp);
});
}, () -> {
config.set(getDataSource());
});
return config;
}
}
|
daemyung/gal
|
src/ogl/Ogl_shader.h
|
<reponame>daemyung/gal
//
// This file is part of the "gfx" project
// See "LICENSE" for license information.
//
#ifndef GFX_OGL_SHADER_GUARD
#define GFX_OGL_SHADER_GUARD
#include <GLES3/gl3.h>
#include "Shader.h"
namespace Gfx_lib {
//----------------------------------------------------------------------------------------------------------------------
class Ogl_device;
//----------------------------------------------------------------------------------------------------------------------
class Ogl_shader final : public Shader {
public:
Ogl_shader(const Shader_desc& desc, Ogl_device* device);
~Ogl_shader() override;
Device* device() const override;
Sc_lib::Signature reflect() const noexcept override;
inline auto shader() const noexcept
{ return shader_; }
private:
void init_signature_(const std::vector<uint32_t>& src);
void init_shader_(const std::string& src);
void fini_shader_();
private:
Ogl_device* device_;
Sc_lib::Signature signature_;
GLuint shader_;
};
//----------------------------------------------------------------------------------------------------------------------
} // of namespace Gfx_lib
#endif // GFX_OGL_SHADER_GUARD
|
developertqw2017/migrationDjango
|
Vecihi/Backend/vecihi/users/views_api.py
|
import json
from django.utils.decorators import method_decorator
from django.db.models import Q
from django.views.decorators.cache import cache_page
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import update_session_auth_hash
from rest_framework import permissions, status, views, viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from actstream import action
from actstream.actions import follow
from actstream.models import user_stream, Action, followers, following
from vecihi.posts.models import Post
from .models import User, ViewedProfileTracking
from .serializers import AccountSerializer, ActionSerializer, ViewedProfileTrackingSerializer
from .permissions import IsAccountOwner
class FollowShipView(views.APIView):
permission_classes = (permissions.IsAuthenticated, )
def post(self, request, pk, *args, **kwargs):
if self.request.user.id == int(pk):
return Response({
'status': 'Bad Request',
'message': 'You cant follow yourself.'
}, status=status.HTTP_400_BAD_REQUEST)
user = User.objects.get(id=request.auth.user.id)
target_user = User.objects.get(id=pk)
follow(user, target_user)
return Response({
"status": "Success",
"message": "You followed " + target_user.username
}, status=status.HTTP_201_CREATED)
class UserFollowersViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = AccountSerializer
def get_queryset(self):
user_id = self.kwargs['userid']
user = User.objects.get(id=user_id)
return followers(user)
class UserFollowingViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = AccountSerializer
def get_queryset(self):
user_id = self.kwargs['userid']
user = User.objects.get(id=user_id)
return following(user)
class ActivityViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Action.objects.all()
serializer_class = ActionSerializer
filter_fields = (
'actor_content_type', 'actor_content_type__model',
'target_content_type', 'target_content_type__model',
'action_object_content_type', 'action_object_content_type__model',
)
class AccountViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = AccountSerializer
def get_queryset(self):
if self.request.query_params.get("search", None):
params = self.request.query_params.get("search", None)
return User.objects.filter( Q(username__icontains=params)|
Q(major__icontains=params)|
Q(first_name__icontains=params)
)
if self.kwargs.get('pk') is None:
return User.objects.all()
user_id = int(self.kwargs['pk'])
if self.request.user.id != user_id:
target_user = User.objects.get(id=user_id)
action = ViewedProfileTracking(actor=self.request.user, visited_profile=target_user)
action.save()
return User.objects.all()
def get_permissions(self):
if self.request.method in permissions.SAFE_METHODS:
return (permissions.AllowAny(),)
if self.request.method == 'POST':
return (permissions.AllowAny(),)
return (permissions.IsAuthenticated(), IsAccountOwner(),)
@method_decorator(cache_page(10))
def dispatch(self, *args, **kwargs):
return super(AccountViewSet, self).dispatch(*args, **kwargs)
@list_route()
def recent_users(self, request):
recent_users = User.objects.all().order_by('-last_login')
page = self.paginate_queryset(recent_users)
if page is not None:
serializer = self.get_serializer(page, context={'request': request}, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(recent_users, context={'request': request}, many=True)
return Response(serializer.data)
@list_route()
def me(self, request, *args, **kwargs):
if request.auth is None:
return Response({
'status': 'Unauthorized',
'message': 'This authentication has been disabled.'
}, status=status.HTTP_401_UNAUTHORIZED)
user = User.objects.get(id=request.auth.user.id)
serializer = self.get_serializer(user, context={'request': request})
return Response(serializer.data)
@list_route()
def who_visited_my_profile(self, request, *args, **kwargs):
if request.auth is None:
return Response({
"status": "Unauthorized",
"message": "This authentication has been disabled."
}, status=status.HTTP_401_UNAUTHORIZED)
response = ViewedProfileTracking.objects.filter(visited_profile=request.auth.user).order_by("-visited_time")
if not len(response):
return Response({}, status=status.HTTP_204_NO_CONTENT)
page = self.paginate_queryset(response)
if page is not None:
serializer = ViewedProfileTrackingSerializer(response, many=True)
return self.get_paginated_response(serializer.data)
serializer = ViewedProfileTrackingSerializer(response, many=True)
return Response(serializer.data)
def create(self, request):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
if serializer.checkPassword(serializer.validated_data):
User.objects.create_user(**serializer.validated_data)
account = authenticate(username=serializer.validated_data['username'],
password=serializer.validated_data['password'])
login(request, account)
token = Token.objects.get(user=account)
serialized = self.serializer_class(account, context={'request': request})
return Response({
'account': serialized.data,
"token": token.key
}, status=status.HTTP_201_CREATED)
return Response({
'status': 'Bad request',
'message': 'User could not be created with received data.',
'errors': serializer.errors
}, status=status.HTTP_400_BAD_REQUEST)
@list_route(methods=['post'])
def register(self, request):
return self.create(request)
def destroy(self, request, pk=None):
account = self.get_object()
account.email = str(account.id)+'_nonactive'+'<EMAIL>'
account.first_name = ''
account.last_name = ''
account.is_active = False
account.is_authenticated = False
account.save()
logout(request)
# return self.delete(request)
return Response({'status': 'deleted clean'})
@detail_route(methods=['put'])
def update_user(self, request, pk=None):
account = self.get_object()
serializer = self.serializer_class(account, data=request.data, partial=True)
if serializer.is_valid(raise_exception=True):
serializer.update(account, serializer.validated_data)
update_session_auth_hash(request, account)
return Response({"status": "Updated!"})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
@detail_route(methods=['patch'])
def set_password(self, request, pk=1):
account = self.get_object()
serializer = self.serializer_class(account, data=request.data, partial=True)
if serializer.is_valid(raise_exception=True):
serializer.update(account, serializer.validated_data)
update_session_auth_hash(request, account)
return Response({'status': 'password set'})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
class LoginView(views.APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
username = request.data.get('username', None)
password = request.data.get('password', None)
account = authenticate(username=username, password=password)
if account is not None:
if account.is_active:
login(request, account)
token, _ = Token.objects.get_or_create(user=account)
serialized = AccountSerializer(account, context={'request': request})
return Response({
'account': serialized.data,
"token": token.key
})
else:
return Response({
'status': 'Unauthorized',
'message': 'This authentication has been disabled.'
}, status=status.HTTP_401_UNAUTHORIZED)
else:
if request.user.is_active:
token, _ = Token.objects.get_or_create(user=account)
serialized = AccountSerializer(request.user, context={'request': request})
return Response({
'account': serialized.data,
'token': token.key
})
return Response({
'status': 'Unauthorized',
'message': 'Username/password combination invalid.'
}, status=status.HTTP_401_UNAUTHORIZED)
class LogoutView(views.APIView):
permission_classes = (permissions.IsAuthenticated,)
def post(self, request, format=None):
request.auth_token.delete()
logout(request)
return Response({}, status=status.HTTP_204_NO_CONTENT)
|
bluebird88/HIS
|
HIS-master/HIS-api/src/main/java/com/neu/his/api/controller/dms/DmsHerbalPrescriptionRecordController.java
|
<reponame>bluebird88/HIS
package com.neu.his.api.controller.dms;
import com.neu.his.common.api.CommonResult;
import com.neu.his.common.dto.dms.DmsHerbalPrescriptionRecordParam;
import com.neu.his.common.dto.dms.DmsHerbalPrescriptionRecordResult;
import com.neu.his.component.RabbitMQOrderSender;
import com.neu.his.dms.service.DmsHerbalPrescriptionRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@Controller
@Api(tags = "DmsHerbalPrescriptionRecordController", description = "草药处方管理")
@RequestMapping("/DmsHerbalPrescriptionRecord")
@CrossOrigin(allowCredentials = "true")
public class DmsHerbalPrescriptionRecordController {
@Autowired
private DmsHerbalPrescriptionRecordService dmsHerbalPrescriptionRecordService;
@Autowired
private RabbitMQOrderSender rabbitMQOrderSender;
/**
* 描述:开立处方(发送)
* <p>author: ma
*/
@ApiOperation(value = "开立处方")
@RequestMapping(value = "/apply", method = RequestMethod.POST)
@ResponseBody
public CommonResult apply(@RequestBody DmsHerbalPrescriptionRecordParam dmsHerbalPrescriptionRecordParam, BindingResult result){
Long currentId = dmsHerbalPrescriptionRecordService.apply(dmsHerbalPrescriptionRecordParam);
if(currentId > 0){
//获取订单超时时间,假设为30s
long delayTimes = 60 * 1000 *60 *12;
//发送延迟消息
rabbitMQOrderSender.sendMessage(currentId, 4, delayTimes);
return CommonResult.success(currentId, "开立成功");
}
return CommonResult.failed("开立失败");
}
/**
* 描述:作废处方
* <p>author: ma
*/
@ApiOperation(value = "作废处方")
@RequestMapping(value = "/invalid", method = RequestMethod.POST)
@ResponseBody
public CommonResult invalid(@RequestParam("ids") List<Long> ids){
int count = dmsHerbalPrescriptionRecordService.invalid(ids);
if(count > 0){
return CommonResult.success(count, "作废成功");
}
return CommonResult.failed("作废失败");
}
/**
* 描述:根据registrationId查询处方
* <p>author: ma
*/
@ApiOperation(value = "根据挂号Id查询处方")
@RequestMapping(value = "/listByReg", method = RequestMethod.POST)
@ResponseBody
public CommonResult<List<DmsHerbalPrescriptionRecordResult>> listByReg(@RequestParam("registrationId") Long registrationId){
List<DmsHerbalPrescriptionRecordResult> list = dmsHerbalPrescriptionRecordService.listByReg(registrationId);
return CommonResult.success(list);
}
/**
* 描述:根据ids查询处方
* <p>author: 赵煜
*/
@ApiOperation(value = "根据ids查询草药处方")
@RequestMapping(value = "/listByIds", method = RequestMethod.POST)
@ResponseBody
public CommonResult<List<DmsHerbalPrescriptionRecordResult>> listByIds(@RequestParam("ids") List<Long> ids){
List<DmsHerbalPrescriptionRecordResult> list = dmsHerbalPrescriptionRecordService.listByIds(ids);
return CommonResult.success(list);
}
}
|
l0y/smallerc
|
ch03/exercises/triangle.c
|
<reponame>l0y/smallerc
#include <stdio.h>
int main() {
int triangleSize;
printf("Please enter a size for your triangle (1 - 20): ");
scanf("%i", &triangleSize);
if (triangleSize < 1 || triangleSize > 20) {
printf("We can't make a triangle that size. Sorry!\n");
printf("We'll use the default size of 10 instead.\n");
triangleSize = 10;
}
// Notice that since we declared row and col above, we do *not*
// include the "int" type declaration inside the for loops below
for (int row = 1; row <= triangleSize; row++) {
for (int col = 1; col <= row; col++) {
printf("*");
}
printf("\n");
}
}
|
JincorTech/music-ico-dashboard
|
src/components/common/VerifyTip/index.js
|
import React from 'react';
const VerifyTip = (props) => {
const {
method
} = props;
const email = (
<div>To activate account - enter PIN code from email</div>
);
const app = (
<div>To activate account - enter PIN code from Google Authenticator</div>
);
return method === 'google_auth' ? app : email;
};
export default VerifyTip;
|
sungmen/Acmicpc_Solve
|
Acmicpc/C++/BOJ2696.cpp
|
<reponame>sungmen/Acmicpc_Solve<filename>Acmicpc/C++/BOJ2696.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
// freopen("input.in", "r", stdin);
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
int t; cin >> t;
while (t--) {
int m; cin >> m;
priority_queue<int> pqMax, pqMin;
vector<int> res;
for (int i = 0; i < m; ++i) {
int n; cin >> n;
if (pqMax.empty()) pqMax.push(-n);
else {
if (-pqMax.top() <= n) {
pqMax.push(-n);
} else {
pqMin.push(n);
}
if (pqMax.size() > pqMin.size() + 1) {
pqMin.push(-pqMax.top());
pqMax.pop();
} else if (pqMin.size() > pqMax.size()) {
pqMax.push(-pqMin.top());
pqMin.pop();
}
}
if (!(i % 2)) res.push_back(-pqMax.top());
}
cout << res.size() << '\n';
for (int i = 0; i < res.size(); ++i) {
if (i > 9 && !(i % 10)) cout << '\n';
cout << res[i] << ' ';
}
cout << '\n';
}
return 0;
}
|
gomeifuku/Ultraino
|
AcousticField3D/src/acousticfield3d/utils/ArrayUtils.java
|
<reponame>gomeifuku/Ultraino
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package acousticfield3d.utils;
import java.util.List;
/**
*
* @author am14010
*/
public class ArrayUtils {
public static int[] toArray(final List<Integer> list){
final int n = list.size();
final int[] array = new int[n];
for(int i = 0; i < n; ++i){
array[i] = list.get(i);
}
return array;
}
}
|
MegRiley/cqf-ruler
|
src/main/java/org/opencds/cqf/qdm/fivepoint4/repository/NegativeSubstanceAdministeredRepository.java
|
package org.opencds.cqf.qdm.fivepoint4.repository;
import org.opencds.cqf.qdm.fivepoint4.model.NegativeSubstanceAdministered;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import javax.annotation.Nonnull;
import java.util.Optional;
@Repository
public interface NegativeSubstanceAdministeredRepository extends JpaRepository<NegativeSubstanceAdministered, String>
{
@Nonnull
Optional<NegativeSubstanceAdministered> findBySystemId(@Nonnull String id);
}
|
jeffpuzzo/jp-rosa-react-form-wizard
|
node_modules/@patternfly/react-tokens/dist/esm/c_options_menu__menu_item_icon_PaddingLeft.js
|
<filename>node_modules/@patternfly/react-tokens/dist/esm/c_options_menu__menu_item_icon_PaddingLeft.js
export const c_options_menu__menu_item_icon_PaddingLeft = {
"name": "--pf-c-options-menu__menu-item-icon--PaddingLeft",
"value": "1.5rem",
"var": "var(--pf-c-options-menu__menu-item-icon--PaddingLeft)"
};
export default c_options_menu__menu_item_icon_PaddingLeft;
|
Crazyhackelkorn/ArduPy
|
shared-bindings/util.h
|
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017 <NAME> for Adafruit Industries
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_UTIL_H
#define MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_UTIL_H
#include "py/obj.h"
#define MP_IOCTL_POLL (0x100 | 1)
// These values are compatible with Linux, which are in turn
// compatible with iBCS2 spec.
#define MP_IOCTL_POLL_RD (0x0001)
#define MP_IOCTL_POLL_WR (0x0004)
#define MP_IOCTL_POLL_ERR (0x0008)
#define MP_IOCTL_POLL_HUP (0x0010)
#if MICROPY_PY_BUILTINS_PROPERTY
typedef struct _mp_obj_property_t {
mp_obj_base_t base;
mp_obj_t proxy[3]; // getter, setter, deleter
} mp_obj_property_t;
#endif // MICROPY_PY_BUILTINS_PROPERTY
typedef struct {
mp_obj_base_t base;
void * module;
} abstract_module_t;
inline abstract_module_t * new_abstruct_module(mp_obj_type_t * type) __attribute__((always_inline));
inline abstract_module_t * new_abstruct_module(mp_obj_type_t * type){
abstract_module_t * self = m_new_obj(abstract_module_t);
self->base.type = type;
return self;
}
#define m_generic_make(name) \
STATIC mp_obj_t name ## _obj_deinit(mp_obj_t self_in) { \
common_hal_ ## name ## _deinit((abstract_module_t *)self_in); \
return mp_const_none; \
} \
MP_DEFINE_CONST_FUN_OBJ_1( \
name ## _deinit_obj, \
name ## _obj_deinit); \
STATIC mp_obj_t name ## _obj___exit__( \
size_t n_args, \
const mp_obj_t * args) { \
common_hal_ ## name ## _deinit((abstract_module_t *)args[0]); \
return mp_const_none; \
} \
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( \
name ## _obj___exit___obj, 4, 4, \
name ## _obj___exit__); \
STATIC mp_obj_t name ## _make_new( \
const mp_obj_type_t * type, \
size_t n_args, \
size_t n_kw, \
const mp_obj_t * args)
#define m_get_pin(index) ((mcu_pin_obj_t *)vals[index].u_obj)
typedef enum{
ERROR,
SUCCESS,
}result_t;
MP_DECLARE_CONST_FUN_OBJ_1(default___enter___obj);
bool try_lock(volatile bool * mutex);
void raise_error_because(const char * msg);
void raise_error_if_not_locked(bool value);
void raise_error_if_deinited(bool deinited);
void raise_error_if(bool reason, const char * msg);
NORETURN void mp_raise_RuntimeError(const char *msg);
NORETURN void mp_raise_AttributeError(const char *msg) ;
void normalize_buffer_bounds(int32_t* start, int32_t end, uint32_t* length);
void generic_method_lookup(mp_obj_t obj, qstr attr, mp_obj_t *dest);
void* mp_to_ptr(mp_obj_t self_in);
#endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_UTIL_H
|
shuLhan/share
|
lib/mlog/multi_logger_example_test.go
|
<gh_stars>10-100
// Copyright 2021, Shulhan <<EMAIL>>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mlog
import (
"bytes"
"fmt"
"log"
"os"
"github.com/shuLhan/share/api/slack"
)
func ExampleMultiLogger() {
buf := bytes.Buffer{}
wouts := []NamedWriter{
NewNamedWriter("stdout", os.Stdout),
NewNamedWriter("buffer", &buf),
}
werrs := []NamedWriter{
NewNamedWriter("stderr", os.Stdout),
}
mlog := NewMultiLogger("", "mlog:", wouts, werrs)
// Create an error writer to slack.
slackWebhookURL := os.Getenv("SLACK_WEBHOOK_URL")
if len(slackWebhookURL) > 0 {
slackChannel := os.Getenv("SLACK_WEBHOOK_CHANNEL")
slackUsername := os.Getenv("SLACK_WEBHOOK_USERNAME")
slackc, err := slack.NewWebhookClient(slackWebhookURL, slackUsername, slackChannel)
if err != nil {
log.Fatal(err)
}
mlog.RegisterErrorWriter(NewNamedWriter("slack", slackc))
}
mlog.Outf("writing to standard output and buffer\n")
mlog.Errf("writing to standard error and slack\n")
mlog.Flush()
fmt.Printf("Output on buffer: %s\n", buf.String())
// Unordered output:
// mlog: writing to standard output and buffer
// mlog: writing to standard error and slack
// Output on buffer: mlog: writing to standard output and buffer
}
|
pdpdds/SDLGameProgramming
|
sdl2/flashback/systemstub.h
|
/*
* REminiscence - Flashback interpreter
* Copyright (C) 2005-2018 <NAME> (<EMAIL>)
*/
#ifndef SYSTEMSTUB_H__
#define SYSTEMSTUB_H__
#include "intern.h"
#include "scaler.h"
struct PlayerInput {
enum {
DIR_UP = 1 << 0,
DIR_DOWN = 1 << 1,
DIR_LEFT = 1 << 2,
DIR_RIGHT = 1 << 3
};
enum {
DF_FASTMODE = 1 << 0,
DF_DBLOCKS = 1 << 1,
DF_SETLIFE = 1 << 2
};
uint8_t dirMask;
bool enter;
bool space;
bool shift;
bool backspace;
bool escape;
char lastChar;
bool save;
bool load;
int stateSlot;
uint8_t dbgMask;
bool quit;
};
struct ScalerParameters {
ScalerType type;
const Scaler *scaler;
int factor;
static ScalerParameters defaults();
};
struct SystemStub {
typedef void (*AudioCallback)(void *param, int16_t *stream, int len);
PlayerInput _pi;
virtual ~SystemStub() {}
virtual void init(const char *title, int w, int h, bool fullscreen, ScalerParameters *scalerParameters) = 0;
virtual void destroy() = 0;
virtual void setScreenSize(int w, int h) = 0;
virtual void setPalette(const uint8_t *pal, int n) = 0;
virtual void setPaletteEntry(int i, const Color *c) = 0;
virtual void getPaletteEntry(int i, Color *c) = 0;
virtual void setOverscanColor(int i) = 0;
virtual void copyRect(int x, int y, int w, int h, const uint8_t *buf, int pitch) = 0;
virtual void fadeScreen() = 0;
virtual void updateScreen(int shakeOffset) = 0;
virtual void processEvents() = 0;
virtual void sleep(int duration) = 0;
virtual uint32_t getTimeStamp() = 0;
virtual void startAudio(AudioCallback callback, void *param) = 0;
virtual void stopAudio() = 0;
virtual uint32_t getOutputSampleRate() = 0;
virtual void lockAudio() = 0;
virtual void unlockAudio() = 0;
};
struct LockAudioStack {
LockAudioStack(SystemStub *stub)
: _stub(stub) {
_stub->lockAudio();
}
~LockAudioStack() {
_stub->unlockAudio();
}
SystemStub *_stub;
};
extern SystemStub *SystemStub_SDL_create();
#endif // SYSTEMSTUB_H__
|
GrimshawA/Nephilim
|
source/UI/UISlider.cpp
|
#include <Nephilim/UI/UISlider.h>
NEPHILIM_NS_BEGIN
NEPHILIM_NS_END
|
Angelussz/ProgramacionCompetitiva
|
pc_Clase17_5/ClimbStairs.cpp
|
class Solution {
public:
int climbStairs(int n) {
int re[n+1];
re[0]=1;
re[1]=1;
for(int i=2;i<=n;i++){
re[i] = re[i-1] + re[i-2];
}
return re[n];
}
};
|
aprasolova/neo-go
|
pkg/core/util.go
|
<gh_stars>0
package core
import (
"errors"
"time"
"github.com/nspcc-dev/neo-go/pkg/config"
"github.com/nspcc-dev/neo-go/pkg/config/netmode"
"github.com/nspcc-dev/neo-go/pkg/core/block"
"github.com/nspcc-dev/neo-go/pkg/core/interop/interopnames"
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
"github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
)
var (
// governingTokenTX represents transaction that is used to create
// governing (NEO) token. It's a part of the genesis block.
governingTokenTX transaction.Transaction
// utilityTokenTX represents transaction that is used to create
// utility (GAS) token. It's a part of the genesis block. It's mostly
// useful for its hash that represents GAS asset ID.
utilityTokenTX transaction.Transaction
)
// createGenesisBlock creates a genesis block based on the given configuration.
func createGenesisBlock(cfg config.ProtocolConfiguration) (*block.Block, error) {
validators, err := validatorsFromConfig(cfg)
if err != nil {
return nil, err
}
nextConsensus, err := getNextConsensusAddress(validators)
if err != nil {
return nil, err
}
base := block.Base{
Version: 0,
PrevHash: util.Uint256{},
Timestamp: uint64(time.Date(2016, 7, 15, 15, 8, 21, 0, time.UTC).Unix()) * 1000, // Milliseconds.
Index: 0,
NextConsensus: nextConsensus,
Script: transaction.Witness{
InvocationScript: []byte{},
VerificationScript: []byte{byte(opcode.PUSH1)},
},
Network: cfg.Magic,
}
b := &block.Block{
Base: base,
Transactions: []*transaction.Transaction{
deployNativeContracts(cfg.Magic),
},
ConsensusData: block.ConsensusData{
PrimaryIndex: 0,
Nonce: 2083236893,
},
}
b.RebuildMerkleRoot()
return b, nil
}
func deployNativeContracts(magic netmode.Magic) *transaction.Transaction {
buf := io.NewBufBinWriter()
emit.Syscall(buf.BinWriter, interopnames.NeoNativeDeploy)
script := buf.Bytes()
tx := transaction.New(magic, script, 0)
tx.Nonce = 0
tx.Signers = []transaction.Signer{
{
Account: hash.Hash160([]byte{byte(opcode.PUSH1)}),
Scopes: transaction.None,
},
}
tx.Scripts = []transaction.Witness{
{
InvocationScript: []byte{},
VerificationScript: []byte{byte(opcode.PUSH1)},
},
}
return tx
}
func validatorsFromConfig(cfg config.ProtocolConfiguration) ([]*keys.PublicKey, error) {
vs, err := committeeFromConfig(cfg)
if err != nil {
return nil, err
}
return vs[:cfg.ValidatorsCount], nil
}
func committeeFromConfig(cfg config.ProtocolConfiguration) ([]*keys.PublicKey, error) {
if len(cfg.StandbyCommittee) < cfg.ValidatorsCount {
return nil, errors.New("validators count can be less than the size of StandbyCommittee")
}
validators := make([]*keys.PublicKey, len(cfg.StandbyCommittee))
for i := range validators {
pubKey, err := keys.NewPublicKeyFromString(cfg.StandbyCommittee[i])
if err != nil {
return nil, err
}
validators[i] = pubKey
}
return validators, nil
}
func getNextConsensusAddress(validators []*keys.PublicKey) (val util.Uint160, err error) {
raw, err := smartcontract.CreateDefaultMultiSigRedeemScript(validators)
if err != nil {
return val, err
}
return hash.Hash160(raw), nil
}
// headerSliceReverse reverses the given slice of *Header.
func headerSliceReverse(dest []*block.Header) {
for i, j := 0, len(dest)-1; i < j; i, j = i+1, j-1 {
dest[i], dest[j] = dest[j], dest[i]
}
}
|
ooz/EDLed
|
src/de/mpg/cbs/edledplugin/stimulus/TimetablePanel.java
|
package de.mpg.cbs.edledplugin.stimulus;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JPanel;
public class TimetablePanel extends JPanel implements Observer, MouseListener, MouseMotionListener, KeyListener {
private enum DragSpot {
NOT_DRAGGED,
LOWER_WEST,
MID_CENTER,
UPPER_EAST;
}
private enum TimeUnit {
MILLISECONDS,
SECONDS,
MINUTES;
}
/**
*
*/
private static final long serialVersionUID = 4421375481242162305L;
/*
* Paddings for the coordinate system.
* Left padding is variable:
* leftPadding = LEFT_CAPTION_PADDING * 2 + <max width of the rendered mediaObjIDs>.
*/
private static final int TOP_PADDING = 40;
private static final int RIGHT_PADDING = 70;
private static final int BOTTOM_PADDING = 90;
private static final int LEFT_CAPTION_PADDING = 5;
private static final int EVENT_BAR_HEIGHT = 30;
private static final int DRAGGER_EDGE_LENGTH = (int) Math.floor((double) (EVENT_BAR_HEIGHT - 2) / 3.0);
private static final String TIMETABLE_CAPTION = "Timetable";
private static final int TIMETABLE_CAPTION_PADDING = 20;
private static final int XAXSIS_DASH_LENGTH = 5;
private final Timetable timetable;
private long currentTime;
private boolean handleMouseEvents = true;
private StimEvent selectedEvent = null;
// private Dragger clickedDragger = null;
private Point mouseDownAt;
private Point mouseUpAt;
private DragSpot draggedAt = DragSpot.NOT_DRAGGED;
private Rectangle lowerWestDragger = null;
private Rectangle midCenterDragger = null;
private Rectangle upperEastDragger = null;
private double msPerPixel;
private TimeUnit timeUnit;
private double[] msPerPixelValues = {1.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 1200.0, 6000.0};
private int leftPadding;
private Font captionFont;
TimetablePanel(final Timetable timetable) {
this.timetable = timetable;
this.timetable.addObserver(this);
this.currentTime = 0;
this.msPerPixel = 100.0;
this.timeUnit = TimeUnit.SECONDS;
this.captionFont = new Font("SansSerif", Font.PLAIN, 12);
setBackground(Color.BLACK);
setMillisecondsPerPixel(50.0);
this.lowerWestDragger = new Rectangle(0, 0, DRAGGER_EDGE_LENGTH, DRAGGER_EDGE_LENGTH);
this.midCenterDragger = new Rectangle(0, 0, DRAGGER_EDGE_LENGTH, DRAGGER_EDGE_LENGTH);
this.upperEastDragger = new Rectangle(0, 0, DRAGGER_EDGE_LENGTH, DRAGGER_EDGE_LENGTH);
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
}
@Override
public void finalize() {
this.timetable.deleteObserver(this);
}
@Override
public void update(Observable o, Object arg) {
if (o == this.timetable) {
removeAll();
paintComponent(getGraphics()); // paint(getGraphics()); caused a deadlock - don't know why yet
revalidate();
}
}
public void setCurrentTime(final long newCurrentTime) {
this.currentTime = newCurrentTime;
repaint();
revalidate();
}
public void setMillisecondsPerPixel(final double msPerPixel) {
this.msPerPixel = msPerPixel;
if (msPerPixel < 100.0) {
this.timeUnit = TimeUnit.MILLISECONDS;
} else if (msPerPixel < 1200.0) {
this.timeUnit = TimeUnit.SECONDS;
} else {
this.timeUnit = TimeUnit.MINUTES;
}
clearSelection();
this.mouseDownAt = null;
this.mouseUpAt = null;
paint(this.getGraphics());
revalidate();
}
public synchronized void setHandleMouseEvents(final boolean flag) {
this.handleMouseEvents = flag;
if (!flag) {
this.mouseDownAt = null;
this.mouseUpAt = null;
}
clearSelection();
}
public synchronized boolean isHandlingMouseEvents() {
return this.handleMouseEvents;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Setting up graphics.
Graphics2D g2D = (Graphics2D) g;
g2D.setFont(this.captionFont);
g2D.setStroke(new BasicStroke(1.0f));
List<String> mediaObjIDs = this.timetable.getMediaObjectIDs();
FontMetrics fontMetrics = g2D.getFontMetrics();
drawCoordinateSystemAndResize(g2D, mediaObjIDs, fontMetrics);
drawCaption(g2D);
drawEventBars(g2D, mediaObjIDs);
drawDraggers(g2D);
drawCurrentTimeLine(g2D, fontMetrics);
drawDraggedArea(g2D, fontMetrics, mediaObjIDs);
// g2d.setBackground(Color.BLACK);
// g2d.fillRect(getX(), getY(), getWidth(), getHeight());
}
private void drawCoordinateSystemAndResize(final Graphics2D g2D,
final List<String> mediaObjIDs,
final FontMetrics fontMetrics) {
// Resize based on timetable.
int maxIDStringWidth = 0;
for (String mediaObjID : mediaObjIDs) {
int _IDStringWidth = fontMetrics.stringWidth(mediaObjID);
if (_IDStringWidth > maxIDStringWidth) {
maxIDStringWidth = _IDStringWidth;
}
}
this.leftPadding = LEFT_CAPTION_PADDING * 2 + maxIDStringWidth;
int xAxisLength = (int) (this.timetable.getDuration() / this.msPerPixel);
int yAxisLength = mediaObjIDs.size() * EVENT_BAR_HEIGHT;
int prefWidth = this.leftPadding
+ xAxisLength
+ RIGHT_PADDING;
int prefHeight = TOP_PADDING
+ yAxisLength
+ BOTTOM_PADDING;
Dimension newPreferredSize = new Dimension(prefWidth, prefHeight);
this.setPreferredSize(newPreferredSize);
this.setMaximumSize(newPreferredSize);
// Clear.
g2D.setPaint(Color.BLACK);
g2D.fillRect(0, 0, prefWidth, prefHeight);
g2D.setPaint(Color.GRAY);
// x-Axis and its captions.
g2D.draw(new Line2D.Float(this.leftPadding, TOP_PADDING + yAxisLength,
this.leftPadding + xAxisLength, TOP_PADDING + yAxisLength));
for (int curTime = 0; curTime <= xAxisLength; curTime += 10) {
g2D.draw(new Line2D.Float(curTime + this.leftPadding, TOP_PADDING + yAxisLength,
curTime + this.leftPadding, TOP_PADDING + yAxisLength + XAXSIS_DASH_LENGTH));
if (curTime % 50 == 0) {
String curTimeString = String.format("%.0f", computeTimeForPixel(curTime, this.timeUnit));
g2D.drawString(curTimeString,
curTime + this.leftPadding - (fontMetrics.stringWidth(curTimeString) / 2),
TOP_PADDING + yAxisLength + 2 * XAXSIS_DASH_LENGTH + fontMetrics.getHeight());
g2D.draw(new Line2D.Float(curTime + this.leftPadding, TOP_PADDING + yAxisLength,
curTime + this.leftPadding, TOP_PADDING + yAxisLength + XAXSIS_DASH_LENGTH * 2));
} else {
g2D.draw(new Line2D.Float(curTime + this.leftPadding, TOP_PADDING + yAxisLength,
curTime + this.leftPadding, TOP_PADDING + yAxisLength + XAXSIS_DASH_LENGTH));
}
}
g2D.drawString(generateXAxsisCaptionString(),
this.leftPadding + xAxisLength + LEFT_CAPTION_PADDING,
TOP_PADDING + yAxisLength);
// y-Axis and its captions.
g2D.draw(new Line2D.Float(this.leftPadding, TOP_PADDING,
this.leftPadding, TOP_PADDING + yAxisLength));
int captionSpacing = (EVENT_BAR_HEIGHT - fontMetrics.getHeight()) / 2;
int mediaObjNr = 0;
for (String mediaObjID : mediaObjIDs) {
int yCoord = TOP_PADDING + yAxisLength - (mediaObjNr * EVENT_BAR_HEIGHT) - captionSpacing;
g2D.drawString(mediaObjID,
LEFT_CAPTION_PADDING,
yCoord);
mediaObjNr++;
}
}
private String generateXAxsisCaptionString() {
switch (this.timeUnit) {
case MILLISECONDS:
return "t in ms";
case SECONDS:
return "t in s";
case MINUTES:
return "t in min";
default:
return "";
}
}
private double computeTimeForPixel(int pixelColumn, TimeUnit unit) {
switch (unit) {
case MILLISECONDS:
return (pixelColumn * this.msPerPixel);
case SECONDS:
return pixelColumn * (this.msPerPixel / 1000.0);
case MINUTES:
return pixelColumn * (this.msPerPixel / 60000.0);
default:
return 0.0;
}
}
private void drawCaption(final Graphics2D g2D) {
g2D.drawString(TIMETABLE_CAPTION, TIMETABLE_CAPTION_PADDING, TIMETABLE_CAPTION_PADDING);
}
private void drawEventBars(final Graphics2D g2D,
final List<String> mediaObjIDs) {
int numberOfMediaObjs = mediaObjIDs.size();
int remainingIDs = mediaObjIDs.size() - 1;
for (String mediaObjID : mediaObjIDs) {
List<StimEvent> happenedEvents = this.timetable.getHappenedEventsFor(mediaObjID);
List<StimEvent> eventsToHappen = this.timetable.getEventsToHappenFor(mediaObjID);
for (StimEvent event : happenedEvents) {
float rbValue = ((float) numberOfMediaObjs - remainingIDs - 1.0f) / (float) numberOfMediaObjs;
g2D.setColor(new Color(rbValue,
1.0f,
rbValue,
1.0f));
g2D.fill(new Rectangle((int) (event.time / this.msPerPixel) + this.leftPadding,
(remainingIDs * EVENT_BAR_HEIGHT + TOP_PADDING),
(int) (event.duration / this.msPerPixel),
EVENT_BAR_HEIGHT));
}
for (StimEvent event : eventsToHappen) {
float rbValue = ((float) numberOfMediaObjs - remainingIDs - 1.0f) / (float) numberOfMediaObjs;
g2D.setColor(new Color(rbValue,
1.0f,
rbValue,
1.0f));
g2D.fill(new Rectangle((int) (event.time / this.msPerPixel) + this.leftPadding,
(remainingIDs * EVENT_BAR_HEIGHT + TOP_PADDING),
(int) (event.duration / this.msPerPixel),
EVENT_BAR_HEIGHT));
}
remainingIDs--;
}
}
private void drawDraggers(final Graphics2D g2D) {
if (selectedEvent != null) {
g2D.setColor(new Color(0.5f, 0.5f, 0.5f));
g2D.fill(this.lowerWestDragger);
g2D.fill(this.midCenterDragger);
g2D.fill(this.upperEastDragger);
}
}
private void drawDraggedArea(final Graphics2D g2D,
final FontMetrics fontMetrics,
final List<String> mediaObjIDs) {
g2D.setColor(new Color(0.0f, 0.8f, 1.0f, 1.0f));
double yLineEnd = this.getPreferredSize().height - BOTTOM_PADDING + 2 * XAXSIS_DASH_LENGTH;
if (this.mouseDownAt != null) {
g2D.draw(new Line2D.Double(this.mouseDownAt.getX(), TOP_PADDING,
this.mouseDownAt.getX(), yLineEnd));
}
if (this.mouseUpAt != null) {
g2D.draw(new Line2D.Double(this.mouseUpAt.getX(), TOP_PADDING,
this.mouseUpAt.getX(), yLineEnd));
}
if (this.selectedEvent != null
&& this.draggedAt != DragSpot.NOT_DRAGGED) {
g2D.setColor(new Color(0.0f, 0.8f, 1.0f, 0.7f));
int yCoordDraggedArea = TOP_PADDING + (mediaObjIDs.size() - 1 - mediaObjIDs.indexOf(this.selectedEvent.mediaObject.getID())) * EVENT_BAR_HEIGHT;
if (this.mouseUpAt.x >= this.mouseDownAt.x) {
g2D.fill(new Rectangle(this.mouseDownAt.x, yCoordDraggedArea, this.mouseUpAt.x - this.mouseDownAt.x, EVENT_BAR_HEIGHT));
} else {
g2D.fill(new Rectangle(this.mouseUpAt.x, yCoordDraggedArea, this.mouseDownAt.x - this.mouseUpAt.x, EVENT_BAR_HEIGHT));
}
}
// Time captions.
if (this.mouseDownAt != null) {
String currentTimeString = String.format("%.1f", computeTimeForPixel(mouseDownAt.x - this.leftPadding, this.timeUnit));
g2D.drawString(currentTimeString,
mouseDownAt.x - (fontMetrics.stringWidth(currentTimeString) / 2),
this.getPreferredSize().height - BOTTOM_PADDING + 2 * XAXSIS_DASH_LENGTH + 3 * fontMetrics.getHeight());
}
if (this.mouseUpAt != null) {
String currentTimeString = String.format("%.1f", computeTimeForPixel(mouseUpAt.x - this.leftPadding, this.timeUnit));
g2D.drawString(currentTimeString,
mouseUpAt.x - (fontMetrics.stringWidth(currentTimeString) / 2),
this.getPreferredSize().height - BOTTOM_PADDING + 2 * XAXSIS_DASH_LENGTH + 4 * fontMetrics.getHeight());
}
}
private void drawCurrentTimeLine(final Graphics2D g2D,
final FontMetrics fontMetrics) {
g2D.setColor(Color.RED);
int curPixelTime = (int) (this.currentTime / this.msPerPixel);
// Vertical red line.
g2D.draw(new Line2D.Float(curPixelTime + this.leftPadding,
TOP_PADDING,
curPixelTime + this.leftPadding,
this.getPreferredSize().height - BOTTOM_PADDING + 2 * XAXSIS_DASH_LENGTH));
// Caption.
String currentTimeString = String.format("%.1f", computeTimeForPixel(curPixelTime, this.timeUnit));
g2D.drawString(currentTimeString,
curPixelTime + this.leftPadding - (fontMetrics.stringWidth(currentTimeString) / 2),
this.getPreferredSize().height - BOTTOM_PADDING + 2 * (XAXSIS_DASH_LENGTH + fontMetrics.getHeight()));
}
private StimEvent eventForClickedPoint(final Point p) {
if (isPointInCoordinateSystem(p)) {
List<String> mediaObjIDs = this.timetable.getMediaObjectIDs();
int mediaObjNrForEvent = mediaObjIDs.size() - ((p.y - TOP_PADDING) / EVENT_BAR_HEIGHT + 1);
String mediaObjIDForEvent = mediaObjIDs.get(mediaObjNrForEvent);
long timeForEvent = (long) ((p.x - this.leftPadding) * this.msPerPixel);
List<StimEvent> allEventsForMediaObj = this.timetable.getHappenedEventsFor(mediaObjIDForEvent);
allEventsForMediaObj.addAll(this.timetable.getEventsToHappenFor(mediaObjIDForEvent));
for (StimEvent event : allEventsForMediaObj) {
if (event.time <= timeForEvent
&& (event.time + event.duration) >= timeForEvent) {
this.lowerWestDragger.x = ((int) (event.time / this.msPerPixel)) + this.leftPadding;
this.lowerWestDragger.y = (mediaObjIDs.size() - mediaObjNrForEvent) * EVENT_BAR_HEIGHT + TOP_PADDING - DRAGGER_EDGE_LENGTH;
this.midCenterDragger.x = this.lowerWestDragger.x + (int) ((event.duration / this.msPerPixel) / 2.0) - (int) (DRAGGER_EDGE_LENGTH / 2.0);
this.midCenterDragger.y = this.lowerWestDragger.y - DRAGGER_EDGE_LENGTH - 1;
this.upperEastDragger.x = ((int) ((event.time + event.duration) / this.msPerPixel)) + this.leftPadding - DRAGGER_EDGE_LENGTH;
this.upperEastDragger.y = this.lowerWestDragger.y + DRAGGER_EDGE_LENGTH - EVENT_BAR_HEIGHT;
return event;
}
}
}
return null;
}
private boolean isPointInCoordinateSystem(final Point p) {
int x = p.x;
int y = p.y;
int width = this.getPreferredSize().width;
int height = this.getPreferredSize().height;
if (x >= this.leftPadding && x < width - RIGHT_PADDING
&& y > TOP_PADDING && y < height - BOTTOM_PADDING) {
return true;
}
return false;
}
private void clearSelection() {
this.selectedEvent = null;
this.draggedAt = DragSpot.NOT_DRAGGED;
}
// Mouse event handlers.
@Override
public void mouseClicked(MouseEvent e) {
requestFocusInWindow();
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
requestFocusInWindow();
if (isHandlingMouseEvents()) {
this.mouseDownAt = new Point(e.getPoint());
this.mouseUpAt = new Point(e.getPoint());
if (this.mouseDownAt.x < this.leftPadding) {
this.mouseDownAt.x = leftPadding;
this.mouseUpAt.x = this.mouseDownAt.x;
}
if (this.mouseDownAt.x > this.getPreferredSize().width - RIGHT_PADDING) {
this.mouseDownAt.x = this.getPreferredSize().width - RIGHT_PADDING;
this.mouseUpAt.x = this.mouseDownAt.x;
}
if (this.selectedEvent == null) {
/* No event is selected: try to find one at the location
* pointed by the user. */
this.selectedEvent = eventForClickedPoint(mouseDownAt);
this.draggedAt = DragSpot.NOT_DRAGGED;
} else {
if (this.lowerWestDragger.contains(this.mouseDownAt)) {
this.draggedAt = DragSpot.LOWER_WEST;
} else if (this.midCenterDragger.contains(this.mouseDownAt)) {
this.draggedAt = DragSpot.MID_CENTER;
} else if (this.upperEastDragger.contains(this.mouseDownAt)) {
this.draggedAt = DragSpot.UPPER_EAST;
} else {
clearSelection();
mousePressed(e);
}
}
repaint();
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (isHandlingMouseEvents()) {
this.mouseUpAt = new Point(e.getPoint());
if (this.mouseUpAt.x < this.leftPadding) {
this.mouseUpAt.x = leftPadding;
}
if (this.mouseUpAt.x > this.getPreferredSize().width - RIGHT_PADDING) {
this.mouseUpAt.x = this.getPreferredSize().width - RIGHT_PADDING;
}
if (this.selectedEvent != null
&& this.draggedAt != DragSpot.NOT_DRAGGED) {
long newTime = -1;
long newDuration = -1;
if (this.draggedAt == DragSpot.LOWER_WEST) {
newTime = (long) ((this.mouseUpAt.x - this.leftPadding) * this.msPerPixel);
newDuration = this.selectedEvent.duration + (this.selectedEvent.time - newTime);
} else if (this.draggedAt == DragSpot.UPPER_EAST) {
newTime = this.selectedEvent.time;
newDuration = ((long) ((this.mouseUpAt.x - this.leftPadding) * this.msPerPixel)) - newTime;
} else if (this.draggedAt == DragSpot.MID_CENTER) {
newTime = ((long) ((this.mouseUpAt.x - this.leftPadding) * this.msPerPixel)) - (this.selectedEvent.duration / 2);
newDuration = this.selectedEvent.duration;
}
if (newTime < 0) {
newTime = 0;
}
if (newDuration < 0) {
newDuration = 0;
}
if (newTime + newDuration > this.timetable.getDuration()) {
newTime = this.timetable.getDuration() - newDuration;
}
StimEvent newEvent = new StimEvent(newTime, newDuration, this.selectedEvent.mediaObject);
this.timetable.replace(this.selectedEvent, newEvent);
clearSelection();
}
repaint();
}
}
// Mouse motion event handlers.
@Override
public void mouseDragged(MouseEvent e) {
if (isHandlingMouseEvents()) {
this.mouseUpAt = e.getPoint();
if (this.mouseUpAt.x < this.leftPadding) {
this.mouseUpAt.x = leftPadding;
}
if (this.mouseUpAt.x > this.getPreferredSize().width - RIGHT_PADDING) {
this.mouseUpAt.x = this.getPreferredSize().width - RIGHT_PADDING;
}
repaint();
}
}
@Override
public void mouseMoved(MouseEvent e) {
}
// Key event handlers.
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_DELETE) {
if (this.selectedEvent != null) {
this.timetable.remove(this.selectedEvent);
clearSelection();
repaint();
}
}
}
@Override
public void keyTyped(KeyEvent e) {
char key = e.getKeyChar();
if (key == '-') {
for (int i = 0; i < this.msPerPixelValues.length; i++) {
if (this.msPerPixelValues[i] == this.msPerPixel
&& (i + 1 < this.msPerPixelValues.length)) {
setMillisecondsPerPixel(this.msPerPixelValues[i + 1]);
return;
}
}
} else if (key == '+') {
for (int i = 0; i < this.msPerPixelValues.length; i++) {
if (this.msPerPixelValues[i] == this.msPerPixel
&& (i - 1 >= 0)) {
setMillisecondsPerPixel(this.msPerPixelValues[i - 1]);
return;
}
}
}
}
}
|
damassa/fmon
|
server/src/components/images/Controller.js
|
const db = require('../../database');
exports.imageById = (req, res, next, id) => {
let sql = `SELECT image FROM images WHERE id = ?`;
db.connect.query(sql, [id], (err, values) => {
if(err || !values) {
return res.status(400).json({
error: err
})
}
req.image = values[0];
next();
});
}
exports.showImage = (req, res) => {
return res.status(200).json(req.image);
}
|
ayhanugurlu/meetinger
|
src/main/java/com/au/example/meetinger/service/MailServiceImpl.java
|
package com.au.example.meetinger.service;
import java.util.Properties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import com.au.example.meetinger.service.data.MailProperty;
@Service
public class MailServiceImpl implements MailService {
MailProperty property = null;
JavaMailSenderImpl javaMailSender = null;
@Override
public JavaMailSender buildMailSender(MailProperty property) {
javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(property.getMailHost());
javaMailSender.setPort(property.getMailPort());
javaMailSender.setUsername(property.getMailUserName());
javaMailSender.setPassword(property.getMailPassword());
Properties prop = javaMailSender.getJavaMailProperties();
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.debug", "true");
return javaMailSender;
}
@Override
public String sendMessage( String mailAddresses, String text,String subject) {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject(subject);
message.setText(text);
message.setTo(mailAddresses);
message.setFrom("<EMAIL>");
try {
javaMailSender.send(message);
return "{\"message\": \"OK\"}";
} catch (Exception e) {
e.printStackTrace();
return "{\"message\": \"Error\"}";
}
}
}
|
kagwicharles/Seniorproject-ui
|
node_modules/@iconify/icons-ic/sharp-sports-bar.js
|
var data = {
"body": "<path d=\"M21 9h-3.56c.35-.59.56-1.27.56-2c0-2.21-1.79-4-4-4c-.34 0-.66.05-.98.13A4.707 4.707 0 0 0 10 2.02c-1.89 0-3.51 1.11-4.27 2.71C4.15 5.26 3 6.74 3 8.5c0 1.86 1.28 3.41 3 3.86V21h11v-2h4V9zM7 10.5c-1.1 0-2-.9-2-2c0-.85.55-1.6 1.37-1.88l.8-.27l.36-.76C8 4.62 8.94 4.02 10 4.02c.79 0 1.39.35 1.74.65l.78.65S13.16 5 13.99 5c1.1 0 2 .9 2 2h-3C9.67 7 9.15 10.5 7 10.5zM19 17h-2v-6h2v6z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
exports.__esModule = true;
exports.default = data;
|
BobbyWhiskey/sg-orbit
|
packages/react-components/src/shared/src/useControllableState.js
|
import { isFunction, isUndefined } from "lodash";
import { useCallback, useRef } from "react";
import { useRefState } from "./useRefState";
function validatePrerequisites(controlledValue, initialValue) {
if (!isUndefined(controlledValue) && !isUndefined(initialValue)) {
throw new Error(
"useControllableState - A controllable state value can either have a controlled value or an initial value, but not both."
);
}
}
function ensureControlledStateHaveNotChanged(controlledValue, isControlled) {
if ((isControlled && isUndefined(controlledValue)) || (!isControlled && !isUndefined(controlledValue))) {
throw new Error("useControllableState - A controllable state value cannot switch between controlled and uncontrolled. Did you inadvertently set a default value (defaultProps) for your controlled prop?");
}
}
function useComputeInitialState(controlledValue, initialValue, defaultValue) {
const result = (state, isControlled, isInitialState = false) => ({ state, isControlled, isInitialState });
const hasComputedRef = useRef(false);
if (hasComputedRef.current) {
return result(null, null);
}
let state;
let isControlled = false;
if (isUndefined(controlledValue)) {
// This prop is "uncontrolled".
state = !isUndefined(initialValue) ? initialValue : defaultValue;
} else {
// This prop is "controlled".
state = controlledValue;
isControlled = true;
}
hasComputedRef.current = true;
return result(state, isControlled, true);
}
function computeSubsequentState(controlledValue, currentState, isControlled) {
let newState = null;
let hasChanged = false;
ensureControlledStateHaveNotChanged(controlledValue, isControlled);
if (isControlled) {
if (currentState !== controlledValue) {
newState = controlledValue;
hasChanged = true;
}
}
return {
newState,
hasChanged
};
}
/**
* This implementation is a port of Semantic UI React "AutoControlledComponent" base component to hooks: https://github.com/Semantic-Org/Semantic-UI-React/blob/master/src/lib/AutoControlledComponent.js.
* The goal is to seemlessly support "controlled" and "uncontrolled" component behaviors by abstracting the complexity in this hook.
* This is achieved by abstracting the state and updating a state value only when a prop is considered "uncontrolled".
*
* @param {Object} controlledValue - The controlled value.
* @param {Object} initialValue - The initial value.
* @param {Object} defaultValue - The default value.
* @param {Object} [options] - A set of optionnal options.
* @returns {[Object, Function]} An array with the first value being the value of the state and the second value being a function to manually update the state value.
* @example
* const [controllableValue, setUncontrolledState] = useControllableState(value, initialValue, defaultValue, {
* onChange: (newValue, isInitialState) => {
* // Optionally compute derived state...
* if (isInitialState) {
* setSelectedValue(newValue)
* }
* }
* });
*
* ...
*
* setUncontrolledState("<NAME>");
*/
export function useControllableState(controlledValue, initialValue, defaultValue, { onChange } = {}) {
validatePrerequisites(controlledValue, initialValue);
let { state: initialState, isControlled: isControlledProp, isInitialState } = useComputeInitialState(controlledValue, initialValue, defaultValue);
const [isControlledRef] = useRefState(isControlledProp);
const transformState = useCallback((newState, context) => {
const transformedState = isFunction(onChange)
? onChange(newState, { ...context, isControlled: isControlledRef.current })
: undefined;
return !isUndefined(transformedState)
? transformedState
: newState;
}, [isControlledRef, onChange]);
if (isInitialState) {
initialState = transformState(initialState, { isInitial: true });
}
// Using a ref instead of useState because when in controlled mode the consumer must already have is own state management code and
// using useState here would cause 2 rerender when the controlled value update.
const [stateRef, setState] = useRefState(initialState);
if (!isInitialState) {
const { newState, hasChanged } = computeSubsequentState(controlledValue, stateRef.current, isControlledRef.current);
if (hasChanged) {
setState(transformState(newState, { isInitial: false }));
}
}
/**
* Safely attempt to set state for a prop that might be "controlled" by the consumer.
* When the prop is "uncontrolled", the state will be updated with the value, otherwise ignored.
*/
const setUncontrolledState = useCallback(maybeState => {
if (!isControlledRef.current) {
if (maybeState !== stateRef.current) {
setState(transformState(maybeState, { isInitial: false }), true);
}
}
}, [stateRef, setState, isControlledRef, transformState]);
return [stateRef.current, setUncontrolledState, isControlledProp];
}
|
ScalablyTyped/SlinkyTyped
|
m/maxim_mazurok__gapi_dot_client_dot_bigquery/src/main/scala/typingsSlinky/maximMazurokGapiClientBigquery/gapi/client/bigquery/EvaluationMetrics.scala
|
<filename>m/maxim_mazurok__gapi_dot_client_dot_bigquery/src/main/scala/typingsSlinky/maximMazurokGapiClientBigquery/gapi/client/bigquery/EvaluationMetrics.scala
package typingsSlinky.maximMazurokGapiClientBigquery.gapi.client.bigquery
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait EvaluationMetrics extends StObject {
/** Populated for ARIMA models. */
var arimaForecastingMetrics: js.UndefOr[ArimaForecastingMetrics] = js.native
/** Populated for binary classification/classifier models. */
var binaryClassificationMetrics: js.UndefOr[BinaryClassificationMetrics] = js.native
/** Populated for clustering models. */
var clusteringMetrics: js.UndefOr[ClusteringMetrics] = js.native
/** Populated for multi-class classification/classifier models. */
var multiClassClassificationMetrics: js.UndefOr[MultiClassClassificationMetrics] = js.native
/** Populated for implicit feedback type matrix factorization models. */
var rankingMetrics: js.UndefOr[RankingMetrics] = js.native
/** Populated for regression models and explicit feedback type matrix factorization models. */
var regressionMetrics: js.UndefOr[RegressionMetrics] = js.native
}
object EvaluationMetrics {
@scala.inline
def apply(): EvaluationMetrics = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[EvaluationMetrics]
}
@scala.inline
implicit class EvaluationMetricsMutableBuilder[Self <: EvaluationMetrics] (val x: Self) extends AnyVal {
@scala.inline
def setArimaForecastingMetrics(value: ArimaForecastingMetrics): Self = StObject.set(x, "arimaForecastingMetrics", value.asInstanceOf[js.Any])
@scala.inline
def setArimaForecastingMetricsUndefined: Self = StObject.set(x, "arimaForecastingMetrics", js.undefined)
@scala.inline
def setBinaryClassificationMetrics(value: BinaryClassificationMetrics): Self = StObject.set(x, "binaryClassificationMetrics", value.asInstanceOf[js.Any])
@scala.inline
def setBinaryClassificationMetricsUndefined: Self = StObject.set(x, "binaryClassificationMetrics", js.undefined)
@scala.inline
def setClusteringMetrics(value: ClusteringMetrics): Self = StObject.set(x, "clusteringMetrics", value.asInstanceOf[js.Any])
@scala.inline
def setClusteringMetricsUndefined: Self = StObject.set(x, "clusteringMetrics", js.undefined)
@scala.inline
def setMultiClassClassificationMetrics(value: MultiClassClassificationMetrics): Self = StObject.set(x, "multiClassClassificationMetrics", value.asInstanceOf[js.Any])
@scala.inline
def setMultiClassClassificationMetricsUndefined: Self = StObject.set(x, "multiClassClassificationMetrics", js.undefined)
@scala.inline
def setRankingMetrics(value: RankingMetrics): Self = StObject.set(x, "rankingMetrics", value.asInstanceOf[js.Any])
@scala.inline
def setRankingMetricsUndefined: Self = StObject.set(x, "rankingMetrics", js.undefined)
@scala.inline
def setRegressionMetrics(value: RegressionMetrics): Self = StObject.set(x, "regressionMetrics", value.asInstanceOf[js.Any])
@scala.inline
def setRegressionMetricsUndefined: Self = StObject.set(x, "regressionMetrics", js.undefined)
}
}
|
alexngn2020/airback
|
airback-services/src/main/java/com/airback/common/domain/OptionVal.java
|
<gh_stars>0
/*Domain class of table m_options*/
package com.airback.common.domain;
import com.airback.core.arguments.ValuedBean;
import com.airback.db.metadata.Column;
import com.airback.db.metadata.Table;
import java.time.LocalDateTime;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.ibatis.type.Alias;
import org.hibernate.validator.constraints.Length;
@SuppressWarnings("ucd")
@Table("m_options")
@Alias("OptionVal")
public class OptionVal extends ValuedBean {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.id
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@Column("id")
private Integer id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.type
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@NotEmpty
@Length(max=45, message="Field value is too long")
@Column("type")
private String type;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.typeVal
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@NotEmpty
@Length(max=255, message="Field value is too long")
@Column("typeVal")
private String typeval;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.orderIndex
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@Column("orderIndex")
private Integer orderindex;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.sAccountId
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@NotNull
@Column("sAccountId")
private Integer saccountid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.createdTime
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@NotNull
@Column("createdTime")
private LocalDateTime createdtime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.createdUser
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@Length(max=45, message="Field value is too long")
@Column("createdUser")
private String createduser;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.extraId
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@Column("extraId")
private Integer extraid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.isDefault
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@NotNull
@Column("isDefault")
private Boolean isdefault;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.refOption
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@Column("refOption")
private Integer refoption;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.color
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@NotEmpty
@Length(max=6, message="Field value is too long")
@Column("color")
private String color;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.fieldgroup
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@NotEmpty
@Length(max=45, message="Field value is too long")
@Column("fieldgroup")
private String fieldgroup;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.isShow
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@Column("isShow")
private Boolean isshow;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column m_options.description
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
@Length(max=65535, message="Field value is too long")
@Column("description")
private String description;
private static final long serialVersionUID = 1;
public final boolean equals(Object obj) {
if (obj == null) { return false;}
if (obj == this) { return true;}
if (!obj.getClass().isAssignableFrom(getClass())) { return false;}
OptionVal item = (OptionVal)obj;
return new EqualsBuilder().append(id, item.id).build();
}
public final int hashCode() {
return new HashCodeBuilder(25, 727).append(id).build();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.id
*
* @return the value of m_options.id
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withId(Integer id) {
this.setId(id);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.id
*
* @param id the value for m_options.id
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.type
*
* @return the value of m_options.type
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public String getType() {
return type;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withType(String type) {
this.setType(type);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.type
*
* @param type the value for m_options.type
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setType(String type) {
this.type = type;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.typeVal
*
* @return the value of m_options.typeVal
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public String getTypeval() {
return typeval;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withTypeval(String typeval) {
this.setTypeval(typeval);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.typeVal
*
* @param typeval the value for m_options.typeVal
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setTypeval(String typeval) {
this.typeval = typeval;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.orderIndex
*
* @return the value of m_options.orderIndex
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public Integer getOrderindex() {
return orderindex;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withOrderindex(Integer orderindex) {
this.setOrderindex(orderindex);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.orderIndex
*
* @param orderindex the value for m_options.orderIndex
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setOrderindex(Integer orderindex) {
this.orderindex = orderindex;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.sAccountId
*
* @return the value of m_options.sAccountId
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public Integer getSaccountid() {
return saccountid;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withSaccountid(Integer saccountid) {
this.setSaccountid(saccountid);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.sAccountId
*
* @param saccountid the value for m_options.sAccountId
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setSaccountid(Integer saccountid) {
this.saccountid = saccountid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.createdTime
*
* @return the value of m_options.createdTime
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public LocalDateTime getCreatedtime() {
return createdtime;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withCreatedtime(LocalDateTime createdtime) {
this.setCreatedtime(createdtime);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.createdTime
*
* @param createdtime the value for m_options.createdTime
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setCreatedtime(LocalDateTime createdtime) {
this.createdtime = createdtime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.createdUser
*
* @return the value of m_options.createdUser
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public String getCreateduser() {
return createduser;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withCreateduser(String createduser) {
this.setCreateduser(createduser);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.createdUser
*
* @param createduser the value for m_options.createdUser
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setCreateduser(String createduser) {
this.createduser = createduser;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.extraId
*
* @return the value of m_options.extraId
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public Integer getExtraid() {
return extraid;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withExtraid(Integer extraid) {
this.setExtraid(extraid);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.extraId
*
* @param extraid the value for m_options.extraId
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setExtraid(Integer extraid) {
this.extraid = extraid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.isDefault
*
* @return the value of m_options.isDefault
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public Boolean getIsdefault() {
return isdefault;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withIsdefault(Boolean isdefault) {
this.setIsdefault(isdefault);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.isDefault
*
* @param isdefault the value for m_options.isDefault
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setIsdefault(Boolean isdefault) {
this.isdefault = isdefault;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.refOption
*
* @return the value of m_options.refOption
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public Integer getRefoption() {
return refoption;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withRefoption(Integer refoption) {
this.setRefoption(refoption);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.refOption
*
* @param refoption the value for m_options.refOption
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setRefoption(Integer refoption) {
this.refoption = refoption;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.color
*
* @return the value of m_options.color
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public String getColor() {
return color;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withColor(String color) {
this.setColor(color);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.color
*
* @param color the value for m_options.color
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setColor(String color) {
this.color = color;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.fieldgroup
*
* @return the value of m_options.fieldgroup
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public String getFieldgroup() {
return fieldgroup;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withFieldgroup(String fieldgroup) {
this.setFieldgroup(fieldgroup);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.fieldgroup
*
* @param fieldgroup the value for m_options.fieldgroup
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setFieldgroup(String fieldgroup) {
this.fieldgroup = fieldgroup;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.isShow
*
* @return the value of m_options.isShow
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public Boolean getIsshow() {
return isshow;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withIsshow(Boolean isshow) {
this.setIsshow(isshow);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.isShow
*
* @param isshow the value for m_options.isShow
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setIsshow(Boolean isshow) {
this.isshow = isshow;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column m_options.description
*
* @return the value of m_options.description
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public String getDescription() {
return description;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table m_options
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public OptionVal withDescription(String description) {
this.setDescription(description);
return this;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column m_options.description
*
* @param description the value for m_options.description
*
* @mbg.generated Sat Feb 09 11:42:26 CST 2019
*/
public void setDescription(String description) {
this.description = description;
}
public enum Field {
id,
type,
typeval,
orderindex,
saccountid,
createdtime,
createduser,
extraid,
isdefault,
refoption,
color,
fieldgroup,
isshow,
description;
public boolean equalTo(Object value) {
return name().equals(value);
}
}
}
|
Haulmont/jmix-old
|
modules/core/src/main/java/io/jmix/core/impl/jpql/ErrorNodesFinder.java
|
<filename>modules/core/src/main/java/io/jmix/core/impl/jpql/ErrorNodesFinder.java
/*
* Copyright 2019 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.jmix.core.impl.jpql;
import org.antlr.runtime.tree.CommonErrorNode;
import org.antlr.runtime.tree.TreeVisitorAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ErrorNodesFinder implements TreeVisitorAction {
protected List<CommonErrorNode> errorNodes = new ArrayList<>();
@Override
public Object pre(Object t) {
if (t instanceof CommonErrorNode) {
errorNodes.add((CommonErrorNode) t);
return t;
}
return t;
}
@Override
public Object post(Object t) {
return t;
}
public List<CommonErrorNode> getErrorNodes() {
return Collections.unmodifiableList(errorNodes);
}
}
|
curtcox/ScreenRecorder
|
src/test/java/com/neomemex/fixed/FixedElementTest.java
|
package com.neomemex.fixed;
import com.neomemex.ocr.OCR;
import org.junit.Test;
import javax.swing.text.Element;
import static org.junit.Assert.*;
/**
* https://web.archive.org/web/20060110035515/http://java.sun.com/products/jfc/tsc/articles/text/element_interface/
*/
public class FixedElementTest {
static OCR.Word word(String text) {
return new OCR.Word(0,0,0,0,text);
}
OCR.Word word = word("bird");
FixedElement parent = FixedElement.of(FixedDocument.of(new OCR.Word[]{word}));
@Test
public void can_create_root() {
assertNotNull(FixedElement.of(FixedDocument.of(new OCR.Word[]{word})));
}
@Test
public void root_with_0_words() {
try {
FixedElement.of(FixedDocument.of(new OCR.Word[0]));
} catch (IllegalArgumentException e) {
assertEquals("Root element must have more than 0 words.",e.getMessage());
}
}
@Test
public void root_with_1_word() {
Element root = FixedElement.of(FixedDocument.of(new OCR.Word[]{
word("text")
}));
assertFalse(root.isLeaf());
equals(root,1,root.getElementCount());
equals(root,0,root.getStartOffset());
equals(root,3,root.getEndOffset());
equals(root,root.getStartOffset(),root.getElement(0).getStartOffset());
equals(root,root.getEndOffset(),root.getElement(0).getEndOffset());
}
private void equals(Element e,int expected,int actual) {
assertEquals(e.toString(),expected,actual);
}
@Test
public void root_with_2_words() {
Element root = FixedElement.of(FixedDocument.of(new OCR.Word[]{
word("one"),
word("two")
}));
assertFalse(root.isLeaf());
equals(root,2,root.getElementCount());
equals(root,0,root.getStartOffset());
equals(root,0,root.getElement(0).getStartOffset());
equals(root, 5,root.getEndOffset());
equals(root,root.getStartOffset(),root.getElement(0).getStartOffset());
equals(root,2,root.getElement(0).getEndOffset());
equals(root,3,root.getElement(1).getStartOffset());
equals(root,root.getEndOffset(),root.getElement(1).getEndOffset());
}
@Test
public void can_create_leaf() {
assertNotNull(FixedElement.leaf(null, parent,0,0));
}
@Test
public void leaf_isLeaf_returns_true_when_parent_is_not_null() {
FixedElement element = FixedElement.leaf(null, parent,0,5);
assertTrue(element.isLeaf());
equals(element,0,element.getElementCount());
equals(element,0,element.getStartOffset());
equals(element,5,element.getEndOffset());
assertSame(parent,element.getParentElement());
}
@Test
public void getDocument_returns_given_document() {
FixedDocument document = FixedDocument.of(new OCR.Word[0]);
Element element = FixedElement.leaf(document, parent,0,0);
assertSame(document,element.getDocument());
}
// @Test
// public void getElement_with_index_0_returns_element_with_startOffset() {
// FixedElement map = FixedElement.leaf(null, parent,0,0);
// Element paragraph = map.getElement(0);
// assertEquals(0,paragraph.getStartOffset());
// }
// @Test
// public void getElement_with_index_0_returns_element_with_endOffset() {
// FixedElement map = FixedElement.leaf(null, parent,0,0);
// Element paragraph = map.getElement(0);
// assertEquals(0,paragraph.getEndOffset());
// }
@Test
public void getElementIndex_returns_neg_1_if_the_element_is_a_leaf() {
Element leaf = FixedElement.leaf(null, parent,0,0);
assertTrue(leaf.isLeaf());
equals(leaf,-1,leaf.getElementIndex(0));
}
@Test
public void root_getElementIndex_returns_0_if_the_location_is_less_than_the_start_offset() {
Element root = FixedElement.of(FixedDocument.of(new OCR.Word[]{
word("text")
}));
assertFalse(root.isLeaf());
equals(root,0,root.getElementIndex(-1));
equals(root,0,root.getElementIndex(-2));
}
@Test
public void root_with_1_getElementIndex_returns_getElementCount_minus_1_if_the_location_is_greater_than_the_end_offset() {
Element root = FixedElement.of(FixedDocument.of(new OCR.Word[]{
word("text")
}));
assertFalse(root.isLeaf());
equals(root,0,root.getElementIndex(5));
equals(root,0,root.getElementIndex(10));
}
@Test
public void root_with_1_getElementIndex_returns_best_match() {
Element root = FixedElement.of(FixedDocument.of(new OCR.Word[]{
word("fi")
}));
assertFalse(root.isLeaf());
equals(root,0,root.getElementIndex(-1));
equals(root,0,root.getElementIndex(0));
equals(root,0,root.getElementIndex(1));
equals(root,0,root.getElementIndex(2));
}
@Test
public void root_with_2_getElementIndex_returns_getElementCount_minus_1_if_the_location_is_greater_than_the_end_offset() {
Element root = FixedElement.of(FixedDocument.of(new OCR.Word[]{
word("one"),
word("two")
}));
assertFalse(root.isLeaf());
equals(root,2,root.getElementCount());
equals(root,1,root.getElementIndex(10));
equals(root,1,root.getElementIndex(8));
equals(root,1,root.getElementIndex(7));
equals(root,1,root.getElementIndex(6));
equals(root,1,root.getElementIndex(5));
}
@Test
public void root_with_2_getElementIndex_returns_best_match() {
Element root = FixedElement.of(FixedDocument.of(new OCR.Word[]{
word("fi"),
word("fi")
}));
assertFalse(root.isLeaf());
equals(root,2,root.getElementCount());
equals(root,0,root.getElementIndex(-1));
equals(root,0,root.getElementIndex(0));
equals(root,0,root.getElementIndex(1));
equals(root,1,root.getElementIndex(2));
equals(root,1,root.getElementIndex(3));
equals(root,1,root.getElementIndex(4));
}
//public int getElementIndex(int offset);
// Gets the child element index closest to the given offset.
// The offset is specified relative to the beginning of the document.
// Returns -1 if the Element is a leaf,
// otherwise returns the index of the Element that best represents the given location.
// Returns 0 if the location is less than the start offset.
// Returns getElementCount() - 1 if the location is greater than or equal to the end offset.
// Params:
// offset – the specified offset >= 0
// Returns:
// the element index >= 0
/**
* Fetches the child element at the given index.
*
* @param index the specified index >= 0
* @return the child element
*/
//public Element getElement(int index);
// public static final Element getParagraphElement(JTextComponent c, int offs) {
// Document doc = c.getDocument();
// if (doc instanceof StyledDocument) {
// return ((StyledDocument)doc).getParagraphElement(offs);
// }
// Element map = doc.getDefaultRootElement();
// int index = map.getElementIndex(offs);
// Element paragraph = map.getElement(index);
// if ((offs >= paragraph.getStartOffset()) && (offs < paragraph.getEndOffset())) {
// return paragraph;
// }
// return null;
// }
}
|
norishigefukushima/OpenCP
|
OpenCP/highDimensionalGaussianFilter.cpp
|
#include "highDimensionalGaussianFilter.hpp"
using namespace std;
using namespace cv;
namespace cp
{
inline double get_l2norm_maxval(const int channel)
{
return sqrt(1024*1024 * channel);
}
template<int gchannel, HDGFSchedule schedule>
void highDimensionalGaussianFilter_(const cv::Mat src, const cv::Mat guide, cv::Mat& dst, const cv::Size ksize, const float sigma_range, const float sigma_space, const int border)
{
const int r = ksize.height / 2;
Mat srcborder; copyMakeBorder(src, srcborder, r, r, r, r, border);
Mat guideborder; copyMakeBorder(guide, guideborder, r, r, r, r, border);
vector<Mat> split_guideborder;
split(guideborder, split_guideborder);
cv::Mat weight_space(ksize, src.type());
const float coeff_space = 1.f / (-2.f * sigma_space * sigma_space);
const int D = 2 * r + 1;
for (int j = 0; j < D; j++)
{
float* wsptr = weight_space.ptr<float>(j);
for (int i = 0; i < D; i++)
{
const float distance = float((i - r) * (i - r) + (j - r) * (j - r));
wsptr[i] = std::exp(distance * coeff_space);
}
}
const float coeff_range = 1.f / (-2.f * sigma_range * sigma_range);
const __m256 mcoeff_range = _mm256_set1_ps(coeff_range);
const int lut_size = (int)ceil(get_l2norm_maxval(gchannel));
cv::AutoBuffer<float> lut(lut_size);
for (int i = 0; i < lut_size; i++)
{
lut[i] = exp(i * i * coeff_range);
}
if (src.channels() == 1)
{
#pragma omp parallel for schedule(dynamic)
for (int j = r; j < srcborder.rows - r; j++)
{
float* dptr = dst.ptr<float>(j - r);
for (int i = r; i < srcborder.cols - r; i += 8)
{
__m256 mdenom = _mm256_setzero_ps();
__m256 mnumer = _mm256_setzero_ps();
for (int y = -r; y <= r; y++)
{
float* wsptr = weight_space.ptr<float>(y + r);
float* Iptr = srcborder.ptr<float>(y + j);
for (int x = -r; x <= r; x++)
{
__m256 mdiff = _mm256_setzero_ps();
AutoBuffer<__m256> msrc(guide.channels());
for (int c = 0; c < gchannel; c++)
{
float* srcptr = split_guideborder[c].ptr<float>(j);
msrc[c] = _mm256_loadu_ps(srcptr + i);
}
for (int c = 0; c < gchannel; c++)
{
float* gptr = split_guideborder[c].ptr<float>(y + j);
__m256 sub = _mm256_sub_ps(msrc[c], _mm256_loadu_ps(gptr + x + i));
mdiff = _mm256_fmadd_ps(sub, sub, mdiff);
}
__m256 mgauss;
if constexpr (schedule == HDGFSchedule::COMPUTE)mgauss = _mm256_exp_ps(_mm256_mul_ps(mdiff, mcoeff_range));
else mgauss = _mm256_i32gather_ps(lut, _mm256_cvtps_epi32(_mm256_sqrt_ps(mdiff)), 4);
__m256 mw = _mm256_mul_ps(_mm256_set1_ps(wsptr[x + r]), mgauss);
mdenom = _mm256_add_ps(mdenom, mw);
mnumer = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr + i + x), mnumer);
}
}
_mm256_store_ps(dptr + i - r, _mm256_div_ps(mnumer, mdenom));
}
}
}
else if (src.channels() == 3)
{
vector<Mat> split_srcborder; split(srcborder, split_srcborder);
vector<Mat> split_dst(3);
split_dst[0].create(src.size(), src.depth());
split_dst[1].create(src.size(), src.depth());
split_dst[2].create(src.size(), src.depth());
#pragma omp parallel for schedule(dynamic)
for (int j = 0; j < src.rows; j++)
{
float* dptr0 = split_dst[0].ptr<float>(j);
float* dptr1 = split_dst[1].ptr<float>(j);
float* dptr2 = split_dst[2].ptr<float>(j);
#if 0
for (int i = r; i < srcborder.cols - r; i++)
{
float denom = 0.f;
float numer0 = 0.f;
float numer1 = 0.f;
float numer2 = 0.f;
for (int y = -r; y <= r; y++)
{
float* wsptr = weight_space.ptr<float>(y + r);
float* Iptr0 = split_srcborder[0].ptr<float>(y + j + r);
float* Iptr1 = split_srcborder[1].ptr<float>(y + j + r);
float* Iptr2 = split_srcborder[2].ptr<float>(y + j + r);
for (int x = -r; x <= r; x++)
{
float diff = 0.f;
for (int c = 0; c < guide.channels(); c++)
{
float* srcptr = split_guideborder[c].ptr<float>(j);
float* gptr = split_guideborder[c].ptr<float>(y + j);
diff += (gptr[x + i] - srcptr[i]) * (gptr[x + i] - srcptr[i]);
}
float w = wsptr[x + r] * exp(diff * coeff_range);
denom += w;
numer0 += w * Iptr0[i + x];
numer1 += w * Iptr1[i + x];
numer2 += w * Iptr2[i + x];
}
}
dptr0[i - r] = numer0 / denom;
dptr1[i - r] = numer1 / denom;
dptr2[i - r] = numer2 / denom;
}
#else
for (int i = 0; i < src.cols; i += 8)
{
__m256 mdenom = _mm256_setzero_ps();
__m256 mnumer0 = _mm256_setzero_ps();
__m256 mnumer1 = _mm256_setzero_ps();
__m256 mnumer2 = _mm256_setzero_ps();
AutoBuffer<__m256> msrc(gchannel);
for (int c = 0; c < gchannel; c++)
{
float* srcptr = split_guideborder[c].ptr<float>(j + r, i + r);
msrc[c] = _mm256_loadu_ps(srcptr);
}
for (int y = 0; y < D; y++)
{
float* wsptr = weight_space.ptr<float>(y);
float* Iptr0 = split_srcborder[0].ptr<float>(y + j, i);
float* Iptr1 = split_srcborder[1].ptr<float>(y + j, i);
float* Iptr2 = split_srcborder[2].ptr<float>(y + j, i);
for (int x = 0; x < D; x++)
{
__m256 mdiff = _mm256_setzero_ps();
for (int c = 0; c < gchannel; c++)
{
float* gptr = split_guideborder[c].ptr<float>(y + j, i);
const __m256 sub = _mm256_sub_ps(msrc[c], _mm256_loadu_ps(gptr + x));
mdiff = _mm256_fmadd_ps(sub, sub, mdiff);
}
__m256 mgauss;
if constexpr (schedule == HDGFSchedule::COMPUTE)mgauss = _mm256_exp_ps(_mm256_mul_ps(mdiff, mcoeff_range));
else mgauss = _mm256_i32gather_ps(lut, _mm256_cvtps_epi32(_mm256_sqrt_ps(mdiff)), 4);
__m256 mw = _mm256_mul_ps(_mm256_set1_ps(wsptr[x]), mgauss);
mdenom = _mm256_add_ps(mdenom, mw);
mnumer0 = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr0 + x), mnumer0);
mnumer1 = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr1 + x), mnumer1);
mnumer2 = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr2 + x), mnumer2);
}
}
_mm256_storeu_ps(dptr0 + i, _mm256_div_ps(mnumer0, mdenom));
_mm256_storeu_ps(dptr1 + i, _mm256_div_ps(mnumer1, mdenom));
_mm256_storeu_ps(dptr2 + i, _mm256_div_ps(mnumer2, mdenom));
}
#endif
}
merge(split_dst, dst);
}
}
void highDimensionalGaussianFilter_Dim(const cv::Mat src, const cv::Mat guide, cv::Mat& dst, const cv::Size ksize, const float sigma_range, const float sigma_space, const int border, HDGFSchedule schedule)
{
const int r = ksize.height / 2;
Mat srcborder; copyMakeBorder(src, srcborder, r, r, r, r, border);
Mat guideborder; copyMakeBorder(guide, guideborder, r, r, r, r, border);
vector<Mat> split_guideborder;
split(guideborder, split_guideborder);
cv::Mat weight_space(ksize, src.type());
const float coeff_space = 1.f / (-2.f * sigma_space * sigma_space);
const int D = 2 * r + 1;
for (int j = 0; j < D; j++)
{
float* wsptr = weight_space.ptr<float>(j);
for (int i = 0; i < D; i++)
{
const float distance = float((i - r) * (i - r) + (j - r) * (j - r));
wsptr[i] = std::exp(distance * coeff_space);
}
}
const float coeff_range = 1.f / (-2.f * sigma_range * sigma_range);
const __m256 mcoeff_range = _mm256_set1_ps(coeff_range);
if (schedule == HDGFSchedule::COMPUTE)
{
if (src.channels() == 1)
{
#pragma omp parallel for schedule(dynamic)
for (int j = r; j < srcborder.rows - r; j++)
{
float* dptr = dst.ptr<float>(j - r);
for (int i = r; i < srcborder.cols - r; i += 8)
{
__m256 mdenom = _mm256_setzero_ps();
__m256 mnumer = _mm256_setzero_ps();
for (int y = -r; y <= r; y++)
{
float* wsptr = weight_space.ptr<float>(y + r);
float* Iptr = srcborder.ptr<float>(y + j);
for (int x = -r; x <= r; x++)
{
__m256 mdiff = _mm256_setzero_ps();
AutoBuffer<__m256> msrc(guide.channels());
for (int c = 0; c < guide.channels(); c++)
{
float* srcptr = split_guideborder[c].ptr<float>(j);
msrc[c] = _mm256_loadu_ps(srcptr + i);
}
for (int c = 0; c < guide.channels(); c++)
{
float* gptr = split_guideborder[c].ptr<float>(y + j);
__m256 sub = _mm256_sub_ps(msrc[c], _mm256_loadu_ps(gptr + x + i));
mdiff = _mm256_fmadd_ps(sub, sub, mdiff);
}
__m256 mw = _mm256_mul_ps(_mm256_set1_ps(wsptr[x + r]), _mm256_exp_ps(_mm256_mul_ps(mdiff, mcoeff_range)));
mdenom = _mm256_add_ps(mdenom, mw);
mnumer = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr + i + x), mnumer);
}
}
_mm256_store_ps(dptr + i - r, _mm256_div_ps(mnumer, mdenom));
}
}
}
else if (src.channels() == 3)
{
vector<Mat> split_srcborder; split(srcborder, split_srcborder);
vector<Mat> split_dst(3);
split_dst[0].create(src.size(), src.depth());
split_dst[1].create(src.size(), src.depth());
split_dst[2].create(src.size(), src.depth());
#pragma omp parallel for schedule(dynamic)
for (int j = 0; j < src.rows; j++)
{
float* dptr0 = split_dst[0].ptr<float>(j);
float* dptr1 = split_dst[1].ptr<float>(j);
float* dptr2 = split_dst[2].ptr<float>(j);
#if 0
for (int i = r; i < srcborder.cols - r; i++)
{
float denom = 0.f;
float numer0 = 0.f;
float numer1 = 0.f;
float numer2 = 0.f;
for (int y = -r; y <= r; y++)
{
float* wsptr = weight_space.ptr<float>(y + r);
float* Iptr0 = split_srcborder[0].ptr<float>(y + j + r);
float* Iptr1 = split_srcborder[1].ptr<float>(y + j + r);
float* Iptr2 = split_srcborder[2].ptr<float>(y + j + r);
for (int x = -r; x <= r; x++)
{
float diff = 0.f;
for (int c = 0; c < guide.channels(); c++)
{
float* srcptr = split_guideborder[c].ptr<float>(j);
float* gptr = split_guideborder[c].ptr<float>(y + j);
diff += (gptr[x + i] - srcptr[i]) * (gptr[x + i] - srcptr[i]);
}
float w = wsptr[x + r] * exp(diff * coeff_range);
denom += w;
numer0 += w * Iptr0[i + x];
numer1 += w * Iptr1[i + x];
numer2 += w * Iptr2[i + x];
}
}
dptr0[i - r] = numer0 / denom;
dptr1[i - r] = numer1 / denom;
dptr2[i - r] = numer2 / denom;
}
#else
for (int i = 0; i < src.cols; i += 8)
{
__m256 mdenom = _mm256_setzero_ps();
__m256 mnumer0 = _mm256_setzero_ps();
__m256 mnumer1 = _mm256_setzero_ps();
__m256 mnumer2 = _mm256_setzero_ps();
AutoBuffer<__m256> msrc(guide.channels());
for (int c = 0; c < guide.channels(); c++)
{
float* srcptr = split_guideborder[c].ptr<float>(j + r, i + r);
msrc[c] = _mm256_loadu_ps(srcptr);
}
for (int y = 0; y < D; y++)
{
float* wsptr = weight_space.ptr<float>(y);
float* Iptr0 = split_srcborder[0].ptr<float>(y + j, i);
float* Iptr1 = split_srcborder[1].ptr<float>(y + j, i);
float* Iptr2 = split_srcborder[2].ptr<float>(y + j, i);
for (int x = 0; x < D; x++)
{
__m256 mdiff = _mm256_setzero_ps();
for (int c = 0; c < guide.channels(); c++)
{
float* gptr = split_guideborder[c].ptr<float>(y + j, i);
const __m256 sub = _mm256_sub_ps(msrc[c], _mm256_loadu_ps(gptr + x));
mdiff = _mm256_fmadd_ps(sub, sub, mdiff);
}
__m256 mw = _mm256_mul_ps(_mm256_set1_ps(wsptr[x]), _mm256_exp_ps(_mm256_mul_ps(mdiff, mcoeff_range)));
mdenom = _mm256_add_ps(mdenom, mw);
mnumer0 = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr0 + x), mnumer0);
mnumer1 = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr1 + x), mnumer1);
mnumer2 = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr2 + x), mnumer2);
}
}
_mm256_storeu_ps(dptr0 + i, _mm256_div_ps(mnumer0, mdenom));
_mm256_storeu_ps(dptr1 + i, _mm256_div_ps(mnumer1, mdenom));
_mm256_storeu_ps(dptr2 + i, _mm256_div_ps(mnumer2, mdenom));
}
#endif
}
merge(split_dst, dst);
}
}
else
{
const int lut_size = (int)ceil(get_l2norm_maxval(guide.channels()));
cv::AutoBuffer<float> lut(lut_size);
for (int i = 0; i < lut_size; i++)
{
lut[i] = exp(i * i * coeff_range);
}
if (src.channels() == 1)
{
#pragma omp parallel for schedule(dynamic)
for (int j = r; j < srcborder.rows - r; j++)
{
float* dptr = dst.ptr<float>(j - r);
for (int i = r; i < srcborder.cols - r; i += 8)
{
__m256 mdenom = _mm256_setzero_ps();
__m256 mnumer = _mm256_setzero_ps();
for (int y = -r; y <= r; y++)
{
float* wsptr = weight_space.ptr<float>(y + r);
float* Iptr = srcborder.ptr<float>(y + j);
for (int x = -r; x <= r; x++)
{
__m256 mdiff = _mm256_setzero_ps();
AutoBuffer<__m256> msrc(guide.channels());
for (int c = 0; c < guide.channels(); c++)
{
float* srcptr = split_guideborder[c].ptr<float>(j);
msrc[c] = _mm256_loadu_ps(srcptr + i);
}
for (int c = 0; c < guide.channels(); c++)
{
float* gptr = split_guideborder[c].ptr<float>(y + j);
__m256 sub = _mm256_sub_ps(msrc[c], _mm256_loadu_ps(gptr + x + i));
mdiff = _mm256_fmadd_ps(sub, sub, mdiff);
}
__m256 mgauss = _mm256_i32gather_ps(lut, _mm256_cvtps_epi32(_mm256_sqrt_ps(mdiff)), 4);
__m256 mw = _mm256_mul_ps(_mm256_set1_ps(wsptr[x + r]), mgauss);
//__m256 mw = _mm256_mul_ps(_mm256_set1_ps(wsptr[x + r]), _mm256_exp_ps(_mm256_mul_ps(mdiff, mcoeff_range)));
mdenom = _mm256_add_ps(mdenom, mw);
mnumer = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr + i + x), mnumer);
}
}
_mm256_store_ps(dptr + i - r, _mm256_div_ps(mnumer, mdenom));
}
}
}
else if (src.channels() == 3)
{
vector<Mat> split_srcborder; split(srcborder, split_srcborder);
vector<Mat> split_dst(3);
split_dst[0].create(src.size(), src.depth());
split_dst[1].create(src.size(), src.depth());
split_dst[2].create(src.size(), src.depth());
#pragma omp parallel for schedule(dynamic)
for (int j = 0; j < src.rows; j++)
{
float* dptr0 = split_dst[0].ptr<float>(j);
float* dptr1 = split_dst[1].ptr<float>(j);
float* dptr2 = split_dst[2].ptr<float>(j);
#if 0
for (int i = r; i < srcborder.cols - r; i++)
{
float denom = 0.f;
float numer0 = 0.f;
float numer1 = 0.f;
float numer2 = 0.f;
for (int y = -r; y <= r; y++)
{
float* wsptr = weight_space.ptr<float>(y + r);
float* Iptr0 = split_srcborder[0].ptr<float>(y + j + r);
float* Iptr1 = split_srcborder[1].ptr<float>(y + j + r);
float* Iptr2 = split_srcborder[2].ptr<float>(y + j + r);
for (int x = -r; x <= r; x++)
{
float diff = 0.f;
for (int c = 0; c < guide.channels(); c++)
{
float* srcptr = split_guideborder[c].ptr<float>(j);
float* gptr = split_guideborder[c].ptr<float>(y + j);
diff += (gptr[x + i] - srcptr[i]) * (gptr[x + i] - srcptr[i]);
}
float w = wsptr[x + r] * exp(diff * coeff_range);
denom += w;
numer0 += w * Iptr0[i + x];
numer1 += w * Iptr1[i + x];
numer2 += w * Iptr2[i + x];
}
}
dptr0[i - r] = numer0 / denom;
dptr1[i - r] = numer1 / denom;
dptr2[i - r] = numer2 / denom;
}
#else
for (int i = 0; i < src.cols; i += 8)
{
__m256 mdenom = _mm256_setzero_ps();
__m256 mnumer0 = _mm256_setzero_ps();
__m256 mnumer1 = _mm256_setzero_ps();
__m256 mnumer2 = _mm256_setzero_ps();
AutoBuffer<__m256> msrc(guide.channels());
for (int c = 0; c < guide.channels(); c++)
{
float* srcptr = split_guideborder[c].ptr<float>(j + r, i + r);
msrc[c] = _mm256_loadu_ps(srcptr);
}
for (int y = 0; y < D; y++)
{
float* wsptr = weight_space.ptr<float>(y);
float* Iptr0 = split_srcborder[0].ptr<float>(y + j, i);
float* Iptr1 = split_srcborder[1].ptr<float>(y + j, i);
float* Iptr2 = split_srcborder[2].ptr<float>(y + j, i);
for (int x = 0; x < D; x++)
{
__m256 mdiff = _mm256_setzero_ps();
for (int c = 0; c < guide.channels(); c++)
{
float* gptr = split_guideborder[c].ptr<float>(y + j, i);
const __m256 sub = _mm256_sub_ps(msrc[c], _mm256_loadu_ps(gptr + x));
mdiff = _mm256_fmadd_ps(sub, sub, mdiff);
}
__m256 mgauss = _mm256_i32gather_ps(lut, _mm256_cvtps_epi32(_mm256_sqrt_ps(mdiff)), 4);
__m256 mw = _mm256_mul_ps(_mm256_set1_ps(wsptr[x]), mgauss);
mdenom = _mm256_add_ps(mdenom, mw);
mnumer0 = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr0 + x), mnumer0);
mnumer1 = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr1 + x), mnumer1);
mnumer2 = _mm256_fmadd_ps(mw, _mm256_loadu_ps(Iptr2 + x), mnumer2);
}
}
_mm256_storeu_ps(dptr0 + i, _mm256_div_ps(mnumer0, mdenom));
_mm256_storeu_ps(dptr1 + i, _mm256_div_ps(mnumer1, mdenom));
_mm256_storeu_ps(dptr2 + i, _mm256_div_ps(mnumer2, mdenom));
}
#endif
}
merge(split_dst, dst);
}
}
}
void highDimensionalGaussianFilter(InputArray src, InputArray guide, OutputArray dst, const cv::Size ksize, const float sigma_range, const float sigma_space, const int border, HDGFSchedule schedule)
{
dst.create(src.size(), src.type());
if (schedule == HDGFSchedule::COMPUTE)
{
switch (guide.channels())
{
case 1:highDimensionalGaussianFilter_<1, HDGFSchedule::COMPUTE>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 2:highDimensionalGaussianFilter_<2, HDGFSchedule::COMPUTE>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 3:highDimensionalGaussianFilter_<3, HDGFSchedule::COMPUTE>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 4:highDimensionalGaussianFilter_<4, HDGFSchedule::COMPUTE>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 5:highDimensionalGaussianFilter_<5, HDGFSchedule::COMPUTE>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 6:highDimensionalGaussianFilter_<6, HDGFSchedule::COMPUTE>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 7:highDimensionalGaussianFilter_<7, HDGFSchedule::COMPUTE>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 8:highDimensionalGaussianFilter_<8, HDGFSchedule::COMPUTE>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 9:highDimensionalGaussianFilter_<9, HDGFSchedule::COMPUTE>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
default:
highDimensionalGaussianFilter_Dim(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border, HDGFSchedule::COMPUTE); break;
}
}
else
{
switch (guide.channels())
{
case 1:highDimensionalGaussianFilter_<1, HDGFSchedule::LUT_SQRT>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 2:highDimensionalGaussianFilter_<2, HDGFSchedule::LUT_SQRT>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 3:highDimensionalGaussianFilter_<3, HDGFSchedule::LUT_SQRT>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 4:highDimensionalGaussianFilter_<4, HDGFSchedule::LUT_SQRT>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 5:highDimensionalGaussianFilter_<5, HDGFSchedule::LUT_SQRT>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 6:highDimensionalGaussianFilter_<6, HDGFSchedule::LUT_SQRT>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 7:highDimensionalGaussianFilter_<7, HDGFSchedule::LUT_SQRT>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 8:highDimensionalGaussianFilter_<8, HDGFSchedule::LUT_SQRT>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
case 9:highDimensionalGaussianFilter_<9, HDGFSchedule::LUT_SQRT>(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border); break;
default:
highDimensionalGaussianFilter_Dim(src.getMat(), guide.getMat(), dst.getMat(), ksize, sigma_range, sigma_space, border, HDGFSchedule::LUT_SQRT); break;
}
}
}
}
|
NewSpring/Heighliner
|
src/util/cache/memory-cache.js
|
import Crypto from "crypto";
export class InMemoryCache {
constructor(cache = {}, secret = "InMemoryCache") {
// XXX this is really only used for testing purposes
this.cache = cache;
this.secret = secret;
}
get(id, lookup, { ttl, cache } = { ttl: 86400, cache: true }) {
let fromCache = false;
return new Promise(done => {
const data = this.cache[id];
if ((!data || !cache) && lookup) return lookup().then(done);
fromCache = true;
return done(data);
}).then(data => {
if (data && !fromCache) {
// async the save
process.nextTick(() => {
this.set(id, data, ttl);
});
}
return data;
});
}
set(id, data, ttl = 86400) {
return new Promise(done => {
// XXX this should technically never fail
try {
// save to cache
this.cache[id] = data;
// clear cache
setTimeout(() => {
delete this.cache[id];
}, ttl * 60);
return done(true);
} catch (e) {
return done(false);
}
});
}
del(id) {
delete this.cache[id];
}
encode(obj, prefix = "") {
const cipher = Crypto.createHmac("sha256", this.secret);
const str = `${prefix}${JSON.stringify(obj)}`;
return cipher.update(str, "utf-8").digest("hex");
}
}
|
kzx1025/spark_improve
|
sql/core/target/java/org/apache/spark/sql/columnar/StringColumnBuilder.java
|
<filename>sql/core/target/java/org/apache/spark/sql/columnar/StringColumnBuilder.java
package org.apache.spark.sql.columnar;
private class StringColumnBuilder extends org.apache.spark.sql.columnar.NativeColumnBuilder<org.apache.spark.sql.catalyst.types.StringType$> {
public StringColumnBuilder () { throw new RuntimeException(); }
}
|
tonykwok/leonardosketch.amino
|
src/org/joshy/gfx/test/drawing/OverlayTest.java
|
<gh_stars>0
package org.joshy.gfx.test.drawing;
import org.joshy.gfx.Core;
import org.joshy.gfx.draw.FlatColor;
import org.joshy.gfx.draw.TransformNode;
import org.joshy.gfx.event.Callback;
import org.joshy.gfx.event.EventBus;
import org.joshy.gfx.event.MouseEvent;
import org.joshy.gfx.node.Node;
import org.joshy.gfx.node.control.Button;
import org.joshy.gfx.node.control.Control;
import org.joshy.gfx.node.control.Textbox;
import org.joshy.gfx.node.layout.Panel;
import org.joshy.gfx.node.shape.Oval;
import org.joshy.gfx.node.shape.Shape;
import org.joshy.gfx.stage.Stage;
import org.joshy.gfx.test.control.GrandTour;
import org.joshy.gfx.util.u;
public class OverlayTest extends GrandTour.Example implements Runnable {
public OverlayTest(String name) {
super(name);
}
public static void main(String ... args) throws Exception {
Core.init();
Core.getShared().defer(new OverlayTest("test"));
}
@Override
public void run() {
Stage stage = Stage.createStage();
try {
stage.setContent(build());
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
@Override
public Control build() throws Exception {
Node n1 = new TransformNode().setRotate(15).setContent(new Button("Button")).setTranslateX(50);
Shape oval = new Oval().setWidth(100).setHeight(30).setFill(FlatColor.GREEN.deriveWithAlpha(0.5));
Node n2 = new TransformNode().setRotate(30).setContent(oval).setTranslateX(80);
Node n3 = new TransformNode().setRotate(45).setContent(new Textbox("text box")).setTranslateX(100);
EventBus.getSystem().addListener(oval, MouseEvent.MousePressed, new Callback<MouseEvent>(){
@Override
public void call(MouseEvent event) throws Exception {
u.p("pressed");
}
});
return new Panel().add(n1,n2,n3);
}
}
|
leaderli/li-runner-flow
|
node_modules/@antv/x6/es/registry/attr/raw.js
|
export const raw = {
xlinkHref: 'xlink:href',
xlinkShow: 'xlink:show',
xlinkRole: 'xlink:role',
xlinkType: 'xlink:type',
xlinkArcrole: 'xlink:arcrole',
xlinkTitle: 'xlink:title',
xlinkActuate: 'xlink:actuate',
xmlSpace: 'xml:space',
xmlBase: 'xml:base',
xmlLang: 'xml:lang',
preserveAspectRatio: 'preserveAspectRatio',
requiredExtension: 'requiredExtension',
requiredFeatures: 'requiredFeatures',
systemLanguage: 'systemLanguage',
externalResourcesRequired: 'externalResourceRequired',
};
//# sourceMappingURL=raw.js.map
|
hdonghong/lifeup
|
src/main/java/com/hdh/lifeup/controller/UserAuthController.java
|
package com.hdh.lifeup.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.hdh.lifeup.config.AppConfig;
import com.hdh.lifeup.config.YbConfig;
import com.hdh.lifeup.model.constant.AuthTypeConst;
import com.hdh.lifeup.model.dto.UserAuthDTO;
import com.hdh.lifeup.model.dto.UserInfoDTO;
import com.hdh.lifeup.model.enums.CodeMsgEnum;
import com.hdh.lifeup.exception.GlobalException;
import com.hdh.lifeup.service.UserAuthService;
import com.hdh.lifeup.util.Result;
import com.hdh.lifeup.model.vo.MobVO;
import com.hdh.lifeup.model.vo.ResultVO;
import com.hdh.lifeup.model.vo.UserAuthVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Optional;
/**
* AuthController class<br/>
* @author hdonghong
* @since 2018/08/20
*/
@Slf4j
@Api(description = "授权/注册/登录模块")
@RestController
@RequestMapping("/auth")
public class UserAuthController {
private YbConfig ybConfig;
private RestTemplateBuilder restTemplateBuilder;
private ObjectMapper objectMapper;
private UserAuthService userAuthService;
private AppConfig appConfig;
private static final String ACCESS_TOKEN = "access_token";
@Autowired
public UserAuthController(YbConfig ybConfig,
RestTemplateBuilder restTemplateBuilder,
ObjectMapper objectMapper,
UserAuthService userAuthService,
AppConfig appConfig) {
this.ybConfig = ybConfig;
this.restTemplateBuilder = restTemplateBuilder;
this.objectMapper = objectMapper;
this.userAuthService = userAuthService;
this.appConfig = appConfig;
}
@ApiOperation(value = "获取请求第三方授权的URL", notes = "支持多种授权,比如易班、QQ")
@ApiImplicitParams({
@ApiImplicitParam(name = "authType", value = "授权类型,比如yb、qq", required = true, paramType = "path"),
@ApiImplicitParam(name = "redirectUri", value = "回调的URI,格式形如:http://lifeup/,不传的话默认为http://net.sarasarasa.lifeup/redirect", paramType = "query")
})
@GetMapping("/{authType}")
public ResultVO<String> getOauthPath(@PathVariable("authType")String authType, String redirectUri) {
String callback;
String originalOauthPath;
String appId;
switch (authType) {
case AuthTypeConst.YB: callback = ybConfig.getRedirectUri();
originalOauthPath = ybConfig.getOauthPath();
appId = ybConfig.getAppId();
break;
default: throw new GlobalException(CodeMsgEnum.UNSUPPORTED_AUTH_TYPE);
}
callback = Optional.ofNullable(redirectUri).orElse(callback);
String oauthPath = String.format(originalOauthPath, appId, callback);
return Result.success(oauthPath);
}
@ApiOperation(value = "易班登录", notes = "拿到code后务必发送给后端")
@ApiImplicitParam(name = "code", value = "用于拉取access_token", required = true, paramType = "query", dataType = "String")
@PostMapping("/yb/login")
public ResultVO<String> ybLogin(@RequestParam("code") String code) throws IOException {
String accessTokenPath = String.format(ybConfig.getTokenPath(),
code, ybConfig.getAppId(), ybConfig.getAppSecret(), ybConfig.getRedirectUri());
RestTemplate restTemplate = restTemplateBuilder.build();
ResponseEntity<String> responseEntity = restTemplate.exchange(accessTokenPath, HttpMethod.GET, null, String.class);
String accessToken = objectMapper.readTree(responseEntity.getBody())
.get(ACCESS_TOKEN).asText();
responseEntity = restTemplate.exchange(ybConfig.getUserInfoPath() + accessToken, HttpMethod.GET, null, String.class);
JsonNode responseBody = objectMapper.readTree(responseEntity.getBody());
if (!"success".equals(responseBody.get("status").asText())) {
log.warn("【易班授权】获取登录信息失败,responseBody = [{}]", responseBody);
throw new GlobalException(CodeMsgEnum.YB_ERROR);
}
JsonNode userInfoJson = responseBody.get("info");
UserAuthDTO userAuthDTO = UserAuthDTO.fromYbUser(userInfoJson);
UserInfoDTO userInfoDTO = UserInfoDTO.fromYbUser(userInfoJson);
String token = userAuthService.oauthLogin(userAuthDTO, userInfoDTO);
return Result.success(token);
}
@ApiOperation(value = " 第三方登录")
@PostMapping({"/qq/login", "/google/login", "/weibo/login"})
public ResultVO<String> thirdPlatformLogin(@RequestBody @Valid UserAuthVO userAuthVO) {
UserInfoDTO userInfoDTO = new UserInfoDTO();
BeanUtils.copyProperties(userAuthVO, userInfoDTO);
// 注册类型:目前有QQ、Google、Weibo
userInfoDTO.setAuthTypes(Lists.newArrayList(userAuthVO.getAuthType()));
UserAuthDTO userAuthDTO = new UserAuthDTO();
// 取生成的userInfoDTO.getUserId,set到userAuthDTO并存到user_auth
userAuthDTO.setAuthType(userAuthVO.getAuthType())
.setAuthIdentifier(userAuthVO.getAuthIdentifier())
.setAccessToken(userAuthVO.getAccessToken());
return Result.success(userAuthService.oauthLogin(userAuthDTO, userInfoDTO));
}
@ApiOperation(value = "手机号+密码登录")
@PostMapping("/phone/login")
public ResultVO<String> phoneLogin(@RequestBody @Valid UserAuthDTO userAuthDTO) {
userAuthDTO.setAuthType(AuthTypeConst.PHONE);
return Result.success(userAuthService.appLogin(userAuthDTO));
}
@ApiOperation(value = "手机号+验证码登录")
@PostMapping("/code/login")
public ResultVO<String> verifyLogin(@RequestBody /*@Valid */MobVO mobVO) {
// 封装POST请求
mobVO.setAppKey(appConfig.getAppKey());
/* // 发起请求
RestTemplate restTemplate = restTemplateBuilder.build();
ResponseEntity<String> responseEntity = restTemplate.postForEntity(
appConfig.getMobApi(), mobVO, String.class
);
// 验证响应
if (responseEntity.getStatusCode() == HttpStatus.OK) {
return Result.success(userAuthService.codeLogin(
new UserAuthDTO().setAuthType(AuthTypeConst.PHONE)
.setAuthIdentifier(mobVO.getPhone())
));
} else {
// 验证失败
log.warn("【Mob短信登录验证】验证失败,responseEntity = [{}]", responseEntity);
throw new GlobalException(CodeMsgEnum.MOB_VERIFY_ERROR);
}*/
return Result.success(userAuthService.codeLogin(
new UserAuthDTO().setAuthType(AuthTypeConst.PHONE)
.setAuthIdentifier(mobVO.getPhone())
));
}
@ApiOperation(value = " 注册系统账号", notes = "传递手机号,密码需要客户端md5一下再传,不需要的字段别传")
@PostMapping("/register")
public ResultVO<String> register(@RequestBody @Valid UserAuthVO userAuthVO) {
return Result.success(userAuthService.register(userAuthVO));
}
}
|
hernad/zimbra9
|
zm-mailbox/store/src/java/com/zimbra/soap/DocumentHandler.java
|
<gh_stars>0
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Synacor, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.soap;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.QName;
import com.google.common.annotations.VisibleForTesting;
import com.zimbra.common.account.Key;
import com.zimbra.common.account.Key.AccountBy;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.Element;
import com.zimbra.common.soap.SoapFaultException;
import com.zimbra.common.util.Pair;
import com.zimbra.common.util.Version;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.AccessManager;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.account.AccountServiceException;
import com.zimbra.cs.account.AuthToken;
import com.zimbra.cs.account.GuestAccount;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Server;
import com.zimbra.cs.mailbox.Mailbox;
import com.zimbra.cs.mailbox.MailboxManager;
import com.zimbra.cs.mailbox.OperationContext;
import com.zimbra.cs.session.AdminSession;
import com.zimbra.cs.session.Session;
import com.zimbra.cs.session.SessionCache;
import com.zimbra.cs.session.SoapSession;
import com.zimbra.cs.util.Zimbra;
import com.zimbra.soap.ZimbraSoapContext.SessionInfo;
/**
* @since May 26, 2004
* @author schemers
*/
public abstract class DocumentHandler {
private QName responseQName;
private long proxyTimeout = -1;
@VisibleForTesting
public void setResponseQName(QName response) {
this.responseQName = response;
}
protected Element getResponseElement(ZimbraSoapContext zc) {
return zc.createElement(responseQName);
}
/**
* Set the timeout in milli seconds for SoapHttpTransport when this request gets proxied.
* @param timeoutMsecs
*/
protected void setProxyTimeout(long timeoutMsecs) {
proxyTimeout = timeoutMsecs;
}
private static String LOCAL_HOST = "";
private static String LOCAL_HOST_ID = "";
public static String getLocalHost() {
synchronized (LOCAL_HOST) {
if (LOCAL_HOST.length() == 0) {
try {
Server localServer = Provisioning.getInstance().getLocalServer();
LOCAL_HOST = localServer.getAttr(Provisioning.A_zimbraServiceHostname);
LOCAL_HOST_ID = localServer.getId();
} catch (Exception e) {
Zimbra.halt("could not fetch local server name from LDAP for request proxying");
}
}
}
return LOCAL_HOST;
}
public static String getLocalHostId() {
if (LOCAL_HOST_ID.length() == 0) {
getLocalHost();
}
return LOCAL_HOST_ID;
}
public void preProxy(Element request, Map<String, Object> context) throws ServiceException {}
public void postProxy(Element request, Element response, Map<String, Object> context) throws ServiceException {}
public abstract Element handle(Element request, Map<String, Object> context) throws ServiceException;
/** Returns the {@link ZimbraSoapContext} object encapsulating the
* containing SOAP request's <pre><context></pre> header element. */
public static ZimbraSoapContext getZimbraSoapContext(Map<String, Object> context) {
return (ZimbraSoapContext) context.get(SoapEngine.ZIMBRA_CONTEXT);
}
/** Generates a new {@link com.zimbra.cs.mailbox.OperationContext}
* object reflecting the constraints serialized in the <tt><context></tt>
* element in the SOAP header.<p>
*
* These optional constraints include:<ul>
* <li>the account ID from the auth token</li>
* <li>the highest change number the client knows about</li>
* <li>how stringently to check accessed items against the known change
* highwater mark</li></ul>
*
* @return A new OperationContext object */
public static OperationContext getOperationContext(ZimbraSoapContext zsc, Map<String, Object> context) throws ServiceException {
return getOperationContext(zsc, context == null ? null : (Session) context.get(SoapEngine.ZIMBRA_SESSION));
}
public static OperationContext getOperationContext(ZimbraSoapContext zsc, Session session) throws ServiceException {
AuthToken at = zsc.getAuthToken();
OperationContext octxt = new OperationContext(at);
octxt.setChangeConstraint(zsc.getChangeConstraintType(), zsc.getChangeConstraintLimit());
octxt.setRequestIP(zsc.getRequestIP()).setSession(session);
octxt.setUserAgent(zsc.getUserAgent());
octxt.setmResponseProtocol(zsc.getmResponseProtocol());
octxt.setmRequestedAccountId(zsc.getRequestedAccountId());
octxt.setmAuthTokenAccountId(zsc.getAuthtokenAccountId());
return octxt;
}
/** Returns the {@link Account} corresponding to the authenticated user.
* The authenticated user is determined from the serialized
* {@link com.zimbra.cs.account.AuthToken} in the SOAP request's
* <pre><context></pre> header element. */
public static Account getAuthenticatedAccount(ZimbraSoapContext zsc) throws ServiceException {
String id = zsc.getAuthtokenAccountId();
AuthToken at = zsc.getAuthToken();
if (GuestAccount.GUID_PUBLIC.equals(id) || (at != null && !at.isZimbraUser())) {
return new GuestAccount(at);
}
Account acct = Provisioning.getInstance().get(AccountBy.id, id, zsc.getAuthToken());
if (acct == null && !(at != null && at.isZMGAppBootstrap())) {
throw ServiceException.AUTH_REQUIRED();
}
return acct;
}
public static Account getRequestedAccount(ZimbraSoapContext zsc) throws ServiceException {
String id = zsc.getRequestedAccountId();
Account acct = Provisioning.getInstance().get(AccountBy.id, id, zsc.getAuthToken());
if (acct == null) {
if (zsc.isDelegatedRequest()) {
throw ServiceException.DEFEND_ACCOUNT_HARVEST(id);
} else {
throw ServiceException.AUTH_EXPIRED();
}
}
return acct;
}
public static Mailbox getRequestedMailbox(ZimbraSoapContext zsc) throws ServiceException {
return getRequestedMailbox(zsc, true);
}
public static Mailbox getRequestedMailbox(ZimbraSoapContext zsc, boolean autoCreate) throws ServiceException {
String id = zsc.getRequestedAccountId();
Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(id, autoCreate);
if (mbox != null) {
ZimbraLog.addMboxToContext(mbox.getId());
}
return mbox;
}
/** Returns whether the command's caller must be authenticated. */
public boolean needsAuth(Map<String, Object> context) {
return true;
}
/** Returns whether this is an administrative command (and thus requires
* a valid admin auth token). */
public boolean needsAdminAuth(Map<String, Object> context) {
return false;
}
/**
* Some requests need to always return valid looking output in able to provide consistent behavior between
* requests against non-existent accounts and those which don't allow access to the requested data.
* For instance FreeBusy requests.
* Only handlers which accept responsibility for measures to prevent account harvesting should return true
*/
public boolean handlesAccountHarvesting() {
return false;
}
/**
* Only handlers which accept responsibility for measures to prevent account harvesting by delegate admins
* should return true
*/
public boolean defendsAgainstDelegateAdminAccountHarvesting() {
return false;
}
public Boolean canAccessAccountCommon(ZimbraSoapContext zsc, Account target, boolean allowSelf)
throws ServiceException {
if (zsc.getAuthtokenAccountId() == null || target == null) {
return Boolean.FALSE;
}
if (allowSelf && target.getId().equals(zsc.getAuthtokenAccountId())) {
return Boolean.TRUE;
}
// 1. delegated auth case has been logged in SoapEngine
// 2. we do not want to log delegated request, where the target account is specified in
// soap context header. Usages for that route are family mailboxes and sharing access.
// we only want to log the "admin" accesses.
if (!zsc.getAuthToken().isDelegatedAuth() && !zsc.isDelegatedRequest()) {
logAuditAccess(null, zsc.getAuthtokenAccountId(), target.getId());
}
return null;
}
public boolean canAccessAccount(ZimbraSoapContext zsc, Account target) throws ServiceException {
Boolean canAccess = canAccessAccountCommon(zsc, target, true);
if (canAccess != null) {
return canAccess.booleanValue();
}
return AccessManager.getInstance().canAccessAccount(zsc.getAuthToken(), target);
}
public boolean canModifyOptions(ZimbraSoapContext zsc, Account acct) throws ServiceException {
if (zsc.isDelegatedRequest()) {
// if we're modifying someone else's options, we need to have admin access to the account
// *and* we need to be able to change our own options (this is a standin for finer-grained access control)
return canAccessAccount(zsc, acct) && getAuthenticatedAccount(zsc).getBooleanAttr(Provisioning.A_zimbraFeatureOptionsEnabled, true);
} else {
// if we're modifying our own options, we just need the appropriate feature enabled
return acct.getBooleanAttr(Provisioning.A_zimbraFeatureOptionsEnabled, true);
}
}
/** Returns whether domain admin auth is sufficient to run this command.
* This should be overriden only on admin commands that can be run in a
* restricted "domain admin" mode. */
public boolean domainAuthSufficient(Map<String, Object> context) {
return false;
}
/** Returns whether the command is in the administration command set. */
public boolean isAdminCommand() {
return false;
}
/** Returns <tt>true</tt> if the operation is read-only, or
* <tt>false</tt> if the operation causes backend state change. */
public boolean isReadOnly() {
return true;
}
/** Returns whether the client making the SOAP request is localhost. */
protected boolean clientIsLocal(Map<String, Object> context) {
HttpServletRequest req = (HttpServletRequest) context.get(SoapServlet.SERVLET_REQUEST);
return req == null ? true : "127.0.0.1".equals(req.getRemoteAddr());
}
/** Updates the {@link ZimbraSoapContext} to treat the specified account
* as the request's authenticated account. If the new account differs
* from the previously authenticated account, we forget about all other
* {@link Session}s. (Those sessions are not deleted from the cache,
* though perhaps that's the right thing to do...) If requested, also
* creates a new Session object associated with the given account.
*
* @param zsc The parsed SOAP header for the auth request.
* @param authToken The new auth token created for the user.
* @param context The <code>SoapEngine</code>'s request state.
* @param getSession Whether to try to generate a new Session.
* @return A new Session object of the appropriate type, or <tt>null</tt>. */
public Session updateAuthenticatedAccount(ZimbraSoapContext zsc, AuthToken authToken, Map<String, Object> context, boolean getSession) {
String oldAccountId = zsc.getAuthtokenAccountId();
String accountId = authToken.getAccountId();
if (accountId != null && !accountId.equals(oldAccountId)) {
zsc.clearSessionInfo();
}
zsc.setAuthToken(authToken);
Session session = (getSession ? getSession(zsc) : null);
if (context != null) {
context.put(SoapEngine.ZIMBRA_SESSION, session);
}
return session;
}
public static Session getReferencedSession(ZimbraSoapContext zsc) {
if (zsc == null) {
return null;
}
SessionInfo sinfo = zsc.getSessionInfo();
return sinfo == null ? null : SessionCache.lookup(sinfo.sessionId, zsc.getAuthtokenAccountId());
}
public Session.Type getDefaultSessionType() {
return Session.Type.SOAP;
}
protected final Session getSession(ZimbraSoapContext zsc, Map<String, Object> context) {
Session session = (Session) context.get(SoapEngine.ZIMBRA_SESSION);
return (session != null ? session : getSession(zsc));
}
/** Fetches the in-memory {@link Session} object appropriate for this
* request. If none already exists, one is created if possible.
*
* @param zsc The encapsulation of the SOAP request's <tt><context</tt>
* element.
* @return A {@link com.zimbra.cs.session.SoapSession}, or <tt>null</tt>. */
protected final Session getSession(ZimbraSoapContext zsc) {
return getSession(zsc, getDefaultSessionType());
}
/** Fetches a {@link Session} object to persist and manage state between
* SOAP requests. If no appropriate session already exists, a new one
* is created if possible.
*
* @param zsc The encapsulation of the SOAP request's <tt><context</tt>
* element.
* @param stype The type of session needed.
* @return An in-memory {@link Session} object of the specified type,
* referenced by the request's {@link ZimbraSoapContext} object,
* or <tt>null</tt>.
* @see SessionCache#SESSION_SOAP
* @see SessionCache#SESSION_ADMIN */
protected Session getSession(ZimbraSoapContext zsc, Session.Type stype) {
if (zsc == null || stype == null || !zsc.isNotificationEnabled()) {
return null;
}
String authAccountId = zsc.getAuthtokenAccountId();
if (authAccountId == null) {
return null;
}
// if they asked for a SOAP session on a remote host and it's a non-proxied request, we don't notify
boolean isLocal = zsc.isAuthUserOnLocalhost();
if (stype == Session.Type.SOAP && !isLocal && !zsc.isSessionProxied()) {
return null;
}
Session s = null;
// if the caller referenced a session of this type, fetch it from the session cache
SessionInfo sinfo = zsc.getSessionInfo();
if (sinfo != null) {
s = SessionCache.lookup(sinfo.sessionId, authAccountId);
if (s == null) {
// purge dangling references from the context's list of referenced sessions
ZimbraLog.session.info("requested session no longer exists: " + sinfo.sessionId);
zsc.clearSessionInfo();
} else if (s.getSessionType() != stype) {
// only want a session of the appropriate type
s = null;
} else if (s instanceof SoapSession) {
SoapSession soap = (SoapSession) s;
if (soap.getCurWaitSetID() != zsc.getCurWaitSetID()) {
// update the waitset ID on the SOAP session
soap.setCurWaitSetID(zsc.getCurWaitSetID());
}
}
}
// if there's no valid referenced session, create a new session of the requested type
if (s == null) {
try {
if (stype == Session.Type.SOAP) {
s = SoapSessionFactory.getInstance().getSoapSession(zsc).register();
} else if (stype == Session.Type.ADMIN) {
s = new AdminSession(authAccountId).register();
}
} catch (ServiceException e) {
ZimbraLog.session.info("exception while creating session", e);
}
if (s != null) {
zsc.recordNewSession(s.getSessionId());
}
}
// if it's a delegated request, try to get a session on the local requested mailbox
// (note that if the requested account is remote, getDelegateSession returns null)
if (s instanceof SoapSession && zsc.isDelegatedRequest()) {
Session delegate = ((SoapSession) s).getDelegateSession(zsc.getRequestedAccountId());
if (delegate != null) {
s = delegate;
}
}
return s;
}
/**
* End the session immediately, removing it from the session cache and cleaning it up
*
* @param s
*/
protected void endSession(Session s) {
SessionCache.clearSession(s);
}
/** Returns the {@link Server} object where an Account (specified by ID)
* is homed. This is similar to {@link Provisioning#getServer(Account),
* except that the account is specified by ID and exceptions are thrown
* on failure rather than returning null.
*
* @param acctId The Zimbra ID of the account.
* @throws ServiceException The following error codes are possible:<ul>
* <li><tt>account.NO_SUCH_ACCOUNT</tt> - if there is no Account
* with the specified ID
* <li><tt>account.PROXY_ERROR</tt> - if the Server associated
* with the Account does not exist</ul> */
protected static Server getServer(String acctId) throws ServiceException {
Account acct = Provisioning.getInstance().get(AccountBy.id, acctId);
if (acct == null) {
throw AccountServiceException.NO_SUCH_ACCOUNT(acctId);
}
String hostname = acct.getAttr(Provisioning.A_zimbraMailHost);
if (hostname == null) {
throw ServiceException.PROXY_ERROR(AccountServiceException.NO_SUCH_SERVER(""), "");
}
Server server = Provisioning.getInstance().get(Key.ServerBy.name, hostname);
if (server == null) {
throw ServiceException.PROXY_ERROR(AccountServiceException.NO_SUCH_SERVER(hostname), "");
}
return server;
}
protected static String getXPath(Element request, String[] xpath) {
int depth = 0;
while (depth < xpath.length - 1 && request != null) {
request = request.getOptionalElement(xpath[depth++]);
}
return (request == null ? null : request.getAttribute(xpath[depth], null));
}
protected static Element getXPathElement(Element request, String[] xpath) {
int depth = 0;
while (depth < xpath.length && request != null) {
request = request.getOptionalElement(xpath[depth++]);
}
return request;
}
protected static void setXPath(Element request, String[] xpath, String value) throws ServiceException {
if (xpath == null || xpath.length == 0)
return;
int depth = 0;
while (depth < xpath.length - 1 && request != null) {
request = request.getOptionalElement(xpath[depth++]);
}
if (request == null) {
throw ServiceException.INVALID_REQUEST("could not find path", null);
}
request.addAttribute(xpath[depth], value);
}
protected Element proxyIfNecessary(Element request, Map<String, Object> context) throws ServiceException {
// if the "target account" is remote and the command is non-admin, proxy.
ZimbraSoapContext zsc = getZimbraSoapContext(context);
String acctId = zsc.getRequestedAccountId();
Provisioning.Reasons reasons = new Provisioning.Reasons();
if (acctId != null && zsc.getProxyTarget() == null && !isAdminCommand() &&
!Provisioning.onLocalServer(getRequestedAccount(zsc), reasons)) {
if (null == zsc.getSoapRequestId()) {
zsc.setNewSoapRequestId();
}
Account authAcct = getAuthenticatedAccount(zsc);
if (authAcct == null) {
ZimbraLog.soap.info("Proxying request: requestedAccountId=%s authAcct <null> reason: %s",
acctId, reasons.getReason());
} else {
ZimbraLog.soap.info("Proxying request: requestedAccountId=%s authAcct name=%s id=%s reason: %s",
acctId, authAcct.getName(), authAcct.getId(), reasons.getReason());
}
return proxyRequest(request, context, acctId);
}
return null;
}
protected Element proxyRequest(Element request, Map<String, Object> context, String acctId) throws ServiceException {
ZimbraSoapContext zsc = getZimbraSoapContext(context);
// new context for proxied request has a different "requested account"
// and an incremented hop count
ZimbraSoapContext zscTarget = new ZimbraSoapContext(zsc, acctId);
return proxyRequest(request, context, getServer(acctId), zscTarget);
}
protected Element proxyRequest(Element request, Map<String, Object> context, AuthToken authToken, String acctId)
throws ServiceException {
ZimbraSoapContext zsc = getZimbraSoapContext(context);
// new context for proxied request has a different auth token and "requested account"
// and an incremented hop count
ZimbraSoapContext zscTarget = new ZimbraSoapContext(zsc, authToken, acctId, null);
return proxyRequest(request, context, getServer(acctId), zscTarget);
}
protected Element proxyRequest(Element request, Map<String, Object> context, Server server)
throws ServiceException {
ZimbraSoapContext zsc = getZimbraSoapContext(context);
// new context for proxied request has an incremented hop count
ZimbraSoapContext pxyCtxt = new ZimbraSoapContext(zsc);
return proxyRequest(request, context, server, pxyCtxt);
}
protected String getProxyAuthToken(String requestedAccountId, Map<String, Object> context) throws ServiceException {
return Provisioning.getInstance().getProxyAuthToken(requestedAccountId, context);
}
protected Element proxyRequest(Element request, Map<String, Object> context, Server server, ZimbraSoapContext zsc)
throws ServiceException {
// figure out whether we can just re-dispatch or if we need to proxy via HTTP
SoapEngine engine = (SoapEngine) context.get(SoapEngine.ZIMBRA_ENGINE);
boolean isLocal = getLocalHostId().equalsIgnoreCase(server.getId());
//reset proxy token if proxying locally; it could previously be set to wrong account
if (isLocal) {
zsc.resetProxyAuthToken();
}
//make sure proxy token is set correctly for current requested acct
if (zsc.getRequestedAccountId() != null) {
try {
AuthToken at = zsc.getAuthToken();
String proxyToken = getProxyAuthToken(zsc.getRequestedAccountId(), context);
if (at != null && (at.getProxyAuthToken() == null || !at.getProxyAuthToken().equals(proxyToken))) {
at.setProxyAuthToken(proxyToken);
}
} catch (ServiceException se) {
ZimbraLog.soap.warn("failed to set proxy auth token", se);
}
}
Element response = null;
request.detach();
if (isLocal && engine != null) {
// executing on same server; just hand back to the SoapEngine
Map<String, Object> contextTarget = new HashMap<String, Object>(context);
contextTarget.put(SoapEngine.ZIMBRA_ENGINE, engine);
contextTarget.put(SoapEngine.ZIMBRA_CONTEXT, zsc);
if (ZimbraLog.soap.isDebugEnabled()) {
ZimbraLog.soap.debug("Proxying request locally: targetServer=%s (id=%s) localHost=%s (id=%s)",
server.getName(), server.getId(), LOCAL_HOST, LOCAL_HOST_ID);
}
response = engine.dispatchRequest(request, contextTarget, zsc);
if (zsc.getResponseProtocol().isFault(response)) {
zsc.getResponseProtocol().updateArgumentsForRemoteFault(response, zsc.getRequestedAccountId());
throw new SoapFaultException("error in proxied request", true, response);
}
} else {
// do any necessary operations before doing a cross-server proxy
preProxy(request, context);
// executing remotely; find our target and proxy there
HttpServletRequest httpreq = (HttpServletRequest) context.get(SoapServlet.SERVLET_REQUEST);
ProxyTarget proxy = new ProxyTarget(server.getId(), zsc.getAuthToken(), httpreq);
if (proxyTimeout >= 0) {
proxy.setTimeouts(proxyTimeout);
}
response = proxyWithNotification(request, proxy, zsc, (Session) context.get(SoapEngine.ZIMBRA_SESSION));
// do any necessary operations after doing a cross-server proxy
postProxy(request, response, context);
}
return response;
}
public static Element proxyWithNotification(Element request, ProxyTarget proxy, ZimbraSoapContext zscProxy, ZimbraSoapContext zscInbound)
throws ServiceException {
return proxyWithNotification(request, proxy, zscProxy, getReferencedSession(zscInbound));
}
public static Element proxyWithNotification(Element request, ProxyTarget proxy, ZimbraSoapContext zscProxy, Session localSession)
throws ServiceException {
Server server = proxy.getServer();
boolean isLocal = getLocalHostId().equalsIgnoreCase(server.getId());
if (isLocal) {
zscProxy.resetProxyAuthToken();
}
if (zscProxy.isNotificationEnabled()) {
// if we've got a SOAP session, make sure to use the appropriate remote session ID
if (localSession instanceof SoapSession.DelegateSession) {
localSession = ((SoapSession.DelegateSession) localSession).getParentSession();
}
// note that requests proxied to *this same host* shouldn't request notification, as the existing local session collects the notifications
if (!(localSession instanceof SoapSession) || localSession.getMailbox() == null) {
zscProxy.disableNotifications();
} else if (!isLocal) {
zscProxy.setProxySession(((SoapSession) localSession).getRemoteSessionId(server));
} else {
zscProxy.setProxySession(localSession.getSessionId());
}
}
Pair<Element, Element> envelope = proxy.execute(request, zscProxy);
// if we've got a SOAP session, handle the returned notifications and session ID
if (localSession instanceof SoapSession && zscProxy.isNotificationEnabled())
((SoapSession) localSession).handleRemoteNotifications(server, envelope.getFirst());
return envelope.getSecond().detach();
}
/**
* This is for logging usage only:
* returns the account name if the account can be found by acctId,
* otherwise returns the acctId if not null,
* otherwise returns empty string.
*
* @param prov
* @param acctId
* @return
*/
private String getAccountLogName(Provisioning prov, String acctId) {
if (acctId == null) {
return "";
}
try {
Account acct = prov.get(AccountBy.id, acctId);
if (acct != null) {
return acct.getName();
}
} catch (ServiceException e) { }
return acctId;
}
public void logAuditAccess(String delegatingAcctId, String authedAcctId, String targetAcctId) {
if (!ZimbraLog.misc.isInfoEnabled())
return;
// 8 => "Response".length()
String reqName = responseQName.getQualifiedName().substring(0, responseQName.getQualifiedName().length()-8);
Provisioning prov = Provisioning.getInstance();
String delegatingAcctName = getAccountLogName(prov, delegatingAcctId);
String authedAcctName = getAccountLogName(prov, authedAcctId);
String targetAcctName = getAccountLogName(prov, targetAcctId);
ZimbraLog.misc.info("delegated access: doc=" + reqName +
(delegatingAcctId==null?"" : ", delegating account="+delegatingAcctName) +
", authenticated account=" + authedAcctName +
", target account=" + targetAcctName);
}
protected static Pair<String, Version> zimbraConnectorClientVersion(ZimbraSoapContext zsc) {
final String UA_ZCO = "ZimbraConnectorForOutlook";
final String UA_ZCB = "ZimbraConnectorForBES";
final String UA_MIGRATION = "ZimbraMigration";
String ua = zsc.getUserAgent();
// user agent is in the format of: name + "/" + version;
// ZCO: ZimbraConnectorForOutlook/7.0.0.0
// ZCB: ZimbraConnectorForBES/7.0.0.0
// MIGRATION: ZimbraMigration/8.0.0.x (where x is latest build number)
if (ua != null) {
String[] parts = ua.split("/");
if (parts.length == 2) {
String app = parts[0];
String version = parts[1];
if (UA_ZCO.equalsIgnoreCase(app) || UA_ZCB.equalsIgnoreCase(app) || UA_MIGRATION.equalsIgnoreCase(app)) {
try {
return new Pair<String, Version>(app, new Version(version, false));
} catch (ServiceException e) {
ZimbraLog.soap.debug("unable to parse zimbra connector client version", e);
}
}
}
}
return null;
}
@VisibleForTesting
public static void resetLocalHost() {
LOCAL_HOST = "";
LOCAL_HOST_ID = "";
}
}
|
jgraber/PythonFriday
|
SQLAlchemy/ORM/alembic/old_migrations_for_blog_only/347126fc065d_initial_tables_orig.py
|
<filename>SQLAlchemy/ORM/alembic/old_migrations_for_blog_only/347126fc065d_initial_tables_orig.py
"""Initial tables
Revision ID: 347126fc065d
Revises:
Create Date: 2021-06-12 17:27:18.833477
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('Author',
sa.Column('Id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('FirstName', sa.String(), nullable=False),
sa.Column('LastName', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('Id')
)
op.create_table('Employee',
sa.Column('Id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('LastName', sa.String(), nullable=False),
sa.Column('FirstName', sa.String(), nullable=False),
sa.Column('BirthDate', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('Id')
)
op.create_table('Publisher',
sa.Column('Id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('Name', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('Id')
)
op.create_table('Book',
sa.Column('Id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('Title', sa.String(), nullable=False),
sa.Column('ISBN', sa.String(length=13), nullable=False),
sa.Column('Pages', sa.Integer(), nullable=True),
sa.Column('PublishedBy', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['PublishedBy'], ['Publisher.Id'], ),
sa.PrimaryKeyConstraint('Id')
)
op.create_table('BookAuthor',
sa.Column('BookId', sa.Integer(), nullable=False),
sa.Column('AuthorId', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['AuthorId'], ['Author.Id'], ),
sa.ForeignKeyConstraint(['BookId'], ['Book.Id'], ),
sa.PrimaryKeyConstraint('BookId', 'AuthorId')
)
op.create_table('BookDetail',
sa.Column('Id', sa.Integer(), nullable=False),
sa.Column('Cover', sa.String(), nullable=True),
sa.Column('Description', sa.String(), nullable=True),
sa.ForeignKeyConstraint(['Id'], ['Book.Id'], ),
sa.PrimaryKeyConstraint('Id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('BookDetail')
op.drop_table('BookAuthor')
op.drop_table('Book')
op.drop_table('Publisher')
op.drop_table('Employee')
op.drop_table('Author')
# ### end Alembic commands ###
|
n8225/readflow
|
pkg/schema/article/mutations.go
|
<reponame>n8225/readflow<gh_stars>0
package article
import (
"errors"
"github.com/graphql-go/graphql"
"github.com/ncarlier/readflow/pkg/helper"
"github.com/ncarlier/readflow/pkg/model"
"github.com/ncarlier/readflow/pkg/schema"
"github.com/ncarlier/readflow/pkg/schema/category"
"github.com/ncarlier/readflow/pkg/service"
)
var updateArticleMutationField = &graphql.Field{
Type: articleUpdateResponseType,
Description: "update article",
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(graphql.ID),
},
"status": &graphql.ArgumentConfig{
Type: articleStatus,
},
"stars": &graphql.ArgumentConfig{
Type: graphql.Int,
},
},
Resolve: updateArticleResolver,
}
func updateArticleResolver(p graphql.ResolveParams) (interface{}, error) {
id, ok := helper.ConvGQLStringToUint(p.Args["id"])
if !ok {
return nil, errors.New("invalid article ID")
}
form := model.ArticleUpdateForm{
ID: id,
Status: helper.GetGQLStringParameter("status", p.Args),
Stars: helper.GetGQLUintParameter("stars", p.Args),
}
article, err := service.Lookup().UpdateArticle(p.Context, form)
if err != nil {
return nil, err
}
return struct {
Article *model.Article
}{
Article: article,
}, nil
}
var markAllArticlesAsReadMutationField = &graphql.Field{
Type: category.ListResponseType,
Description: "set all articles (of a category if provided) to read status",
Args: graphql.FieldConfigArgument{
"category": &graphql.ArgumentConfig{
Type: graphql.ID,
},
},
Resolve: markAllArticlesAsReadResolver,
}
func markAllArticlesAsReadResolver(p graphql.ResolveParams) (interface{}, error) {
var categoryID *uint
if val, ok := helper.ConvGQLStringToUint(p.Args["category"]); ok {
categoryID = &val
}
_, err := service.Lookup().MarkAllArticlesAsRead(p.Context, categoryID)
if err != nil {
return nil, err
}
return category.CategoriesResolver(p)
}
var addArticleMutationField = &graphql.Field{
Type: articleType,
Description: "add new article",
Args: graphql.FieldConfigArgument{
"url": &graphql.ArgumentConfig{
Type: graphql.NewNonNull(graphql.String),
},
"category": &graphql.ArgumentConfig{
Type: graphql.ID,
},
},
Resolve: addArticleResolver,
}
func addArticleResolver(p graphql.ResolveParams) (interface{}, error) {
var categoryID *uint
if val, ok := helper.ConvGQLStringToUint(p.Args["category"]); ok {
categoryID = &val
}
url, _ := p.Args["url"].(string)
form := model.ArticleCreateForm{
URL: &url,
CategoryID: categoryID,
}
return service.Lookup().CreateArticle(p.Context, form, service.ArticleCreationOptions{})
}
var cleanHistoryMutationField = &graphql.Field{
Type: category.ListResponseType,
Description: "remove all read articles",
Resolve: cleanHistoryResolver,
}
func cleanHistoryResolver(p graphql.ResolveParams) (interface{}, error) {
_, err := service.Lookup().CleanHistory(p.Context)
if err != nil {
return nil, err
}
return category.CategoriesResolver(p)
}
func init() {
schema.AddMutationField("addArticle", addArticleMutationField)
schema.AddMutationField("updateArticle", updateArticleMutationField)
schema.AddMutationField("markAllArticlesAsRead", markAllArticlesAsReadMutationField)
schema.AddMutationField("cleanHistory", cleanHistoryMutationField)
}
|
simpleviewinc/sv-keg
|
repos/keg-core/core/mocks/redux/index.js
|
<reponame>simpleviewinc/sv-keg
export * from './connect'
export * from './store'
|
ayxue/BaiduSaxoOpenAPI
|
dueros/directive/Display/template/BaseTemplate.py
|
#!/usr/bin/env python2
# -*- encoding=utf-8 -*-
# description:
# author:jack
# create_time: 2018/5/26
"""
模板展示基类
"""
from dueros.directive.Display.template.TextStructure import TextStructure
from dueros.directive.Display.template.ImageStructure import ImageStructure
from dueros.directive.Display.template.TextType import TextType
class BaseTemplate(object):
def __init__(self, field=[]):
self.data = {}
self.supportSetField = field
def set_background_image(self, url, width_pixels='', height_pixels=''):
"""
设置背景图片
:param url:
:param width_pixels:
:param height_pixels:
:return:
"""
if url:
image = self.create_image_structure(url, width_pixels, height_pixels)
if image:
self.data['backgroundImage'] = image.get_data()
def create_image_structure(self, url, width_pixels, height_pixels):
"""
创建imageStructure
:param url:
:param width_pixels:
:param height_pixels:
:return:
"""
if url:
image = ImageStructure()
image.set_url(url)
if width_pixels:
image.set_width_pixels(width_pixels)
if height_pixels:
image.set_height_pixels(height_pixels)
return image
def create_text_structure(self, content, text_type=TextType.PLAIN_TEXT):
"""
创建TextStructure
:type content: object
:param content:
:param text_type:
:return:
"""
if content:
texture = TextStructure()
texture.set_text(content)
if TextType.inEnum(text_type):
texture.set_type(text_type)
else:
texture.set_type(TextType.PLAIN_TEXT)
return texture
def get_data(self):
return self.data
def __getattr__(self, item):
"""
添加魔术方法
:param item:
:return:
"""
# 获取操作类型 set
operation = item[0:3]
# 获取被操作的属性
field = item[4:]
if operation == 'set' and field and (field.lower() in self.supportSetField):
def function(*args):
self.data[field.lower()] = args[0]
return function
else:
def function(*args):
print('不支持', operation, field)
return function
if __name__ == '__main__':
bodytemplate = BaseTemplate(['token'])
bodytemplate.set_token('a')
bodytemplate.set_background_image('aaaa')
print(bodytemplate.get_data())
|
zealoussnow/chromium
|
chromecast/graphics/cast_touch_event_gate_test.cc
|
<gh_stars>1000+
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/graphics/cast_touch_event_gate.h"
#include <memory>
#include "base/run_loop.h"
#include "chromecast/graphics/cast_touch_activity_observer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/window.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/events/test/events_test_utils.h"
using testing::_;
using testing::AtLeast;
using testing::Eq;
namespace chromecast {
class MockEventHandler : public ui::EventHandler {
public:
~MockEventHandler() override = default;
MOCK_METHOD1(OnTouchEvent, void(ui::TouchEvent* event));
};
class MockEventGateObserver : public CastTouchActivityObserver {
public:
~MockEventGateObserver() override = default;
MOCK_METHOD1(OnTouchEventsDisabled, void(bool disabled));
MOCK_METHOD0(OnTouchActivity, void());
};
class CastTouchEventGateTest : public aura::test::AuraTestBase {
public:
~CastTouchEventGateTest() override = default;
void SetUp() override {
aura::test::AuraTestBase::SetUp();
event_gate_ = std::make_unique<CastTouchEventGate>(root_window());
event_handler_ = std::make_unique<MockEventHandler>();
root_window()->AddPreTargetHandler(event_handler_.get());
generator_ = std::make_unique<ui::test::EventGenerator>(root_window());
gate_observer_ = std::make_unique<MockEventGateObserver>();
event_gate_->AddObserver(gate_observer_.get());
}
void TearDown() override {
root_window()->RemovePreTargetHandler(event_handler_.get());
event_gate_.reset();
aura::test::AuraTestBase::TearDown();
}
CastTouchEventGate& event_gate() { return *event_gate_; }
MockEventGateObserver& gate_observer() { return *gate_observer_; }
MockEventHandler& mock_event_handler() { return *event_handler_; }
ui::test::EventGenerator& event_generator() { return *generator_; }
private:
std::unique_ptr<CastTouchEventGate> event_gate_;
std::unique_ptr<MockEventGateObserver> gate_observer_;
std::unique_ptr<MockEventHandler> event_handler_;
std::unique_ptr<ui::test::EventGenerator> generator_;
};
TEST_F(CastTouchEventGateTest, DisabledByDefaultTest) {
// Tap leads to 2 touch events.
EXPECT_CALL(mock_event_handler(), OnTouchEvent(_)).Times(2);
// Expect no notifications to the observer.
EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(_)).Times(0);
EXPECT_CALL(gate_observer(), OnTouchActivity()).Times(0);
event_generator().GestureTapAt(gfx::Point(50, 50));
base::RunLoop().RunUntilIdle();
}
TEST_F(CastTouchEventGateTest, EnabledBlocksEvent) {
// No event should get through.
EXPECT_CALL(mock_event_handler(), OnTouchEvent(_)).Times(0);
// We should receive a notification at the observer that the gate was enabled.
EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(Eq(true))).Times(1);
// Also that it was disabled at destruction.
EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(Eq(false))).Times(1);
// And that the tap event was observed (multiple events)
EXPECT_CALL(gate_observer(), OnTouchActivity()).Times(AtLeast(2));
event_gate().SetEnabled(true);
event_generator().GestureTapAt(gfx::Point(50, 50));
base::RunLoop().RunUntilIdle();
}
TEST_F(CastTouchEventGateTest, EnableThenDisable) {
EXPECT_CALL(mock_event_handler(), OnTouchEvent(_)).Times(2);
EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(Eq(true))).Times(1);
EXPECT_CALL(gate_observer(), OnTouchEventsDisabled(Eq(false))).Times(1);
EXPECT_CALL(gate_observer(), OnTouchActivity()).Times(AtLeast(2));
event_gate().SetEnabled(true);
event_generator().GestureTapAt(gfx::Point(50, 50));
event_gate().SetEnabled(false);
event_generator().GestureTapAt(gfx::Point(50, 50));
base::RunLoop().RunUntilIdle();
}
} // namespace chromecast
|
mdrillin/modeshape
|
index-providers/modeshape-lucene-index-provider/src/test/java/org/modeshape/jcr/index/lucene/LuceneIndexProviderTest.java
|
/*
* ModeShape (http://www.modeshape.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.modeshape.jcr.index.lucene;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import javax.jcr.Node;
import javax.jcr.PropertyType;
import org.junit.Test;
import org.modeshape.common.FixFor;
import org.modeshape.common.util.FileUtil;
import org.modeshape.jcr.LocalIndexProviderTest;
import org.modeshape.jcr.api.JcrTools;
import org.modeshape.jcr.api.index.IndexDefinition;
import org.modeshape.jcr.api.index.InvalidIndexDefinitionException;
import org.modeshape.jcr.api.query.Query;
/**
* Unit test for {@link LuceneIndexProvider}. Since this is a local provider in term of repository locality, we want to run
* at least the same tests as for {@link org.modeshape.jcr.index.local.LocalIndexProvider}
*
* @author <NAME> (<EMAIL>)
*/
public class LuceneIndexProviderTest extends LocalIndexProviderTest {
@Override
public void beforeEach() throws Exception {
super.beforeEach();
tools = new JcrTools();
}
@Override
protected InputStream repositoryConfiguration() {
return resource("config/repo-config-persistent-lucene-provider-no-indexes.json");
}
@Override
protected String providerName() {
return "lucene";
}
@Test
@FixFor( "MODE-2520" )
public void shouldUseMultiColumnIndex() throws Exception {
registerNodeType("nt:testType");
Map<String, Integer> properties = new HashMap<>();
properties.put("stringProp", PropertyType.STRING);
properties.put("longProp", PropertyType.LONG);
properties.put("jcr:name", PropertyType.NAME);
registerValueIndex("multiColIndex", "nt:testType", null, "*", properties);
Node root = session().getRootNode();
Node node1 = root.addNode("node1", "nt:testType");
node1.setProperty("stringProp", "string1");
Node node2 = root.addNode("node2", "nt:testType");
node2.setProperty("longProp", 1);
Node node3 = root.addNode("node3", "nt:testType");
node3.setProperty("stringProp", "string3");
node3.setProperty("longProp", 2);
session.save();
Query query = jcrSql2Query("SELECT * FROM [nt:testType] WHERE stringProp LIKE 'string%'");
validateQuery().rowCount(2L).hasNodesAtPaths("/node1", "/node3").useIndex("multiColIndex").validate(query, query.execute());
query = jcrSql2Query("SELECT * FROM [nt:testType] WHERE longProp >= 1");
validateQuery().rowCount(2L).hasNodesAtPaths("/node2", "/node3").useIndex("multiColIndex").validate(query, query.execute());
query = jcrSql2Query("SELECT * FROM [nt:testType] WHERE longProp > 1 AND stringProp LIKE 'string%' ");
validateQuery().rowCount(1L).hasNodesAtPaths("/node3").useIndex("multiColIndex").validate(query, query.execute());
query = jcrSql2Query("SELECT * FROM [nt:testType] WHERE NAME() LIKE 'node%' ");
validateQuery().rowCount(3L).hasNodesAtPaths("/node1", "/node2", "/node3").useIndex("multiColIndex").validate(query, query.execute());
}
@Test(expected = InvalidIndexDefinitionException.class)
public void shouldNotAllowMultiColumnTextIndex() throws Exception {
Map<String, Integer> properties = new HashMap<>();
properties.put("prop1", PropertyType.STRING);
properties.put("prop2", PropertyType.STRING);
registerIndex("multiColTextIndex", IndexDefinition.IndexKind.TEXT, providerName(), "nt:unstructured", null, "*", properties);
}
@Test
public void shouldUseIndexForFTSOnStringProperty() throws Exception {
registerNodeType("nt:testType");
registerTextIndex("textIndex", "nt:testType", null, "*", "FTSProp", PropertyType.STRING);
Node root = session().getRootNode();
Node node1 = root.addNode("node", "nt:testType");
String propertyText = "the quick Brown fox jumps over to the dog in at the gate";
node1.setProperty("FTSProp", propertyText);
session.save();
Query query = jcrSql2Query("select [jcr:path] from [nt:testType] as n where contains([nt:testType].*,'" + propertyText + "')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node").useIndex("textIndex").validate(query, query.execute());
jcrSql2Query("select [jcr:path] from [nt:testType] as n where contains(FTSProp,'" + propertyText + "')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node").useIndex("textIndex").validate(query, query.execute());
jcrSql2Query("select [jcr:path] from [nt:testType] as n where contains(FTSProp,'" + propertyText.toUpperCase() + "')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node").useIndex("textIndex").validate(query, query.execute());
jcrSql2Query("select [jcr:path] from [nt:testType] as n where contains(FTSProp,'the quick Dog')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node").useIndex("textIndex").validate(query, query.execute());
jcrSql2Query("select [jcr:path] from [nt:testType] as n where contains(n.*,'the quick Dog')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node").useIndex("textIndex").validate(query, query.execute());
jcrSql2Query("select [jcr:path] from [nt:testType] as n where contains(FTSProp,'the quick jumps over gate')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node").useIndex("textIndex").validate(query, query.execute());
jcrSql2Query("select [jcr:path] from [nt:testType] as n where contains(n.*,'the quick jumps over gate')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node").useIndex("textIndex").validate(query, query.execute());
jcrSql2Query("select [jcr:path] from [nt:testType] as n where contains(FTSProp,'the gate')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node").useIndex("textIndex").validate(query, query.execute());
jcrSql2Query("select [jcr:path] from [nt:testType] as n where contains(n.*,'the gate')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node").useIndex("textIndex").validate(query, query.execute());
}
@Test
public void shouldUseIndexForFTSOnBinaryProperty() throws Exception {
registerTextIndex("textIndex", "nt:resource", null, "*", "jcr:data", PropertyType.BINARY);
tools.uploadFile(session, "/node", resourceStream("text-file.txt"));
session.save();
Query query = jcrSql2Query("select [jcr:path] from [nt:resource] as n where contains(n.*,'the quick jumps')");
validateQuery().rowCount(1L).hasNodesAtPaths("/node/jcr:content").useIndex("textIndex").validate(query, query.execute());
}
@FixFor("MODE-2565")
@Override
@Test
public void shouldNotReindexOnStartup() throws Exception {
super.shouldNotReindexOnStartup();
}
@Override
protected void assertStorageLocationUnchangedAfterRestart() throws Exception {
// register the total size and last modified timestamp of the place where indexes are stored for the default provider..
File indexesDir1 = new File("target/persistent_repository/indexes/lucene_primary/default/ref1");
assertTrue(indexesDir1.exists() && indexesDir1.isDirectory() && indexesDir1.canRead());
long sizeDir1 = FileUtil.size(indexesDir1.getPath());
final AtomicLong lastModifiedDateDir1 = lastModifiedFileTime(indexesDir1, "_0.*");
File indexesDir2 = new File("target/persistent_repository/indexes/lucene_primary/default/ref2");
assertTrue(indexesDir2.exists() && indexesDir2.isDirectory() && indexesDir2.canRead());
long sizeDir2 = FileUtil.size(indexesDir1.getPath());
final AtomicLong lastModifiedDateDir2 = lastModifiedFileTime(indexesDir2, "_0.*");
startRepository();
printMessage("Repository restart complete");
// and now check that the storage folder is unchanged
assertEquals(sizeDir1, FileUtil.size(indexesDir1.getPath()));
assertEquals(lastModifiedDateDir1.get(), lastModifiedFileTime(indexesDir1, "_0.*").get());
assertEquals(sizeDir2, FileUtil.size(indexesDir2.getPath()));
assertEquals(lastModifiedDateDir2.get(), lastModifiedFileTime(indexesDir2, "_0.*").get());
}
}
|
zhangkn/iOS14Header
|
System/Library/PrivateFrameworks/Silex.framework/SXActionEngine.h
|
<reponame>zhangkn/iOS14Header
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:43:30 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/Silex.framework/Silex
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <libobjc.A.dylib/SXActionProvider.h>
@class NSMutableDictionary, NSString;
@interface SXActionEngine : NSObject <SXActionProvider> {
NSMutableDictionary* _additionFactories;
NSMutableDictionary* _hostNameFactories;
}
@property (nonatomic,readonly) NSMutableDictionary * additionFactories; //@synthesize additionFactories=_additionFactories - In the implementation block
@property (nonatomic,readonly) NSMutableDictionary * hostNameFactories; //@synthesize hostNameFactories=_hostNameFactories - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(id)init;
-(NSMutableDictionary *)additionFactories;
-(id)actionForURL:(id)arg1 ;
-(NSMutableDictionary *)hostNameFactories;
-(id)actionForAddition:(id)arg1 ;
-(void)registerFactory:(id)arg1 URLHost:(id)arg2 ;
-(void)registerFactory:(id)arg1 additionType:(Class)arg2 ;
@end
|
jasonkliu/shifts
|
app/controllers/hooks_controller.rb
|
#Allow RT to bill job. Scenarios to handle:
#1. user is not logged into Shift, so should take him to log in and bill -- login must match RT login
#2. user is logged into Shift and is different user from RT -- display error on Shift main page (dashboard)
#3. user is logged into Shift, same netid as from RT, but with invalid parameters -- display error on Shift main page (dashboard)
#4. same users and valid parameters -- perform billing and redirect back to RT
# RT sends sth like this:
# http://APP_URL/hooks/add_job?
# url=http://uhu.its.yale.edu/Ticket/Display.html?id=26003
# &date=2009-09-20
# &category=1
# &total=0.0833333333333333
# &creator=RT
# &comments=Ticket_12345:_[Kayne]%20Yo%20Imgonna%20letyoufinish
# &netid=dtt22
# Test URL: http://APP_URL/rt?url=http://uhu.its.yale.edu/Ticket/Display.html?id=12345&date=2009-09-20&category=1&total=0.0833333333333333&creator=RT&comments=Ticket_12345:_[Kayne]%20Yo%20Immagonna%20letyoufinish&netid=dtt22
class HooksController < ApplicationController
# skip all before filters to add_job
# skip_filter filter_chain, only: 'add_job'
# this method hides the billing params from URL when you redirected to CAS
# so that people are less tempted to mess around
def add_job
session[:external] = params.clone
session[:external][:ip] = request.remote_ip
redirect_to action: :add_job_after
end
def add_job_after
p = session[:external]
unless p.blank?
#if currently logged in user of RT and Payform are different
if current_user.login != p[:netid]
#if RT is actually sending a valid netid
if (rt_user = User.find_by_login p[:netid])
flash[:big_notice] = "ALERT: Payform is not billing for #{rt_user.name} \
because #{current_user.name} is logged in. \
Please log #{current_user.name} out of Payform and try billing again from RT."
else
flash[:error] = "Please report to Admin. ERROR: Invalid user"
end
# if user is matched
elsif p[:total] && p[:comments] && p[:date]
#only bill to STC
if (dept = Department.find_by_name "STC")
@payform_item = PayformItem.new(hours: p[:total].to_f,
description: p[:comments],
category: Category.find_by_name("RT"),
payform: Payform.build(dept, current_user, Time.now),
source_url: p[:url],
date: Date.today)
if @payform_item.save
flash[:notice] = "Successfully updated payform."
if p[:url]
# SUCCESS!!!
session[:external] = nil
redirect_to p[:url] and return
end
else
flash[:error] = "Please report to Admin. ERROR: Could not save to payform."
end
else
flash[:error] = "Please report to Admin. ERROR: Department not found."
end
else
flash[:error] = "Please report to Admin. ERROR: Invalid Params."
end
# FAIL
# log tampering attemps
logger.info("**Billing failed** IP #{p[:ip]} sends this to hooks/add_job: #{p.to_json}")
# clear relevant session detail
session[:external] = nil
else
logger.info("**Billing failed** add_job_after called with session[:external] empty.")
end
redirect_to(root_path)
end
end
|
350dotorg/akcrm
|
cms/forms.py
|
from actionkit import Client
from actionkit.models import CoreTag, CorePage
from django import forms
from django.conf import settings
from akcrm.cms.models import AllowedTag
class AllowedTagForm(forms.Form):
tag_name = forms.CharField(required=True)
def clean_tag_name(self):
tag_name = self.cleaned_data['tag_name'].strip()
if AllowedTag.objects.filter(tag_name=tag_name).exists():
raise forms.ValidationError("A tag with this name has already been installed.")
return tag_name
def create_core_tag(self, new_tag_name):
actionkit = Client()
tag = actionkit.Tag.create(dict(name=new_tag_name))
return tag['id']
def create_tag_page(self, tag_id):
actionkit = Client()
page = actionkit.ImportPage.create(dict(name="activator_tag_page_%s" % tag_id))
actionkit.ImportPage.save(dict(id=page['id'], tags=[
tag_id, settings.AKTIVATOR_TAG_PAGE_TAG_ID]))
return page['id']
def save(self):
tag_name = self.cleaned_data['tag_name'].strip()
try:
core_tag = CoreTag.objects.using("ak").get(name=tag_name)
except CoreTag.DoesNotExist:
tag_id = self.create_core_tag(tag_name)
else:
tag_id = core_tag.id
try:
core_page = CorePage.objects.using("ak").filter(
pagetags__tag=tag_id).get(pagetags__tag=settings.AKTIVATOR_TAG_PAGE_TAG_ID)
except CorePage.DoesNotExist:
page_id = self.create_tag_page(tag_id)
else:
page_id = core_page.id
self.cleaned_data.update({'ak_tag_id': tag_id, 'ak_page_id': page_id})
return AllowedTag.objects.create(**self.cleaned_data)
|
vibedrive/website
|
site/views/default.js
|
var html = require('choo/html')
var wrapper = require('../components/wrapper')
var format = require('../components/format')
module.exports = wrapper(view)
function view (state, emit) {
return html`
<div class="x xw xjc c12 p1">
<div class="p1 c8 sm-c12">
<div class="fs2 fwb">${state.page.title}</div>
</div>
<div class="c8 sm-c12 p1 copy">
${format(state.page.text)}
</div>
</div>
`
}
|
Samsung/cynara
|
src/cyad/CommandlineParser/RawPolicyResult.h
|
/*
* Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file src/cyad/CommandlineParser/RawPolicyResult.h
* @author <NAME> <<EMAIL>>
* @version 1.0
* @brief An abstraction of raw PolicyType
*/
#ifndef SRC_CYAD_COMMANDLINEPARSER_RAWPOLICYRESULT_H_
#define SRC_CYAD_COMMANDLINEPARSER_RAWPOLICYRESULT_H_
namespace Cynara {
class RawPolicyResult {
public:
RawPolicyResult(const std::string &type, const std::string &metadata)
: m_type(type), m_metadata(metadata) {}
~RawPolicyResult() {}
const std::string &policyType(void) const {
return m_type;
}
const std::string &metadata(void) const {
return m_metadata;
}
private:
std::string m_type;
std::string m_metadata;
};
} /* namespace Cynara */
#endif /* SRC_CYAD_COMMANDLINEPARSER_RAWPOLICYRESULT_H_ */
|
isunktheship/art-collection-repo
|
scripts/collection.rb
|
<gh_stars>0
require '../config/environment'
require 'mechanize'
require 'nokogiri'
require 'pp'
puts "Running import script..."
def get_print_uids collection_id
collection_url = "http://expressobeans.com/members/collections.php?id=#{collection_id}&ipp=500"
args = %w[isunktheship manchester1]
print_uids = []
a = Mechanize.new
a.get('http://expressobeans.com/login.php?ref=1') do |page|
# Click the login link
login_page = a.click(page.link_with(:text => /Login/))
# Submit the login form
my_page = login_page.form_with(:action => './ucp.php?mode=login') do |f|
f.username = args[0]
f.password = <PASSWORD>[1]
end.click_button
# Get collection
a.get(collection_url) do |collection|
html = Nokogiri::HTML(collection.body)
links = html.xpath("//*[contains(@href, 'detail.php')]")
links.each do |link|
print_uids << link['href'].split("detail.php/")[-1].to_i
end
end
end
print_uids.uniq!
end
def get_print_details print_uid
url = "http://expressobeans.com/public/detail.php/#{print_uid}"
mechanize = Mechanize.new
page = mechanize.get(url)
html = Nokogiri::HTML(page.body)
details = {}
details["eb_uid"] = print_uid
details["title"] = page.title
details["artist"] = html.xpath("//a[contains(@title, 'More by this Artist')]").text.strip
# Print Year
# Print Class
# Print Status
# Print Release Date
# Print Run
# Print Technique
# Print Size
# Print Markings
detail_rows = html.xpath("//dl[contains(@class, 'itemListingInfo')]/dd[3]/table/tr")
detail_rows.each do |row|
details[ row.xpath("td[1]").text.strip.sub(":","").downcase ] = row.xpath("td[2]").text.strip
end
edition_stats = html.xpath("//table[contains(@class, 'editionStats')]/tr")
edition_stats.each do |row|
if row.xpath("th[1]").text.strip == "Original Price"
details[ "price" ] = row.xpath("td[1]").text.strip.sub("$", "")
break
end
end
return details
end
def import_print_details details
p = Print.where(title: details['title']).first_or_create
p.run_size = details['run'] if details['run']
p.original_price = details['price'] if details['price']
begin
p.release_date = Date.strptime(details['released'], "%m/%d/%y") if details['released'] && details['released'].to_s != ""
rescue
end
p.eb_uid = details['eb_uid'] if details['eb_uid']
p.save
artist_name = details['artist'].split(",") if details['artist']
a = Artist.where(last_name: artist_name[0], first_name: artist_name[1]).first_or_create
print_size = details['artist'].sub(" ", "").downcase.split("x")
p_size = PrintSize.where(height: print_size[0], width: print_size[1]).first_or_create
p.artist = a
p.print_size = p_size
p.print_class = PrintClass.where(title: details['class']).first_or_create if details['class']
p.print_status = PrintStatus.where(title: details['status']).first_or_create if details['status']
p.print_technique = PrintTechnique.where(title: details['technique']).first_or_create if details['technique']
p.print_marking = PrintMarking.where(title: details['markings']).first_or_create if details['markings']
p.save
end
collection_id = 36459
print_uids = get_print_uids collection_id
# pp print_uids
print_uids.each do |print_uid|
details = get_print_details print_uid
pp details
# puts "importing print: #{details['eb_uid']}"
import_print_details details
# break
end
|
gopa1959/test
|
setup.py
|
<gh_stars>0
import os
from setuptools import setup, find_packages
import edx_data_research
# Utility function to read the README file.
# Used for the long_description. It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
classifiers = [
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Topic :: Scientific/Engineering :: Information Analysis",
"Topic :: Scientific/Engineering :: Visualization",
"Topic :: Software Development :: Libraries :: Python Modules"
]
setup(name = 'moocx',
version = edx_data_research.__version__,
author = edx_data_research.__author__,
author_email = edx_data_research.__email__,
description = ("This is a public repository for the tools developed and used by the McGillX research team to package, analyse, and manipulate the data that is collected through McGill's online courses offered via the edX platform."),
license = edx_data_research.__license__,
packages = find_packages(),
package_data = {
'' : ['reporting/data/*']
},
url = 'https://github.com/McGillX/edx_data_research',
long_description = read('README.md'),
keywords = "mcgillx edx analytics mooc data python",
classifiers = classifiers,
entry_points = {
'console_scripts' : ['moocx=edx_data_research.cli.cli:main'],
},
)
|
watermarkchurch/broken-link-checker
|
test/helpers/server.js
|
"use strict";
const fixture = require("./fixture");
const basicAuthHeader = require("basic-auth-header");
const {createDeflate, createGzip} = require("zlib");
const {createReadStream} = require("fs");
const escapeStringRegexp = require("escape-string-regexp");
const nock = require("nock");
const {URL} = require("universal-url");
const addDeadMock = (...urls) =>
{
const error = new Error("mocked ECONNREFUSED");
const pattern = pathPattern("/path/to/resource.html");
error.code = "ECONNREFUSED";
urls.forEach(url =>
{
nock(url)
.persist().get(pattern).replyWithError(error)
.persist().head(pattern).replyWithError(error);
});
};
const addMock = (...urls) =>
{
urls.forEach((url, i) =>
{
const instance = nock(url);
intercept(instance,
{
path: /^.*fake\.html.*$/,
methods:
{
all: { statusCode:404 }
}
});
intercept(instance,
{
path: ["/", "/index.html"],
methods:
{
all:
{
body: stream("/index.html"),
headers: { "content-type":"text/html" },
statusCode: 200
}
}
});
intercept(instance,
{
path: "/auth/index.html",
auth: { user:"user", pass:"<PASSWORD>" },
methods:
{
all:
{
body: stream("/auth/index.html"),
headers: { "content-type":"text/html" },
statusCode: 200
}
}
});
intercept(instance,
{
path: "/auth/intransitive.html",
auth: { user:"user2", pass:"<PASSWORD>" },
methods:
{
all:
{
body: stream("/auth/intransitive.html"),
headers: { "content-type":"text/html" },
statusCode: 200
}
}
});
intercept(instance,
{
path: "/auth/transitive.html",
auth: { user:"user", pass:"<PASSWORD>" },
methods:
{
all:
{
body: stream("/auth/transitive.html"),
headers: { "content-type":"text/html" },
statusCode: 200
}
}
});
intercept(instance,
{
path: "/auth/transitive-redirect.html",
auth: { user:"user", pass:"<PASSWORD>" },
methods:
{
all:
{
headers: { location:"/auth/transitive-redirected.html" },
statusCode: 302
}
}
});
intercept(instance,
{
path: "/auth/transitive-redirected.html",
auth: { user:"user", pass:"<PASSWORD>" },
methods:
{
all:
{
body: stream("/auth/transitive-redirected.html"),
headers: { "content-type":"text/html" },
statusCode: 200
}
}
});
intercept(instance,
{
path: "/circular-redirect/redirect.html",
methods:
{
all:
{
headers: { location:"/circular-redirect/redirected.html" },
statusCode: 302
}
}
});
intercept(instance,
{
path: "/compression/deflate.html",
methods:
{
all:
{
body: stream("/compression/deflate.html", "deflate"),
headers:
{
"content-encoding": "deflate",
"content-type": "text/html"
},
statusCode: 200
}
}
});
intercept(instance,
{
path: "/compression/gzip.html",
methods:
{
all:
{
body: stream("/compression/gzip.html", "gzip"),
headers:
{
"content-encoding": "gzip",
"content-type": "text/html"
},
statusCode: 200
}
}
});
intercept(instance,
{
path: "/disallowed/header.html",
methods:
{
all:
{
body: stream("/disallowed/header.html"),
headers:
{
"content-type": "text/html",
"x-robots-tag": "nofollow"/*,
"x-robots-tag: unavailable_after": "1-Jan-3000 00:00:00 EST"*/
},
statusCode: 200
}
}
});
intercept(instance,
{
path: "/method-not-allowed/any.html",
methods:
{
all: { statusCode:405 }
}
});
intercept(instance,
{
path: "/method-not-allowed/head.html",
methods:
{
get:
{
body: stream("/method-not-allowed/head.html"),
headers: { "content-type":"text/html" },
statusCode: 200
},
head:
{
statusCode: 405
}
}
});
intercept(instance,
{
path: "/non-html/empty",
methods:
{
all:
{
body: stream("/non-html/empty"),
statusCode: 200
}
}
});
intercept(instance,
{
path: "/non-html/image.gif",
methods:
{
all:
{
body: stream("/non-html/image.gif"),
headers: { "content-type":"image/gif" },
statusCode: 200
}
}
});
// TODO :: rename to "simple" ?
intercept(instance,
{
path: "/normal/fake.html",
methods:
{
all: { statusCode:404 }
}
});
intercept(instance,
{
path: "/redirect/redirect.html",
methods:
{
all:
{
headers: { location:"/redirect/redirect2.html" },
statusCode: 302
}
}
});
intercept(instance,
{
path: "/redirect/redirect2.html",
methods:
{
all:
{
headers: { location:"/redirect/redirected.html" },
statusCode: 301
}
}
});
intercept(instance,
{
path: "/unknown/http-999.html",
methods:
{
all: { statusCode:999 }
}
});
intercept(instance,
{
path: "/robots.txt",
methods:
{
all:
{
body: stream("/robots.txt"),
headers: { "content-type":"text/plain" },
statusCode: 200
}
}
});
[
"/circular/index.html",
"/circular/no-links.html",
"/circular/with-links.html",
"/circular-redirect/redirected.html",
"/disallowed/header2.html",
"/disallowed/index.html",
"/disallowed/meta.html",
"/disallowed/meta2.html",
"/disallowed/rel.html",
"/disallowed/rel2.html",
"/disallowed/robots-txt.html",
"/disallowed/robots-txt2.html",
"/external-redirect/index.html",
"/external-redirect/redirected.html",
"/normal/index.html",
"/normal/no-links.html",
"/normal/with-links.html",
"/redirect/index.html",
"/redirect/redirected.html"
]
.forEach(path => intercept(instance,
{
path: path,
methods:
{
all:
{
body: stream(path),
headers: { "content-type":"text/html" },
statusCode: 200
}
}
}));
// These fixtures require multiple mocks
if (urls.length >= 2)
{
if (i === 0)
{
// Redirect first mock to next mock
// TODO :: make this more explicit in test suite somehow -- special case object for server, created per test?
intercept(instance,
{
path: "/auth/intransitive-redirect.html",
auth: { user:"user", pass:"<PASSWORD>" },
methods:
{
all:
{
headers: { location:new URL("/auth/intransitive-redirected.html", urls[1]).href },
statusCode: 302
}
}
});
intercept(instance,
{
path: "/external-redirect/redirect.html",
methods:
{
all:
{
headers: { location:new URL("/external-redirect/redirected.html", urls[1]).href },
statusCode: 302
}
}
});
}
else if (i === 1)
{
intercept(instance,
{
path: "/auth/intransitive-redirected.html",
auth: { user:"user", pass:"<PASSWORD>" },
methods:
{
all:
{
body: stream("/auth/intransitive-redirected.html"),
headers: { "content-type":"text/html" },
statusCode: 200
}
}
});
}
}
else
{
// Cannot redirect to another mock -- make sure tests fail
intercept(instance,
{
path: "/auth/intransitive-redirect.html",
methods:
{
all: { statusCode:500 }
}
});
intercept(instance,
{
path: "/external-redirect/redirect.html",
methods:
{
all: { statusCode:500 }
}
});
}
});
};
// NOTE :: `config` gets mutated
const intercept = (nockInstance, config) =>
{
if (config.methods.all)
{
config.methods.get = config.methods.all;
config.methods.head = config.methods.all;
}
if (!Array.isArray(config.path))
{
config.path = [config.path];
}
if (config.auth)
{
config.auth = basicAuthHeader(config.auth.user, config.auth.pass);
}
if (config.auth && config.methods.get.headers)
{
config.methods.get.headers.authorization = config.auth;
}
if (config.auth && config.methods.head.headers)
{
config.methods.head.headers.authorization = config.auth;
}
if (typeof config.methods.get.body !== "function")
{
config.methods.get.body = () => null;
}
const response = method =>
{
return function callback(url, requestBody)
{
if (!config.auth)
{
return [
config.methods[method].statusCode,
method === "get" ? config.methods.get.body() : null,
config.methods[method].headers
];
}
else if (config.auth && this.req.headers.authorization===config.auth)
{
return [
config.methods[method].statusCode,
method === "get" ? config.methods.get.body() : null,
Object.assign({ authorization: this.req.headers.authorization }, config.methods[method].headers)
];
}
else
{
return [401, null, null];
}
};
};
config.path.forEach(path =>
{
const pattern = pathPattern(path);
if (config.methods.get)
{
nockInstance.persist().get(pattern).reply(response("get"));
}
if (config.methods.head)
{
nockInstance.persist().head(pattern).reply(response("head"));
}
});
};
const pathPattern = path =>
{
if (path instanceof RegExp)
{
return path;
}
else
{
path = escapeStringRegexp(path);
path += "(?:\\?(?:.+)?)?"; // adds support for possible queries
path += "(?:\\#(?:.+)?)?"; // adds support for possible hashes
return new RegExp(`^${path}$`);
}
};
const removeMocks = () => nock.cleanAll();
const stream = (path, compression=false) =>
{
return () =>
{
const stream = createReadStream( fixture.path(path) );
if (compression === "deflate")
{
return stream.pipe(createDeflate());
}
else if (compression === "gzip")
{
return stream.pipe(createGzip());
}
else
{
return stream;
}
};
};
module.exports =
{
start: addMock,
startDead: addDeadMock,
stop: removeMocks
};
|
dhatim/safesql
|
safesql/src/main/java/org/dhatim/safesql/SafeSqlImpl.java
|
package org.dhatim.safesql;
class SafeSqlImpl implements SafeSql {
private final String sql;
private final Object[] parameters;
private String string;
SafeSqlImpl(String sql, Object[] parameters) {
this.sql = sql;
this.parameters = parameters;
}
@Override
public String asSql() {
return sql;
}
@Override
public Object[] getParameters() {
return parameters.clone();
}
@Override
public String asString() {
if (string == null) {
string = SafeSql.super.asString();
}
return string;
}
}
|
zelros/cinnamon
|
src/cinnamon/drift/tests/test_xgboost_model_drift_explainer.py
|
<reponame>zelros/cinnamon<gh_stars>10-100
import pandas as pd, numpy as np
from numpy.testing import assert_allclose
from sklearn import datasets
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor, XGBClassifier
from cinnamon.drift import ModelDriftExplainer
from cinnamon.drift.drift_utils import (DriftMetricsNum, DriftMetricsCat,
PerformanceMetricsDrift,
assert_drift_metrics_equal,
assert_drift_metrics_list_equal,
assert_performance_metrics_drift_equal)
from cinnamon.common.stat_utils import (BaseStatisticalTestResult, Chi2TestResult,
RegressionMetrics, ClassificationMetrics)
from ...common.constants import NUMPY_atol
RANDOM_SEED = 2021
def test_boston_xgboost_ModelDriftExplainer():
boston = datasets.load_boston()
boston_df = pd.DataFrame(boston.data, columns=boston.feature_names)
X_train, X_test, y_train, y_test = train_test_split(boston_df, boston.target, test_size=0.3,
random_state=RANDOM_SEED)
model = XGBRegressor(n_estimators=1000,
booster="gbtree",
objective="reg:squarederror",
learning_rate=0.05,
max_depth=6,
seed=RANDOM_SEED,
use_label_encoder=False)
model.fit(X=X_train, y=y_train, eval_set=[(X_test, y_test)], early_stopping_rounds=20, verbose=0)
drift_explainer = ModelDriftExplainer(model)
drift_explainer.fit(X_train, X_test, y_train, y_test)
# prediction drift
prediction_drift_ref = [DriftMetricsNum(mean_difference=-0.7889487954289152, wasserstein=1.0808420273082935, ks_test=BaseStatisticalTestResult(statistic=0.052743086529884034, pvalue=0.9096081584010306))]
assert_drift_metrics_list_equal(drift_explainer.get_prediction_drift(),
prediction_drift_ref)
# target drift
assert_drift_metrics_equal(drift_explainer.get_target_drift(),
DriftMetricsNum(mean_difference=-0.609240261671129,
wasserstein=1.3178114778471604,
ks_test=BaseStatisticalTestResult(statistic=0.07857567647933393,
pvalue=0.4968030078636394)))
# performance_metrics_drift
assert_performance_metrics_drift_equal(drift_explainer.get_performance_metrics_drift(),
PerformanceMetricsDrift(RegressionMetrics(mse=0.3643813701486243,
explained_variance=0.9960752192224699),
RegressionMetrics(mse=12.419719495108291,
explained_variance=0.8095694395593922)))
# tree_based_drift_values "node_size"
assert_allclose(drift_explainer.get_tree_based_drift_values(type='node_size'),
np.array([[4.31765569],
[0.53994982],
[1.2299105 ],
[0.05466186],
[2.40478511],
[5.62793724],
[2.3531374 ],
[3.78890353],
[0.73237733],
[1.65802895],
[1.39955313],
[2.47726252],
[6.99832357]]),
atol=NUMPY_atol)
# tree_based_drift_values "mean"
assert_allclose(drift_explainer.get_tree_based_drift_values(type='mean'),
np.array([[-0.04545056],
[ 0.00084117],
[ 0.18597606],
[-0.00062653],
[ 0.24192436],
[-0.55327918],
[-0.05149254],
[-0.25770117],
[ 0.03011812],
[ 0.0020817 ],
[-0.15965889],
[-0.13940995],
[-0.04227164]]),
atol=NUMPY_atol)
# tree_based_drift_values "mean_norm"
assert_allclose(drift_explainer.get_tree_based_drift_values(type='mean_norm'),
np.array([[ 0.05234698],
[ 0.0058806 ],
[ 0.00328171],
[-0.00030556],
[ 0.07280695],
[-0.29861327],
[-0.00603697],
[-0.2603778 ],
[ 0.01561826],
[-0.02779742],
[-0.01725041],
[-0.03128068],
[-0.03379194]]),
atol=NUMPY_atol)
# feature_drift_LSTAT
assert_drift_metrics_equal(drift_explainer.get_feature_drift('LSTAT'),
DriftMetricsNum(mean_difference=0.7378638864109419,
wasserstein=0.8023078352661315,
ks_test=BaseStatisticalTestResult(statistic=0.08887154326494201,
pvalue=0.3452770147763923)))
# feature_drift_feature_0
assert_drift_metrics_equal(drift_explainer.get_feature_drift(0),
DriftMetricsNum(mean_difference=-1.1253475613291695,
wasserstein=1.1305975918079103,
ks_test=BaseStatisticalTestResult(statistic=0.0618123699078204,
pvalue=0.7813257636577198)))
# all feature drifts
feature_drifts_ref = [DriftMetricsNum(mean_difference=-1.1253475613291695, wasserstein=1.1305975918079103, ks_test=BaseStatisticalTestResult(statistic=0.0618123699078204, pvalue=0.7813257636577198)),
DriftMetricsNum(mean_difference=-0.7548691644365135, wasserstein=0.8747398156407966, ks_test=BaseStatisticalTestResult(statistic=0.02951234017246506, pvalue=0.9999448615410187)),
DriftMetricsNum(mean_difference=-0.17914585191793364, wasserstein=0.7212444246208749, ks_test=BaseStatisticalTestResult(statistic=0.07381801962533452, pvalue=0.5764298225321844)),
DriftMetricsNum(mean_difference=0.02337942313410645, wasserstein=0.02337942313410646, ks_test=BaseStatisticalTestResult(statistic=0.02337942313410645, pvalue=0.9999998980177341)),
DriftMetricsNum(mean_difference=-0.010584444692238959, wasserstein=0.01748104742789176, ks_test=BaseStatisticalTestResult(statistic=0.07296312815938151, pvalue=0.5907168134992118)),
DriftMetricsNum(mean_difference=-0.015463871543265562, wasserstein=0.07063187630092177, ks_test=BaseStatisticalTestResult(statistic=0.056645851917930416, pvalue=0.86067051746252)),
DriftMetricsNum(mean_difference=-0.5575044603033064, wasserstein=1.22835637823372, ks_test=BaseStatisticalTestResult(statistic=0.04114629794826048, pvalue=0.9894125780752614)),
DriftMetricsNum(mean_difference=0.12717342030924828, wasserstein=0.17319668822479928, ks_test=BaseStatisticalTestResult(statistic=0.07244275944097532, pvalue=0.5998930415655818)),
DriftMetricsNum(mean_difference=-0.28690900981266765, wasserstein=0.3868941421349984, ks_test=BaseStatisticalTestResult(statistic=0.03631430270591734, pvalue=0.9978241882813342)),
DriftMetricsNum(mean_difference=-13.692387749033628, wasserstein=14.388492417484393, ks_test=BaseStatisticalTestResult(statistic=0.08039696699375558, pvalue=0.4679944796162433)),
DriftMetricsNum(mean_difference=0.20367603330359785, wasserstein=0.205839280404401, ks_test=BaseStatisticalTestResult(statistic=0.06322479928635147, pvalue=0.7594689122671989)),
DriftMetricsNum(mean_difference=6.062043190603617, wasserstein=6.4615822925958994, ks_test=BaseStatisticalTestResult(statistic=0.06341064525721082, pvalue=0.7559278097560319)),
DriftMetricsNum(mean_difference=0.7378638864109419, wasserstein=0.8023078352661315, ks_test=BaseStatisticalTestResult(statistic=0.08887154326494201, pvalue=0.3452770147763923))]
assert_drift_metrics_list_equal(drift_explainer.get_feature_drifts(),
feature_drifts_ref)
# tree_based_correction_weights with default params
assert_allclose(drift_explainer.get_tree_based_correction_weights(),
np.array([1.16419732, 1.10087397, 1.21368666, 1.13727639, 1.13989036,
1.18977695, 1.01215575, 1.10059681, 0.72558209, 1.00675234,
1.10666682, 0.88555298, 1.12977301, 1.16608115, 0.91400419,
0.44987693, 1.04860138, 1.15972868, 0.74749602, 0.78955673,
1.23054107, 1.0929581 , 1.15461204, 0.93743351, 0.89136442,
1.18001834, 1.09512827, 1.20852801, 1.07037641, 0.85541822,
0.71586788, 1.10300282, 1.25814986, 0.96320127, 0.96420466,
1.01631317, 1.31017151, 0.99762216, 0.91570282, 1.23407839,
1.01356292, 1.03317556, 0.98659978, 1.14176654, 0.8256704 ,
1.05326507, 1.15819153, 0.96044076, 1.04398531, 0.97956093,
1.13806087, 0.92484557, 0.60986512, 0.91123648, 1.06589494,
0.84968641, 1.1733163 , 0.93350917, 0.88924206, 1.05747077,
0.93490889, 0.79767375, 0.92145929, 0.37230812, 1.10293867,
1.09235481, 1.37000448, 0.89159463, 1.05314073, 1.04337542,
1.17859982, 1.05619742, 1.19299521, 0.49073022, 1.12006103,
1.10935394, 1.20617108, 0.98542949, 1.19876176, 0.49210116,
0.76742674, 1.06288453, 0.98133668, 0.79451027, 1.05343443,
1.17409533, 1.0322569 , 0.84641052, 0.72454594, 1.0972863 ,
1.11972538, 1.0166767 , 1.12840246, 0.90672729, 0.70155724,
1.18006586, 0.92539464, 0.32431158, 1.04676889, 1.07684215,
1.12142957, 1.12868632, 0.80044461, 1.11108876, 1.07978027,
0.83810027, 0.97369048, 0.94380991, 1.06643724, 1.03637159,
1.09826332, 1.21987827, 1.1017478 , 0.92381585, 1.05592795,
0.77292046, 1.26144311, 1.11049506, 0.50631903, 0.69105845,
1.05058848, 0.92704126, 0.59578928, 1.09463525, 1.01638428,
0.96861518, 1.06710481, 1.0882454 , 0.69635315, 0.84551532,
1.16587031, 0.91786233, 1.21218501, 1.11080734, 0.86970289,
1.09885839, 1.23491866, 0.61032684, 0.94564681, 0.94738328,
1.059863 , 1.13433497, 0.83917301, 1.15907066, 0.84877355,
0.33947135, 0.49498701, 0.88139004, 0.99945658, 0.95302861,
1.48348648, 1.09300884, 1.11657693, 1.13850024, 0.33491379,
0.50668992, 1.24825669, 1.13978931, 1.20383783, 0.94804158,
0.99665375, 1.22177126, 1.0945194 , 1.02675212, 1.30485921,
0.58660552, 0.55305576, 1.17434394, 1.17382957, 1.1202571 ,
0.96642816, 1.01531836, 1.10319784, 0.86347228, 1.00810461,
0.56946217, 1.08268008, 0.86923329, 1.0317189 , 0.93847969,
0.845586 , 0.97831139, 1.00289034, 1.14807371, 0.86903538,
1.13722926, 1.1006587 , 1.16877497, 1.01227611, 1.07845423,
1.11708513, 1.19417547, 1.2778751 , 0.98797798, 1.07728855,
1.05499927, 1.04710719, 1.08808864, 0.96846122, 1.32186046,
0.8530053 , 1.04979525, 1.09932135, 0.7429571 , 0.92881187,
1.30223646, 0.42061162, 1.19721629, 0.73952189, 1.04644862,
1.17597349, 1.0840867 , 0.74224707, 1.13574442, 0.94866608,
0.95590973, 0.94671777, 0.9254706 , 0.9839863 , 1.0244442 ,
0.77062547, 0.84602691, 0.9576317 , 0.88120068, 0.89514653,
1.15687421, 1.05989279, 1.13865161, 1.04575364, 1.11247464,
1.17972616, 0.95284698, 0.99251302, 0.98733136, 1.10005399,
1.28689456, 1.00010831, 1.28234576, 0.89869426, 1.11778495,
1.05600081, 1.12962457, 1.03721409, 1.07050115, 1.31205803,
1.22222613, 1.1449303 , 0.94381272, 0.47570943, 0.98423073,
0.57225095, 1.09066898, 0.96422086, 0.89040329, 0.32512642,
1.02420319, 1.32294277, 1.08759698, 1.10158941, 0.61790862,
0.96842455, 1.13527867, 0.85848503, 1.1100173 , 0.86949728,
0.81562783, 1.15702292, 0.84311207, 1.12182998, 1.06690836,
0.76243479, 0.92992144, 0.93082927, 0.51646473, 0.75581889,
1.13794611, 0.88634101, 1.01195516, 1.0558324 , 1.05306641,
1.08135681, 1.06816819, 1.09851691, 1.33354986, 1.13348136,
1.09352752, 1.01020482, 1.16867974, 1.10760027, 0.95324276,
0.9707388 , 1.1306543 , 1.1445239 , 0.96796771, 0.96245229,
1.2453499 , 0.9909731 , 0.64256786, 1.0459765 , 1.05809618,
0.92863222, 1.04914003, 0.94390974, 0.88043042, 1.12183045,
1.21387541, 1.06464791, 0.9586424 , 0.95162604, 1.14590447,
1.11224052, 0.76397902, 1.09903285, 1.02689233, 1.02270401,
1.06316529, 1.09481799, 1.05671481, 0.92147167, 1.14338271,
0.97165919, 1.05255944, 0.66238535, 1.11540372, 1.10107548,
0.84405474, 1.11217045, 0.77474588, 1.01380398, 0.83058349,
1.16788829, 0.85915848, 0.75478956, 1.10948121, 1.03640738,
1.16700158, 1.07234547, 0.91683386, 0.931275 , 1.06521399,
0.73163952, 1.05447144, 1.14416767, 1.07729212, 1.18850243,
1.10836293, 1.1817005 , 1.1238247 , 1.09186981, 1.17053314,
0.99844788, 1.01820715, 1.25297799, 1.09458313]),
atol=NUMPY_atol)
# tree_based_correction_weights with "max_depth = 2"
assert_allclose(drift_explainer.get_tree_based_correction_weights(max_depth=2),
np.array([1.06705916, 1.00782503, 1.03194615, 1.01143602, 1.04150287,
1.00490137, 1.00716356, 1.01372945, 1.01984372, 1.0415846 ,
1.03286222, 0.99840509, 1.06628184, 1.03063623, 0.96939166,
0.8038806 , 1.03194615, 1.06036313, 0.98854907, 0.97907688,
1.013492 , 0.88872912, 1.05886575, 1.02508135, 1.04243298,
1.02569367, 1.01785115, 1.02850978, 0.9878603 , 0.96039109,
1.05294481, 1.05615545, 1.05709789, 1.02261963, 1.05662473,
1.00474926, 1.03737369, 1.01897035, 1.01220578, 1.06800669,
1.05100332, 1.01640816, 1.02526032, 1.05518344, 0.99446514,
1.00321176, 1.03888114, 1.04169193, 1.01280588, 1.0248593 ,
1.0249929 , 1.02327516, 0.80835604, 0.92040462, 1.01850082,
1.02153529, 0.90401362, 1.02508135, 1.04124058, 1.02249592,
1.00350377, 1.05380244, 1.00418732, 0.71625784, 1.03046312,
1.06836601, 1.06196184, 1.03166289, 1.00493671, 1.00978167,
1.00664191, 1.04896893, 1.03335223, 0.80286263, 1.01784813,
1.0230165 , 1.03333042, 0.84973661, 1.03394422, 0.76627792,
1.05628382, 1.01554171, 1.01177573, 0.7684792 , 1.00713751,
1.02989149, 1.05380244, 1.00484896, 0.76382491, 1.01011393,
0.95893291, 1.01303789, 1.05380244, 0.90396531, 0.80832806,
1.03219578, 1.05623757, 0.70414909, 1.03159602, 1.01011393,
1.02227181, 1.02247586, 1.04243298, 1.03888114, 1.03306075,
0.97684241, 1.01143497, 1.00390841, 1.01690221, 1.023098 ,
1.05092364, 1.02605504, 1.03239116, 1.04243298, 1.03159602,
1.00770838, 1.01753144, 1.06355041, 0.80286263, 0.75878782,
1.00042124, 0.86210717, 0.81805437, 1.01595349, 1.01736054,
1.0028074 , 1.01347956, 1.02344056, 0.81918853, 1.02189 ,
1.027844 , 1.06352663, 1.03735179, 1.0109767 , 1.06018503,
1.02446896, 1.04069356, 0.93041787, 0.92321909, 1.02691114,
1.0261104 , 1.05804732, 1.00032953, 1.04715949, 1.01143497,
0.64937092, 0.75612285, 1.02438357, 1.01978483, 1.02372891,
1.06364573, 1.0249929 , 1.02795647, 1.02206413, 0.62444111,
0.81441905, 1.04560518, 1.02249592, 1.0202202 , 1.04272037,
0.85373068, 1.05937769, 1.01905612, 1.02037054, 1.05917458,
0.70315177, 0.84265141, 1.03564249, 1.03158103, 1.05625255,
1.01155734, 1.02473125, 1.0248593 , 1.03110024, 1.0105692 ,
0.76655379, 1.01929869, 1.00111594, 1.03218851, 1.05161489,
1.05380244, 0.9806052 , 1.00321176, 1.03293578, 1.00571659,
1.08229672, 1.0087436 , 1.08268708, 1.04243298, 1.01435934,
1.03569911, 1.01924758, 1.07414099, 1.04461879, 1.01836087,
1.02202067, 1.05894745, 1.03006066, 1.02643593, 1.05709789,
1.01168096, 1.06689953, 1.02196073, 0.83395358, 1.00043922,
1.15795501, 0.71625784, 1.03587309, 0.75878782, 1.05380244,
1.05484844, 1.04243298, 0.84244514, 1.03735179, 1.02792702,
1.02966407, 1.03335223, 0.96005168, 1.02455794, 1.01088373,
1.04243298, 1.04050496, 1.02249592, 1.02036971, 1.0415846 ,
1.05424294, 1.03218851, 1.01418897, 1.03564249, 1.01220578,
1.01143497, 0.8492266 , 1.02931471, 1.01486963, 1.03774678,
1.05063759, 1.01603176, 1.06950223, 1.02451342, 1.01562316,
1.02864778, 1.0332124 , 1.01418897, 1.02793579, 1.03888114,
1.05004129, 1.01177573, 1.00748309, 0.94426584, 1.01767718,
0.86049152, 1.01984239, 1.03821867, 1.05709789, 0.70139784,
1.0416767 , 1.05709789, 1.03913362, 1.00816457, 0.76974082,
1.0415846 , 1.04090503, 1.04243298, 1.04440392, 1.01973511,
1.03564249, 1.02943286, 1.02796848, 1.0157813 , 1.02045684,
1.02864778, 0.8525487 , 1.00884064, 0.74854892, 1.01284357,
1.03997235, 1.02153529, 1.00782503, 1.03267649, 1.02778381,
1.01143497, 1.02772656, 1.02722247, 1.03643174, 1.03194615,
1.04763263, 1.04621989, 1.02569346, 1.05618285, 1.04243298,
1.04243298, 1.01450463, 1.01649063, 0.89104104, 1.05294481,
1.03799457, 1.01188382, 0.9310142 , 1.01736054, 1.01340682,
1.03173974, 1.01418897, 1.02446896, 1.00350377, 1.03888114,
1.02809208, 1.01160488, 1.00987981, 1.03888114, 1.02291403,
1.00799433, 1.0415846 , 1.03267649, 1.01177573, 0.9816398 ,
0.96714353, 1.03913362, 1.01143497, 1.00839094, 1.02525736,
1.01476836, 1.03806175, 1.02312352, 1.04720395, 1.03598462,
0.99556151, 0.90878994, 0.98549045, 0.89692268, 1.04950095,
1.03267649, 1.01143497, 0.87793868, 1.02596249, 1.03568617,
1.03888114, 1.0181819 , 0.99735705, 1.00522002, 1.0416767 ,
1.01143497, 1.02867809, 1.01459792, 0.8948014 , 1.05592543,
1.01303789, 1.03286268, 1.03194615, 1.0187867 , 1.02966407,
1.03347725, 0.86450652, 1.07528078, 1.00782503]),
atol=NUMPY_atol)
# sample_weights1
assert_allclose(drift_explainer.sample_weights1[:5],
np.array([1., 1., 1., 1., 1.]),
atol=NUMPY_atol)
# sample_weights2
assert_allclose(drift_explainer.sample_weights2[:5],
np.array([1., 1., 1., 1., 1.]),
atol=NUMPY_atol)
assert drift_explainer.cat_feature_indices == []
assert drift_explainer.class_names == []
assert drift_explainer.feature_names == ['CRIM',
'ZN',
'INDUS',
'CHAS',
'NOX',
'RM',
'AGE',
'DIS',
'RAD',
'TAX',
'PTRATIO',
'B',
'LSTAT']
assert drift_explainer.iteration_range == (0, 143)
assert drift_explainer.n_features == 13
assert drift_explainer.task == 'regression'
def test_breast_cancer_xgboost_ModelDriftExplainer():
dataset = datasets.load_breast_cancer()
X = pd.DataFrame(dataset.data, columns=dataset.feature_names)
y = dataset.target
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.3, random_state=RANDOM_SEED)
clf = XGBClassifier(n_estimators=1000,
booster="gbtree",
objective="binary:logistic",
learning_rate=0.05,
max_depth=6,
use_label_encoder=False,
seed=RANDOM_SEED)
clf.fit(X=X_train, y=y_train, eval_set=[(X_valid, y_valid)], early_stopping_rounds=20, verbose=0)
drift_explainer = ModelDriftExplainer(clf)
drift_explainer.fit(X1=X_train, X2=X_valid, y1=y_train, y2=y_valid)
# prediction drift "raw"
prediction_drift_ref = [DriftMetricsNum(mean_difference=0.005498574879272855, wasserstein=0.3764544601013494, ks_test=BaseStatisticalTestResult(statistic=0.08323782655969908, pvalue=0.3542889176877513))]
assert_drift_metrics_list_equal(drift_explainer.get_prediction_drift(),
prediction_drift_ref)
# prediction drift "proba"
prediction_drift_proba_ref = [DriftMetricsNum(mean_difference=0.00798452225707491, wasserstein=0.024082025832758043, ks_test=BaseStatisticalTestResult(statistic=0.08323782655969908, pvalue=0.3542889176877513))]
assert_drift_metrics_list_equal(drift_explainer.get_prediction_drift(prediction_type='proba'),
prediction_drift_proba_ref)
# target drift
assert_drift_metrics_equal(drift_explainer.get_target_drift(),
DriftMetricsCat(wasserstein=0.0024097093655411628,
jensen_shannon=0.0017616379091961293,
chi2_test=Chi2TestResult(statistic=0.0,
pvalue=1.0,
dof=1,
contingency_table=pd.DataFrame([[148.0, 250.0], [64.0, 107.0]],
index=['X1', 'X2'], columns=[0, 1]))))
# performance_metrics_drift
assert_performance_metrics_drift_equal(drift_explainer.get_performance_metrics_drift(),
PerformanceMetricsDrift(ClassificationMetrics(accuracy=1.0, log_loss=0.016039305599991362),
ClassificationMetrics(accuracy=0.9473684210526315, log_loss=0.11116574995208815)))
# tree_based_drift_values "node_size"
assert_allclose(drift_explainer.get_tree_based_drift_values(type='node_size'),
np.array([[0.1263785 ],
[0.86245768],
[0.03015075],
[0.5015792 ],
[0.345185 ],
[0.01076813],
[0.48651996],
[0.5553289 ],
[0.00502513],
[0.02160804],
[0.05284761],
[0.16747726],
[0.01615219],
[0.21016901],
[0.06186914],
[0.61067109],
[0.13051384],
[0.00904523],
[0.1728764 ],
[0.0583929 ],
[0.970708 ],
[0.78384477],
[1.04602337],
[1.23239211],
[1.55243827],
[0.09348557],
[0.55188395],
[1.57008003],
[0.27572543],
[0.05313921]]),
atol=NUMPY_atol)
# tree_based_drift_values "mean"
assert_allclose(drift_explainer.get_tree_based_drift_values(type='mean'),
np.array([[-9.33158904e-03],
[ 1.15870292e-02],
[ 2.25198024e-03],
[-5.45754250e-03],
[ 5.29567213e-03],
[ 1.24361599e-03],
[ 2.21942302e-02],
[-3.17637413e-03],
[ 9.47460649e-06],
[ 4.13937125e-03],
[ 1.80148733e-03],
[-1.81682108e-03],
[ 7.62334093e-05],
[ 1.50764895e-03],
[-2.89777474e-03],
[-1.19719725e-02],
[ 4.80747869e-03],
[ 1.99959485e-03],
[-4.34269903e-04],
[ 1.51119076e-03],
[ 2.62156736e-03],
[-9.64497653e-04],
[-1.93085931e-02],
[-2.76468329e-03],
[ 1.09498474e-02],
[-5.65097244e-03],
[ 1.16655661e-03],
[-1.93422930e-03],
[ 8.26090050e-04],
[-2.78114137e-03]]),
atol=NUMPY_atol)
# tree_based_drift_values "mean_norm"
assert_allclose(drift_explainer.get_tree_based_drift_values(type='mean_norm'),
np.array([[ 0.00128017],
[-0.00862285],
[ 0.00227804],
[-0.00702226],
[ 0.01434936],
[ 0.00044783],
[ 0.01191792],
[ 0.00368157],
[-0.0001583 ],
[-0.00016892],
[ 0.00055728],
[ 0.00208376],
[-0.00037917],
[-0.00193379],
[-0.00055455],
[-0.0112573 ],
[ 0.00458787],
[-0.00033537],
[ 0.00311544],
[-0.00054474],
[-0.00204518],
[ 0.00557142],
[-0.01681621],
[-0.02567387],
[ 0.01606102],
[-0.00331497],
[ 0.00925461],
[-0.00053606],
[ 0.00542589],
[-0.00056559]]),
atol=NUMPY_atol)
# feature_drift mean perimeter
assert_drift_metrics_equal(drift_explainer.get_feature_drift('mean perimeter'),
DriftMetricsNum(mean_difference=-0.5394598724617197,
wasserstein=3.3009656469481903,
ks_test=BaseStatisticalTestResult(statistic=0.07401040289165124,
pvalue=0.4998149146505402)))
# feature_drift_feature_4
assert_drift_metrics_equal(drift_explainer.get_feature_drift(4),
DriftMetricsNum(mean_difference=-0.0011612596608774894,
wasserstein=0.0016581176349584157,
ks_test=BaseStatisticalTestResult(statistic=0.10195715419201269,
pvalue=0.1528888570418342)))
# all feature drifts
feature_drifts_ref = [DriftMetricsNum(mean_difference=-0.06832955714243738, wasserstein=0.5165887184460309, ks_test=BaseStatisticalTestResult(statistic=0.07067501248934732, pvalue=0.5585303796186362)),
DriftMetricsNum(mean_difference=0.014966205295483093, wasserstein=0.48581195450938897, ks_test=BaseStatisticalTestResult(statistic=0.07262922801140204, pvalue=0.5235102002710166)),
DriftMetricsNum(mean_difference=-0.5394598724617197, wasserstein=3.3009656469481903, ks_test=BaseStatisticalTestResult(statistic=0.07401040289165124, pvalue=0.4998149146505402)),
DriftMetricsNum(mean_difference=-17.377639660289788, wasserstein=51.29123100884536, ks_test=BaseStatisticalTestResult(statistic=0.06404831173410915, pvalue=0.6798041178199972)),
DriftMetricsNum(mean_difference=-0.0011612596608774894, wasserstein=0.0016581176349584157, ks_test=BaseStatisticalTestResult(statistic=0.10195715419201269, pvalue=0.1528888570418342)),
DriftMetricsNum(mean_difference=-0.003067542684181135, wasserstein=0.006741856651679452, ks_test=BaseStatisticalTestResult(statistic=0.06678127479502777, pvalue=0.6292065348385405)),
DriftMetricsNum(mean_difference=-0.006204282970407593, wasserstein=0.006991872085574072, ks_test=BaseStatisticalTestResult(statistic=0.05695142378559464, pvalue=0.8061165226745349)),
DriftMetricsNum(mean_difference=-0.002757498369038165, wasserstein=0.0030981202797613783, ks_test=BaseStatisticalTestResult(statistic=0.07233536101560434, pvalue=0.5289539515277676)),
DriftMetricsNum(mean_difference=-0.0015799582708866666, wasserstein=0.0029724940491933365, ks_test=BaseStatisticalTestResult(statistic=0.07430426988744894, pvalue=0.4945853439694361)),
DriftMetricsNum(mean_difference=-0.0005908483940168588, wasserstein=0.0007386144171148141, ks_test=BaseStatisticalTestResult(statistic=0.08001998295571425, pvalue=0.4016092513985777)),
DriftMetricsNum(mean_difference=0.0037102162861089028, wasserstein=0.024305223485850316, ks_test=BaseStatisticalTestResult(statistic=0.07703723294836756, pvalue=0.4491840353305204)),
DriftMetricsNum(mean_difference=0.02886939669105759, wasserstein=0.05198642040612427, ks_test=BaseStatisticalTestResult(statistic=0.0476211466690176, pvalue=0.9335508976473271)),
DriftMetricsNum(mean_difference=0.07566076581739134, wasserstein=0.21045070968879498, ks_test=BaseStatisticalTestResult(statistic=0.07721355314584619, pvalue=0.44639850985093277)),
DriftMetricsNum(mean_difference=-1.0084665432425268, wasserstein=3.717517793646603, ks_test=BaseStatisticalTestResult(statistic=0.07694907284962826, pvalue=0.4505043319421054)),
DriftMetricsNum(mean_difference=-0.0003356947309647645, wasserstein=0.0005335116518263824, ks_test=BaseStatisticalTestResult(statistic=0.0786828881248347, pvalue=0.4227052366505618)),
DriftMetricsNum(mean_difference=-0.0007019634870257772, wasserstein=0.0019131883246642555, ks_test=BaseStatisticalTestResult(statistic=0.08865967263216668, pvalue=0.28293492039886137)),
DriftMetricsNum(mean_difference=-0.0013409832539892468, wasserstein=0.003182003266331656, ks_test=BaseStatisticalTestResult(statistic=0.08345822680654735, pvalue=0.3510440105305035)),
DriftMetricsNum(mean_difference=2.3271988597960494e-05, wasserstein=0.0006830131799347609, ks_test=BaseStatisticalTestResult(statistic=0.0452555173528461, pvalue=0.9552787666453139)),
DriftMetricsNum(mean_difference=0.0011282174468835414, wasserstein=0.0012097365629316194, ks_test=BaseStatisticalTestResult(statistic=0.07890328837168298, pvalue=0.41933341366069177)),
DriftMetricsNum(mean_difference=-0.0002275110538070466, wasserstein=0.000301250179258867, ks_test=BaseStatisticalTestResult(statistic=0.05733345088013165, pvalue=0.7993870994743999)),
DriftMetricsNum(mean_difference=-0.06736449792823507, wasserstein=0.5360777131270384, ks_test=BaseStatisticalTestResult(statistic=0.05892033265743924, pvalue=0.772495994489099)),
DriftMetricsNum(mean_difference=-0.1677551500191079, wasserstein=0.4373399159540389, ks_test=BaseStatisticalTestResult(statistic=0.05468864791795233, pvalue=0.8423784026321328)),
DriftMetricsNum(mean_difference=-0.2752897528578728, wasserstein=3.3780036145640473, ks_test=BaseStatisticalTestResult(statistic=0.0704986922918687, pvalue=0.5621042713248987)),
DriftMetricsNum(mean_difference=-20.36132563401793, wasserstein=61.92498604131765, ks_test=BaseStatisticalTestResult(statistic=0.057495077727820386, pvalue=0.7963855471533337)),
DriftMetricsNum(mean_difference=-0.0031193050045549287, wasserstein=0.0032626057186517362, ks_test=BaseStatisticalTestResult(statistic=0.09193628963531106, pvalue=0.24521731583934214)),
DriftMetricsNum(mean_difference=-0.006255693526110079, wasserstein=0.013996743806753077, ks_test=BaseStatisticalTestResult(statistic=0.09212730318257957, pvalue=0.24304491278560958)),
DriftMetricsNum(mean_difference=-0.014588629316171553, wasserstein=0.01665632422345645, ks_test=BaseStatisticalTestResult(statistic=0.08436921449352024, pvalue=0.3384205412836392)),
DriftMetricsNum(mean_difference=-0.0035156151077022635, wasserstein=0.005018610787857414, ks_test=BaseStatisticalTestResult(statistic=0.04593141144318082, pvalue=0.9493671446153595)),
DriftMetricsNum(mean_difference=0.001843304240500776, wasserstein=0.007164130594492942, ks_test=BaseStatisticalTestResult(statistic=0.07614093861118458, pvalue=0.4637484909517612)),
DriftMetricsNum(mean_difference=-0.0014582808780746054, wasserstein=0.0027211234535249344, ks_test=BaseStatisticalTestResult(statistic=0.07605277851244527, pvalue=0.46509038807816905))]
assert_drift_metrics_list_equal(drift_explainer.get_feature_drifts(),
feature_drifts_ref)
# tree_based_correction_weights with default params
assert_allclose(drift_explainer.get_tree_based_correction_weights(),
np.array([1.09688861, 0.9762864 , 1.00014947, 1.01476245, 1.01354627,
0.9767973 , 1.04556855, 0.85788803, 0.90761728, 0.95980924,
1.46309695, 1.01011298, 0.96974536, 1.05906244, 0.97232291,
0.99180543, 0.98516202, 1.00942547, 1.26310403, 0.9748277 ,
1.01451781, 0.97868663, 0.97123145, 0.9733829 , 1.20145142,
0.9586891 , 0.97539291, 0.9768325 , 0.97842638, 0.98211348,
1.02099763, 0.95255366, 0.95910583, 0.97749069, 0.91711393,
1.0435607 , 0.92132381, 0.9767973 , 0.84949809, 1.08825167,
0.99230282, 0.97842638, 0.94620344, 0.99724424, 0.9036093 ,
0.98324182, 1.01734828, 0.96964598, 1.06762684, 0.96974536,
0.9949011 , 1.2057241 , 1.01011298, 0.99340268, 0.9664361 ,
0.97450892, 0.97488189, 0.9762864 , 1.01691498, 0.98512894,
1.00555434, 0.96905592, 0.96974536, 0.91122304, 0.93102404,
0.96065739, 0.92940275, 0.98132391, 1.12690028, 0.96900604,
0.94353279, 0.9762864 , 0.94343761, 1.0492391 , 0.93949154,
0.9934877 , 0.96645436, 1.03202716, 0.93938445, 0.92132381,
1.11859089, 1.02045142, 1.09223617, 0.98554884, 1.00350732,
0.94494111, 0.90379319, 0.90379319, 1.06169248, 0.96778998,
1.15590687, 1.01416578, 0.90558469, 1.00045202, 0.86778472,
1.07007739, 1.12243864, 0.98477793, 0.98689794, 1.10220873,
0.98352155, 0.9797077 , 0.95116113, 1.12059577, 0.92132381,
0.98599024, 0.95152545, 0.93661173, 0.97842638, 1.00527655,
1.19862131, 0.9949011 , 1.01011298, 1.00984077, 0.93130539,
0.92132381, 0.96974536, 1.05286115, 1.01476245, 0.9767973 ,
0.92061277, 0.90067896, 0.9949011 , 0.9767973 , 1.39335122,
0.94681491, 0.94807998, 0.93084373, 0.95346645, 0.96806721,
1.05752417, 0.97923458, 0.9207142 , 1.03982842, 1.03194528,
0.96923814, 0.96976656, 1.11572012, 0.91239922, 0.99233025,
1.15136868, 0.89028972, 0.96380939, 1.10862893, 0.98877476,
0.90374205, 0.97767417, 0.96089942, 1.04194554, 1.06896318,
0.9818003 , 0.91027932, 1.03095402, 1.09436284, 0.93486541,
1.01214388, 0.91603461, 0.89441691, 1.15426558, 0.93306278,
1.21696406, 1.07087497, 0.98775857, 0.9748277 , 1.18333091,
0.9311599 , 1.01432607, 0.96806721, 0.96493244, 0.94681491,
0.9767973 , 1.02117961, 0.9818436 , 0.97395557, 0.90716718,
1.00951905, 1.11828809, 0.98335911, 0.88741634, 0.94236893,
0.98855728, 0.9610783 , 1.00511946, 0.9610783 , 1.05466407,
0.99150881, 0.89978799, 0.92824642, 0.9733829 , 0.98657956,
0.9767973 , 0.95808787, 0.96570979, 0.9767973 , 0.98211348,
1.00552185, 1.01538974, 1.07342214, 1.24891905, 0.97457285,
0.9818003 , 0.97151205, 1.05201347, 1.02833475, 0.96964598,
1.04067146, 1.29794378, 1.01433355, 1.11445973, 1.17866278,
0.97602717, 0.97940093, 0.96672796, 0.9036093 , 1.04055059,
1.08716264, 0.91713342, 0.97842638, 0.97929098, 0.91711393,
1.07971923, 0.94648404, 1.06588569, 0.93929923, 0.86900744,
0.9733829 , 0.99358489, 0.93222083, 0.981091 , 0.98941224,
1.14817263, 1.00549738, 0.9264055 , 0.9748277 , 1.00375663,
0.99860652, 1.03187757, 1.00944462, 1.01416578, 1.19213111,
0.9861027 , 1.12463125, 0.98891136, 0.9488511 , 1.18800708,
0.93474089, 1.15864599, 0.99223952, 0.9513338 , 0.99024567,
1.16595902, 0.97767417, 1.02270935, 0.91477253, 0.9767973 ,
1.15087793, 0.94273799, 0.95093785, 0.96452201, 1.02728696,
1.01577319, 0.97395557, 0.97675389, 1.03329837, 0.95444102,
1.24367776, 0.93817417, 0.91544856, 0.99685911, 0.96439299,
0.95498178, 1.01416578, 0.96520215, 1.00139353, 1.00549738,
0.97190444, 1.00996603, 1.00851361, 1.02635158, 0.99412489,
0.92994705, 1.1962142 , 1.00936136, 0.92669589, 1.00291292,
1.02880622, 0.9610783 , 0.89966342, 0.93919222, 0.94716181,
1.00306662, 0.97671976, 0.97785108, 0.99097539, 0.96974536,
1.04667349, 0.97762583, 0.99467277, 0.93224644, 1.0239402 ,
1.00218875, 0.9767973 , 0.97933463, 0.93395503, 0.98953181,
0.96951773, 1.04147533, 0.97395557, 0.9767973 , 1.05049822,
0.85858325, 1.00839429, 0.95997819, 0.91703499, 0.9764657 ,
1.02576597, 1.05536556, 0.95116113, 0.9767973 , 1.00944462,
0.99493695, 1.00070629, 0.89818716, 0.97842638, 1.15284526,
0.9926688 , 0.97577954, 0.97078205, 0.99270135, 1.10890484,
1.0400484 , 0.9949011 , 0.96735107, 0.99550516, 0.98019335,
0.89467117, 0.85698742, 1.04524239, 0.91764191, 0.99135506,
0.98274187, 1.13238986, 1.04141147, 0.95901436, 0.96155602,
0.97395557, 1.116924 , 1.01011298, 1.38139845, 1.06746572,
1.23827099, 0.9767973 , 0.9782942 , 0.91954068, 0.9436986 ,
1.00983344, 0.97842638, 0.96974536, 0.99754785, 1.0792625 ,
0.9782942 , 0.9347743 , 1.07728331, 0.98969799, 0.96230798,
1.00826171, 0.97846367, 1.0976199 , 0.87795576, 0.98224721,
0.9818003 , 0.888337 , 0.95865103, 0.90196546, 0.99737843,
0.85545711, 0.97395557, 1.09080592, 0.88192188, 0.90172028,
1.10812858, 1.02735467, 0.97096186, 1.11491658, 1.00854637,
1.01446387, 1.00485001, 0.89966342, 1.10834215, 1.07745083,
0.9554235 , 1.02499975, 1.05634889, 1.04846522, 1.07746242,
0.99881543, 0.98052599, 0.99233025]),
atol=NUMPY_atol)
# tree_based_correction_weights with "max_depth = 1"
assert_allclose(drift_explainer.get_tree_based_correction_weights(max_depth=1),
np.array([0.99060717, 1.00097782, 1.01195055, 0.99190102, 0.99296686,
1.00097782, 1.02115759, 0.95965535, 0.99190102, 0.99190102,
1.03780921, 0.99190102, 1.00097782, 1.02115759, 1.00097782,
1.00097782, 0.99190102, 0.99190102, 1.03818753, 1.00097782,
0.99190102, 0.99190102, 1.00097782, 0.99190102, 1.02609205,
1.01195055, 1.00097782, 1.00097782, 0.99190102, 0.98308249,
0.99190102, 0.98862601, 1.00097782, 0.99190102, 0.99190102,
1.00097782, 0.99190102, 1.00097782, 0.98176558, 1.02377208,
0.99296686, 0.99190102, 0.98964166, 0.99190102, 0.98308249,
0.98176558, 1.00097782, 1.00097782, 1.02115759, 1.00097782,
1.00097782, 1.03348572, 0.99190102, 1.00295377, 0.98308249,
1.00097782, 1.00097782, 1.00097782, 1.00097782, 0.99190102,
1.01977884, 1.00097782, 1.00097782, 0.98308249, 0.98308249,
0.99190102, 1.00913713, 0.99190102, 1.01802648, 1.00232049,
0.98964166, 1.00097782, 0.99296686, 1.02115759, 1.01195055,
0.98176558, 1.00097782, 1.02115759, 0.99190102, 0.99190102,
1.01693375, 1.00097782, 1.01350404, 0.99190102, 0.97093225,
0.99070507, 0.99190102, 0.99190102, 1.00778359, 1.00097782,
1.03391585, 0.99190102, 0.98960065, 1.00097782, 0.98308249,
1.02115759, 1.01514945, 1.00097782, 0.99190102, 1.01345846,
1.00407111, 1.00097782, 0.99190102, 1.02115759, 0.99190102,
0.98308249, 0.99296686, 0.98308249, 0.99190102, 1.01195055,
1.02400318, 1.00097782, 0.99190102, 0.99190102, 0.9900491 ,
0.99190102, 1.00097782, 1.01011723, 0.99190102, 1.00097782,
0.99190102, 0.99190102, 1.00097782, 1.00097782, 1.02609205,
0.99190102, 0.96963163, 0.98862601, 0.99190102, 1.00097782,
1.01693375, 1.01195055, 0.99190102, 0.99193593, 1.02115759,
1.00097782, 1.00097782, 1.02400318, 0.98308249, 0.99190102,
1.02719463, 0.96867101, 1.00097782, 1.02115759, 1.01454525,
0.99190102, 0.99190102, 0.99990338, 1.02115759, 1.02115759,
0.99190102, 0.98308249, 1.00097782, 1.03710965, 1.02477633,
1.00097782, 0.99190102, 0.99296686, 1.02643535, 0.99190102,
1.0377968 , 1.02115759, 1.00295377, 1.00097782, 1.0215352 ,
0.98968833, 1.00097782, 1.00097782, 1.00097782, 0.99190102,
1.00097782, 0.99190102, 1.00097782, 0.99190102, 0.99190102,
0.99190102, 1.02115759, 0.99190102, 0.98308249, 0.98964166,
1.01095792, 1.00097782, 1.02115759, 1.00097782, 1.00093062,
0.99190102, 0.99190102, 0.98176558, 0.99190102, 0.99190102,
1.00097782, 1.00097782, 1.00083388, 1.00097782, 0.98308249,
1.00097782, 0.99190102, 1.02115759, 1.02443358, 1.00097782,
0.99190102, 0.99990338, 1.00083388, 1.0229736 , 1.00097782,
1.00305635, 1.02380811, 0.99831398, 1.02487216, 1.02238979,
1.00097782, 0.99190102, 1.00097782, 0.98308249, 1.00124462,
1.02115759, 0.99070507, 0.99190102, 0.99190102, 0.99190102,
1.02115759, 0.99990338, 1.02115759, 0.98743885, 0.98175514,
0.99190102, 1.01195055, 0.98308249, 0.99190102, 0.99190102,
1.00300905, 0.99190102, 1.00207785, 1.00097782, 0.99190102,
1.01195055, 1.02643535, 0.99190102, 0.99190102, 1.01331097,
0.99190102, 0.98964166, 1.02106398, 0.99096913, 1.01350404,
0.99190102, 1.02609205, 0.99190102, 0.99990338, 0.99190102,
1.03639558, 0.99190102, 0.98308249, 0.98964166, 1.00097782,
1.02719463, 0.99190102, 0.99930399, 0.99070507, 1.01195055,
0.99190102, 0.99190102, 0.98968833, 1.00097782, 0.99190102,
1.02506037, 0.97603687, 0.99190102, 1.00097782, 1.00097782,
0.99190102, 0.99190102, 0.99296686, 1.01207895, 0.99190102,
0.99296686, 0.99190102, 0.99190102, 1.01195055, 1.00295377,
0.99190102, 1.03776028, 1.00097782, 0.99190102, 1.00097782,
0.99190102, 1.00097782, 0.99190102, 0.98862601, 0.99990338,
1.00097782, 0.99070507, 0.99190102, 1.00097782, 1.00097782,
1.00166545, 0.98308249, 1.00097782, 0.98743885, 0.99190102,
0.99190102, 1.00097782, 0.99190102, 0.98964166, 0.98176558,
0.99990338, 1.00310274, 0.99190102, 1.00097782, 1.02115759,
1.01207895, 0.99190102, 1.00295377, 0.98308249, 0.99190102,
1.01207895, 0.99060717, 0.99190102, 1.00097782, 0.99190102,
1.00097782, 0.99190102, 0.98308249, 0.99190102, 1.03545037,
1.00026788, 1.01195055, 1.00097782, 0.99190102, 1.02715847,
1.02115759, 1.00097782, 0.99990338, 0.99190102, 0.99162617,
0.98308249, 0.98308249, 1.02115759, 0.97603687, 0.99190102,
0.99190102, 1.01331097, 1.01195055, 0.97972288, 0.99190102,
0.99190102, 1.02115759, 0.99190102, 1.02747846, 1.02377208,
1.03353577, 1.00097782, 1.00097782, 0.99190102, 0.99203397,
0.99190102, 0.99190102, 1.00097782, 0.99190102, 1.03035393,
1.00097782, 0.99190102, 1.02119353, 1.00097782, 1.00097782,
0.98308249, 0.99990338, 1.02377208, 0.99190102, 1.00097782,
0.99190102, 0.98308249, 0.99190102, 0.98743885, 1.01195055,
0.97603687, 0.99190102, 1.02115759, 0.99190102, 0.99059663,
1.02377208, 1.00097782, 1.00134271, 1.02115759, 1.00097782,
0.99190102, 1.00097782, 0.99190102, 1.0013055 , 0.9577269 ,
0.99190102, 1.00097782, 1.02115759, 1.00077649, 1.01928347,
0.99070507, 0.98308249, 0.99190102]),
atol=NUMPY_atol)
# sample_weights1
assert_allclose(drift_explainer.sample_weights1[:5],
np.array([1., 1., 1., 1., 1.]),
atol=NUMPY_atol)
# sample_weights2
assert_allclose(drift_explainer.sample_weights2[:5],
np.array([1., 1., 1., 1., 1.]),
atol=NUMPY_atol)
assert drift_explainer.cat_feature_indices == []
assert drift_explainer.class_names == ['0', '1']
assert drift_explainer.feature_names == ['mean radius',
'mean texture',
'mean perimeter',
'mean area',
'mean smoothness',
'mean compactness',
'mean concavity',
'mean concave points',
'mean symmetry',
'mean fractal dimension',
'radius error',
'texture error',
'perimeter error',
'area error',
'smoothness error',
'compactness error',
'concavity error',
'concave points error',
'symmetry error',
'fractal dimension error',
'worst radius',
'worst texture',
'worst perimeter',
'worst area',
'worst smoothness',
'worst compactness',
'worst concavity',
'worst concave points',
'worst symmetry',
'worst fractal dimension']
assert drift_explainer.iteration_range == (0, 126)
assert drift_explainer.n_features == 30
assert drift_explainer.task == 'classification'
def test_iris_xgboost_XGBClassifier():
dataset = datasets.load_iris()
X = pd.DataFrame(dataset.data, columns=dataset.feature_names)
y = dataset.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=RANDOM_SEED)
clf = XGBClassifier(n_estimators=1000,
booster="gbtree",
objective="binary:logistic",
learning_rate=0.05,
max_depth=6,
use_label_encoder=False,
seed=RANDOM_SEED)
clf.fit(X=X_train, y=y_train, eval_set=[(X_test, y_test)], early_stopping_rounds=20, verbose=0)
drift_explainer = ModelDriftExplainer(clf)
drift_explainer.fit(X1=X_train, X2=X_test, y1=y_train, y2=y_test)
# prediction drift "raw"
prediction_drift_ref = [DriftMetricsNum(mean_difference=0.31093458145383807, wasserstein=0.310934581453838, ks_test=BaseStatisticalTestResult(statistic=0.06349206349206349, pvalue=0.9987212484986797)),
DriftMetricsNum(mean_difference=0.3232848411632908, wasserstein=0.3318073130907522, ks_test=BaseStatisticalTestResult(statistic=0.12698412698412698, pvalue=0.6467769104301901)),
DriftMetricsNum(mean_difference=-0.5564053781212321, wasserstein=0.5568392310587188, ks_test=BaseStatisticalTestResult(statistic=0.17142857142857143, pvalue=0.2821678346768163))]
assert_drift_metrics_list_equal(drift_explainer.get_prediction_drift(),
prediction_drift_ref)
# prediction drift "proba"
prediction_drift_proba_ref = [DriftMetricsNum(mean_difference=0.06122570359665486, wasserstein=0.06138405880136859, ks_test=BaseStatisticalTestResult(statistic=0.1111111111111111, pvalue=0.793799989988573)),
DriftMetricsNum(mean_difference=0.08154049228640303, wasserstein=0.08205600790975118, ks_test=BaseStatisticalTestResult(statistic=0.12698412698412698, pvalue=0.6467769104301901)),
DriftMetricsNum(mean_difference=-0.1427661934187488, wasserstein=0.14276781702443725, ks_test=BaseStatisticalTestResult(statistic=0.19047619047619047, pvalue=0.1805850065949114))]
assert_drift_metrics_list_equal(drift_explainer.get_prediction_drift(prediction_type='proba'),
prediction_drift_proba_ref)
# target drift
assert_drift_metrics_equal(drift_explainer.get_target_drift(),
DriftMetricsCat(wasserstein=0.09523809523809523,
jensen_shannon=0.07382902143706498,
chi2_test=Chi2TestResult(statistic=1.3333333333333333,
pvalue=0.5134171190325922,
dof=2,
contingency_table=pd.DataFrame([[33.0, 34.0, 38.0], [17.0, 16.0, 12.0]],
index=['X1', 'X2'], columns=[0, 1, 2]))))
# performance_metrics_drift
assert_performance_metrics_drift_equal(drift_explainer.get_performance_metrics_drift(),
PerformanceMetricsDrift(ClassificationMetrics(accuracy=1.0, log_loss=0.045063073312242824),
ClassificationMetrics(accuracy=0.9333333333333333, log_loss=0.16192325585418277)))
# tree_based_drift_values "node_size"
assert_allclose(drift_explainer.get_tree_based_drift_values(type='node_size'),
np.array([[ 1.96002375],
[ 4.03749391],
[16.37810068],
[24.55940758]]),
atol=NUMPY_atol)
# tree_based_drift_values "mean"
assert_allclose(drift_explainer.get_tree_based_drift_values(type='mean'),
np.array([[ 0. , 0.18063744, -0.0278192 ],
[ 0. , -0.00393914, -0.06837239],
[ 0.31093455, 0.03153828, -0.26869759],
[ 0. , 0.11504829, -0.19151622]]),
atol=NUMPY_atol)
# tree_based_drift_values "mean_norm"
assert_allclose(drift_explainer.get_tree_based_drift_values(type='mean_norm'),
np.array([[ 0. , 0.01680469, 0.00507903],
[ 0. , -0.00718861, 0.02268815],
[ 0.31093455, -0.12144406, 0.0417556 ],
[ 0. , 0.06756211, -0.16671063]]),
atol=NUMPY_atol)
# feature_drift - argument as a string
assert_drift_metrics_equal(drift_explainer.get_feature_drift('petal width (cm)'),
DriftMetricsNum(mean_difference=-0.16412698412698457,
wasserstein=0.16412698412698412,
ks_test=BaseStatisticalTestResult(statistic=0.17142857142857143,
pvalue=0.2821678346768163)))
# feature_drift - argument as integer
assert_drift_metrics_equal(drift_explainer.get_feature_drift(2),
DriftMetricsNum(mean_difference=-0.2765079365079357,
wasserstein=0.2777777777777778,
ks_test=BaseStatisticalTestResult(statistic=0.1523809523809524,
pvalue=0.41885114043708227)))
# all feature drifts
feature_drifts_ref = [DriftMetricsNum(mean_difference=-0.18571428571428505, wasserstein=0.19968253968253974, ks_test=BaseStatisticalTestResult(statistic=0.16507936507936508, pvalue=0.3237613427576299)),
DriftMetricsNum(mean_difference=-0.08825396825396803, wasserstein=0.1301587301587301, ks_test=BaseStatisticalTestResult(statistic=0.14285714285714285, pvalue=0.499646880472137)),
DriftMetricsNum(mean_difference=-0.2765079365079357, wasserstein=0.2777777777777778, ks_test=BaseStatisticalTestResult(statistic=0.1523809523809524, pvalue=0.41885114043708227)),
DriftMetricsNum(mean_difference=-0.16412698412698457, wasserstein=0.16412698412698412, ks_test=BaseStatisticalTestResult(statistic=0.17142857142857143, pvalue=0.2821678346768163))]
assert_drift_metrics_list_equal(drift_explainer.get_feature_drifts(),
feature_drifts_ref)
# tree_based_correction_weights with default params
assert_allclose(drift_explainer.get_tree_based_correction_weights(),
np.array([1.52938066, 0.70303783, 0.69585122, 1.14692382, 1.14698728,
0.72033464, 1.22632416, 0.72033464, 1.22632416, 1.142113 ,
1.23736756, 1.142113 , 0.56368673, 0.86018518, 1.22632416,
1.22632416, 0.7208303 , 1.22632416, 1.14698728, 1.14698728,
0.69775839, 1.04277591, 1.23736756, 1.22632416, 0.70428396,
1.13630004, 0.7208303 , 0.69775839, 1.142113 , 0.73174406,
1.23736756, 1.22632416, 1.22632416, 0.69785836, 1.19780314,
1.15211681, 1.14698728, 1.22632416, 0.69585122, 1.03271783,
1.15703378, 0.57917234, 1.1944477 , 1.40219276, 0.70476857,
1.23736756, 1.03271783, 0.69775839, 1.22632416, 0.71906011,
1.12826509, 1.142113 , 1.22632416, 1.19985586, 0.70585718,
0.72652107, 1.22632416, 1.142113 , 1.15703378, 1.22632416,
1.19780314, 1.142113 , 1.142113 , 0.72028392, 1.22632416,
0.78968558, 0.71906011, 1.19780314, 1.22632416, 1.24462716,
0.68456622, 1.23933794, 0.39611022, 0.69585122, 1.15703378,
1.19780314, 0.61547879, 1.24462716, 0.7208303 , 1.22632416,
0.7018943 , 0.69785836, 1.32591399, 0.82419426, 1.19011568,
1.22632416, 1.15703378, 0.69775839, 0.68852529, 1.24462716,
1.22632416, 0.70428396, 1.19780314, 0.34753964, 0.71906011,
0.84691392, 1.22632416, 1.04749734, 1.22632416, 1.142113 ,
0.69775839, 0.72702098, 0.84691392, 1.02224718, 0.72028392]),
atol=NUMPY_atol)
# tree_based_correction_weights with "max_depth = 1"
assert_allclose(drift_explainer.get_tree_based_correction_weights(max_depth=1),
np.array([0.94703727, 0.81154305, 0.80612326, 1.0295544 , 1.0295544 ,
0.81154305, 1.20640805, 0.81154305, 1.20640805, 1.0295544 ,
1.21451906, 1.0295544 , 0.82080803, 0.82908081, 1.20640805,
1.20640805, 0.81154305, 1.20640805, 1.0295544 , 1.0295544 ,
0.80612326, 1.0295544 , 1.21451906, 1.20640805, 0.81154305,
1.0295544 , 0.81154305, 0.80612326, 1.0295544 , 0.81154305,
1.21451906, 1.20640805, 1.20640805, 0.81154305, 1.20640805,
1.0295544 , 1.0295544 , 1.20640805, 0.80612326, 0.9700073 ,
1.0295544 , 0.83122672, 0.9700073 , 0.94703727, 0.81154305,
1.21451906, 0.9700073 , 0.80612326, 1.20640805, 0.81154305,
1.0295544 , 1.0295544 , 1.20640805, 0.9700073 , 0.81154305,
0.81154305, 1.20640805, 1.0295544 , 1.0295544 , 1.20640805,
1.20640805, 1.0295544 , 1.0295544 , 0.81154305, 1.20640805,
0.82080803, 0.81154305, 1.20640805, 1.20640805, 1.21451906,
0.81154305, 1.21451906, 0.83122672, 0.80612326, 1.0295544 ,
1.20640805, 0.84918986, 1.21451906, 0.81154305, 1.20640805,
0.81154305, 0.81154305, 0.95784911, 0.82080803, 0.9700073 ,
1.20640805, 1.0295544 , 0.80612326, 0.81154305, 1.21451906,
1.20640805, 0.81154305, 1.20640805, 0.83122672, 0.81154305,
1.0295544 , 1.20640805, 1.0295544 , 1.20640805, 1.0295544 ,
0.80612326, 0.81154305, 1.0295544 , 0.96352923, 0.81154305]),
atol=NUMPY_atol)
# sample_weights1
assert_allclose(drift_explainer.sample_weights1[:5],
np.array([1., 1., 1., 1., 1.]),
atol=NUMPY_atol)
# sample_weights2
assert_allclose(drift_explainer.sample_weights2[:5],
np.array([1., 1., 1., 1., 1.]),
atol=NUMPY_atol)
assert drift_explainer.cat_feature_indices == []
assert drift_explainer.class_names == ['0', '1', '2']
assert drift_explainer.feature_names == ['sepal length (cm)',
'sepal width (cm)',
'petal length (cm)',
'petal width (cm)']
assert drift_explainer.iteration_range == (0, 97)
assert drift_explainer.n_features == 4
assert drift_explainer.task == 'classification'
|
tarikgwa/test
|
html/app/code/Magento/Msrp/view/base/web/js/msrp.js
|
<reponame>tarikgwa/test
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'jquery',
'underscore',
'jquery/ui',
'mage/dropdown',
'mage/template'
], function ($) {
'use strict';
$.widget('mage.addToCart', {
options: {
showAddToCart: true,
submitUrl: '',
cartButtonId: '',
singleOpenDropDown: true,
dialog: {}, // Options for mage/dropdown
dialogDelay: 500, // Delay in ms after resize dropdown shown again
origin: '', //Required, type of popup: 'msrp', 'tier' or 'info' popup
// Selectors
cartForm: '.form.map.checkout',
msrpLabelId: '#map-popup-msrp',
priceLabelId: '#map-popup-price',
popUpAttr: '[data-role=msrp-popup-template]',
popupCartButtonId: '#map-popup-button',
paypalCheckoutButons: '[data-action=checkout-form-submit]',
popupId: '',
realPrice: '',
isSaleable: '',
msrpPrice: '',
helpLinkId: '',
addToCartButton: '',
// Text options
productName: '',
addToCartUrl: ''
},
openDropDown: null,
triggerClass: 'dropdown-active',
popUpOptions: {
appendTo: 'body',
dialogContentClass: 'active',
closeOnMouseLeave: false,
autoPosition: true,
closeOnClickOutside: false,
'dialogClass': 'popup map-popup-wrapper',
position: {
my: 'left top',
collision: 'fit none',
at: 'left bottom',
within: 'body'
},
shadowHinter: 'popup popup-pointer'
},
popupOpened: false,
/**
* Creates widget instance
* @private
*/
_create: function () {
if (this.options.origin === 'msrp') {
this.initMsrpPopup();
} else if (this.options.origin === 'info') {
this.initInfoPopup();
} else if (this.options.origin === 'tier') {
this.initTierPopup();
}
$(this.options.cartButtonId).on('click', this._addToCartSubmit.bind(this));
},
/**
* Init msrp popup
* @private
*/
initMsrpPopup: function () {
var popupDOM = $(this.options.popUpAttr)[0],
$msrpPopup = $(popupDOM.innerHTML.trim());
$msrpPopup.find(this.options.productIdInput).val(this.options.productId);
$('body').append($msrpPopup);
$msrpPopup.trigger('contentUpdated');
$msrpPopup.find('button')
.on('click',
this.handleMsrpAddToCart.bind(this))
.filter(this.options.popupCartButtonId)
.text($(this.options.addToCartButton).text());
$msrpPopup.find(this.options.paypalCheckoutButons).on('click',
this.handleMsrpPaypalCheckout.bind(this));
$(this.options.popupId).on('click',
this.openPopup.bind(this));
this.$popup = $msrpPopup;
},
/**
* Init info popup
* @private
*/
initInfoPopup: function () {
var infoPopupDOM = $('[data-role=msrp-info-template]')[0],
$infoPopup = $(infoPopupDOM.innerHTML.trim());
$('body').append($infoPopup);
$(this.options.helpLinkId).on('click', function (e) {
this.popUpOptions.position.of = $(e.target);
$infoPopup.dropdownDialog(this.popUpOptions).dropdownDialog('open');
this._toggle($infoPopup);
}.bind(this));
this.$popup = $infoPopup;
},
/**
* Init tier price popup
* @private
*/
initTierPopup: function () {
var popupDOM = $(this.options.popUpAttr)[0],
$tierPopup = $(popupDOM.innerHTML.trim());
$('body').append($tierPopup);
$tierPopup.find(this.options.productIdInput).val(this.options.productId);
this.popUpOptions.position.of = $(this.options.helpLinkId);
$tierPopup.find('button').on('click',
this.handleTierAddToCart.bind(this))
.filter(this.options.popupCartButtonId)
.text($(this.options.addToCartButton).text());
$tierPopup.find(this.options.paypalCheckoutButons).on('click',
this.handleTierPaypalCheckout.bind(this));
$(this.options.attr).on('click', function (e) {
this.$popup = $tierPopup;
this.tierOptions = $(e.target).data('tier-price');
this.openPopup(e);
}.bind(this));
},
/**
* handle 'AddToCart' click on Msrp popup
* @param {Object} ev
*
* @private
*/
handleMsrpAddToCart: function (ev) {
ev.preventDefault();
if (this.options.addToCartButton) {
$(this.options.addToCartButton).click();
this.closePopup(this.$popup);
}
},
/**
* handle 'paypal checkout buttons' click on Msrp popup
*
* @private
*/
handleMsrpPaypalCheckout: function () {
this.closePopup(this.$popup);
},
/**
* handle 'AddToCart' click on Tier popup
*
* @param {Object} ev
* @private
*/
handleTierAddToCart: function (ev) {
ev.preventDefault();
if (this.options.addToCartButton &&
this.options.inputQty && !isNaN(this.tierOptions.qty)
) {
$(this.options.inputQty).val(this.tierOptions.qty);
$(this.options.addToCartButton).click();
this.closePopup(this.$popup);
}
},
/**
* handle 'paypal checkout buttons' click on Tier popup
*
* @private
*/
handleTierPaypalCheckout: function () {
if (this.options.inputQty && !isNaN(this.tierOptions.qty)
) {
$(this.options.inputQty).val(this.tierOptions.qty);
this.closePopup(this.$popup);
}
},
/**
* Open and set up popup
*
* @param {Object} event
*/
openPopup: function (event) {
var options = this.tierOptions || this.options;
this.popUpOptions.position.of = $(event.target);
this.$popup.find(this.options.msrpLabelId).html(options.msrpPrice);
this.$popup.find(this.options.priceLabelId).html(options.realPrice);
this.$popup.dropdownDialog(this.popUpOptions).dropdownDialog('open');
this._toggle(this.$popup);
if (!this.options.isSaleable) {
this.$popup.find('form').hide();
}
},
/**
*
* @param {HTMLElement} $elem
* @private
*/
_toggle: function ($elem) {
$(document).on('mouseup.msrp touchend.msrp', function (e) {
if (!$elem.is(e.target) && $elem.has(e.target).length === 0) {
this.closePopup($elem);
}
}.bind(this));
$(window).on('resize', function () {
this.closePopup($elem);
}.bind(this));
},
/**
*
* @param {HTMLElement} $elem
*/
closePopup: function ($elem) {
$elem.dropdownDialog('close');
$(document).off('mouseup.msrp touchend.msrp');
},
/**
* Handler for addToCart action
*/
_addToCartSubmit: function () {
this.element.trigger('addToCart', this.element);
if (this.element.data('stop-processing')) {
return false;
}
if (this.options.addToCartButton) {
$(this.options.addToCartButton).click();
return false;
}
if (this.options.addToCartUrl) {
$('.mage-dropdown-dialog > .ui-dialog-content').dropdownDialog('close');
}
$(this.options.cartForm).submit();
}
});
return $.mage.addToCart;
});
|
RAVURISREESAIHARIKRISHNA/JavaSE
|
BufferedReadderStringDemo/src/bufferedreadderstringdemo/BufferedReadderStringDemo.java
|
<gh_stars>0
package bufferedreadderstringdemo;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BufferedReadderStringDemo
{
public static void main(String[] args)
{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
String str;
while (true)
{
try
{
str = b.readLine();
} catch (java.io.IOException e)
{
System.out.println("here");
str = null;
e.printStackTrace();
}
System.out.println(str);
if (str.equals("stop"))
{//Using equals because == will compare Object References..
System.exit(0);
}
}
}
}
|
piaochung/blog
|
Spring-Boot/core/core/src/main/java/hello/core/member/Grade.java
|
package hello.core.member;
public enum Grade {
BASIC, VIP
}
|
dainst/cilantro
|
workers/default/omp/omp_api.py
|
import os
import logging
import json
from urllib.request import Request, urlopen
from urllib.error import HTTPError
omp_api_uri = os.environ['OMP_URI']
auth_key = os.environ['OMP_AUTH_KEY']
log = logging.getLogger(__name__)
def publish(import_xml_file_path, press_code):
"""
Publish the documents referenced in the passed XML via OMP-Import-Plugin.
The paramater file contains OMP-specific XML which contains file paths to
documents which shall be imported to OJS. It is read and passed to a POST
request (in UTF-8) to the OJS import plugin.
Server address and port can be given optionally.
The Import-Plugin needs authentication which is (for now) hard-coded.
:param str import_xml_file_path: OMP-Import-XML
:param str press_code: Name of press that will be imported to
:return: Tuple of return code and text of the POST request to OJS
"""
with open(import_xml_file_path, "r") as f:
import_data = f.read()
headers = {'Content-Type': 'application/xml',
'ompAuthorization': auth_key}
request_url = f"{_get_api_url()}/import/{press_code}"
return _make_request(request_url, headers,
import_data.encode(encoding='utf-8'))
def _get_api_url():
return omp_api_uri
def _make_request(url, headers, import_data=None):
"""Make the request to OMP and return response code and content."""
log.debug(f"Request: URL: {url} Headers: {headers} Data: {import_data}")
request = Request(url, headers=headers,
data=import_data)
try:
with urlopen(request) as response:
response_text = response.read().decode('utf-8')
except HTTPError as e:
log.error(f"Request failed with: {e.read()}")
raise
try:
return response.getcode(), json.loads(response_text)
except json.JSONDecodeError as e:
log.error(f"Failed to parse response as JSON: {response_text}")
raise
|
ceekay1991/AliPayForDebug
|
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/APLogAdditions.h
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
@class NSString;
@interface APLogAdditions : NSObject
{
NSString *_deviceModel;
NSString *_language;
NSString *_userID;
NSString *_clientVersion;
long long _maximumSizeOfLog;
long long _maximumNumberOfLogFiles;
long long _maximumLengthOfLine;
}
+ (id)sharedInstance;
@property(nonatomic) long long maximumLengthOfLine; // @synthesize maximumLengthOfLine=_maximumLengthOfLine;
@property(nonatomic) long long maximumNumberOfLogFiles; // @synthesize maximumNumberOfLogFiles=_maximumNumberOfLogFiles;
@property(nonatomic) long long maximumSizeOfLog; // @synthesize maximumSizeOfLog=_maximumSizeOfLog;
@property(retain, nonatomic) NSString *clientVersion; // @synthesize clientVersion=_clientVersion;
@property(retain, nonatomic) NSString *userID; // @synthesize userID=_userID;
@property(retain, nonatomic) NSString *language; // @synthesize language=_language;
@property(retain, nonatomic) NSString *deviceModel; // @synthesize deviceModel=_deviceModel;
- (void).cxx_destruct;
- (_Bool)privacyAuthed;
- (id)idfa;
- (id)getBrandNewUUID;
- (void)logToFile:(id)arg1;
- (id)defaultUploadLogTypes;
@property(retain, nonatomic) NSString *platformID;
@property(retain, nonatomic) NSString *configServerURL;
@property(retain, nonatomic) NSString *logServerURL;
@property(readonly, nonatomic) NSString *clientID;
@property(readonly, nonatomic) NSString *UTDID;
@property(readonly, nonatomic) NSString *UUID;
- (_Bool)privacyAuthed;
- (id)idfa;
- (void)logToFile:(id)arg1;
- (id)defaultUploadLogTypes;
@end
|
davecramer/pljvm
|
plj-java/performance/src/main/java/org/postgresql/pljvm/MeasureCall.java
|
package org.postgresql.pljvm;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class MeasureCall {
public static void main(String []args) throws Exception{
Connection connection = createConnection("localhost", 5432, "test");
}
static Connection createConnection(String host, int port, String database) throws SQLException{
return DriverManager.getConnection(host+':'+port, "test","");
}
static boolean createLanguage(Connection connection) throws Exception{
try ( Statement statement = connection.createStatement() ){
statement.execute("CREATE EXTENSION PLJVM");
}
return true;
}
}
|
AtakanFire/adlGame
|
source/engine/adlMemory.h
|
<reponame>AtakanFire/adlGame
#ifndef adl_memory_h__
#define adl_memory_h__
#define ADL_NEW(Class_name, ...) new Class_name(__VA_ARGS__);
#define ADL_DELETE(ptr) \
if(ptr != nullptr) \
{ \
delete ptr; \
ptr = nullptr; \
}
#endif // adl_memory_h__
|
oixhwotl/RecursoDeAndroidProgramming
|
REF/AndExam4_1/src/andexam/ver4_1/c31_gesture/TouchDump.java
|
<gh_stars>0
package andexam.ver4_1.c31_gesture;
import andexam.ver4_1.*;
import java.util.*;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
public class TouchDump extends Activity {
ArrayList<String> arTouch = new ArrayList<String>();
TextView mResult;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.touchdump);
mResult = (TextView)findViewById(R.id.result);
}
final static String[] arAction = {
"DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
"PDOWN", "PUP"
};
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
int pureaction = action & MotionEvent.ACTION_MASK;
//int pid = (action & MotionEvent.ACTION_POINTER_ID_MASK)
// >> MotionEvent.ACTION_POINTER_ID_SHIFT;
// for 2.2 later
int pid = (action & MotionEvent.ACTION_POINTER_INDEX_MASK)
>> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
String info = "p" + pid + " " + arAction[pureaction];
for (int i=0; i < event.getPointerCount();i++) {
info += String.format(" p%d(%d,%d)", event.getPointerId(i),
(int)event.getX(i), (int)event.getY(i));
}
if (event.getPointerCount() > 1) {
int dx = (int)(event.getX(0) - event.getX(1));
int dy = (int)(event.getY(0) - event.getY(1));
int distance = (int)(Math.sqrt(dx * dx + dy * dy));
info += " dis=" + distance;
}
AppendText(info);
return true;
}
void AppendText(String text) {
if (arTouch.size() > 15) {
arTouch.remove(0);
}
arTouch.add(text);
StringBuilder result = new StringBuilder();
for (String s : arTouch) {
result.append(s);
result.append("\n");
}
mResult.setText(result.toString());
}
}
|
MongoTheGeek/sdl_android
|
sdl_android/src/main/java/com/smartdevicelink/proxy/rpc/SingleTireStatus.java
|
package com.smartdevicelink.proxy.rpc;
import com.smartdevicelink.proxy.RPCStruct;
import com.smartdevicelink.proxy.rpc.enums.ComponentVolumeStatus;
import java.util.Hashtable;
/**
* Tire pressure status of a single tire.
* <p><b>Parameter List</b></p>
* <table border="1" rules="all">
* <tr>
* <th>Name</th>
* <th>Type</th>
* <th>Description</th>
* <th>SmartDeviceLink Ver. Available</th>
* </tr>
* <tr>
* <td>status</td>
* <td>ComponentVolumeStatus</td>
* <td>Describes the volume status of a single tire
* See {@linkplain ComponentVolumeStatus}
* </td>
* <td>SmartDeviceLink 2.0</td>
* </tr>
* </table>
* @since SmartDeviceLink 2.0
*/
public class SingleTireStatus extends RPCStruct {
public static final String KEY_STATUS = "status";
/**
* Constructs a newly allocated SingleTireStatus object
*/
public SingleTireStatus() { }
/**
* Constructs a newly allocated SingleTireStatus object indicated by the Hashtable parameter
* @param hash The Hashtable to use
*/
public SingleTireStatus(Hashtable<String, Object> hash) {
super(hash);
}
/**
* set the volume status of a single tire
* @param status the volume status of a single tire
*/
public void setStatus(ComponentVolumeStatus status) {
setValue(KEY_STATUS, status);
}
/**
* get the volume status of a single tire
* @return the volume status of a single tire
*/
public ComponentVolumeStatus getStatus() {
return (ComponentVolumeStatus) getObject(ComponentVolumeStatus.class, KEY_STATUS);
}
}
|
maciej-barczak-red/pxCore
|
examples/pxScene2d/external/libnode-v8.9.4/deps/v8/test/mjsunit/wasm/export-global.js
|
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
load("test/mjsunit/wasm/wasm-constants.js");
load("test/mjsunit/wasm/wasm-module-builder.js");
(function exportImmutableGlobal() {
var builder = new WasmModuleBuilder();
let globals = [
[kWasmI32, 'i32_noinit'], // -
[kWasmI32, 'i32', 4711], // -
[kWasmF32, 'f32_noinit'], // -
[kWasmF32, 'f32', Math.fround(3.14)], // -
[kWasmF64, 'f64_noinit'], // -
[kWasmF64, 'f64', 1 / 7] // -
];
for (let g of globals) {
let global_builder = builder.addGlobal(g[0], false).exportAs(g[1]);
if (g[2]) global_builder.init = g[2];
}
var module = builder.instantiate();
for (let g of globals) {
assertEquals("number", typeof module.exports[g[1]], g[1]);
assertEquals(g[2] || 0, module.exports[g[1]], g[1]);
}
})();
(function cannotExportMutableGlobal() {
var builder = new WasmModuleBuilder();
builder.addGlobal(kWasmI32, true).exportAs('g');
assertThrows(() => builder.instantiate(), WebAssembly.CompileError);
})();
(function cannotExportI64Global() {
var builder = new WasmModuleBuilder();
builder.addGlobal(kWasmI64, false).exportAs('g');
assertThrows(() => builder.instantiate(), WebAssembly.LinkError);
})();
(function duplicateGlobalExportName() {
var builder = new WasmModuleBuilder();
builder.addGlobal(kWasmI64, false).exportAs('g');
builder.addGlobal(kWasmI64, false).exportAs('g');
assertThrows(
() => builder.instantiate(), WebAssembly.CompileError,
/Duplicate export name 'g' for global 0 and global 1/);
})();
(function exportNameClashWithFunction() {
var builder = new WasmModuleBuilder();
builder.addGlobal(kWasmI64, false).exportAs('foo');
builder.addFunction('f', kSig_v_v).addBody([]).exportAs('foo');
assertThrows(
() => builder.instantiate(), WebAssembly.CompileError,
/Duplicate export name 'foo' for global 0 and function 0/);
})();
|
miguelperezcolom/mateu-financials
|
src/main/java/io/mateu/financials/domain/model/LitigationLogRecord.java
|
package io.mateu.financials.domain.model;
import io.mateu.mdd.shared.annotations.Output;
import lombok.MateuMDDEntity;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
@MateuMDDEntity
public class LitigationLogRecord {
@ManyToOne
@NotNull
private Litigation litigation;
@Output
private LocalDateTime when;
private String text;
}
|
greck2908/robot-software
|
master-firmware/src/gui.cpp
|
<gh_stars>10-100
#include <thread>
#include "gui.h"
#include <string.h>
#include <stdio.h>
#include <gfx.h>
#include "gui/Menu.h"
#include "gui/PositionPage.h"
#include "gui/MovePage.h"
#include "gui/ActuatorPage.h"
#include "gui/MenuPage.h"
#include "gui/ScorePage.h"
#include "gui/GoapActionPage.h"
#include "main.h"
#include "strategy.h"
static void gui_thread()
{
gfxInit();
gwinSetDefaultStyle(&WhiteWidgetStyle, GFXOFF);
gwinSetDefaultFont(gdispOpenFont("DejaVuSans32"));
gdispClear(GFX_SILVER);
gwinSetDefaultBgColor(GFX_SILVER);
gdispSetOrientation(gOrientation90);
WARNING("GUI init done");
Menu m;
PositionPage base_position_page;
MovePage base_move_page;
ScorePage score_page;
std::vector<GoapActionPage> action_pages;
auto goap_actions = strategy_get_actions();
std::transform(goap_actions.begin(), goap_actions.end(),
std::back_inserter(action_pages),
[](actions::NamedAction<StrategyState>* action) {
return GoapActionPage(*action);
});
MenuPage actions_menu(m, "Actions",
action_pages.size() >= 1 ? &action_pages[0] : nullptr,
action_pages.size() >= 2 ? &action_pages[1] : nullptr,
action_pages.size() >= 3 ? &action_pages[2] : nullptr,
action_pages.size() >= 4 ? &action_pages[3] : nullptr,
action_pages.size() >= 5 ? &action_pages[4] : nullptr,
action_pages.size() >= 6 ? &action_pages[5] : nullptr);
auto base_menu = MenuPage(m, "Base", &base_position_page, &base_move_page);
auto front_left_page = ActuatorPage("actuator-front-left");
auto front_center_page = ActuatorPage("actuator-front-center");
auto front_right_page = ActuatorPage("actuator-front-right");
auto back_left_page = ActuatorPage("actuator-back-left");
auto back_center_page = ActuatorPage("actuator-back-center");
auto back_right_page = ActuatorPage("actuator-back-right");
auto actuator_menu = MenuPage(m, "Actuators",
&front_left_page,
&front_center_page,
&front_right_page,
&back_left_page,
&back_center_page,
&back_right_page);
auto root_page = MenuPage(m, "Robot", &base_menu, &score_page, &actuator_menu, &actions_menu);
m.enter_page(&root_page);
m.enter_page(&score_page);
m.event_loop();
while (true) {
}
}
void gui_start()
{
std::thread thd(gui_thread);
thd.detach();
}
|
hcxp/hcxp
|
app/graphql/resolvers/venues_resolver.rb
|
<reponame>hcxp/hcxp
class Resolvers::VenuesResolver
include Resolvers::ValidationResolver
def call(obj, args, ctx)
first_or_last_required!(args)
col = obj ? obj.venues : Venue.all
params = {
query: args[:query]
}
service = VenuesIndexService.new(col, params)
service.call
end
end
|
michimune/azure-cli-extensions
|
src/db-up/azext_db_up/util.py
|
<filename>src/db-up/azext_db_up/util.py
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import random
import os
from knack.config import CLIConfig
from azure.cli.core.commands import LongRunningOperation, _is_poller
CONFIG_DIR = os.path.expanduser(os.path.join('~', '.azext_db_up'))
ENV_VAR_PREFIX = 'AZEXT'
MYSQL_CONFIG_SECTION = 'mysql_up'
POSTGRES_CONFIG_SECTION = 'postgres_up'
SQL_CONFIG_SECTION = 'sql_up'
CONFIG_MAP = {
'mysql': MYSQL_CONFIG_SECTION,
'postgres': POSTGRES_CONFIG_SECTION,
'sql': SQL_CONFIG_SECTION
}
DB_CONFIG = CLIConfig(config_dir=CONFIG_DIR, config_env_var_prefix=ENV_VAR_PREFIX)
def create_random_resource_name(prefix='azure', length=15):
append_length = length - len(prefix)
digits = [str(random.randrange(10)) for i in range(append_length)]
return prefix + ''.join(digits)
def get_config_value(db_type, option, fallback='_fallback_none'):
config_section = CONFIG_MAP[db_type]
if fallback == '_fallback_none':
return DB_CONFIG.get(config_section, option)
return DB_CONFIG.get(config_section, option, fallback=fallback)
def set_config_value(db_type, option, value):
config_section = CONFIG_MAP[db_type]
DB_CONFIG.set_value(config_section, option, value)
def update_kwargs(kwargs, key, value):
if value is not None:
kwargs[key] = value
def resolve_poller(result, cli_ctx, name):
if _is_poller(result):
return LongRunningOperation(cli_ctx, 'Starting {}'.format(name))(result)
return result
|
ivadasz/DragonFlyBSD
|
usr.sbin/installer/dfuibe_installer/flow.h
|
<reponame>ivadasz/DragonFlyBSD
/*
* Copyright (c)2004 The DragonFly Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the DragonFly Project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* flow.h
* $Id: flow.h,v 1.10 2005/03/20 18:40:40 den Exp $
*/
#ifndef __FLOW_H_
#define __FLOW_H_
#define DISK_MIN 2048
#define HAMMER_MIN 51200
#if defined(__i386__)
#define SWAP_MAX 32768
#elif defined(__x86_64__)
#define SWAP_MAX 524288
#endif
#define MTPT_ROOT 0
#define MTPT_SWAP 1
#define MTPT_VAR 2
#define MTPT_TMP 3
#define MTPT_USR 4
#define MTPT_HOME 5
struct i_fn_args;
int use_hammer;
int during_install;
/*** PROTOTYPES ***/
/* Menus */
#ifdef ENABLE_NLS
void state_lang_menu(struct i_fn_args *);
#endif
void state_welcome(struct i_fn_args *);
void state_welcome_system(struct i_fn_args *);
void state_configure_menu(struct i_fn_args *);
void state_utilities_menu(struct i_fn_args *);
void state_environment_menu(struct i_fn_args *);
void state_diagnostics_menu(struct i_fn_args *);
void state_diskutil_menu(struct i_fn_args *);
/* Install */
void state_begin_install(struct i_fn_args *);
void state_begin_upgrade(struct i_fn_args *);
void state_select_disk(struct i_fn_args *);
void state_ask_fs(struct i_fn_args *);
void state_format_disk(struct i_fn_args *);
void state_select_slice(struct i_fn_args *);
void state_create_subpartitions(struct i_fn_args *);
void state_install_os(struct i_fn_args *);
void state_install_bootstrap(struct i_fn_args *);
void state_finish_install(struct i_fn_args *);
void state_reboot(struct i_fn_args *);
void state_setup_remote_installation_server(struct i_fn_args *);
/* Entry Point */
int flow(int, char *, char *, int livecd_configuration, int upgrade_menu_toggle);
#endif /* !__FLOW_H_ */
|
asceenl/lasp
|
lasp/lasp_atomic.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Provides a simple atomic variable:
>>> a = Atomic(0)
Retrieve the value
>>> b = a()
Set a new value:
>>> a <<= b
Get conversion to boolean:
>>> if a:
do something
Atomic increment:
>>> A += 1
@author: <NAME> - ASCEE
"""
from threading import Lock
class Atomic:
def __init__(self, val):
self._val = val
self._lock = Lock()
def __iadd__(self, toadd):
with self._lock:
self._val += toadd
return self
def __isub__(self, toadd):
with self._lock:
self._val -= toadd
return self
def __bool__(self):
with self._lock:
return self._val
def __ilshift__(self, other):
with self._lock:
self._val = other
return self
def __call__(self):
with self._lock:
return self._val
|
dtk/dtk-server
|
application/model/task/template/content/action_match.rb
|
<reponame>dtk/dtk-server
#
# Copyright (C) 2010-2016 dtk contributors
#
# This file is part of the dtk project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module DTK; class Task; class Template
class Content
class ActionMatch
def initialize(insert_action = nil)
@insert_action = insert_action
# the rest of these attributes are about what matched
@action = nil
@in_multinode_stage = nil
@internode_stage_index = nil
@execution_block_index = nil
@action_position = nil
end
attr_accessor :insert_action, :action, :internode_stage_index, :execution_block_index, :action_position, :in_multinode_stage
def node_id
@action && @action.node_id
end
def match_found?
!@action.nil?
end
def is_assembly_wide?
@action && @action.node && @action.node.is_assembly_wide_node?
end
end
end
end; end; end
|
thariyarox/ORG-carbon-identity
|
components/identity/org.wso2.carbon.identity.provider/src/main/java/org/wso2/carbon/identity/provider/openid/dao/OpenIDAssociationDAO.java
|
/*
* Copyright 2005-2008 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.provider.openid.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.axiom.om.util.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openid4java.association.Association;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.persistence.JDBCPersistenceManager;
import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil;
import org.wso2.carbon.identity.provider.openid.OpenIDServerConstants;
/**
* The DAO used to access the identity database. This basically store, load and
* remove associations from the database.
*
* @author WSO2 Inc.
*
*/
public class OpenIDAssociationDAO {
private String associationStore;
private static Log log = LogFactory.getLog(OpenIDAssociationDAO.class);
/**
* Create the DAO with the identity database connection.
*
* @param dbConnection
* @param privateAssociations
* if this DAO stores private associations
*/
public OpenIDAssociationDAO(String storeType) {
associationStore = storeType;
}
/**
* Tries to store the association in the identity database. But if the entry
* already exists this operation doesn't do anything useful.
*
* @param association
*/
public synchronized void storeAssociation(Association association) {
Connection connection = null;
PreparedStatement prepStmt = null;
try {
connection = JDBCPersistenceManager.getInstance().getDBConnection();
if (!isAssociationExist(connection, association.getHandle())) {
prepStmt = connection.prepareStatement(OpenIDSQLQueries.STORE_ASSOCIATION);
prepStmt.setString(1, association.getHandle());
prepStmt.setString(2, association.getType());
prepStmt.setTimestamp(3, new java.sql.Timestamp(association.getExpiry().getTime()));
prepStmt.setString(4, Base64.encode(association.getMacKey().getEncoded()));
prepStmt.setString(5, associationStore);
prepStmt.execute();
connection.commit();
log.debug("Association " + association.getHandle() +
" successfully stored in the database.");
} else {
log.debug("Association " + association.getHandle() +
" already exist in the databse.");
}
} catch (SQLException e) {
log.error("Failed to store the association " + association.getHandle() +
". Error while accessing the database. ", e);
} catch (IdentityException e) {
log.error("Failed to store the association " + association.getHandle() +
". Error while accessing the database. ", e);
} finally {
IdentityDatabaseUtil.closeStatement(prepStmt);
IdentityDatabaseUtil.closeConnection(connection);
}
}
/**
* Loads the association in the identity database.
*
* @param handle
* @return <code>Association</code>
*/
public synchronized Association loadAssociation(String handle) {
Connection connection = null;
PreparedStatement prepStmt = null;
ResultSet results = null;
try {
connection = JDBCPersistenceManager.getInstance().getDBConnection();
prepStmt = connection.prepareStatement(OpenIDSQLQueries.LOAD_ASSOCIATION);
prepStmt.setString(1, handle);
results = prepStmt.executeQuery();
if (results.next()) {
log.debug("Loading association " + handle);
return buildAssociationObject(results);
}
} catch (SQLException e) {
log.error("Failed to load the association " + handle +
". Error while accessing the database. ", e);
} catch (IdentityException e) {
log.error("Failed to load the association " + handle +
". Error while accessing the database. ", e);
} finally {
IdentityDatabaseUtil.closeAllConnections(connection, results, prepStmt);
}
log.debug("Failed to load the association " + handle + " from the database.");
return null;
}
/**
* Tries to remove the association from the database. But if the entry
* doesn't exist, then this method throws an exception.
*
* @param handle
*/
public synchronized void removeAssociation(String handle) {
Connection connection = null;
PreparedStatement prepStmt = null;
try {
connection = JDBCPersistenceManager.getInstance().getDBConnection();
if (isAssociationExist(connection, handle)) {
prepStmt = connection.prepareStatement(OpenIDSQLQueries.REMOVE_ASSOCIATION);
prepStmt.setString(1, handle);
prepStmt.execute();
connection.commit();
log.debug("Association " + handle + " successfully removed from the database.");
} else {
log.debug("Association " + handle + " does not exist in the databse.");
}
} catch (SQLException e) {
log.error("Failed to remove the association " + handle +
". Error while accessing the database. ", e);
} catch (IdentityException e) {
log.error("Failed to remove the association " + handle +
". Error while accessing the database. ", e);
} finally {
IdentityDatabaseUtil.closeStatement(prepStmt);
IdentityDatabaseUtil.closeConnection(connection);
}
}
/**
* Check if the entry exist in the database
*
* @param connection
* @return boolean
* @throws SQLException
*/
private synchronized boolean isAssociationExist(Connection connection, String handle) {
PreparedStatement prepStmt = null;
ResultSet results = null;
boolean result = false;
try {
prepStmt = connection.prepareStatement(OpenIDSQLQueries.CHECK_ASSOCIATION_ENTRY_EXIST);
prepStmt.setString(1, handle);
results = prepStmt.executeQuery();
if (results.next()) {
result = true;
log.debug("Association " + handle + " found");
}
} catch (SQLException e) {
log.error("Failed to load the association " + handle +
". Error while accessing the database. ", e);
} finally {
IdentityDatabaseUtil.closeResultSet(results);
IdentityDatabaseUtil.closeStatement(prepStmt);
}
log.debug("Association " + handle + " not found");
return result;
}
/**
* Builds the Association object
*
* @param results
* @return <code>Association</code>
* @throws SQLException
*/
private synchronized Association buildAssociationObject(ResultSet results) {
Association assoc = null;
String assocHandle = null;
try {
assocHandle = results.getString(1);
String assocType = results.getString(2);
java.util.Date expireIn = new java.util.Date(results.getTimestamp(3).getTime());
String macKey = results.getString(4);
String assocStore = results.getString(5);
// we check if params are missing
if (assocHandle == null || assocType == null || expireIn == null || macKey == null ||
assocStore == null) {
log.error("Required data missing. Cannot build the Association object");
return null;
}
// Here we check if we are loading the correct associations
if (associationStore.equals(OpenIDServerConstants.ASSOCIATION_STORE_TYPE_PRIVATE) &&
assocStore.equals(OpenIDServerConstants.ASSOCIATION_STORE_TYPE_SHARED)) {
log.error("Invalid association data found. Tried to load a Private Association but found a Shared Association");
return null;
} else if (associationStore.equals(OpenIDServerConstants.ASSOCIATION_STORE_TYPE_SHARED) &&
assocStore.equals(OpenIDServerConstants.ASSOCIATION_STORE_TYPE_PRIVATE)) {
log.error("Invalid association data found. Tried to load a Shared Association but found a Private Association");
return null;
}
// Checks for association handle
if (Association.TYPE_HMAC_SHA1.equals(assocType)) {
assoc = Association.createHmacSha1(assocHandle, Base64.decode(macKey), expireIn);
} else if (Association.TYPE_HMAC_SHA256.equals(assocType)) {
assoc =
Association.createHmacSha256(assocHandle, Base64.decode(macKey), expireIn);
} else {
log.error("Invalid association type " + assocType + " loaded from database");
return null;
}
} catch (SQLException e) {
log.error("Failed to build the Association for "+ assocHandle + ". Error while accessing the database.",e);
} finally {
IdentityDatabaseUtil.closeResultSet(results);
}
log.debug("Association " + assocHandle + " loaded successfully from the database.");
return assoc;
}
}
|
jaouahbi/VampPlugins
|
marsyas-vamp/marsyas/src/marsyas/marsystems/HarmonicStrength.h
|
/*
** Copyright (C) 1998-2010 <NAME> <<EMAIL>>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef MARSYAS_HARMONICSTRENGTH_H
#define MARSYAS_HARMONICSTRENGTH_H
#include <marsyas/system/MarSystem.h>
namespace Marsyas
{
/**
\class HarmonicStrength
\ingroup Processing
\brief Calculates the relative strength of harmonics
Calculates the strength of multiples of the base_frequency
compared to the overall spectrum rms.
Controls:
- \b mrs_real/base_frequency [w] : sets the fundamental
frequency.
- \b mrs_realvec/harmonics [w] : which harmonics to examine.
Need not be integer multiples (e.g. 0.5, 1.5, is ok)
- \b mrs_realvec/harmonicsSize [w] : how many harmonics
(long story, it's a workaround for some weird memory thing)
- \b mrs_real/harmonicsWidth [w] : percent of frequency range to
search for a peak.
- \b mrs_natural/type [w] : 0 = output harmonic strength
relative to spectrum rms; 1 = output absolute (interpolated)
power of harmonic strength; 2 = log of #1
-b \b mrs_real/inharmonicity_B : string stiffness
*/
class marsyas_EXPORT HarmonicStrength: public MarSystem
{
private:
/// Add specific controls needed by this MarSystem.
void addControls();
/// Reads changed controls and sets up variables if necessary.
void myUpdate(MarControlPtr sender);
MarControlPtr ctrl_base_frequency_;
MarControlPtr ctrl_harmonics_;
MarControlPtr ctrl_harmonicsSize_;
MarControlPtr ctrl_harmonicsWidth_;
MarControlPtr ctrl_inharmonicity_B_;
mrs_real find_peak_magnitude(mrs_real central_bin,
mrs_realvec& in, mrs_natural t,
mrs_real low, mrs_real high);
mrs_real quadratic_interpolation(mrs_real best_bin,
mrs_realvec& in, mrs_natural t);
public:
/// HarmonicStrength constructor.
HarmonicStrength(std::string name);
/// HarmonicStrength copy constructor.
HarmonicStrength(const HarmonicStrength& a);
/// HarmonicStrength destructor.
~HarmonicStrength();
/// Implementation of the MarSystem::clone() method.
MarSystem* clone() const;
/// Implementation of the MarSystem::myProcess method.
void myProcess(realvec& in, realvec& out);
};
}
//namespace Marsyas
#endif
//MARSYAS_HARMONICSTRENGTH_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.