text
stringlengths
2
1.04M
meta
dict
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; class Solution { public static void main(String args[]) { Scanner in = new Scanner(System.in); int R = in.nextInt(); int L = in.nextInt(); List<Integer> sequenceLine = getSequenceLine(R, L); printSequenceLine(sequenceLine); } private static List<Integer> getSequenceLine(int first, int lineNumber) { List<Integer> currentLine = new ArrayList<>(); currentLine.add(Integer.valueOf(first)); for (int i = 2; i <= lineNumber; i++) { currentLine = getNextSequenceLine(currentLine); } return currentLine; } private static List<Integer> getNextSequenceLine(List<Integer> currentLine) { List<Integer> nextLine = new ArrayList<>(); int startIndex = 0, currentIndex = 1; while (currentIndex < currentLine.size()) { if (currentLine.get(startIndex) != currentLine.get(currentIndex)) { nextLine.add(currentIndex - startIndex); nextLine.add(currentLine.get(startIndex)); startIndex = currentIndex; } currentIndex++; } nextLine.add(currentIndex - startIndex); nextLine.add(currentLine.get(startIndex)); return nextLine; } private static void printSequenceLine(List<Integer> sequenceLine) { System.out.println(sequenceLine.stream().map(i -> i.toString()).collect(Collectors.joining(" "))); } }
{ "content_hash": "2ac34ebdf12f42bb61a5aebb2569acd2", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 100, "avg_line_length": 26.181818181818183, "alnum_prop": 0.68125, "repo_name": "fabriziocucci/CodinGame", "id": "77efff65c73fc150817b5a767397da1efe610cda", "size": "1440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "medium/conway-sequence/java/src/main/java/Solution.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "3360" }, { "name": "Java", "bytes": "80650" } ], "symlink_target": "" }
/** * Implementation specific classes relating to {@link net.tridentsdk.event}.* */ package net.tridentsdk.server.event;
{ "content_hash": "440b89456753e66d94b7c4b56ada7fbd", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 77, "avg_line_length": 24.6, "alnum_prop": 0.7479674796747967, "repo_name": "orangelynx/Trident", "id": "9d24cf4425d8f4a5b9ac80ece30123f68a017b08", "size": "772", "binary": false, "copies": "3", "ref": "refs/heads/bleeding-edge", "path": "src/main/java/net/tridentsdk/server/event/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "15410" }, { "name": "Java", "bytes": "874832" }, { "name": "Shell", "bytes": "2113" } ], "symlink_target": "" }
<def-group> <definition class="compliance" id="set_iptables_default_rule" version="2"> <metadata> <title>Change the default policy to DROP (from ACCEPT) for the INPUT built-in chain</title> <affected family="unix"> <platform>Red Hat Enterprise Linux 6</platform> </affected> <description>Change the default policy to DROP (from ACCEPT) for the INPUT built-in chain.</description> <reference source="DS" ref_id="20131011" ref_url="test_attestation" /> </metadata> <criteria> <criterion comment=":INPUT DROP [0:0]" test_ref="test_iptables_input_drop" /> <criterion comment=":INPUT ACCEPT [0:0]" negate="true" test_ref="test_iptables_input_accept" /> </criteria> </definition> <ind:textfilecontent54_test check="all" check_existence="at_least_one_exists" comment="Check /etc/sysconfig/iptables for line :INPUT DROP [0:0]" id="test_iptables_input_drop" version="1"> <ind:object object_ref="obj_iptables_input_drop" /> </ind:textfilecontent54_test> <ind:textfilecontent54_object id="obj_iptables_input_drop" version="1"> <ind:filepath>/etc/sysconfig/iptables</ind:filepath> <ind:pattern operation="pattern match">^[\s]*:INPUT\sDROP\s\[0:0\]</ind:pattern> <ind:instance datatype="int">1</ind:instance> </ind:textfilecontent54_object> <ind:textfilecontent54_test check="all" check_existence="at_least_one_exists" comment="Check /etc/sysconfig/iptables for line :INPUT ACCEPT [0:0]" id="test_iptables_input_accept" version="1"> <ind:object object_ref="obj_iptables_input_accept" /> </ind:textfilecontent54_test> <ind:textfilecontent54_object id="obj_iptables_input_accept" version="1"> <ind:filepath>/etc/sysconfig/iptables</ind:filepath> <ind:pattern operation="pattern match">^[\s]*:INPUT\sACCEPT\s\[0:0\]</ind:pattern> <ind:instance datatype="int">1</ind:instance> </ind:textfilecontent54_object> </def-group>
{ "content_hash": "3c73b55bfed6986cafe062dfe9a883d4", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 101, "avg_line_length": 43.71111111111111, "alnum_prop": 0.688357905439756, "repo_name": "ykhodorkovskiy/clip", "id": "1e6db123c24bdd22f2b1b00e2af5a852a2103992", "size": "1967", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/scap-security-guide/scap-security-guide-0.1.20/RHEL/6/input/checks/set_iptables_default_rule.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "209" }, { "name": "C", "bytes": "13809" }, { "name": "Groff", "bytes": "246662" }, { "name": "HTML", "bytes": "1333" }, { "name": "Makefile", "bytes": "88495" }, { "name": "Python", "bytes": "95048" }, { "name": "Shell", "bytes": "17539" } ], "symlink_target": "" }
package main import ( "fmt" "strings" "time" "github.com/influxdata/influxdb/client/v2" "github.com/miaolz123/conver" "github.com/miaolz123/stockdb/stockdb" ) type influxdb struct { client client.Client status int64 } // newInfluxdb create a Influxdb struct func newInfluxdb() Driver { var err error driver := &influxdb{} driver.client, err = client.NewHTTPClient(client.HTTPConfig{ Addr: config["influxdb.host"], Username: config["influxdb.username"], Password: config["influxdb.password"], }) if err != nil { log(logFatal, "Influxdb connect error: ", err) } if _, _, err := driver.client.Ping(30 * time.Second); err != nil { log(logError, "Influxdb connect error: ", err) } else { driver.status = 1 log(logSuccess, "Influxdb connect successfully") } go func(driver *influxdb) { for { if _, _, err := driver.client.Ping(30 * time.Second); err != nil { driver.status = 0 driver.reconnect() } time.Sleep(time.Minute) } }(driver) return driver } // reconnect the client func (driver *influxdb) reconnect() { for { time.Sleep(1 * time.Minute) var err error if driver.client, err = client.NewHTTPClient(client.HTTPConfig{ Addr: config["influxdb.host"], Username: config["influxdb.username"], Password: config["influxdb.password"], }); err == nil { if _, _, err = driver.client.Ping(30 * time.Second); err == nil { log(logSuccess, "Influxdb reconnect successfully") driver.status = 1 break } } log(logError, "Influxdb reconnect error: ", err) time.Sleep(2 * time.Minute) } } // close this client func (driver *influxdb) close() error { log(logSuccess, "Influxdb disconnected successfully") return driver.client.Close() } // check the client is connected func (driver *influxdb) check() error { if driver.status < 1 { return errInfluxdbNotConnected } return nil } // putMarket create a new market to stockdb func (driver *influxdb) putMarket(market string) (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } q := client.NewQuery(fmt.Sprintf(`CREATE DATABASE "market_%s"`, market), "", "") if response, err := driver.client.Query(q); err != nil { log(logError, err) resp.Message = err.Error() return } else if err = response.Error(); err != nil { log(logError, err) resp.Message = err.Error() return } resp.Success = true return } // records2BatchPoints parse struct from OHLC to BatchPoints func (driver *influxdb) records2BatchPoints(data []stockdb.OHLC, opt stockdb.Option) (bp client.BatchPoints, err error) { if driver.status < 1 { err = errInfluxdbNotConnected return } bp, err = client.NewBatchPoints(client.BatchPointsConfig{ Database: "market_" + opt.Market, Precision: "s", }) if err != nil { return } timeOffsets := [4]int64{0, 1, 1, 2} for _, datum := range data { tags := [4]map[string]string{ {"type": "open"}, {"type": "high"}, {"type": "low"}, {"type": "close"}, } fields := [4]map[string]interface{}{ {"price": datum.Open}, {"price": datum.High}, {"price": datum.Low}, {"price": datum.Close}, } for i := 0; i < 4; i++ { tags[i]["id"] = fmt.Sprint(opt.Period) fields[i]["period"] = opt.Period fields[i]["amount"] = datum.Volume / 4.0 pt, err := client.NewPoint("symbol_"+opt.Symbol, tags[i], fields[i], time.Unix(datum.Time+timeOffsets[i], 0)) if err != nil { return bp, err } bp.AddPoint(pt) } } return } // PutOHLC add an OHLC record to stockdb func (driver *influxdb) PutOHLC(datum stockdb.OHLC, opt stockdb.Option) (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } if opt.Market == "" { opt.Market = defaultOption.Market } if opt.Symbol == "" { opt.Symbol = defaultOption.Symbol } if opt.Period < minPeriod { opt.Period = defaultOption.Period } bp, err := driver.records2BatchPoints([]stockdb.OHLC{datum}, opt) if err != nil { log(logError, err) resp.Message = err.Error() return } if err := driver.client.Write(bp); err != nil { if strings.Contains(err.Error(), "database not found") { resp = driver.putMarket(opt.Market) if resp.Success { return driver.PutOHLC(datum, opt) } return } log(logError, err) resp.Message = err.Error() return } resp.Success = true return } // PutOHLCs add OHLC records to stockdb func (driver *influxdb) PutOHLCs(data []stockdb.OHLC, opt stockdb.Option) (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } if opt.Market == "" { opt.Market = defaultOption.Market } if opt.Symbol == "" { opt.Symbol = defaultOption.Symbol } if opt.Period < minPeriod { opt.Period = defaultOption.Period } bp, err := driver.records2BatchPoints(data, opt) if err != nil { log(logError, err) resp.Message = err.Error() return } if err := driver.client.Write(bp); err != nil { if strings.Contains(err.Error(), "database not found") { resp = driver.putMarket(opt.Market) if resp.Success { return driver.PutOHLCs(data, opt) } return } log(logError, err) resp.Message = err.Error() return } resp.Success = true return } // orders2BatchPoints parse struct from Order to BatchPoints func (driver *influxdb) orders2BatchPoints(data []stockdb.Order, opt stockdb.Option) (bp client.BatchPoints, err error) { if driver.status < 1 { err = errInfluxdbNotConnected return } bp, err = client.NewBatchPoints(client.BatchPointsConfig{ Database: "market_" + opt.Market, Precision: "s", }) if err != nil { return } for _, datum := range data { if datum.ID == "" { datum.ID = fmt.Sprint(datum.Type, datum.Amount, "@", datum.Price) } tag := map[string]string{ "id": datum.ID, "type": datum.Type, } field := map[string]interface{}{ "period": 0, "price": datum.Price, "amount": datum.Amount, } pt, err := client.NewPoint("symbol_"+opt.Symbol, tag, field, time.Unix(datum.Time, 0)) if err != nil { return bp, err } bp.AddPoint(pt) } return } // PutOrder add an order record to stockdb func (driver *influxdb) PutOrder(datum stockdb.Order, opt stockdb.Option) (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } if opt.Market == "" { opt.Market = defaultOption.Market } if opt.Symbol == "" { opt.Symbol = defaultOption.Symbol } bp, err := driver.orders2BatchPoints([]stockdb.Order{datum}, opt) if err != nil { log(logError, err) resp.Message = err.Error() return } if err := driver.client.Write(bp); err != nil { if strings.Contains(err.Error(), "database not found") { resp = driver.putMarket(opt.Market) if resp.Success { return driver.PutOrder(datum, opt) } return } log(logError, err) resp.Message = err.Error() return } resp.Success = true return } // PutOrders add order records to stockdb func (driver *influxdb) PutOrders(data []stockdb.Order, opt stockdb.Option) (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } if opt.Market == "" { opt.Market = defaultOption.Market } if opt.Symbol == "" { opt.Symbol = defaultOption.Symbol } bp, err := driver.orders2BatchPoints(data, opt) if err != nil { log(logError, err) resp.Message = err.Error() return } if err := driver.client.Write(bp); err != nil { if strings.Contains(err.Error(), "database not found") { resp = driver.putMarket(opt.Market) if resp.Success { return driver.PutOrders(data, opt) } return } log(logError, err) resp.Message = err.Error() return } resp.Success = true return } // GetStats return the stats of StockDB func (driver *influxdb) GetStats() (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } stats := make(map[string]stockdb.Stats) q := client.NewQuery("SHOW STATS FOR 'shard'", "", "s") if response, err := driver.client.Query(q); err == nil && response.Err == "" && len(response.Results) > 0 { result := response.Results[0] if result.Err == "" { for _, series := range result.Series { if strings.Contains(series.Tags["database"], "market_") { market := strings.TrimPrefix(series.Tags["database"], "market_") s := stats[market] s.Market = market s.Disk += conver.Int64Must(series.Values[0][0]) stats[market] = s } } } } data := []stockdb.Stats{} for _, s := range stats { q := client.NewQuery("SELECT COUNT(price) FROM /symbol_/", "market_"+s.Market, "s") if response, err := driver.client.Query(q); err == nil && response.Err == "" && len(response.Results) > 0 { result := response.Results[0] if result.Err == "" { for _, series := range result.Series { if len(series.Values) > 0 { s.Record += conver.Int64Must(series.Values[0][1]) } } } } data = append(data, s) } resp.Data = data resp.Success = true return } // getTimeRange return the first and the last record time func (driver *influxdb) getTimeRange(opt stockdb.Option) (ranges [2]int64) { params := [2]string{"FIRST", "LAST"} for i, param := range params { raw := fmt.Sprintf(`SELECT %v("price") FROM "symbol_%v"`, param, opt.Symbol) q := client.NewQuery(raw, "market_"+opt.Market, "s") if response, err := driver.client.Query(q); err == nil && response.Err == "" && len(response.Results) > 0 { result := response.Results[0] if result.Err == "" && len(result.Series) > 0 && len(result.Series[0].Values) > 0 && len(result.Series[0].Values[0]) > 0 { ranges[i] = conver.Int64Must(result.Series[0].Values[0][0]) } } } return } // GetMarkets return the list of market name func (driver *influxdb) GetMarkets() (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } data := []string{} q := client.NewQuery("SHOW DATABASES", "", "s") if response, err := driver.client.Query(q); err == nil && response.Err == "" && len(response.Results) > 0 { result := response.Results[0] if result.Err == "" && len(result.Series) > 0 && len(result.Series[0].Values) > 0 { for _, v := range result.Series[0].Values { if len(v) > 0 { name := fmt.Sprint(v[0]) if strings.HasPrefix(name, "market_") { data = append(data, strings.TrimPrefix(name, "market_")) } } } } } resp.Data = data resp.Success = true return } // GetSymbols return the list of symbol name func (driver *influxdb) GetSymbols(market string) (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } data := []string{} q := client.NewQuery("SHOW MEASUREMENTS", "market_"+market, "s") if response, err := driver.client.Query(q); err == nil && response.Err == "" && len(response.Results) > 0 { result := response.Results[0] if result.Err == "" && len(result.Series) > 0 && len(result.Series[0].Values) > 0 { for _, v := range result.Series[0].Values { if len(v) > 0 { name := fmt.Sprint(v[0]) if strings.HasPrefix(name, "symbol_") { data = append(data, strings.TrimPrefix(name, "symbol_")) } } } } } resp.Data = data resp.Success = true return } // GetTimeRange return the first and the last record time func (driver *influxdb) GetTimeRange(opt stockdb.Option) (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } if opt.Market == "" { opt.Market = defaultOption.Market } if opt.Symbol == "" { opt.Symbol = defaultOption.Symbol } resp.Data = driver.getTimeRange(opt) resp.Success = true return } // GetPeriodRange return the min and the max record period func (driver *influxdb) GetPeriodRange(opt stockdb.Option) (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } data := [2]int64{0, 0} q := client.NewQuery(fmt.Sprintf(`SELECT MIN("period") FROM "symbol_%v"`, opt.Symbol), "market_"+opt.Market, "s") if response, err := driver.client.Query(q); err == nil && response.Err == "" && len(response.Results) > 0 { result := response.Results[0] if result.Err == "" && len(result.Series) > 0 && len(result.Series[0].Values) > 0 && len(result.Series[0].Values[0]) > 1 { data[0] = conver.Int64Must(result.Series[0].Values[0][1]) ranges := driver.getTimeRange(opt) data[1] = ranges[1] - ranges[0] } } resp.Data = data resp.Success = true return } // getOHLCQuery return a query of OHLC func (driver *influxdb) getOHLCQuery(opt stockdb.Option) (q client.Query) { ranges := driver.getTimeRange(opt) if opt.EndTime <= 0 || opt.EndTime > ranges[1] { opt.EndTime = ranges[1] } if opt.BeginTime <= 0 { opt.BeginTime = opt.EndTime - 999*opt.Period } if opt.BeginTime < ranges[0] { opt.BeginTime = ranges[0] } raw := fmt.Sprintf(`SELECT FIRST("price"), MAX("price"), MIN("price"), LAST("price"), SUM("amount") FROM "symbol_%v" WHERE "period" <= %v AND time >= %vs AND time < %vs GROUP BY time(%vs)`, opt.Symbol, opt.Period, opt.BeginTime, opt.EndTime, opt.Period) q = client.NewQuery(raw, "market_"+opt.Market, "s") return q } // result2ohlc parse record result to OHLC func (driver *influxdb) result2ohlc(result client.Result, opt stockdb.Option) (data []stockdb.OHLC) { if len(result.Series) > 0 { serie := result.Series[0] offset := 0 for i := range serie.Values { d := stockdb.OHLC{ Time: conver.Int64Must(serie.Values[i][0]), Volume: conver.Float64Must(serie.Values[i][5]), } if conver.Float64Must(serie.Values[i][3]) <= 0.0 { if opt.InvalidPolicy != "ibid" { continue } offset++ if i-offset < 0 { offset = 0 continue } d.Open = conver.Float64Must(serie.Values[i-offset][4]) d.High = conver.Float64Must(serie.Values[i-offset][4]) d.Low = conver.Float64Must(serie.Values[i-offset][4]) d.Close = conver.Float64Must(serie.Values[i-offset][4]) } else { offset = 0 d.Open = conver.Float64Must(serie.Values[i][1]) d.High = conver.Float64Must(serie.Values[i][2]) d.Low = conver.Float64Must(serie.Values[i][3]) d.Close = conver.Float64Must(serie.Values[i][4]) } data = append(data, d) } } return } // GetOHLC get OHLC records func (driver *influxdb) GetOHLCs(opt stockdb.Option) (resp response) { if err := driver.check(); err != nil { log(logError, 367, err) resp.Message = err.Error() return } if opt.Market == "" { opt.Market = defaultOption.Market } if opt.Symbol == "" { opt.Symbol = defaultOption.Symbol } if opt.Period < minPeriod { opt.Period = defaultOption.Period } if response, err := driver.client.Query(driver.getOHLCQuery(opt)); err != nil { log(logError, err) resp.Message = err.Error() return } else if response.Err != "" { log(logError, response.Err) resp.Message = response.Err return } else if len(response.Results) > 0 { result := response.Results[0] if result.Err != "" { log(logError, result.Err) resp.Message = result.Err return } resp.Data = driver.result2ohlc(result, opt) resp.Success = true } return } // getDepthQuery return a query of market depth func (driver *influxdb) getDepthQuery(opt stockdb.Option) (q client.Query) { ranges := driver.getTimeRange(opt) if opt.BeginTime <= 0 || opt.BeginTime > ranges[1] { opt.BeginTime = ranges[1] } raw := fmt.Sprintf(`SELECT price, amount, type FROM "symbol_%v" WHERE time >= %vs AND time <= %vs LIMIT 300`, opt.Symbol, opt.BeginTime, opt.BeginTime+opt.Period) q = client.NewQuery(raw, "market_"+opt.Market, "s") return q } // result2depth parse result to market depth func (driver *influxdb) result2depth(result client.Result, opt stockdb.Option) (data stockdb.Depth) { if len(result.Series) > 0 { serie := result.Series[0] d := struct { open float64 high float64 low float64 dif float64 volume float64 }{} for i := range serie.Values { if _type := fmt.Sprint(serie.Values[i][2]); _type == "high" || _type == "low" { continue } price := conver.Float64Must(serie.Values[i][1]) if d.open == 0.0 { d.open = price d.high = price d.low = price } if price > d.high { d.high = price } if price < d.low { d.low = price } d.volume += conver.Float64Must(serie.Values[i][2]) } d.dif = d.high - d.low if d.dif > 0.0 { for i := 0; i <= 10; i++ { price := d.low + d.dif/10*conver.Float64Must(i) if i == 0 || price <= d.open { data.Bids = append([]stockdb.OrderBook{{ Price: price, Amount: d.volume / 10.0, }}, data.Bids...) } else if i == 10 || price >= d.open { data.Asks = append(data.Asks, stockdb.OrderBook{ Price: price, Amount: d.volume / 10.0, }) } } } } return } // GetDepth get simulated market depth func (driver *influxdb) GetDepth(opt stockdb.Option) (resp response) { if err := driver.check(); err != nil { log(logError, err) resp.Message = err.Error() return } if opt.Market == "" { opt.Market = defaultOption.Market } if opt.Symbol == "" { opt.Symbol = defaultOption.Symbol } if opt.Period < 0 { opt.Period = 0 } if response, err := driver.client.Query(driver.getDepthQuery(opt)); err != nil { log(logError, err) resp.Message = err.Error() return } else if response.Err != "" { log(logError, response.Err) resp.Message = response.Err return } else if len(response.Results) > 0 { result := response.Results[0] if result.Err != "" { log(logError, result.Err) resp.Message = result.Err return } resp.Data = driver.result2depth(result, opt) resp.Success = true } return }
{ "content_hash": "42dcbef2ae9586bcf7201c873e1fa5c0", "timestamp": "", "source": "github", "line_count": 669, "max_line_length": 125, "avg_line_length": 26.66965620328849, "alnum_prop": 0.6394462504203564, "repo_name": "miaolz123/stockdb", "id": "bd342f5c7a294ab7ba1c1250ffc7040f8635e915", "size": "17842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "influxdb.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3336" }, { "name": "Go", "bytes": "35106" }, { "name": "JavaScript", "bytes": "24561" }, { "name": "Makefile", "bytes": "55" }, { "name": "Shell", "bytes": "102" }, { "name": "Smarty", "bytes": "350" } ], "symlink_target": "" }
require "test_helper" require "stringio" class SnappyReaderTest < Test::Unit::TestCase def setup @buffer = StringIO.new Snappy::Writer.new @buffer do |w| w << "foo" w << "bar" w << "baz" w << "quux" end @buffer.rewind end def subject @subject ||= Snappy::Reader.new @buffer end sub_test_case "#initialize" do test "should yield itself to the block" do yielded = nil returned = Snappy::Reader.new @buffer do |r| yielded = r end assert_equal returned, yielded end test "should read the header" do assert_equal Snappy::Writer::MAGIC, subject.magic assert_equal Snappy::Writer::DEFAULT_VERSION, subject.default_version assert_equal Snappy::Writer::MINIMUM_COMPATIBLE_VERSION, subject.minimum_compatible_version end end sub_test_case :initialize_without_headers do def setup @buffer = StringIO.new @buffer << Snappy.deflate("HelloWorld" * 10) @buffer.rewind end test "should inflate with a magic header" do assert_equal "HelloWorld" * 10, subject.read end test "should not receive `length' in eaching" do dont_allow(@buffer).length subject.read end end sub_test_case "#io" do test "should be a constructor argument" do assert_equal @buffer, subject.io end test "should not receive `length' in initializing" do dont_allow(@buffer).length Snappy::Reader.new @buffer end end sub_test_case "#each" do def setup @buffer = StringIO.new Snappy::Writer.new @buffer do |w| w << "foo" w << "bar" w.dump! w << "baz" w << "quux" end @buffer.rewind end test "should yield each chunk" do chunks = [] subject.each do |chunk| chunks << chunk end assert_equal %w[foobar bazquux], chunks end test "should return enumerator w/o block" do eacher = subject.each assert_instance_of Enumerator, eacher chunks = [] chunks << eacher.next chunks << eacher.next assert_raise(StopIteration) { eacher.next } assert_equal %w[foobar bazquux], chunks end end sub_test_case "#read" do test "should return the bytes" do assert_equal "foobarbazquux", subject.read end end sub_test_case "#each_line" do def setup @buffer = StringIO.new Snappy::Writer.new @buffer do |w| w << "foo\n" w << "bar" w.dump! w << "baz\n" w << "quux\n" end @buffer.rewind end test "should yield each line" do lines = [] subject.each_line do |line| lines << line end assert_equal %w[foo barbaz quux], lines end test "should return enumerator w/o block" do eacher = subject.each_line assert_instance_of Enumerator, eacher lines = [] loop { lines << eacher.next } assert_equal %w[foo barbaz quux], lines end test "each_line split by sep_string" do buffer = StringIO.new Snappy::Writer.new buffer do |w| w << %w[a b c].join(",") w.dump! w << %w[d e f].join(",") end buffer.rewind reader = Snappy::Reader.new buffer eacher = reader.each_line(",") lines = [] loop { lines << eacher.next } assert_equal %w[a b cd e f], lines end end end
{ "content_hash": "85e61517f1de35aa18962d3f7d8fafb5", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 97, "avg_line_length": 23.493150684931507, "alnum_prop": 0.5857142857142857, "repo_name": "miyucy/snappy", "id": "7621887217199b8ec2cc6b0db111abbc2ed9bb7f", "size": "3461", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/snappy_reader_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2951" }, { "name": "Dockerfile", "bytes": "253" }, { "name": "Java", "bytes": "2010" }, { "name": "Ruby", "bytes": "22194" }, { "name": "Shell", "bytes": "136" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd" > <!--加载配置文件--> <!--<context:property-placeholder location="classpath:db.properties"/> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> &lt;!&ndash; PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,即我们可以在下面配好多个properties文件 &ndash;&gt; <array> <value>classpath:db.properties</value> </array> </property> </bean>--> <!-- 数据源1 --> <bean id="dataSource_db1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 可不用配置driverClassName--> <!--<property name="driverClassName" value="${jdbc.driverClass}"/>--> <property name="url" value="${db1.url}" /> <property name="username" value="${db1.username}" /> <property name="password" value="${db1.password}" /> <!-- 配置初始化大小、最小空闲、最大连接数--> <property name="initialSize" value="2" /> <property name="minIdle" value="2" /> <property name="maxActive" value="200" /> <!-- 配置获取连接等待超时的时间 单位毫秒 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <!-- 检测连接是否有效的sql,要求是一个查询语句 --> <property name="validationQuery" value="SELECT 1 FROM DUAL" /> <!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 --> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <!-- 申请连接时执行validationQuery检测连接是否有效,不需要检测--> <property name="testOnReturn" value="false" /> <!-- 归还连接时执行validationQuery检测连接是否有效,不需要检测--> <!-- 打开PSCache,如果是mysql,在mysql5.5以下的版本中没有PSCache功能,建议关闭掉。 5.5及以上版本有PSCache,建议开启。 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="100" /> <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 --> <property name="filters" value="stat" /> </bean> <!--数据源2--> <bean id="dataSource_db2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 可不用配置driverClassName--> <!--<property name="driverClassName" value="${jdbc.driverClass}"/>--> <property name="url" value="${db2.url}" /> <property name="username" value="${db2.username}" /> <property name="password" value="${db2.password}" /> <!-- 配置初始化大小、最小空闲、最大连接数--> <property name="initialSize" value="2" /> <property name="minIdle" value="2" /> <property name="maxActive" value="200" /> <!-- 配置获取连接等待超时的时间 单位毫秒 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <!-- 检测连接是否有效的sql,要求是一个查询语句 --> <property name="validationQuery" value="SELECT 1 FROM DUAL" /> <!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 --> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <!-- 申请连接时执行validationQuery检测连接是否有效,不需要检测--> <property name="testOnReturn" value="false" /> <!-- 归还连接时执行validationQuery检测连接是否有效,不需要检测--> <!-- 打开PSCache,如果是mysql,在mysql5.5以下的版本中没有PSCache功能,建议关闭掉。 5.5及以上版本有PSCache,建议开启。 --> <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="100" /> <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 --> <property name="filters" value="stat" /> </bean> <!-- 多数据源配置 --> <bean id ="dataSource" class= "com.ul.core.spring.datasource.DynamicDataSource" > <property name ="targetDataSources"> <map key-type ="java.lang.String"> <entry value-ref ="dataSource_db1" key= "db1"></entry > <entry value-ref ="dataSource_db2" key= "db2"></entry > </map > </property > <!-- 指定默认数据源 --> <property name ="defaultTargetDataSource" ref= "dataSource_db1"></property > </bean> <!-- 动态数据源注解指定切换 @DataSource --> <bean id="dataSourceAspect" class="com.ul.core.spring.datasource.DataSourceAspect"></bean> <aop:config> <aop:aspect ref="dataSourceAspect"> <aop:pointcut id="beforeOperation" expression="execution(* com.ul.biz.*.mapper.*Mapper.*(..))"/> <aop:before pointcut-ref="beforeOperation" method="beforeMethod"/> </aop:aspect> </aop:config> <!-- Spring和MyBatis整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件,**表示迭代查找,classpath后要加*,不然读不到jar包中的配置 --> <property name="mapperLocations" value="classpath*:mapper/*/*Mapper.xml" /> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ul.biz.*.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/> <!-- 注解方式配置事物 在service中使用@Transactional 只回滚运行时异常--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
{ "content_hash": "ad6500caa0ae766dacee9441893c409f", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 139, "avg_line_length": 45.911764705882355, "alnum_prop": 0.646252402306214, "repo_name": "zingson/jsunday", "id": "7208b69012be843cde052f55083299720435086b", "size": "9143", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jsunday-thh/ul-framework/src/main/resources/application-datasource.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "95" }, { "name": "FreeMarker", "bytes": "4772" }, { "name": "HTML", "bytes": "3798" }, { "name": "Java", "bytes": "251444" } ], "symlink_target": "" }
/// <reference path="../interfaces/togeojson.d.ts" /> import pLimit from 'p-limit'; import {OAuth2Client} from 'google-auth-library'; import {ErrorReporting} from '@google-cloud/error-reporting'; import {ITable} from '../interfaces/table'; import {ISheet} from '../interfaces/sheet'; import getCsv from './get-csv'; import updateTableExportProgress from '../export-progress/update-table'; import getArchiveFolder from '../drive/get-archive-folder'; import getFusiontableStyles from '../fusiontables/get-styles'; import getDriveUploadFolder from '../drive/get-upload-folder'; import uploadToDrive from '../drive/upload'; import getArchiveIndexSheet from '../drive/get-archive-index-sheet'; import insertExportRowInIndexSheet from '../drive/insert-export-row-in-index-sheet'; import logFileExportInIndexSheet from '../drive/log-file-export-in-index-sheet'; import addFilePermissions from '../drive/add-file-permissions'; import logExportStart from '../export-log/log-export-start'; import logTableStart from '../export-log/log-table-start'; import logTableFinish from '../export-log/log-table-finish'; import logExportFinish from '../export-log/log-export-finish'; import {web as serverCredentials} from '../config/credentials.json'; import {IStyle} from '../interfaces/style'; import {IFile} from '../interfaces/file'; const errors = new ErrorReporting({ reportUnhandledRejections: true, projectId: serverCredentials.project_id }); /** * Export a table from FusionTables and save it to Drive */ interface IDoExportOptions { ipHash: string; auth: OAuth2Client; exportId: string; tables: ITable[]; } export default async function(options: IDoExportOptions): Promise<string> { const {ipHash, auth, exportId, tables} = options; const limit = pLimit(1); let folderId: string; let archiveSheet: ISheet; logExportStart(exportId, tables.length); try { const archiveFolderId = await getArchiveFolder(auth); [folderId, archiveSheet] = await Promise.all([ getDriveUploadFolder(auth, archiveFolderId), getArchiveIndexSheet(auth, archiveFolderId) ]); await insertExportRowInIndexSheet(auth, archiveSheet, folderId); } catch (error) { throw error; } tables.map((table, index) => limit(() => saveTable({ tableId: index + 1, table, ipHash, auth, folderId, archiveSheet, exportId, isLast: index === tables.length - 1 }) ) ); return folderId; } /** * Save a table from FusionTables to Drive */ interface ISaveTableOptions { tableId: number; table: ITable; ipHash: string; auth: OAuth2Client; folderId: string; archiveSheet: ISheet; exportId: string; isLast: boolean; } async function saveTable(options: ISaveTableOptions): Promise<void> { const {tableId, table, auth, exportId, isLast} = options; const saveStart = Date.now(); let fileSize: number = 0; let roundedFileSize: number = 0; let isLarge: boolean = false; let hasGeometryData: boolean = false; let driveFile: IFile | undefined; let styles: IStyle[] = []; logTableStart(exportId, tableId); try { const csv = await getCsv(auth, table); fileSize = Buffer.byteLength(csv.data, 'utf8') / 1024 / 1024; roundedFileSize = Math.pow(2, Math.floor(Math.log(fileSize) / Math.log(2))); isLarge = fileSize > 20; hasGeometryData = csv.hasGeometryData || false; [driveFile, styles] = await Promise.all([ uploadToDrive(auth, options.folderId, csv), getFusiontableStyles(auth, table.id) ]); await Promise.all([ logFileExportInIndexSheet({ auth, sheet: options.archiveSheet, table, driveFile, styles, hasGeometryData, isLarge }), addFilePermissions(auth, driveFile.id, table.permissions), updateTableExportProgress({ exportId, tableId: table.id, status: 'success', driveFile, styles, isLarge, fileSize: roundedFileSize, latency: Date.now() - saveStart, hasGeometryData }) ]); logTableFinish(exportId, tableId, 'success', roundedFileSize); if (isLast) { logExportFinish(exportId); } } catch (error) { errors.report(error); await updateTableExportProgress({ exportId, tableId: table.id, status: 'error', error: error.message, driveFile, styles, isLarge, fileSize: roundedFileSize, latency: Date.now() - saveStart, hasGeometryData }); logTableFinish(exportId, tableId, 'error', roundedFileSize); if (isLast) { logExportFinish(exportId); } } }
{ "content_hash": "4f0945136c52b0cb96405b392ec80265", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 84, "avg_line_length": 28.573170731707318, "alnum_prop": 0.6756295347844644, "repo_name": "google/fusion-tables-drive-export", "id": "5e906c889bf43c2a97cf18f6b66a78506ffea255", "size": "5281", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server-src/lib/do-export.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11188" }, { "name": "HTML", "bytes": "59799" }, { "name": "TypeScript", "bytes": "103669" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>Episode 86: From Meatballs to Mods - BlahCade Podcast</title> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="description" content=""> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="Episode 86: From Meatballs to Mods"> <meta name="twitter:description" content=""> <meta property="og:type" content="article"> <meta property="og:title" content="Episode 86: From Meatballs to Mods"> <meta property="og:description" content=""> <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon"> <link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon"> <link rel="stylesheet" type="text/css" href="//blahcadepinball.com/themes/uno/assets/css/uno.css?v=1488194523958" /> <link rel="canonical" href="http://blahcadepinball.com/2017/01/31/Episode-86-From-Meatballs-to-Mods.html" /> <meta name="referrer" content="origin" /> <meta property="og:site_name" content="BlahCade Podcast" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Episode 86: From Meatballs to Mods" /> <meta property="og:description" content="https://shoutengine.com/BlahCadePodcast/from-meatballs-to-mods-30637 (Shout Engine) https://itunes.apple.com/us/podcast/blahcade-podcast/id1039748922?mt&#x3D;2 (iTunes) This DLC contains the following new features: Rogue 1 Zen Pinball Release New Table Clue Dr Who Masters of Time Android Al&amp;#8217;s Garage Band Listener Challenge Thanks for listening. If" /> <meta property="og:url" content="http://blahcadepinball.com/2017/01/31/Episode-86-From-Meatballs-to-Mods.html" /> <meta property="article:tag" content="farsight" /> <meta property="article:tag" content=" gottlieb" /> <meta property="article:tag" content=" listener-challenge" /> <meta name="twitter:card" content="summary" /> <meta name="twitter:title" content="Episode 86: From Meatballs to Mods" /> <meta name="twitter:description" content="https://shoutengine.com/BlahCadePodcast/from-meatballs-to-mods-30637 (Shout Engine) https://itunes.apple.com/us/podcast/blahcade-podcast/id1039748922?mt&#x3D;2 (iTunes) This DLC contains the following new features: Rogue 1 Zen Pinball Release New Table Clue Dr Who Masters of Time Android Al&amp;#8217;s Garage Band Listener Challenge Thanks for listening. If" /> <meta name="twitter:url" content="http://blahcadepinball.com/2017/01/31/Episode-86-From-Meatballs-to-Mods.html" /> <script type="application/ld+json"> null </script> <meta name="generator" content="HubPress" /> <link rel="alternate" type="application/rss+xml" title="BlahCade Podcast" href="http://blahcadepinball.com/rss/" /> </head> <body class="post-template tag-farsight tag-gottlieb tag-listener-challenge no-js"> <span class="mobile btn-mobile-menu"> <i class="icon icon-list btn-mobile-menu__icon"></i> <i class="icon icon-x-circle btn-mobile-close__icon hidden"></i> </span> <header class="panel-cover panel-cover--collapsed " style="background-image: url(/images/cover.jpg)"> <div class="panel-main"> <div class="panel-main__inner panel-inverted"> <div class="panel-main__content"> <a href="http://blahcadepinball.com" title="link to homepage for BlahCade Podcast"><img src="/images/logo.png" width="80" alt="BlahCade Podcast logo" class="panel-cover__logo logo" /></a> <h1 class="panel-cover__title panel-title"><a href="http://blahcadepinball.com" title="link to homepage for BlahCade Podcast">BlahCade Podcast</a></h1> <hr class="panel-cover__divider" /> <p class="panel-cover__description">Digital Pinball, Real Pinball, Movies, Snacks (but mostly Digital Pinball)</p> <hr class="panel-cover__divider panel-cover__divider--secondary" /> <div class="navigation-wrapper"> <nav class="cover-navigation cover-navigation--primary"> <ul class="navigation"> <li class="navigation__item"><a href="http://blahcadepinball.com/#blog" title="link to BlahCade Podcast blog" class="blog-button">Blog</a></li> </ul> </nav> <nav class="cover-navigation navigation--social"> <ul class="navigation"> <!-- Twitter --> <li class="navigation__item"> <a href="https://twitter.com/blahcade" title="Twitter account"> <i class='icon icon-social-twitter'></i> <span class="label">Twitter</span> </a> </li> <!-- Google Plus --> <li class="navigation__item"> <a href="https://plus.google.com/111201633898451444599/" title="Google+ account"> <i class='icon icon-social-google-plus'></i> <span class="label">Google-plus</span> </a> </li> <!-- Github --> <li class="navigation__item"> <a href="https://github.com/blahcadepodcast/" title="Github account"> <i class='icon icon-social-github'></i> <span class="label">Github</span> </a> </li> </li> <!-- Email --> <li class="navigation__item"> <a href="mailto:blahblahblahcade@gmail.com" title="Email blahblahblahcade@gmail.com"> <i class='icon icon-mail'></i> <span class="label">Email</span> </a> </li> </ul> </nav> </div> </div> </div> <div class="panel-cover--overlay"></div> </div> </header> <div class="content-wrapper"> <div class="content-wrapper__inner"> <article class="post-container post-container--single"> <header class="post-header"> <div class="post-meta"> <time datetime="31 Jan 2017" class="post-meta__date date">31 Jan 2017</time> &#8226; <span class="post-meta__tags tags">on <a href="http://blahcadepinball.com/tag/farsight/">farsight</a>, <a href="http://blahcadepinball.com/tag/gottlieb/"> gottlieb</a>, <a href="http://blahcadepinball.com/tag/listener-challenge/"> listener-challenge</a></span> <span class="post-meta__author author"><img src="https://avatars.githubusercontent.com/u/17490735?v&#x3D;3" alt="profile image for BlahCade Podcast" class="avatar post-meta__avatar" /> by BlahCade Podcast</span> </div> <h1 class="post-title">Episode 86: From Meatballs to Mods</h1> </header> <section class="post tag-farsight tag-gottlieb tag-listener-challenge"> <div id="preamble"> <div class="sectionbody"> <div class="paragraph"> <p><a href="https://shoutengine.com/BlahCadePodcast/from-meatballs-to-mods-30637" class="bare">https://shoutengine.com/BlahCadePodcast/from-meatballs-to-mods-30637</a> (Shout Engine)</p> </div> <div class="paragraph"> <p><a href="https://itunes.apple.com/us/podcast/blahcade-podcast/id1039748922?mt=2" class="bare">https://itunes.apple.com/us/podcast/blahcade-podcast/id1039748922?mt=2</a> (iTunes)</p> </div> <div class="paragraph"> <p>This DLC contains the following new features:</p> </div> <div class="ulist"> <ul> <li> <p>Rogue 1 Zen Pinball Release</p> </li> <li> <p>New Table Clue</p> </li> <li> <p>Dr Who Masters of Time Android</p> </li> <li> <p>Al&#8217;s Garage Band</p> </li> <li> <p>Listener Challenge</p> </li> </ul> </div> <div class="paragraph"> <p>Thanks for listening. If you have any ideas about stuff we should talk about, contact us using the Social links.</p> </div> </div> </div> <div class="sect1"> <h2 id="_social_links">Social Links</h2> <div class="sectionbody"> <div class="ulist"> <ul> <li> <p><a href="http://trylootcrate.com/blahcade">Try LootCrate and Get 10% Off Crates with Code <code>bridge10</code></a></p> </li> <li> <p><a href="https://represent.com/blahcade-shirt">BlahCade T-shirts on represent.com</a></p> </li> <li> <p><a href="https://twitter.com/blahcade">@BlahCade on Twitter</a></p> </li> <li> <p><a href="https://paypal.me/blahcade">Support us with a PayPal Donation</a></p> </li> <li> <p><a href="mailto:blahblahblahcade@gmail.com">blahblahblahcade@gmail.com</a></p> </li> </ul> </div> </div> </div> <div class="sect1"> <h2 id="_timings">Timings</h2> <div class="sectionbody"> <div class="ulist"> <ul> <li> <p>Introduction - 0:30</p> </li> <li> <p>Ikea Brekky - 0:50</p> </li> <li> <p>Rogue 1 on Zen Pinball - 4:05</p> </li> <li> <p><em>Al&#8217;s Garage Band</em> by Alvin G and Co. - 12:25</p> </li> <li> <p>FarSight Newsletter now has fix info per platform - 17:30</p> </li> <li> <p>Table Hint: Cactus Jacks - 20:15</p> </li> <li> <p>Listener Challenge: Mod an existing table to improve it - 21:45</p> <div class="ulist"> <ul> <li> <p>Dr Who: Extra Ramp - 23:05</p> </li> <li> <p>Judge Dredd: Badlands mini-layfield - 25:15</p> </li> <li> <p>No Good Gophers: Pop bumper re-design - 28:11</p> </li> <li> <p>Cyclone/Hurricane: Crazy coaster habit rails - 30:05</p> </li> <li> <p>Goin Nuts: Deployable playfield elements - 31:45</p> </li> <li> <p>Centaur: Multiball PacDude glowing orbs - 34:15</p> </li> </ul> </div> </li> <li> <p>Promos - 40:30</p> </li> <li> <p>Outtro - 42:10</p> </li> </ul> </div> </div> </div> </section> </article> <section class="post-comments"> <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = 'blahcadepodcast'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a> </section> <footer class="footer"> <span class="footer__copyright">&copy; 2017. All rights reserved.</span> <span class="footer__copyright"><a href="http://uno.daleanthony.com" title="link to page for Uno Ghost theme">Uno theme</a> by <a href="http://daleanthony.com" title="link to website for Dale-Anthony">Dale-Anthony</a></span> <span class="footer__copyright">Proudly published with <a href="http://hubpress.io" title="link to Hubpress website">Hubpress</a></span> </footer> </div> </div> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?v="></script> <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js?v="></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js?v="></script> <script type="text/javascript"> jQuery( document ).ready(function() { // change date with ago jQuery('ago.ago').each(function(){ var element = jQuery(this).parent(); element.html( moment(element.text()).fromNow()); }); }); hljs.initHighlightingOnLoad(); </script> <script src='https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script> <script type="text/javascript" src="//blahcadepinball.com/themes/uno/assets/js/main.js?v=1488194523958"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-83260356-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
{ "content_hash": "e6f07b7f38db7ed745321f154f9e41e2", "timestamp": "", "source": "github", "line_count": 332, "max_line_length": 409, "avg_line_length": 39.08433734939759, "alnum_prop": 0.6139796547472256, "repo_name": "blahcadepodcast/blahcadepodcast.github.io", "id": "1f18cd1b39ac0a4b7cd1edbba8a2d79e741c1af3", "size": "12976", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2017/01/31/Episode-86-From-Meatballs-to-Mods.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "466631" }, { "name": "CoffeeScript", "bytes": "6630" }, { "name": "HTML", "bytes": "5408105" }, { "name": "JavaScript", "bytes": "238406" }, { "name": "Ruby", "bytes": "806" }, { "name": "Shell", "bytes": "2265" } ], "symlink_target": "" }
casperjs --verbose --cookies-file=cookies.txt app.js
{ "content_hash": "e8ca240443245ad3f80b4b36ecdcae7f", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 52, "avg_line_length": 52, "alnum_prop": 0.7884615384615384, "repo_name": "Nainterceptor/ENIDownloader", "id": "fc38a184141546baadb09b401ca00e0b88020931", "size": "73", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "crawl.sh", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2442" }, { "name": "Shell", "bytes": "504" } ], "symlink_target": "" }
/* globals Department, Livechat */ import { Meteor } from 'meteor/meteor'; import { ReactiveVar } from 'meteor/reactive-var'; import { Template } from 'meteor/templating'; import swal from 'sweetalert2'; import visitor from '../../imports/client/visitor'; Template.switchDepartment.helpers({ departments() { return Department.find({ showOnRegistration: true, _id: { $ne: Livechat.department, }, }); }, error() { return Template.instance().error.get(); }, showError() { return Template.instance().error.get() ? 'show' : ''; }, }); Template.switchDepartment.onCreated(function() { this.error = new ReactiveVar(); }); Template.switchDepartment.events({ 'submit form'(e, instance) { e.stopPropagation(); e.preventDefault(); const departmentId = instance.$('.switch-department-select').val(); if (!departmentId) { instance.error.set(t('Please_choose_a_department')); return; } instance.error.set(); swal({ text: t('Are_you_sure_do_you_want_switch_the_department'), title: '', type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: t('Yes'), cancelButtonText: t('No'), html: false, }).then((result) => { if (!result.value) { return; } const guestData = { roomId: visitor.getRoom(), visitorToken: visitor.getToken(), departmentId, }; Meteor.call('livechat:setDepartmentForVisitor', guestData, (error, result) => { if (error) { instance.error.set(error.error); } else if (result) { instance.error.set(); Livechat.department = departmentId; Livechat.showSwitchDepartmentForm = false; swal({ title: t('Department_switched'), type: 'success', timer: 2000, }); } else { instance.error.set(t('No_available_agents_to_transfer')); } }); }); }, 'click #btnCancel'() { Livechat.showSwitchDepartmentForm = false; }, });
{ "content_hash": "83ed4489034e38eeca92a9a6e37d2b13", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 82, "avg_line_length": 23, "alnum_prop": 0.6392339544513458, "repo_name": "4thParty/Rocket.Chat", "id": "b14c6e8921a1863f2b5960e79717dc7042647b0e", "size": "1932", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "packages/rocketchat-livechat/.app/client/views/switchDepartment.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "549" }, { "name": "CSS", "bytes": "390935" }, { "name": "Cap'n Proto", "bytes": "3959" }, { "name": "CoffeeScript", "bytes": "30843" }, { "name": "Dockerfile", "bytes": "1874" }, { "name": "HTML", "bytes": "657188" }, { "name": "JavaScript", "bytes": "4580635" }, { "name": "Ruby", "bytes": "4653" }, { "name": "Shell", "bytes": "32548" }, { "name": "Standard ML", "bytes": "1843" } ], "symlink_target": "" }
In order to accept your pull request, we need you to submit a CLA. You only need to do this once to work on any of Facebook's open source projects. If you submit a pull request to this project and you have never submitted a Facebook CLA, a GitHub Bot will comment on the pull request asking you to submit a CLA. Feel free to wait until then to submit it (it only takes a few seconds) or complete your CLA proactively, here: <https://code.facebook.com/cla> ## Tracking Features and Getting Help If you'd like to implement new features, check out this projects [GitHub Issues](https://github.com/osquery/osquery-python/issues). Community contributions are welcomed and encouraged. If you want to suggest a feature, you should create a GitHub issue outlining your feature request. If you need help, have questions, or want to participate in a forum-style conversation with the core developers and users of this projects, create an issue. Generally, use GitHub Issues for everything. ## Code Formatting ### Lint #### Running the linter With the exception of the thrift autogenerated code, all code must be pylint compliant. After installing `pylint` and/or running `pip install -r requirements.txt` from the root of this repository, run the following to lint the code: ``` python setup.py lint ``` Once you run that, a bunch of output will come out. The very last thing that lint should say is: ``` Global evaluation ----------------- Your code has been rated at 10.00/10 (previous run: 10.00/10, +0.00) ``` If the code rating has dropped below `10.00/10`, please fix the code so that it is compliant. #### Adding ignores Under the hood, `python setup.py lint` just runs `pylint` with a few options on the relevant parts of the codebase. Sometime, `pylint` is unreasonable. For that reason, you may ignore specific messages on a file-by-file basis by adding text like `# pylint: disable=too-few-public-methods` to the top of your file, right below the license docstring, before any imports. If you'd like to edit the arguments that `pylint` itself is ran with, edit the `PylintCommand` class' `_pylint_arguments` property. Ignoring lint warnings is generally not something you should default to doing. With great power comes great responsibility. ### Style Generally, be consistent. We don't have a good auto-formatter configured, so ensure that the style of you code matches existing style. If you feel strongly that a given style in use throughout the codebase is egregious, feel free to submit a pull request with your update and we can discuss it's merits. We adhere to [PEP 8](https://www.python.org/dev/peps/pep-0008/) for style, as well as [PEP 257](https://www.python.org/dev/peps/pep-0257/) for docstring conventions. If you notice that the codebase is not compliant with those specifications, please file an issue and/or submit a pull request with a patch. ### Testing To run the tests, run the following from the root of the repository: ``` # install dependencies pip install -r requirements.txt # build the module python setup.py build # test the module python setup.py test ``` ## Packaging We build the osquery package as a [wheel](https://pypi.python.org/pypi/wheel). To build the wheel, run the following from the root of this repository: ``` # install dependencies pip install -r requirements.txt # build package python setup.py bdist_wheel # upload the package twine upload dist/* ```
{ "content_hash": "72eb3955dae0d7730da51619aa4cd61c", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 85, "avg_line_length": 32.367924528301884, "alnum_prop": 0.7618770037889828, "repo_name": "glensc/osquery-python", "id": "9a6c258a9aff19ec66652a3e2855c2807b7a79c8", "size": "3473", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CONTRIBUTING.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "40573" }, { "name": "Thrift", "bytes": "2911" } ], "symlink_target": "" }
namespace content { struct LoadCommittedDetails; } namespace gfx { class Image; } namespace extensions { class Extension; class LocationBarController; class RulesRegistryService; class ScriptBadgeController; class ScriptBubbleController; class ScriptExecutor; // Per-tab extension helper. Also handles non-extension apps. class TabHelper : public content::WebContentsObserver, public ExtensionFunctionDispatcher::Delegate, public base::SupportsWeakPtr<TabHelper>, public content::NotificationObserver, public content::WebContentsUserData<TabHelper> { public: // Different types of action when web app info is available. // OnDidGetApplicationInfo uses this to dispatch calls. enum WebAppAction { NONE, // No action at all. CREATE_SHORTCUT, // Bring up create application shortcut dialog. UPDATE_SHORTCUT // Update icon for app shortcut. }; // Observer base class for classes that need to be notified when content // scripts and/or tabs.executeScript calls run on a page. class ScriptExecutionObserver { public: // Map of extensions IDs to the executing script paths. typedef std::map<std::string, std::set<std::string> > ExecutingScriptsMap; // Automatically observes and unobserves |tab_helper| on construction // and destruction. |tab_helper| must outlive |this|. explicit ScriptExecutionObserver(TabHelper* tab_helper); ScriptExecutionObserver(); // Called when script(s) have executed on a page. // // |executing_scripts_map| contains all extensions that are executing // scripts, mapped to the paths for those scripts. This may be an empty set // if the script has no path associated with it (e.g. in the case of // tabs.executeScript). virtual void OnScriptsExecuted( const content::WebContents* web_contents, const ExecutingScriptsMap& executing_scripts_map, int32 on_page_id, const GURL& on_url) = 0; protected: virtual ~ScriptExecutionObserver(); TabHelper* tab_helper_; }; virtual ~TabHelper(); void AddScriptExecutionObserver(ScriptExecutionObserver* observer) { script_execution_observers_.AddObserver(observer); } void RemoveScriptExecutionObserver(ScriptExecutionObserver* observer) { script_execution_observers_.RemoveObserver(observer); } void CreateApplicationShortcuts(); bool CanCreateApplicationShortcuts() const; void set_pending_web_app_action(WebAppAction action) { pending_web_app_action_ = action; } // App extensions ------------------------------------------------------------ // Sets the extension denoting this as an app. If |extension| is non-null this // tab becomes an app-tab. WebContents does not listen for unload events for // the extension. It's up to consumers of WebContents to do that. // // NOTE: this should only be manipulated before the tab is added to a browser. // TODO(sky): resolve if this is the right way to identify an app tab. If it // is, than this should be passed in the constructor. void SetExtensionApp(const Extension* extension); // Convenience for setting the app extension by id. This does nothing if // |extension_app_id| is empty, or an extension can't be found given the // specified id. void SetExtensionAppById(const std::string& extension_app_id); // Set just the app icon, used by panels created by an extension. void SetExtensionAppIconById(const std::string& extension_app_id); const Extension* extension_app() const { return extension_app_; } bool is_app() const { return extension_app_ != NULL; } const WebApplicationInfo& web_app_info() const { return web_app_info_; } // If an app extension has been explicitly set for this WebContents its icon // is returned. // // NOTE: the returned icon is larger than 16x16 (its size is // extension_misc::EXTENSION_ICON_SMALLISH). SkBitmap* GetExtensionAppIcon(); content::WebContents* web_contents() const { return content::WebContentsObserver::web_contents(); } ScriptExecutor* script_executor() { return script_executor_.get(); } LocationBarController* location_bar_controller() { return location_bar_controller_.get(); } ActiveTabPermissionGranter* active_tab_permission_granter() { return active_tab_permission_granter_.get(); } ScriptBubbleController* script_bubble_controller() { return script_bubble_controller_.get(); } // Sets a non-extension app icon associated with WebContents and fires an // INVALIDATE_TYPE_TITLE navigation state change to trigger repaint of title. void SetAppIcon(const SkBitmap& app_icon); private: explicit TabHelper(content::WebContents* web_contents); friend class content::WebContentsUserData<TabHelper>; // content::WebContentsObserver overrides. virtual void RenderViewCreated( content::RenderViewHost* render_view_host) OVERRIDE; virtual void DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) OVERRIDE; virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; virtual void DidCloneToNewWebContents( content::WebContents* old_web_contents, content::WebContents* new_web_contents) OVERRIDE; // ExtensionFunctionDispatcher::Delegate overrides. virtual extensions::WindowController* GetExtensionWindowController() const OVERRIDE; virtual content::WebContents* GetAssociatedWebContents() const OVERRIDE; // Message handlers. void OnDidGetApplicationInfo(int32 page_id, const WebApplicationInfo& info); void OnInlineWebstoreInstall(int install_id, int return_route_id, const std::string& webstore_item_id, const GURL& requestor_url); void OnGetAppInstallState(const GURL& requestor_url, int return_route_id, int callback_id); void OnRequest(const ExtensionHostMsg_Request_Params& params); void OnContentScriptsExecuting( const ScriptExecutionObserver::ExecutingScriptsMap& extension_ids, int32 page_id, const GURL& on_url); void OnWatchedPageChange(const std::vector<std::string>& css_selectors); // App extensions related methods: // Resets app_icon_ and if |extension| is non-null uses ImageLoader to load // the extension's image asynchronously. void UpdateExtensionAppIcon(const Extension* extension); const Extension* GetExtension(const std::string& extension_app_id); void OnImageLoaded(const gfx::Image& image); // WebstoreStandaloneInstaller::Callback. virtual void OnInlineInstallComplete(int install_id, int return_route_id, bool success, const std::string& error); // content::NotificationObserver. virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE; // Requests application info for the specified page. This is an asynchronous // request. The delegate is notified by way of OnDidGetApplicationInfo when // the data is available. void GetApplicationInfo(int32 page_id); // Sends our tab ID to |render_view_host|. void SetTabId(content::RenderViewHost* render_view_host); // Data for app extensions --------------------------------------------------- // Our content script observers. Declare at top so that it will outlive all // other members, since they might add themselves as observers. ObserverList<ScriptExecutionObserver> script_execution_observers_; // If non-null this tab is an app tab and this is the extension the tab was // created for. const Extension* extension_app_; // Icon for extension_app_ (if non-null) or a manually-set icon for // non-extension apps. SkBitmap extension_app_icon_; // Process any extension messages coming from the tab. ExtensionFunctionDispatcher extension_function_dispatcher_; // Cached web app info data. WebApplicationInfo web_app_info_; // Which deferred action to perform when OnDidGetApplicationInfo is notified // from a WebContents. WebAppAction pending_web_app_action_; content::NotificationRegistrar registrar_; scoped_ptr<ScriptExecutor> script_executor_; scoped_ptr<LocationBarController> location_bar_controller_; scoped_ptr<ActiveTabPermissionGranter> active_tab_permission_granter_; scoped_ptr<ScriptBubbleController> script_bubble_controller_; RulesRegistryService* rules_registry_service_; Profile* profile_; // Vend weak pointers that can be invalidated to stop in-progress loads. base::WeakPtrFactory<TabHelper> image_loader_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(TabHelper); }; } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_TAB_HELPER_H_
{ "content_hash": "5cc476dc8d949d129dcfc3344f64a4c1", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 80, "avg_line_length": 36.63821138211382, "alnum_prop": 0.7068678575391102, "repo_name": "loopCM/chromium", "id": "c5b6d23cc82354337d986647cc7de27492447551", "size": "9908", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "chrome/browser/extensions/tab_helper.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package hotstu.github.secretshare.utils; import android.content.Context; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; public class DeviceUtils { public static String uniqueId(Context context) { final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String tmDevice, tmSerial, androidId; tmDevice = tm.getDeviceId(); if (tmDevice != null) return tmDevice; tmSerial = tm.getSubscriberId(); if (tmSerial != null) return tmSerial; androidId = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID); if (androidId != null) return androidId; else return "--nounidqueid--"; } public static String getMacAddress(Context context) { WifiManager wimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); String macAddress = wimanager.getConnectionInfo().getMacAddress(); if (macAddress == null) { macAddress = "--nomacaddr--"; } return macAddress; } }
{ "content_hash": "d9566cfb0cdfae6ea06cd9d75b77c8b3", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 138, "avg_line_length": 34.52777777777778, "alnum_prop": 0.6395816572807723, "repo_name": "hotstu/secretshare", "id": "8a34499119b75c477af395239be41eff39c44fd2", "size": "1243", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/hotstu/github/secretshare/utils/DeviceUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "201839" } ], "symlink_target": "" }
RSpec::Matchers.define :have_key_schema do |attribute_name| match do |attribute| attribute.has_key_schema?(attribute_name, @key_type) end chain :key_type do |type| @key_type = type end end
{ "content_hash": "e40416c6cfb663640728ac2de2be4c19", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 59, "avg_line_length": 22.88888888888889, "alnum_prop": 0.6893203883495146, "repo_name": "AgarFu/awspec", "id": "1df679928aca607728404bef34ebc2dd7f4f39b3", "size": "206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/awspec/matcher/have_key_schema.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "378761" }, { "name": "Shell", "bytes": "58" } ], "symlink_target": "" }
'use strict'; const LiveReloadPlugin = require('webpack-livereload-plugin'); const devMode = process.env.NODE_ENV === 'development'; /** * Fast source maps rebuild quickly during development, but only give a link * to the line where the error occurred. The stack trace will show the bundled * code, not the original code. Keep this on `false` for slower builds but * usable stack traces. Set to `true` if you want to speed up development. */ const USE_FAST_SOURCE_MAPS = false; module.exports = { entry: './app/main.jsx', output: { path: __dirname, filename: './public/bundle.js', publicPath: '/' }, context: __dirname, devtool: devMode && USE_FAST_SOURCE_MAPS ? 'cheap-module-eval-source-map' : 'source-map', resolve: { extensions: ['.js', '.jsx', '.json', '*'] }, module: { loaders: [ { test: /\.css$/, loader: "style-loader!css-loader"} ], rules: [{ test: /jsx?$/, exclude: /(node_modules|bower_components)/, use: [{ loader: 'babel-loader', options: { presets: ['react', 'es2015', 'stage-2'] } }] }], }, plugins: devMode ? [ new LiveReloadPlugin({ appendScriptTag: true }) ] : [] };
{ "content_hash": "87eb202f17a1a2c5cdecd1a459faf3a9", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 78, "avg_line_length": 25.20408163265306, "alnum_prop": 0.594331983805668, "repo_name": "ellejeong/benefeel", "id": "f9151785fcfe18ee2eeed689a3fcf1b2a9fbf967", "size": "1235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webpack.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2381" }, { "name": "HTML", "bytes": "493" }, { "name": "JavaScript", "bytes": "83298" }, { "name": "Shell", "bytes": "1794" } ], "symlink_target": "" }
typedef struct grpc_tls_custom_verification_check_request grpc_tls_custom_verification_check_request; typedef struct grpc_tls_certificate_verifier grpc_tls_certificate_verifier; typedef struct grpc_tls_certificate_verifier_external grpc_tls_certificate_verifier_external; typedef void (*grpc_tls_on_custom_verification_check_done_cb)( grpc_tls_custom_verification_check_request* request, void* callback_arg, grpc_status_code status, const char* error_details); extern "C" grpc_tls_certificate_verifier* grpc_tls_certificate_verifier_external_create( grpc_tls_certificate_verifier_external* external_verifier); namespace grpc { namespace experimental { // Contains the verification-related information associated with a connection // request. Users should not directly create or destroy this request object, but // shall interact with it through CertificateVerifier's Verify() and Cancel(). class TlsCustomVerificationCheckRequest { public: explicit TlsCustomVerificationCheckRequest( grpc_tls_custom_verification_check_request* request); ~TlsCustomVerificationCheckRequest() {} grpc::string_ref target_name() const; grpc::string_ref peer_cert() const; grpc::string_ref peer_cert_full_chain() const; grpc::string_ref common_name() const; std::vector<grpc::string_ref> uri_names() const; std::vector<grpc::string_ref> dns_names() const; std::vector<grpc::string_ref> email_names() const; std::vector<grpc::string_ref> ip_names() const; grpc_tls_custom_verification_check_request* c_request() { return c_request_; } private: grpc_tls_custom_verification_check_request* c_request_ = nullptr; }; // The base class of all internal verifier implementations, and the ultimate // class that all external verifiers will eventually be transformed into. // To implement a custom verifier, do not extend this class; instead, // implement a subclass of ExternalCertificateVerifier. Note that custom // verifier implementations can compose their functionality with existing // implementations of this interface, such as HostnameVerifier, by delegating // to an instance of that class. class CertificateVerifier { public: explicit CertificateVerifier(grpc_tls_certificate_verifier* v); ~CertificateVerifier(); // Verifies a connection request, based on the logic specified in an internal // verifier. The check on each internal verifier could be either synchronous // or asynchronous, and we will need to use return value to know. // // request: the verification information associated with this request // callback: This will only take effect if the verifier is asynchronous. // The function that gRPC will invoke when the verifier has already // completed its asynchronous check. Callers can use this function // to perform any additional checks. The input parameter of the // std::function indicates the status of the verifier check. // sync_status: This will only be useful if the verifier is synchronous. // The status of the verifier as it has already done it's // synchronous check. // return: return true if executed synchronously, otherwise return false bool Verify(TlsCustomVerificationCheckRequest* request, std::function<void(grpc::Status)> callback, grpc::Status* sync_status); // Cancels a verification request previously started via Verify(). // Used when the connection attempt times out or is cancelled while an async // verification request is pending. // // request: the verification information associated with this request void Cancel(TlsCustomVerificationCheckRequest* request); // Gets the core verifier used internally. grpc_tls_certificate_verifier* c_verifier() { return verifier_; } private: static void AsyncCheckDone( grpc_tls_custom_verification_check_request* request, void* callback_arg, grpc_status_code status, const char* error_details); grpc_tls_certificate_verifier* verifier_ = nullptr; grpc::internal::Mutex mu_; std::map<grpc_tls_custom_verification_check_request*, std::function<void(grpc::Status)>> request_map_ ABSL_GUARDED_BY(mu_); }; // The base class of all external, user-specified verifiers. Users should // inherit this class to implement a custom verifier. // Note that while implementing the custom verifier that extends this class, it // is possible to compose an existing ExternalCertificateVerifier or // CertificateVerifier, inside the Verify() and Cancel() function of the new // custom verifier. class ExternalCertificateVerifier { public: // A factory method for creating a |CertificateVerifier| from this class. All // the user-implemented verifiers should use this function to be converted to // verifiers compatible with |TlsCredentialsOptions|. // The resulting CertificateVerifier takes ownership of the newly instantiated // Subclass. template <typename Subclass, typename... Args> static std::shared_ptr<CertificateVerifier> Create(Args&&... args) { grpc::internal::GrpcLibraryInitializer g_gli_initializer; g_gli_initializer.summon(); auto* external_verifier = new Subclass(std::forward<Args>(args)...); return std::make_shared<CertificateVerifier>( grpc_tls_certificate_verifier_external_create( external_verifier->base_)); } // The verification logic that will be performed after the TLS handshake // completes. Implementers can choose to do their checks synchronously or // asynchronously. // // request: the verification information associated with this request // callback: This should only be used if your check is done asynchronously. // When the asynchronous work is done, invoke this callback function // with the proper status, indicating the success or the failure of // the check. The implementer MUST NOT invoke this |callback| in the // same thread before Verify() returns, otherwise it can lead to // deadlocks. // sync_status: This should only be used if your check is done synchronously. // Modifies this value to indicate the success or the failure of // the check. // return: return true if your check is done synchronously, otherwise return // false virtual bool Verify(TlsCustomVerificationCheckRequest* request, std::function<void(grpc::Status)> callback, grpc::Status* sync_status) = 0; // Cancels a verification request previously started via Verify(). // Used when the connection attempt times out or is cancelled while an async // verification request is pending. The implementation should abort whatever // async operation it is waiting for and quickly invoke the callback that was // passed to Verify() with a status indicating the cancellation. // // request: the verification information associated with this request virtual void Cancel(TlsCustomVerificationCheckRequest* request) = 0; protected: ExternalCertificateVerifier(); virtual ~ExternalCertificateVerifier(); private: struct AsyncRequestState { AsyncRequestState(grpc_tls_on_custom_verification_check_done_cb cb, void* arg, grpc_tls_custom_verification_check_request* request) : callback(cb), callback_arg(arg), cpp_request(request) {} grpc_tls_on_custom_verification_check_done_cb callback; void* callback_arg; TlsCustomVerificationCheckRequest cpp_request; }; static int VerifyInCoreExternalVerifier( void* user_data, grpc_tls_custom_verification_check_request* request, grpc_tls_on_custom_verification_check_done_cb callback, void* callback_arg, grpc_status_code* sync_status, char** sync_error_details); static void CancelInCoreExternalVerifier( void* user_data, grpc_tls_custom_verification_check_request* request); static void DestructInCoreExternalVerifier(void* user_data); // TODO(yihuazhang): after the insecure build is removed, make this an object // member instead of a pointer. grpc_tls_certificate_verifier_external* base_ = nullptr; grpc::internal::Mutex mu_; std::map<grpc_tls_custom_verification_check_request*, AsyncRequestState> request_map_ ABSL_GUARDED_BY(mu_); }; // A CertificateVerifier that doesn't perform any additional checks other than // certificate verification, if specified. // Note: using this solely without any other authentication mechanisms on the // peer identity will leave your applications to the MITM(Man-In-The-Middle) // attacks. Users should avoid doing so in production environments. class NoOpCertificateVerifier : public CertificateVerifier { public: NoOpCertificateVerifier(); }; // A CertificateVerifier that will perform hostname verification, to see if the // target name set from the client side matches the identity information // specified on the server's certificate. class HostNameCertificateVerifier : public CertificateVerifier { public: HostNameCertificateVerifier(); }; } // namespace experimental } // namespace grpc #endif // GRPCPP_SECURITY_TLS_CERTIFICATE_VERIFIER_H
{ "content_hash": "7b7c0c2e9906d31c43754f0519bd6ca7", "timestamp": "", "source": "github", "line_count": 202, "max_line_length": 80, "avg_line_length": 45.56930693069307, "alnum_prop": 0.7389462248777838, "repo_name": "stanley-cheung/grpc", "id": "0c9f35a96a4c3805e35ce7c65cfb02ec426a9728", "size": "10391", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/grpcpp/security/tls_certificate_verifier.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "5444" }, { "name": "Batchfile", "bytes": "37697" }, { "name": "C", "bytes": "1340616" }, { "name": "C#", "bytes": "113402" }, { "name": "C++", "bytes": "17499842" }, { "name": "CMake", "bytes": "29311" }, { "name": "CSS", "bytes": "1519" }, { "name": "Cython", "bytes": "258997" }, { "name": "Dockerfile", "bytes": "181867" }, { "name": "Go", "bytes": "34794" }, { "name": "HTML", "bytes": "14" }, { "name": "Java", "bytes": "14329" }, { "name": "JavaScript", "bytes": "5572" }, { "name": "Objective-C", "bytes": "724877" }, { "name": "Objective-C++", "bytes": "79586" }, { "name": "PHP", "bytes": "488004" }, { "name": "PowerShell", "bytes": "5008" }, { "name": "Python", "bytes": "3829879" }, { "name": "Ruby", "bytes": "649843" }, { "name": "Shell", "bytes": "774868" }, { "name": "Starlark", "bytes": "874094" }, { "name": "Swift", "bytes": "7487" }, { "name": "XSLT", "bytes": "9846" } ], "symlink_target": "" }
describe('Amoeba.View.PaginatedCollection', function() { var container, view; container = view = void 0; beforeEach(function() { container = new Amoeba.Collection.Container; container.resetPage(1, [ { id: 1 } ]); return view = new Amoeba.View.PaginatedCollection({ container: container }); }); it('should have a default current page of 1', function() { view = new Amoeba.View.PaginatedCollection({ container: container }); return view.currentPage.should.equal(1); }); it('should load up the page if passed in', function() { view = new Amoeba.View.PaginatedCollection({ page: 5, container: container }); return view.currentPage.should.equal(5); }); describe('#renderPage', function() { it('should create the page', function() { var spy; spy = sinon.spy(view, 'createPage'); view.renderPage(1, container.pages[1]); view.pages[1].should.not.be.undefined; return spy.should.have.been.calledWith(1, container.pages[1]); }); it('should not rerender the page', function() { var spy; view.renderPage(1, container.pages[1]); spy = sinon.spy(view, 'getPageEl'); view.renderPage(1, container.pages[1]); return spy.should.not.have.been.called; }); it('should show the new page if it exists', function() { var $page; view.renderPage(1, container.pages[1]); $page = view.getPageEl(1).addClass('hide'); view.refresh(); return $page.hasClass('hide').should.be["false"]; }); it('should add the page number to the new el', function() { view.renderPage(1, container.pages[1]); return view.getPageEl(1).hasClass('page-1').should.be["true"]; }); it('should append the new page if it does not exist', function() { view.renderPage(1, container.pages[1]); return view.$('.page-1').should.exist; }); describe('swtiching pages', function() { beforeEach(function() { container.resetPage(2, [ { id: 2 } ]); view.refresh(); return view.renderPage(2, container.pages[2]); }); it('should hide the current page', function() { view.getPageEl(1).hasClass('hide').should.be["true"]; return view.pages[1].rendered.should.be["false"]; }); return it('should change the current page', function() { return view.currentPage.should.equal(2); }); }); it('should render the new page', function() { view.renderPage(1, container.pages[1]); return view.pages[1].rendered.should.be["true"]; }); return it('should trigger a render event', function() { var callback; callback = sinon.spy(); view.on('renderPage', callback); view.renderPage(1, container.pages[1]); return callback.should.have.been.calledWith(1); }); }); describe('#refresh', function() { describe('existing page', function() { beforeEach(function() { return view.refresh(); }); it('should remove the page if the collection is dirty', function() { var spy; container.pages[1].dirty = true; spy = sinon.spy(view, 'removePage'); sinon.stub(container, 'fetch'); view.refresh(); return spy.should.have.been.calledWith(1); }); return it('should mark the page as unrendered', function() { var spy; spy = sinon.spy(view, 'getPageEl'); view.refresh(); return spy.should.have.been.calledWith(1); }); }); it('should fetch the page', function() { var spy; spy = sinon.spy(container, 'fetch'); view.refresh(); return spy.should.have.been.calledWithMatch(1, { silent: true }); }); return it('should render the page', function() { var spy; spy = sinon.spy(view, 'renderPage'); view.refresh(); return spy.should.have.been.calledWith(1, container.pages[1]); }); }); describe('#removePage', function() { beforeEach(function() { return view.refresh(); }); it('should show the zero state when there is no more models'); it('should be called when the container removes a page', function() { container.remove(1); return expect(view.pages[1]).to.be.undefined; }); return it('should remove the view', function() { var spy; spy = sinon.spy(view.pages[1].view, 'remove'); view.removePage(1); spy.should.have.been.called; return view.getPageEl(1).should.not.exist; }); }); return describe('#createPage', function() { it('should render the view', function() { var spy; spy = sinon.spy(view, '_render'); view.createPage(1, container.pages[1]); spy.should.have.been.called; return view.pages[1].view.collection.should.equal(container.pages[1]); }); return it('should not be rendered', function() { view.createPage(1, container.pages[1]); return view.pages[1].rendered.should.be["false"]; }); }); });
{ "content_hash": "8ddc26306eae4d15bfe809cb73afb07c", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 76, "avg_line_length": 33.294117647058826, "alnum_prop": 0.596780526109148, "repo_name": "AmoebaLabs/amoeba-js", "id": "d86c2050e1e70883b67250bafbee8398da9d6e5e", "size": "5095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/javascripts/amoeba/views/paginated_collection_spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "40639" }, { "name": "JavaScript", "bytes": "225128" }, { "name": "Ruby", "bytes": "6048" } ], "symlink_target": "" }
import argparse import os import pandas as pd from sklearn.svm import SVC import cPickle as pickle import openface from src.image_reader import get_image_list from src.features_calculator import image_to_features def do_talking(message): # just a helper function to make code more readable if args.verbose: print(message) def parent_folder(path): return os.path.basename(os.path.dirname(path)) def create_classifier(features, labels): clf = SVC(C=1, kernel='linear', probability=True) clf.fit(features, labels) return clf def calculate_features(images, model, output_path, verbose=False): feature_values = [image_to_features(img, model, verbose) for img in images] features_df = pd.DataFrame(feature_values) features_df.to_csv(output_path, index=False, header=False) return features_df def calculate_labels(images, output_path): participants_set = {parent_folder(image) for image in images} participant_as_index = {p: ind for ind, p in enumerate(participants_set)} images_with_ind = [[participant_as_index[parent_folder(image)], parent_folder(image)] for image in images] labels_df = pd.DataFrame(images_with_ind, columns=['numeric', 'text']) labels_df.to_csv(output_path) return labels_df def calculate_svm_model(features_df, labels_df, output_dir): features = features_df.as_matrix() labels_only_df = labels_df.ix[:, 'numeric'] labels = labels_only_df.as_matrix() clf = create_classifier(features, labels) model_path = os.path.join(output_dir, 'model.pkl') with open(model_path, 'wb') as model_file: pickle.dump(clf, model_file) def main(args): if not os.path.exists(args.out_dir): os.makedirs(args.out_dir) model = openface.TorchNeuralNet(args.networkModel, args.img_dim) print('Start processing...') if not (os.path.exists(args.img_dir)): raise ValueError('Input directory does not exist: {}'.format(args.img_dir)) images = get_image_list(args.img_dir) do_talking('Found {} images to process'.format(len(images))) features_path = os.path.join(args.out_dir, 'features.csv') features_df = calculate_features(images, model, features_path, args.verbose) labels_path = os.path.join(args.out_dir, 'labels.csv') labels_df = calculate_labels(images, labels_path) calculate_svm_model(features_df, labels_df, args.out_dir) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('img_dir', type=str, help='Directory with aligned images') parser.add_argument('out_dir', type=str, help='Output directory') parser.add_argument('--networkModel', type=str, help='Path to Torch network model.', default=os.path.join('/home/anna/src/openface/models/openface', 'nn4.small2.v1.t7')) parser.add_argument('--img-dim', type=int,help='Default image dimension.', default=96) parser.add_argument('--verbose', action='store_true') args = parser.parse_args() main(args)
{ "content_hash": "c376af13fa20dd6eccc7945bf0fee886", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 110, "avg_line_length": 30.3, "alnum_prop": 0.6907590759075908, "repo_name": "aeivazi/classroom-tracking", "id": "c8b5eabf38022d46656fbfe3351231c0fb9018e8", "size": "3158", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/utils/create_model_face_prediction.py", "mode": "33261", "license": "mit", "language": [ { "name": "C++", "bytes": "73598" }, { "name": "Python", "bytes": "24763" } ], "symlink_target": "" }
package org.springframework.core.io; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import org.springframework.core.NestedIOException; import org.springframework.core.log.LogAccessor; import org.springframework.lang.Nullable; import org.springframework.util.ResourceUtils; /** * Convenience base class for {@link Resource} implementations, pre-implementing * typical behavior. * * <p> * The "exists" method will check whether a File or InputStream can be opened; * "isOpen" will always return false; "getURL" and "getFile" throw an exception; * and "toString" will return the description. * * @author Juergen Hoeller * @author Sam Brannen * @since 28.12.2003 */ public abstract class AbstractResource implements Resource { private static final LogAccessor logAccessor = new LogAccessor(AbstractResource.class); /** * This implementation checks whether a File can be opened, falling back to * whether an InputStream can be opened. This will cover both directories and * content resources. */ @Override public boolean exists() { // Try file existence: can we find the file in the file system? try { return getFile().exists(); } catch (IOException ex) { // Fall back to stream existence: can we open the stream? try { getInputStream().close(); return true; } catch (Throwable isEx) { logAccessor.debug(ex, () -> "Could not close InputStream for resource: " + getDescription()); return false; } } } /** * This implementation always returns {@code true} for a resource that * {@link #exists() exists} (revised as of 5.1). */ @Override public boolean isReadable() { return exists(); } /** * This implementation always returns {@code false}. */ @Override public boolean isOpen() { return false; } /** * This implementation always returns {@code false}. */ @Override public boolean isFile() { return false; } /** * This implementation throws a FileNotFoundException, assuming that the * resource cannot be resolved to a URL. */ @Override public URL getURL() throws IOException { throw new FileNotFoundException(getDescription() + " cannot be resolved to URL"); } /** * This implementation builds a URI based on the URL returned by * {@link #getURL()}. */ @Override public URI getURI() throws IOException { URL url = getURL(); try { return ResourceUtils.toURI(url); } catch (URISyntaxException ex) { throw new NestedIOException("Invalid URI [" + url + "]", ex); } } /** * This implementation throws a FileNotFoundException, assuming that the * resource cannot be resolved to an absolute file path. */ @Override public File getFile() throws IOException { throw new FileNotFoundException(getDescription() + " cannot be resolved to absolute file path"); } /** * This implementation returns {@link Channels#newChannel(InputStream)} with the * result of {@link #getInputStream()}. * <p> * This is the same as in {@link Resource}'s corresponding default method but * mirrored here for efficient JVM-level dispatching in a class hierarchy. */ @Override public ReadableByteChannel readableChannel() throws IOException { return Channels.newChannel(getInputStream()); } /** * This implementation reads the entire InputStream to calculate the content * length. Subclasses will almost always be able to provide a more optimal * version of this, e.g. checking a File length. * * @see #getInputStream() */ @Override public long contentLength() throws IOException { InputStream is = getInputStream(); try { long size = 0; byte[] buf = new byte[256]; int read; while ((read = is.read(buf)) != -1) { size += read; } return size; } finally { try { is.close(); } catch (IOException ex) { logAccessor.debug(ex, () -> "Could not close InputStream for resource: " + getDescription()); } } } /** * This implementation checks the timestamp of the underlying File, if * available. * * @see #getFileForLastModifiedCheck() */ @Override public long lastModified() throws IOException { File fileToCheck = getFileForLastModifiedCheck(); long lastModified = fileToCheck.lastModified(); if (lastModified == 0L && !fileToCheck.exists()) { throw new FileNotFoundException(getDescription() + " cannot be resolved in the file system for checking its last-modified timestamp"); } return lastModified; } /** * Determine the File to use for timestamp checking. * <p> * The default implementation delegates to {@link #getFile()}. * * @return the File to use for timestamp checking (never {@code null}) * @throws FileNotFoundException if the resource cannot be resolved as an * absolute file path, i.e. is not available in a * file system * @throws IOException in case of general resolution/reading failures */ protected File getFileForLastModifiedCheck() throws IOException { return getFile(); } /** * This implementation throws a FileNotFoundException, assuming that relative * resources cannot be created for this resource. */ @Override public Resource createRelative(String relativePath) throws IOException { throw new FileNotFoundException("Cannot create a relative resource for " + getDescription()); } /** * This implementation always returns {@code null}, assuming that this resource * type does not have a filename. */ @Override @Nullable public String getFilename() { return null; } /** * This implementation compares description strings. * * @see #getDescription() */ @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof Resource && ((Resource) other).getDescription().equals(getDescription()))); } /** * This implementation returns the description's hash code. * * @see #getDescription() */ @Override public int hashCode() { return getDescription().hashCode(); } /** * This implementation returns the description of this resource. * * @see #getDescription() */ @Override public String toString() { return getDescription(); } }
{ "content_hash": "1c09e55c3cdd5dc3956f21c057076985", "timestamp": "", "source": "github", "line_count": 253, "max_line_length": 100, "avg_line_length": 25.42292490118577, "alnum_prop": 0.6957400497512438, "repo_name": "emacslisp/Java", "id": "18ff823da742479fe33e9c8934968efda59a6975", "size": "7053", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "SpringFrameworkReading/src/org/springframework/core/io/AbstractResource.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "430451" }, { "name": "HTML", "bytes": "77076" }, { "name": "Java", "bytes": "7657508" }, { "name": "JavaScript", "bytes": "184534" }, { "name": "SCSS", "bytes": "432566" }, { "name": "Shell", "bytes": "214" } ], "symlink_target": "" }
%-------------------------------------------------------------------------- % Author: Mina Henein - mina.henein@anu.edu.au - 30/06/17 % Contributors: %-------------------------------------------------------------------------- % frontEndSolverExample clear all % close all %% 1. Config % time nSteps = 51; t0 = 0; tN = 10; t = linspace(t0,tN,nSteps); % waypoints staticPose1 = [5,8,0,0,0,0]'; staticPose2 = [4 16 4 pi/2 0 0]'; dynamicWaypoints = [0:2:tN; 4 5 7 10 7 3; 12 11 10 5 8 14; 8 5 2 3 6 4]; % construct trajectories staticTrajectory1 = StaticPoseTrajectory(staticPose1,'R3xso3'); staticTrajectory2 = StaticPoseTrajectory(staticPose2,'R3xso3'); robotTrajectory = PositionModelPoseTrajectory(dynamicWaypoints,'R3','smoothingspline'); % construct config & set properties % CameraConfig is subclass of Config with properties specific to % applications with a camera config = CameraConfig(); % set properties of Config config.set('t',t); config.set('rngSeed',1); % config.set('noiseModel','Gaussian'); config.set('noiseModel','Off'); config.set('poseParameterisation','R3xso3'); % config.set('poseParameterisation','logSE3'); % temporarily changed function handles to public for setting config.absoluteToRelativePoseHandle = @AbsoluteToRelativePoseR3xso3; config.absoluteToRelativePointHandle = @AbsoluteToRelativePositionR3xso3; config.relativeToAbsolutePoseHandle = @RelativeToAbsolutePoseR3xso3; config.relativeToAbsolutePointHandle = @RelativeToAbsolutePositionR3xso3; config.set('cameraPointParameterisation','euclidean'); config.set('cameraControlInput','relativePose'); config.set('poseVertexLabel' ,'VERTEX_POSE_LOG_SE3'); config.set('pointVertexLabel' ,'VERTEX_POINT_3D'); config.set('planeVertexLabel' ,'VERTEX_PLANE_4D'); config.set('posePoseEdgeLabel' ,'EDGE_LOG_SE3'); config.set('posePointEdgeLabel' ,'EDGE_3D'); config.set('pointPlaneEdgeLabel' ,'EDGE_1D'); config.set('posePriorEdgeLabel','EDGE_6D'); config.set('graphFileFolderName' ,'GraphFiles'); config.set('groundTruthFileName' ,'groundTruthFrontEnd.graph'); config.set('measurementsFileName','measurementsFrontEnd.graph'); config.set('stdPosePrior' ,[0.001,0.001,0.001,pi/600,pi/600,pi/600]'); config.set('stdPointPrior',[0.001,0.001,0.001]'); config.set('stdPosePose' ,[0.01,0.01,0.01,pi/90,pi/90,pi/90]'); config.set('stdPosePoint' ,[0.02,0.02,0.02]'); config.set('stdPointPlane',0.001); % set properties of CameraConfig config.set('fieldOfView',[-pi/3,pi/3,-pi/6,pi/6,1,10]); %az,el,r limits config.set('cameraRelativePose',GP_Pose([0,0,0,0,0,-pi/8]')); % set properties of solverConfig % dimensions config.set('dimPose',6); config.set('dimPoint',3); % plane parameterisation' config.set('planeNormalParameterisation','S2'); % constraints config.set('applyAngleConstraints',0); config.set('automaticAngleConstraints',0); % first linearisation point config.set('startPose','initial'); % static assumption config.set('staticAssumption',0); % solver settings config.set('sortVertices',0); config.set('sortEdges',0); config.set('processing','batch'); config.set('nVerticesThreshold',100); config.set('nEdgesThreshold',200); config.set('solveRate',5); config.set('solverType','Levenberg-Marquardt'); config.set('threshold',10e-4); config.set('maxNormDX',1e10); config.set('maxIterations',1000); config.set('displayProgress',1); config.set('savePath',pwd); config.set('plotPlanes',1); %% 2. Generate Environment if config.rngSeed; rng(config.rngSeed); end; environment = Environment(); environment.addRectangle([10,15],100,'mixed',staticTrajectory1); environment.addRectangle([8,6],50,'mixed',staticTrajectory2); % environment.addRectangle([2,3],50,'edges',robotTrajectory); %% 3. Initialise Sensor cameraTrajectory = RelativePoseTrajectory(robotTrajectory,config.cameraRelativePose); sensor = SimulatedEnvironmentSensor(); sensor.addEnvironment(environment); sensor.addCamera(config.fieldOfView,cameraTrajectory); sensor.setVisibility(config); %% 5. Generate Measurements & Save to Graph File sensor.generateMeasurements(config); %% 6. load graph files groundTruthCell = graphFileToCell(config,config.groundTruthFileName); measurementsCell = graphFileToCell(config,config.measurementsFileName); %% 7. Solve %no constraints timeStart = tic; graph0 = Graph(); solver = graph0.process(config,measurementsCell,groundTruthCell); solverEnd = solver(end); totalTime = toc(timeStart); fprintf('\nTotal time solving: %f\n',totalTime) %get desired graphs & systems graph0 = solverEnd.graphs(1); graphN = solverEnd.graphs(end); fprintf('\nChi-squared error: %f\n',solverEnd.systems(end).chiSquaredError) %save results to graph file graphN.saveGraphFile(config,'resultsFrontEnd.graph'); %% 8. Error analysis %load ground truth into graph, sort if required graphGT = Graph(config,groundTruthCell); results = errorAnalysis(config,graphGT,graphN); %% 9. Plot %% 9.1 Plot environment figure viewPoint = [-50,25]; axisLimits = [-1,15,-1,20,-1,10]; title('Environment') axis equal xlabel('x') ylabel('y') zlabel('z') view(viewPoint) axis(axisLimits) hold on staticTrajectory1.plot() staticTrajectory2.plot() cameraTrajectory.plot(t) environment.plot(t) %% 9.1 Plot intial, final and ground-truth solutions %no constraints figure subplot(1,2,1) spy(solverEnd.systems(end).A) subplot(1,2,2) spy(solverEnd.systems(end).H) h = figure; xlabel('x') ylabel('y') zlabel('z') hold on %plot initial solution plotGraph(config,graph0,[0 1 1]); %plot groundtruth plotGraphFile(config,groundTruthCell,[1 0 0]); %plot results resultsCell = graphFileToCell(config,'results.graph'); plotGraphFile(config,resultsCell,'r')
{ "content_hash": "082d0171a69ab19b26c01c532eb2285d", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 89, "avg_line_length": 33.23668639053255, "alnum_prop": 0.7361580915079223, "repo_name": "MinaHenein/do-slam", "id": "818a8cc11c64497baaed43db9e65a10d02bab680", "size": "5617", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Applications/frontEndSolverExample.m", "mode": "33188", "license": "mit", "language": [ { "name": "BlitzBasic", "bytes": "550" }, { "name": "C", "bytes": "59819" }, { "name": "CSS", "bytes": "2552" }, { "name": "HTML", "bytes": "19065" }, { "name": "M", "bytes": "2510" }, { "name": "MATLAB", "bytes": "1791844" }, { "name": "Makefile", "bytes": "4321" }, { "name": "Mathematica", "bytes": "5114" }, { "name": "Objective-C", "bytes": "802" }, { "name": "TeX", "bytes": "83994" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Septoria himeranthi Speg. ### Remarks null
{ "content_hash": "c92a8ea0546dc6fe18e9c55836b997f4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 25, "avg_line_length": 10, "alnum_prop": 0.7076923076923077, "repo_name": "mdoering/backbone", "id": "b56605f64b3d337d9017616ea9a2a2d18ce76a77", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Septoria/Septoria himeranthi/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR arm) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) set(BUILD_TESTING 0) set(COMPILE_EXAMPLES 0) set(CMAKE_VERBOSE_MAKEGILE ON) #Get project root set(PROJECT_ROOT ${CMAKE_CURRENT_LIST_DIR}/../../../) get_filename_component(PROJECT_ROOT ${PROJECT_ROOT} ABSOLUTE) set(TARGET_ROOT ${PROJECT_ROOT}/rootfs) set(CMAKE_C_COMPILER ${PROJECT_ROOT}/cross_compiler/bin/arm-linux-gnueabihf-gcc) set(CMAKE_CXX_COMPILER ${PROJECT_ROOT}/cross_compiler/bin/arm-linux-gnueabihf-g++) set(PKG_CONFIG_EXECUTABLE ${PROJECT_ROOT}/tools/arm-linux-gnueabihf-pkg-config) set(TARGET_ROOT ${PROJECT_ROOT}/rootfs) set(CMAKE_SYSROOT ${TARGET_ROOT}) set(CMAKE_FIND_ROOT_PATH ${TARGET_ROOT}) set(BOOST_INCLUDEDIR ${TARGET_ROOT}/usr/include/boost/) set(BOOST_LIBRARYDIR ${TARGET_ROOT}/usr/lib/arm-linux-gnueabihf/) set( CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ${TARGET_ROOT}/usr/local/lib/cmake # ${TARGET_ROOT}/opt/ros/kinetic ) SET(FLAGS "-isystem ${TARGET_ROOT}/opt/ros/kinetic/include/ \ -Wl,-rpath-link,${TARGET_ROOT}/usr/lib/arm-linux-gnueabihf/mesa \ -Wl,-rpath-link,${TARGET_ROOT}/lib/arm-linux-gnueabihf/mesa-egl \ -Wl,-rpath-link,${TARGET_ROOT}/opt/vc/lib \ -Wl,-rpath-link,${TARGET_ROOT}/lib/arm-linux-gnueabihf \ -Wl,-rpath-link,${TARGET_ROOT}/usr/lib/arm-linux-gnueabihf \ -Wl,-rpath-link,${TARGET_ROOT}/usr/local/lib \ -Wl,-rpath-link,${TARGET_ROOT}/opt/ros/kinetic/lib" ) UNSET(CMAKE_C_FLAGS CACHE) UNSET(CMAKE_CXX_FLAGS CACHE) SET(CMAKE_CXX_FLAGS ${FLAGS} CACHE STRING "" FORCE) SET(CMAKE_C_FLAGS ${FLAGS} CACHE STRING "" FORCE) #cmake --help-module FindPythonLibs | tail -10 set(PYTHON_LIBRARY ${TARGET_ROOT}/usr/lib/python3.5/config-3.5m-arm-linux-gnueabihf/libpython3.5.so) set( PYTHON_INCLUDE_DIRS ${TARGET_ROOT}/usr/include/arm-linux-gnueabihf/python3.5m/ ${TARGET_ROOT}/usr/include/python3.5m/ ) include_directories(${TARGET_ROOT}/usr/include/python3.5m/) set(PYTHON_MULTIARCH arm-linux-gnueabihf)
{ "content_hash": "7050a90c2ab430276395505f9289a868", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 100, "avg_line_length": 32.40625, "alnum_prop": 0.7357762777242044, "repo_name": "ncku-ros2-research/cross-compile-ros2", "id": "2f48441d5cde042d92203a986b67faa27ba2d2e6", "size": "2074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ros2_ws/rostoolchain.cmake", "mode": "33188", "license": "mit", "language": [ { "name": "CMake", "bytes": "2074" }, { "name": "Makefile", "bytes": "607" }, { "name": "Shell", "bytes": "999" } ], "symlink_target": "" }
import React, { Component } from 'react' import Header from '../../components/Header' import './App.css' class App extends Component { render () { return ( <div className='App'> <Header /> <p className='App-intro'> To get started, edit <code>src/App.js</code> and save to reload. </p> </div> ) } } export default App
{ "content_hash": "e70ef1157e3cc6b04bffad93e8976781", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 74, "avg_line_length": 20.944444444444443, "alnum_prop": 0.5702917771883289, "repo_name": "jmahc/GitHupdates", "id": "2985db42da9750cb65b7c6aeaf34df063794e433", "size": "377", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/scenes/App/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "404" }, { "name": "HTML", "bytes": "1590" }, { "name": "JavaScript", "bytes": "3457" } ], "symlink_target": "" }
"""The plugin for serving data from a TensorFlow debugger.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import glob import json import os import re from werkzeug import wrappers from mxconsole.framework import tensor_util from mxconsole.platform import tf_logging as logging from mxconsole.backend import http_util from mxconsole.backend.event_processing import event_accumulator from mxconsole.backend.event_processing import event_file_loader from mxconsole.plugins import base_plugin # The prefix of routes provided by this plugin. PLUGIN_PREFIX_ROUTE = 'debugger' # HTTP routes. _HEALTH_PILLS_ROUTE = '/health_pills' # The POST key of HEALTH_PILLS_ROUTE for a JSON list of node names. _NODE_NAMES_POST_KEY = 'node_names' # The POST key of HEALTH_PILLS_ROUTE for the run to retrieve health pills for. _RUN_POST_KEY = 'run' # The default run to retrieve health pills for. _DEFAULT_RUN = '.' # The POST key of HEALTH_PILLS_ROUTE for the specific step to retrieve health # pills for. _STEP_POST_KEY = 'step' # A glob pattern for files containing debugger-related events. _DEBUGGER_EVENTS_GLOB_PATTERN = 'events.debugger*' class DebuggerPlugin(base_plugin.TBPlugin): """TensorFlow Debugger plugin. Receives requests for debugger-related data. That data could include health pills, which unveil the status of tensor values. """ def get_plugin_apps(self, multiplexer, logdir): """Obtains a mapping between routes and handlers. Stores the logdir. Args: multiplexer: The EventMultiplexer that provides TB data. logdir: The logdir string - the directory of events files. Returns: A mapping between routes and handlers (functions that respond to requests). """ self._event_multiplexer = multiplexer self._logdir = logdir return { _HEALTH_PILLS_ROUTE: self._serve_health_pills_handler, } @wrappers.Request.application def _serve_health_pills_handler(self, request): """A (wrapped) werkzeug handler for serving health pills. Accepts POST requests and responds with health pills. The request accepts several POST parameters: node_names: (required string) A JSON-ified list of node names for which the client would like to request health pills. run: (optional string) The run to retrieve health pills for. Defaults to '.'. This data is sent via POST (not GET) since URL length is limited. step: (optional integer): The session run step for which to retrieve health pills. If provided, the handler reads the health pills of that step from disk (which is slow) and produces a response with only health pills at that step. If not provided, the handler returns a response with health pills at all steps sampled by the event multiplexer (the fast path). The motivation here is that, sometimes, one desires to examine health pills at a specific step (to say find the first step that causes a model to blow up with NaNs). get_plugin_apps must be called before this slower feature is used because that method passes the logdir (directory path) to this plugin. This handler responds with a JSON-ified object mapping from node names to a list (of size 1) of health pill event objects, each of which has these properties. { 'wall_time': float, 'step': int, 'node_name': string, 'output_slot': int, # A list of 12 floats that summarizes the elements of the tensor. 'value': float[], } Node names for which there are no health pills to be found are excluded from the mapping. Args: request: The request issued by the client for health pills. Returns: A werkzeug BaseResponse object. """ if request.method != 'POST': logging.error( '%s requests are forbidden by the debugger plugin.', request.method) return wrappers.Response(status=405) if _NODE_NAMES_POST_KEY not in request.form: logging.error( 'The %r POST key was not found in the request for health pills.', _NODE_NAMES_POST_KEY) return wrappers.Response(status=400) jsonified_node_names = request.form[_NODE_NAMES_POST_KEY] try: node_names = json.loads(jsonified_node_names) except Exception as e: # pylint: disable=broad-except # Different JSON libs raise different exceptions, so we just do a # catch-all here. This problem is complicated by how Tensorboard might be # run in many different environments, as it is open-source. logging.error('Could not decode node name JSON string %r: %s', jsonified_node_names, e) return wrappers.Response(status=400) if not isinstance(node_names, list): logging.error('%r is not a JSON list of node names:', jsonified_node_names) return wrappers.Response(status=400) run = request.form.get(_RUN_POST_KEY, _DEFAULT_RUN) step_string = request.form.get(_STEP_POST_KEY, None) if step_string is None: # Use all steps sampled by the event multiplexer (Relatively fast). mapping = self._obtain_sampled_health_pills(run, node_names) else: # Read disk to obtain the health pills for that step (Relatively slow). # Make sure that the directory for the run exists. # Determine the directory of events file to read. events_directory = self._logdir if run != _DEFAULT_RUN: # Use the directory for the specific run. events_directory = os.path.join(events_directory, run) step = int(step_string) try: mapping = self._obtain_health_pills_at_step( events_directory, node_names, step) except IOError as error: logging.error( 'Error retrieving health pills for step %d: %s', step, error) return wrappers.Response(status=404) # Convert event_accumulator.HealthPillEvents to JSON-able dicts. jsonable_mapping = {} for node_name, events in mapping.items(): jsonable_mapping[node_name] = [e._asdict() for e in events] return http_util.Respond(request, jsonable_mapping, 'application/json') def _obtain_sampled_health_pills(self, run, node_names): """Obtains the health pills for a run sampled by the event multiplexer. This is much faster than the alternative path of reading health pills from disk. Args: run: The run to fetch health pills for. node_names: A list of node names for which to retrieve health pills. Returns: A dictionary mapping from node name to a list of event_accumulator.HealthPillEvents. """ mapping = {} for node_name in node_names: try: mapping[node_name] = self._event_multiplexer.HealthPills(run, node_name) except KeyError: logging.info('No health pills found for node %r.', node_name) continue return mapping def _obtain_health_pills_at_step(self, events_directory, node_names, step): """Reads disk to obtain the health pills for a run at a specific step. This could be much slower than the alternative path of just returning all health pills sampled by the event multiplexer. It could take tens of minutes to complete this call for large graphs for big step values (in the thousands). Args: events_directory: The directory containing events for the desired run. node_names: A list of node names for which to retrieve health pills. step: The step to obtain health pills for. Returns: A dictionary mapping from node name to a list of health pill objects (see docs for _serve_health_pills_handler for properties of those objects). Raises: IOError: If no files with health pill events could be found. """ # Obtain all files with debugger-related events. pattern = os.path.join(events_directory, _DEBUGGER_EVENTS_GLOB_PATTERN) file_paths = glob.glob(pattern) if not file_paths: raise IOError( 'No events files found that matches the pattern %r.', pattern) # Sort by name (and thus by timestamp). file_paths.sort() mapping = collections.defaultdict(list) node_name_set = frozenset(node_names) for file_path in file_paths: should_stop = self._process_health_pill_event( node_name_set, mapping, step, file_path) if should_stop: break return mapping def _process_health_pill_event(self, node_name_set, mapping, target_step, file_path): """Creates health pills out of data in an event. Creates health pills out of the event and adds them to the mapping. Args: node_name_set: A set of node names that are relevant. mapping: The mapping from node name to event_accumulator.HealthPillEvents. This object may be destructively modified. target_step: The target step at which to obtain health pills. file_path: The path to the file with health pill events. Returns: Whether we should stop reading events because future events are no longer relevant. """ events_loader = event_file_loader.EventFileLoader(file_path) for event in events_loader.Load(): if not event.HasField('summary'): logging.warning('An event in a debugger events file lacks a summary.') continue if event.step < target_step: # This event is not of the relevant step. We perform this check # first because the majority of events will be eliminated from # consideration by this check. continue if event.step > target_step: # We have passed the relevant step. No need to read more events. return True for value in event.summary.value: # Since we seek health pills for a specific step, this function # returns 1 health pill per node per step. The wall time is the # seconds since the epoch. health_pill = self._process_health_pill_value( node_name_set, event.wall_time, event.step, value) if not health_pill: continue mapping[health_pill.node_name].append(health_pill) # Keep reading events. return False def _process_health_pill_value(self, node_name_set, wall_time, step, value): """Creates a dict containing various properties of a health pill. Args: node_name_set: A set of node names that are relevant. wall_time: The wall time in seconds. step: The session run step of the event. value: The health pill value. Returns: An event_accumulator.HealthPillEvent. Or None if one could not be created. """ if not value.HasField('tensor'): logging.warning( 'An event in a debugger events file lacks a tensor value.') return None if value.tag != event_accumulator.HEALTH_PILL_EVENT_TAG: logging.warning( ('A debugger-related event lacks the %r tag. It instead has ' 'the %r tag.'), event_accumulator.HEALTH_PILL_EVENT_TAG, value.tag) return None match = re.match(r'^(.*):(\d+):DebugNumericSummary$', value.node_name) if not match: logging.warning( ('A event with a health pill has an invalid watch, (i.e., an ' 'unexpected debug op): %r'), value.node_name) return None node_name = match.group(1) if node_name not in node_name_set: # This event is not relevant. return None # Since we seek health pills for a specific step, this function # returns 1 health pill per node per step. The wall time is the # seconds since the epoch. return event_accumulator.HealthPillEvent( wall_time=wall_time, step=step, node_name=node_name, output_slot=int(match.group(2)), value=list(tensor_util.MakeNdarray(value.tensor)))
{ "content_hash": "75f6048b052b3439cc1d46fff4e43390", "timestamp": "", "source": "github", "line_count": 324, "max_line_length": 80, "avg_line_length": 36.97530864197531, "alnum_prop": 0.6778797996661102, "repo_name": "bravomikekilo/mxconsole", "id": "524c09892c96fc382dacf32ae7d50ae68d5954a2", "size": "12669", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mxconsole/plugins/debugger/debugger_plugin.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "27900" }, { "name": "CSS", "bytes": "5107" }, { "name": "HTML", "bytes": "584168" }, { "name": "JavaScript", "bytes": "1734943" }, { "name": "Protocol Buffer", "bytes": "71639" }, { "name": "Python", "bytes": "981371" }, { "name": "Shell", "bytes": "1566" }, { "name": "TypeScript", "bytes": "786869" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.coolweather.app" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/cat" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.coolweather.app.ChooseAreaActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.coolweather.app.WeatherActivity"> </activity> <service android:name="service.AutoUpdateService"> </service> <receiver android:name="receiver.AutoUpdateReceiver"> </receiver> </application> </manifest>
{ "content_hash": "e4d0c177a11ef43a102ece29878b2a48", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 76, "avg_line_length": 32.10526315789474, "alnum_prop": 0.5975409836065574, "repo_name": "sfwuguang/coolweather", "id": "573d2b59010fbfe9d2689f8533fa4ee59d12a0ed", "size": "1220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "24278" } ], "symlink_target": "" }
package com.sap.cloud.lm.sl.cf.core.cf.v2; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.collections4.MapUtils; import com.sap.cloud.lm.sl.cf.client.lib.domain.CloudApplicationExtended; import com.sap.cloud.lm.sl.cf.core.model.DeployedMtaModule; import com.sap.cloud.lm.sl.cf.core.model.SupportedParameters; import com.sap.cloud.lm.sl.cf.core.model.SupportedParameters.RoutingParameterSet; import com.sap.cloud.lm.sl.cf.core.parser.IdleUriParametersParser; import com.sap.cloud.lm.sl.cf.core.parser.UriParametersParser; import com.sap.cloud.lm.sl.common.util.ListUtil; import com.sap.cloud.lm.sl.mta.model.DeploymentDescriptor; import com.sap.cloud.lm.sl.mta.model.Module; import com.sap.cloud.lm.sl.mta.util.PropertiesUtil; public class ApplicationUrisCloudModelBuilder { private final DeploymentDescriptor descriptor; private final CloudApplicationExtended.AttributeUpdateStrategy applicationAttributeUpdateStrategy; public ApplicationUrisCloudModelBuilder(DeploymentDescriptor descriptor, CloudApplicationExtended.AttributeUpdateStrategy applicationAttributeUpdateStrategy) { this.descriptor = descriptor; this.applicationAttributeUpdateStrategy = applicationAttributeUpdateStrategy; } public List<String> getApplicationUris(Module module, List<Map<String, Object>> propertiesList, DeployedMtaModule deployedModule) { List<String> uris = getUriParametersParser(module).parse(propertiesList); if (shouldKeepExistingUris(propertiesList)) { return appendExistingUris(uris, deployedModule); } return uris; } private boolean shouldKeepExistingUris(List<Map<String, Object>> propertiesList) { return (boolean) getPropertyValue(propertiesList, SupportedParameters.KEEP_EXISTING_ROUTES, false) || applicationAttributeUpdateStrategy.shouldKeepExistingRoutes(); } private Object getPropertyValue(List<Map<String, Object>> propertiesList, String propertyName, Object defaultValue) { return PropertiesUtil.getPropertyValue(propertiesList, propertyName, defaultValue); } private List<String> appendExistingUris(List<String> uris, DeployedMtaModule deployedModule) { List<String> result = new ArrayList<>(uris); if (deployedModule != null) { result.addAll(deployedModule.getUris()); } return ListUtil.removeDuplicates(result); } public List<String> getApplicationDomains(Module module, List<Map<String, Object>> propertiesList) { return getUriParametersParser(module).getApplicationDomains(propertiesList); } public List<String> getIdleApplicationUris(Module module, List<Map<String, Object>> propertiesList) { RoutingParameterSet parametersType = RoutingParameterSet.DEFAULT_IDLE; Map<String, Object> moduleParameters = module.getParameters(); String defaultHost = (String) moduleParameters.getOrDefault(parametersType.host, null); String defaultRoutePath = (String) module.getParameters() .get(SupportedParameters.ROUTE_PATH); String defaultDomain = getDefaultDomain(parametersType, moduleParameters); return new IdleUriParametersParser(defaultHost, defaultDomain, defaultRoutePath).parse(propertiesList); } private UriParametersParser getUriParametersParser(Module module) { RoutingParameterSet parametersType = RoutingParameterSet.DEFAULT; Map<String, Object> moduleParameters = module.getParameters(); String defaultHost = (String) moduleParameters.getOrDefault(parametersType.host, null); String routePath = (String) module.getParameters() .get(SupportedParameters.ROUTE_PATH); String defaultDomain = getDefaultDomain(parametersType, moduleParameters); return new UriParametersParser(defaultHost, defaultDomain, routePath); } private String getDefaultDomain(RoutingParameterSet parametersType, Map<String, Object> moduleParameters) { if (descriptor.getParameters() .containsKey(parametersType.domain)) { return (String) descriptor.getParameters() .get(parametersType.domain); } return (String) moduleParameters.getOrDefault(parametersType.domain, null); } }
{ "content_hash": "96ed8f8b57bc1ea115d81a8a0f2df00c", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 135, "avg_line_length": 49.68539325842696, "alnum_prop": 0.7394843962008141, "repo_name": "boyan-velinov/cf-mta-deploy-service", "id": "d576b87d8557664716c266d5648ef74d61580b69", "size": "4422", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/cf/v2/ApplicationUrisCloudModelBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2325" }, { "name": "Java", "bytes": "2541164" }, { "name": "JavaScript", "bytes": "23473" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_03) on Tue Mar 04 12:30:56 CET 2008 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> Uses of Class de.opsdesign.yax.types.Pipeline (Yax - an XProc (XML Pipeline) Implementation 0.11.0-SNAPSHOT API) </TITLE> <META NAME="date" CONTENT="2008-03-04"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class de.opsdesign.yax.types.Pipeline (Yax - an XProc (XML Pipeline) Implementation 0.11.0-SNAPSHOT API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../de/opsdesign/yax/types/Pipeline.html" title="class in de.opsdesign.yax.types"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?de/opsdesign/yax/types/\class-usePipeline.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Pipeline.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>de.opsdesign.yax.types.Pipeline</B></H2> </CENTER> No usage of de.opsdesign.yax.types.Pipeline <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../de/opsdesign/yax/types/Pipeline.html" title="class in de.opsdesign.yax.types"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?de/opsdesign/yax/types/\class-usePipeline.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Pipeline.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright © 2008 <a href="http://www.opsdesign.de">OPS Design GmbH</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "39604b707cf30f5556f76c2f7c9fa8cc", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 210, "avg_line_length": 43.296551724137935, "alnum_prop": 0.601784007645747, "repo_name": "lewismc/yax", "id": "e7c4578686cf3695641fc02ee2539272219375f1", "size": "6278", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/html/apidocs/de/opsdesign/yax/types/class-use/Pipeline.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "188343" }, { "name": "JavaScript", "bytes": "28474" }, { "name": "Shell", "bytes": "21771" } ], "symlink_target": "" }
'use strict'; var url = require('url'); var Help = require('./HelpService'); module.exports.helpGET = function helpGET (req, res, next) { Help.helpGET(req.swagger.params, res, next); };
{ "content_hash": "390c7d1807a12c1da2458362acc05927", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 60, "avg_line_length": 17.545454545454547, "alnum_prop": 0.6683937823834197, "repo_name": "iandrosov/df16-harvest-api", "id": "af7eaa4ad850c7cc7b3d1078c8fd1743858226f7", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "controllers/Help.js", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "16854" } ], "symlink_target": "" }
// // avatarCustomization101.js // // Blueprint App to teach users how to use materials, blendshapes, and flow for their avatars. // // Created by Robin Wilson and Mark Brosche 2/20/2019 // Avatar created by Jimi Youm 2/20/2019 // Copyright 2019 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html /* global GlobalDebugger */ (function() { // Include flow to access GlobalDebugger available in flow.js var FLOW_DELAY_MS = 2000; Script.setTimeout(function() { Script.include(Script.resolvePath("./resources/modules/flow.js")); }, FLOW_DELAY_MS); // Modules var AppUi = Script.require("appUi"), URL = Script.resolvePath("./resources/avatarCustomization101_ui.html"), CONFIG = Script.require(Script.resolvePath("./resources/config.js")), BLENDSHAPE_DATA = Script.require(Script.resolvePath("./resources/modules/blendshapes.json")), MATERIAL_DATA = Script.require(Script.resolvePath("./resources/modules/materials.js")), AVATAR_URL = Script.resolvePath("./resources/avatar/avatar.fst"); // Static strings var STRING_MATERIAL = CONFIG.STRING_MATERIAL, STRING_BLENDSHAPES = CONFIG.STRING_BLENDSHAPES, STRING_FLOW = CONFIG.STRING_FLOW, STRING_INFO = CONFIG.STRING_INFO, STRING_STATE = CONFIG.STRING_STATE; var DEBUG = false; // #region UTILITY // Deep copy object utility function deepCopy(objectToCopy) { var newObject; try { newObject = JSON.parse(JSON.stringify(objectToCopy)); } catch (e) { console.error("Error with deepCopy utility method" + e); } return newObject; } // Color functions found https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb // Convert color format hex to rgb function hexToRgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } // Convert color format rgb to hex var BITS_16 = 16; var SHIFT_LEFT_24 = 24; var SHIFT_LEFT_16 = 16; var SHIFT_LEFT_8 = 8; function rgbToHex(colorObject) { var r = colorObject.r; var g = colorObject.g; var b = colorObject.b; var str = "" + ((1 << SHIFT_LEFT_24) + (r << SHIFT_LEFT_16) + (g << SHIFT_LEFT_8) + b).toString(BITS_16).slice(1); if (DEBUG) { print("RgbToHex" + str); } return str; } // Convert color format array to rgb var RGB_255 = 255.0; function arrayToRGB(color) { if (Array.isArray(color)) { var rgbFormat = { r: Math.floor( color[0] * RGB_255 ), g: Math.floor( color[1] * RGB_255 ), b: Math.floor( color[2] * RGB_255 ) }; if (DEBUG) { print("arrayToRGB" + JSON.stringify(rgbFormat)); } return rgbFormat; } else { return color; } } // #endregion UTILITY // #region MIRROR var MIRROR_DISTANCE_Z_M = 0.5, MIRROR_DISTANCE_Y_M = 0.8, LIFETIME_MS = 10000, mirrorCubeID; // Creates mirror function spawnMirror() { // Remove old mirror MyAvatar.getAvatarEntitiesVariant().forEach(function(avatarEntity) { var name = Entities.getEntityProperties(avatarEntity.id, 'name').name; if (name === "Avatar 101 Mirror") { Entities.deleteEntity(avatarEntity.id); } }); // Create new mirror var position = Vec3.sum( MyAvatar.position, Vec3.multiplyQbyV(MyAvatar.orientation, { x: 0, y: MIRROR_DISTANCE_Y_M, z: -MIRROR_DISTANCE_Z_M }) ); mirrorCubeID = Entities.addEntity({ type: "Box", name: "Avatar 101 Mirror", dimensions: { "x": 0.6, "y": 0.7, "z": 0.001 }, lifetime: LIFETIME_MS, position: position, rotation: MyAvatar.orientation, userData: "{\"grabbableKey\":{\"grabbable\":false}}", collisionless: true, script: Script.resolvePath("./resources/modules/mirrorClient.js?v9") }, "avatar"); } // Delete mirror entity function deleteMirror() { // Delete mirror entity if it exists if (mirrorCubeID) { Entities.deleteEntity(mirrorCubeID); mirrorCubeID = null; } } // #endregion MIRROR // #region AVATAR // Save and change the avatar to Avi function saveAvatarAndChangeToAvi() { AvatarBookmarks.addBookmark(CONFIG.STRING_BOOKMARK_NAME); changeAvatarToAvi(); } // Load saved avatar if saved, if not send user an alert function restoreAvatar() { var bookmarksObject = AvatarBookmarks.getBookmarks(); if (bookmarksObject[CONFIG.STRING_BOOKMARK_NAME]) { AvatarBookmarks.loadBookmark(CONFIG.STRING_BOOKMARK_NAME); AvatarBookmarks.removeBookmark(CONFIG.STRING_BOOKMARK_NAME); setIsAviEnabledFalse(); } else { Window.alert("No bookmark was saved in the avatar app."); } } // Switch avatar to Avi // Update state to avi to enabled function changeAvatarToAvi() { // Set avatar to Avi.fst MyAvatar.useFullAvatarURL(AVATAR_URL); MyAvatar.setAttachmentsVariant([]); dynamicData.state.isAviEnabled = true; } // Contains all steps to set the app state to isAviEnabled = false function setIsAviEnabledFalse() { dynamicData.state.isAviEnabled = false; dynamicData.state.activeTabName = STRING_INFO; deleteJacketMaterial(); removeBlendshapes(); deleteMirror(); updateUI(STRING_STATE); } // #endregion AVATAR // #region MATERIAL // This takes the format of the UI defined in config.js and converts it into // the argument format update material expects // propertyName // newMaterialData { value: "" map: "" } // componentType: STRING_COLOR / STRING_SLIDER / STRING_MAP_ONLY // isPBR: boolean function updateMaterialProperty(propertyName, newMaterialData, componentType, isPBR) { var propertyMap = propertyName + "Map"; if (DEBUG) { print("Update Material Property key: ", propertyName, " value: ", newMaterialData.value); print("Update Material Property key: ", propertyMap, " map: ", newMaterialData.map); print("Update Material Property isPBR: ", isPBR); } // update UI values var type = isPBR ? "pbr" : "shadeless"; // prep data for changing material entity in updateMaterial() var updates = { unlit: !isPBR }; if (newMaterialData.value !== undefined) { // null is a valid entry var value = newMaterialData.value; if (componentType === CONFIG.STRING_COLOR) { value = convertHexToArrayColor(newMaterialData.value); } else if (componentType === CONFIG.STRING_MAP_ONLY) { value = addFileDirectory(newMaterialData.value); } // slider value does not need to be changed updates[propertyName] = value; dynamicData[STRING_MATERIAL][type][propertyName].value = newMaterialData.value; } if (newMaterialData.map !== undefined && componentType !== CONFIG.STRING_MAP_ONLY) { // null is a valid entry updates[propertyMap] = addFileDirectory(newMaterialData.map); dynamicData[STRING_MATERIAL][type][propertyName].map = newMaterialData.map; } updateMaterial({ materials: updates }, false, isPBR); } // Convert hex color to array color function convertHexToArrayColor(hexColor){ if (hexColor) { // hex -> rgb -> array var rgb = hexToRgb(hexColor); return [ rgb.r / RGB_255, rgb.g / RGB_255, rgb.b / RGB_255 ]; } } // Add file directory to file name function addFileDirectory(file) { if (file && file.indexOf("no.jpg") !== -1) { // the "nothing selected" texture return null; } return MATERIAL_DATA.directory + file; } // prioritize a properties over b properties function mergeObjectProperties(a, b) { for (var key in b) { if (b[key] === null && a[key]) { // remove any values in a if new b value is null delete a[key]; } else { a[key] = b[key]; } } return a; } // Array color to hex color function convertArrayToHexColor(arrayColor){ // array -> rgb -> hex var rgb = arrayToRGB(arrayColor); var hex = rgbToHex(rgb); return hex; } // button is pressed and must loop through all UI elements to update // newMaterialData.materials passed in // for Named buttons only var PBR_INDEX = 2; var SHADELESS_INDEX = 1; function updateMaterialDynamicDataUI(newMaterialDataToApply, isPBR) { // set the UI drop-down index to hifi-PBR (index 2) or shadeless (index 1) dynamicData[STRING_MATERIAL].selectedTypeIndex = isPBR ? PBR_INDEX : SHADELESS_INDEX; var type = isPBR ? "pbr" : "shadeless"; // Update UI with values var dynamicPropertyData = dynamicData[STRING_MATERIAL][type]; var newMaterials = newMaterialDataToApply.materials; // Loop through all newMaterialProperties for (var property in newMaterials) { var key = property; var value = newMaterials[key]; if (DEBUG) { print("Key is :", key, " dynamic property data is :", JSON.stringify(dynamicPropertyData)); } if (key === "model" || key === "unlit") { // property doesnt exist in ui properties continue; } if (key.indexOf("Map") !== -1) { // is a Map var uiValue = value.replace(MATERIAL_DATA.directory, ""); // remove path url if (dynamicPropertyData[key]) { // is Map Only dynamicPropertyData[key].value = uiValue; dynamicPropertyData[key].map = uiValue; } else { // is slider or color component type var uiProperty = key.replace("Map", ""); dynamicPropertyData[uiProperty].map = uiValue; } } else { // is Color or Slider value dynamicPropertyData[key].value = Array.isArray(value) ? convertArrayToHexColor(value) // is color : value; } } } // Update material or create a new material var materialID; function updateMaterial(newMaterialData, isNamed, isPBR) { var materialEntityProperties; // these properties change var description = newMaterialData.description ? newMaterialData.description : ""; // default value var materialMappingScale = newMaterialData.materialMappingScale ? newMaterialData.materialMappingScale : { x: 1, y: 1 }; // default value var newMaterials = newMaterialData.materials; // If material already exists and isNamed === false // Merge old material properties and new material properties if (materialID && !isNamed) { var oldMaterialDataString; var oldMaterials = {}; var oldMaterialProperties = Entities.getEntityProperties(materialID, ["materialData", "materialMappingScale", "description"]); oldMaterialDataString = oldMaterialProperties.materialData; description = oldMaterialProperties.description; materialMappingScale = oldMaterialProperties.materialMappingScale; try { // get old materials values and properties to carry over to new oldMaterials = JSON.parse(oldMaterialDataString).materials; } catch (e) { console.error("Issues parsing oldMaterialDataString " + e); return; } // merge new materials and old material properties together newMaterials = mergeObjectProperties(oldMaterials, newMaterials); if (newMaterials["unlit"] && !isPBR) { // unlit exists and is false // is shadeless delete newMaterials["unlit"]; } } // Create new material if (!materialID) { // Delete old material entity // In case materialID reference was lost but material still exists on Avi MyAvatar.getAvatarEntitiesVariant().forEach(function(avatarEntity) { var name = Entities.getEntityProperties(avatarEntity.id, 'name').name; if (name === "Avatar101-Material") { Entities.deleteEntity(avatarEntity.id); } }); newMaterials.model = "hifi_pbr"; materialEntityProperties = { type: "Material", name: "Avatar101-Material", parentID: MyAvatar.sessionUUID, materialURL: "materialData", // utilize material data to define properties priority: 1, // multiple materials can be parented, highest priority is rendered parentMaterialName: 2, // avatar submesh description: description, // description of the material materialMappingScale: materialMappingScale, // scale of the material materialData: JSON.stringify({ materialVersion: 1, materials: newMaterials }) }; materialID = Entities.addEntity(materialEntityProperties, "avatar"); } else { // Update old material var updates = { description: description, materialMappingScale: materialMappingScale, materialData: JSON.stringify({ materialVersion: 1, materials: newMaterials }) }; Entities.editEntity(materialID, updates); } if (isNamed) { // is Named // Update the ui with new properties setMaterialPropertiesToDefaults(); updateMaterialDynamicDataUI(newMaterialData, isPBR); } } // For both shadeless properties in dynamic data // Set back to default values function setMaterialPropertiesToDefaults() { // shadeless setDefaults(dynamicData[STRING_MATERIAL].shadeless, defaultMaterialProperties.shadeless); // pbr setDefaults(dynamicData[STRING_MATERIAL].pbr, defaultMaterialProperties.pbr); } // Take the dynamic data object and use the default object // to set values to default value function setDefaults(dynamicObject, defaultObject) { for (var key in defaultObject) { var defaultValue = defaultObject[key].value; var defaultMap = defaultObject[key].map; dynamicObject[key].value = defaultValue; dynamicObject[key].map = defaultMap; } } // Apply the named material to material entity function applyNamedMaterial(materialName) { // Set the selected material in UI dynamicData[STRING_MATERIAL].selectedMaterial = materialName; switch (materialName){ case CONFIG.STRING_DEFAULT: setMaterialPropertiesToDefaults(); dynamicData[STRING_MATERIAL].selectedTypeIndex = 0; // "Select one" deleteJacketMaterial(); break; case CONFIG.STRING_GLASS: // updateMaterial materialName, isNamed, isPBR updateMaterial(MATERIAL_DATA.glass, true, true); break; case CONFIG.STRING_CHAINMAIL: updateMaterial(MATERIAL_DATA.chainmail, true, true); break; case CONFIG.STRING_DISCO: updateMaterial(MATERIAL_DATA.disco, true, true); break; case CONFIG.STRING_RED: updateMaterial(MATERIAL_DATA.red, true, false); break; case CONFIG.STRING_TEXTURE: updateMaterial(MATERIAL_DATA.texture, true, false); break; } } // Delete material function deleteJacketMaterial() { if (materialID) { Entities.deleteEntity(materialID); materialID = null; } } // #endregion MATERIAL // #region BLENDSHAPES // Take newBlendshapeData and update selected blendshape, properties, and the avatar blendshapes function updateBlendshapes(newBlendshapeData, isName) { if (DEBUG) { print("New blendshape data", JSON.stringify(newBlendshapeData)); } if (!isName) { // is not named blendshape, ensure last blendshape is not selected dynamicData[STRING_BLENDSHAPES].selected = ""; } // update all dynamic data blendshapes for (var property in newBlendshapeData) { // set it in dynamic data for ui dynamicData[STRING_BLENDSHAPES].updatedProperties[property] = newBlendshapeData[property]; // set it on the avatar MyAvatar.setBlendshape(property, newBlendshapeData[property]); } } // Apply the named blendshape to avatar function applyNamedBlendshapes(blendshapeName) { // Set the selected blendshape data in UI dynamicData[STRING_BLENDSHAPES].selected = blendshapeName; switch (blendshapeName){ case "default": updateBlendshapes(BLENDSHAPE_DATA.defaults, true); break; case "awe": updateBlendshapes(BLENDSHAPE_DATA.awe, true); break; case "laugh": updateBlendshapes(BLENDSHAPE_DATA.laugh, true); break; case "angry": updateBlendshapes(BLENDSHAPE_DATA.angry, true); break; } } // Set Blendshapes back to default var BLENDSHAPE_RESET_MS = 50; function removeBlendshapes() { MyAvatar.hasScriptedBlendshapes = true; applyNamedBlendshapes("default"); Script.setTimeout(function () { MyAvatar.hasScriptedBlendshapes = false; // updateUI(STRING_BLENDSHAPES); }, BLENDSHAPE_RESET_MS); } // #endregion BLENDSHAPES // #region FLOW // Called when user navigates to flow tab function addRemoveFlowDebugSpheres(isEnabled, setShowDebugSpheres) { // draw debug circles on the joints var flowSettings = GlobalDebugger.getDisplayData(); // the state of flow is the opposite of what we want if (flowSettings.debug !== isEnabled) { GlobalDebugger.toggleDebugShapes(); // set the setting if setShowDebugSpheres is true if (setShowDebugSpheres) { dynamicData[STRING_FLOW].showDebug = isEnabled; } } } // Add collisions or remove collisions using the toggleCollisions flow function function addRemoveCollisions(isEnabled) { // draw debug circles on the joints var flowSettings = GlobalDebugger.getDisplayData(); // the state of flow is the opposite of what we want if (flowSettings.collisions !== isEnabled) { GlobalDebugger.toggleCollisions(); dynamicData[STRING_FLOW].enableCollisions = isEnabled; } } // Update flow options function updateFlow(newFlowDataToApply, subtype) { if (DEBUG) { print("updating flow: ", subtype, JSON.stringify(newFlowDataToApply)); } // propertyName is the key and value is the new property value // for example newFlowDataToApply = { stiffness: 0.5 } for (var propertyName in newFlowDataToApply) { var newValue = newFlowDataToApply[propertyName]; if (subtype === CONFIG.FLOW_EVENTS_SUBTYPE.STRING_HAIR) { GlobalDebugger.setJointDataValue("leaf", propertyName, newValue); dynamicData[STRING_FLOW].hairFlowOptions[propertyName] = newValue; } else if (subtype === CONFIG.FLOW_EVENTS_SUBTYPE.STRING_JOINTS) { GlobalDebugger.setCollisionDataValue("HeadTop_End", propertyName, newValue); dynamicData[STRING_FLOW].jointFlowOptions[propertyName] = newValue; } } } // #endregion FLOW // #region APP // Create menu button and connect all callbacks to signals on startup var ui; var dynamicData; // UI data var defaultMaterialProperties; // set default UI values to be parsed when setDefaults() is called for materials function startup() { // Set initial UI data for our app and Vue // App data will be populated after updateUI is called in onMessage EVENT_BRIDGE_OPEN_MESSAGE dynamicData = deepCopy(CONFIG.INITIAL_DYNAMIC_DATA); defaultMaterialProperties = { shadeless: deepCopy(CONFIG.INITIAL_DYNAMIC_DATA[STRING_MATERIAL].shadeless), pbr: deepCopy(CONFIG.INITIAL_DYNAMIC_DATA[STRING_MATERIAL].pbr) }; // Create the tablet app ui = new AppUi({ buttonName: CONFIG.BUTTON_NAME, home: URL, onMessage: onMessage, // UI event listener // Icons are located in graphicsDirectory // AppUI is looking for icons named with the BUTTON_NAME "avatar-101" // For example: avatar-101-a.svg for active button icon, avatar-101-i.svg for inactive button icon graphicsDirectory: Script.resolvePath("./resources/icons/"), onOpened: onOpened, onClosed: onClosed }); // Connect unload function to the script ending Script.scriptEnding.connect(unload); // Connect function callback to model url changed signal MyAvatar.skeletonModelURLChanged.connect(onAvatarModelURLChanged); } // Checks the current avatar model and sees if the avatar url is Avi function onAvatarModelURLChanged() { if (MyAvatar.skeletonModelURL === AVATAR_URL) { dynamicData.state.isAviEnabled = true; if (!mirrorCubeID) { spawnMirror(); } // if your last closed tab has extra setup functionality // ensure you have the correct view for the current tab switchTabs(dynamicData.state.activeTabName); } else { setIsAviEnabledFalse(); } updateUI(STRING_STATE); } // Called each time app is closed function onClosed() { // save lastTab that the user was on dynamicData.state.activeTabName = currentTab; MyAvatar.hasScriptedBlendshapes = false; addRemoveFlowDebugSpheres(false); deleteMirror(); } // Called each time app is opened function onOpened() { if (DEBUG) { print("ACA101 onOpened: isAviEnabled ", MyAvatar.skeletonModelURL === AVATAR_URL); print("ACA101 onOpened: activeTabName is ", dynamicData.state.activeTabName); } // Checks avatar model url onAvatarModelURLChanged(); spawnMirror(); updateUI(STRING_STATE); } // Functionality for each time a tab is switched var currentTab; function switchTabs(tabName) { var previousTab = currentTab; currentTab = tabName; // Flow tab conditionals if (currentTab === STRING_FLOW && dynamicData[STRING_FLOW].showDebug){ // enable debug spheres addRemoveFlowDebugSpheres(true); } else if (previousTab === STRING_FLOW && currentTab !== STRING_FLOW){ // disable debug spheres addRemoveFlowDebugSpheres(false); } // Blendshape tab conditionals if (currentTab === STRING_BLENDSHAPES) { // enable scripted blendshapes MyAvatar.hasScriptedBlendshapes = true; } else if (previousTab === STRING_BLENDSHAPES && currentTab !== STRING_BLENDSHAPES){ // disable scripted blendshapes MyAvatar.hasScriptedBlendshapes = false; } updateUI(STRING_STATE); } // Unload functions function unload() { onClosed(); // Set blendshapes back to normal removeBlendshapes(); deleteJacketMaterial(); // Disconnect function callback from signal when model url changes MyAvatar.skeletonModelURLChanged.disconnect(onAvatarModelURLChanged); } // #endregion APP // #region EVENTS // Handles events recieved from the UI function onMessage(data) { // EventBridge message from HTML script. // Check against EVENT_NAME to ensure we're getting the correct messages from the correct app if (!data.type || data.type.indexOf(CONFIG.APP_NAME) === -1) { if (DEBUG) { print("Event type event name index check: ", !data.type, data.type.indexOf(CONFIG.APP_NAME) === -1); } return; } data.type = data.type.replace(CONFIG.APP_NAME, ""); if (DEBUG) { print("onMessage: ", data.type); print("subtype: ", data.subtype); } switch (data.type) { case CONFIG.EVENT_BRIDGE_OPEN_MESSAGE: onOpened(); updateUI(); break; case CONFIG.EVENT_UPDATE_AVATAR: switch (data.subtype) { case CONFIG.EVENT_CHANGE_AVATAR_TO_AVI_AND_SAVE_AVATAR: saveAvatarAndChangeToAvi(); break; case CONFIG.EVENT_RESTORE_SAVED_AVATAR: restoreAvatar(); break; case CONFIG.EVENT_CHANGE_AVATAR_TO_AVI_WITHOUT_SAVING_AVATAR: changeAvatarToAvi(); break; default: break; } updateUI(STRING_STATE); break; case CONFIG.EVENT_CHANGE_TAB: switchTabs(data.value); updateUI(STRING_STATE); break; case CONFIG.EVENT_UPDATE_MATERIAL: // delegates the method depending on if // event has name property or updates property if (DEBUG) { print("MATERIAL EVENT" , data.subtype, " ", data.name, " ", data.updates); } switch (data.subtype) { case CONFIG.MATERIAL_EVENTS_SUBTYPE.STRING_MODEL_TYPE_SELECTED: applyNamedMaterial(CONFIG.STRING_DEFAULT); dynamicData[STRING_MATERIAL].selectedTypeIndex = data.updates; break; case CONFIG.MATERIAL_EVENTS_SUBTYPE.STRING_NAMED_MATERIAL_SELECTED: applyNamedMaterial(data.name); break; case CONFIG.MATERIAL_EVENTS_SUBTYPE.STRING_UPDATE_PROPERTY: var propertyName = data.updates.propertyName; var newMaterialData = data.updates.newMaterialData; var componentType = data.updates.componentType; var isPBR = data.updates.isPBR; console.log("update Property" + propertyName + JSON.stringify(newMaterialData)); updateMaterialProperty(propertyName, newMaterialData, componentType, isPBR); break; } updateUI(STRING_MATERIAL); break; case CONFIG.EVENT_UPDATE_BLENDSHAPE: if (data.name) { applyNamedBlendshapes(data.name); } else { updateBlendshapes(data.updates); } updateUI(STRING_BLENDSHAPES); break; case CONFIG.EVENT_UPDATE_FLOW: switch (data.subtype) { case CONFIG.FLOW_EVENTS_SUBTYPE.STRING_DEBUG_TOGGLE: if (DEBUG) { print("TOGGLE DEBUG SPHERES ", data.updates); } addRemoveFlowDebugSpheres(data.updates, true); break; case CONFIG.FLOW_EVENTS_SUBTYPE.STRING_COLLISIONS_TOGGLE: addRemoveCollisions(data.updates); break; case CONFIG.FLOW_EVENTS_SUBTYPE.STRING_HAIR: updateFlow(data.updates, CONFIG.FLOW_EVENTS_SUBTYPE.STRING_HAIR); break; case CONFIG.FLOW_EVENTS_SUBTYPE.STRING_JOINTS: updateFlow(data.updates, CONFIG.FLOW_EVENTS_SUBTYPE.STRING_JOINTS); break; default: console.error("Flow recieved no matching subtype"); break; } updateUI(STRING_FLOW); break; default: break; } } // Send information to update the UI function updateUI(type) { var messageObject = { type: CONFIG.UPDATE_UI, subtype: type ? type : "", value: type ? dynamicData[type] : dynamicData }; if (DEBUG) { print("Update UI", type); } ui.sendToHtml(messageObject); } // #endregion EVENTS // Initialize the app startup(); })();
{ "content_hash": "8ca12bda2d90df01865a388d4a546eef", "timestamp": "", "source": "github", "line_count": 866, "max_line_length": 122, "avg_line_length": 35.352193995381064, "alnum_prop": 0.5711252653927813, "repo_name": "RebeccaStankus/hifi-content", "id": "cd6bb80995b802fe43aaf2836befec2f78592baf", "size": "30615", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "marketplaceItems/avatarCustomization101/appResources/appData/avatarCustomization101_app.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "161840" }, { "name": "F*", "bytes": "6774" }, { "name": "GLSL", "bytes": "3603" }, { "name": "HTML", "bytes": "376523" }, { "name": "JavaScript", "bytes": "5355428" }, { "name": "Makefile", "bytes": "317" }, { "name": "PLSQL", "bytes": "83896" }, { "name": "QML", "bytes": "73180" } ], "symlink_target": "" }
import Base: convert, haskey, setindex!, getindex export slider, togglebutton, button, checkbox, textbox, textarea, radiobuttons, dropdown, selection, togglebuttons, html, latex, hbox, vbox, progress, widget, selection_slider, set! const Empty = VERSION < v"0.4.0-dev" ? Nothing : Void ### Layout Widgets type Layout <: Widget box::Any end type Box <: Widget layout::Any vert::Bool children::Vector{Widget} Box(layout, vert, children) = begin b = new(layout, vert, children) layout.box = b b end end hbox(children::Vararg{Widget}) = Box(Layout(nothing), false, collect(children)) vbox(children::Vararg{Widget}) = Box(Layout(nothing), true, collect(children)) ### Input widgets """Helps init widget's value and signal depending on which ones were set""" function init_wsigval(signal, value; default=value, typ=typeof(default)) if signal == nothing if value == nothing value = default end _typ = typ === Void ? typeof(value) : typ signal = Signal(_typ, value) else #signal set if value == nothing value = signal.value else #signal set and value set push!(signal, value) end end signal, value end ########################## Slider ############################ type Slider{T<:Number} <: InputWidget{T} signal::Signal{T} label::AbstractString value::T range::Range{T} orientation::String readout::Bool readout_format::AbstractString continuous_update::Bool end # differs from median(r) in that it always returns an element of the range medianelement(r::Range) = r[(1+length(r))>>1] slider(args...) = Slider(args...) """ slider(range; value, signal, label="", readout=true, continuous_update=true) Create a slider widget with the specified `range`. Optionally specify the starting `value` (defaults to the median of `range`), provide the (Reactive.jl) `signal` coupled to this slider, and/or specify a string `label` for the widget. """ slider{T}(range::Range{T}; value=nothing, signal=nothing, label="", orientation="horizontal", readout=true, readout_format=T <: Integer ? "d" : ".3f", continuous_update=true, syncsig=true) = begin signal, value = init_wsigval(signal, value; typ=T, default=medianelement(range)) s = Slider(signal, label, value, range, orientation, readout, readout_format, continuous_update) if syncsig #keep the slider updated if the signal changes keep_updated(val) = begin if val != s.value s.value = val update_view(s) end nothing end preserve(map(keep_updated, signal; typ=Void)) end s end ######################### Checkbox ########################### type Checkbox <: InputWidget{Bool} signal::Signal{Bool} label::AbstractString value::Bool end checkbox(args...) = Checkbox(args...) """ checkbox(value=false; label="", signal) Provide a checkbox with the specified starting (boolean) `value`. Optional provide a `label` for this widget and/or the (Reactive.jl) `signal` coupled to this widget. """ checkbox(value::Bool; signal=nothing, label="") = begin signal, value = init_wsigval(signal, value) Checkbox(signal, label, value) end checkbox(; label="", value=nothing, signal=nothing) = begin signal, value = init_wsigval(signal, value; default=false) Checkbox(signal, label, value) end ###################### ToggleButton ######################## type ToggleButton <: InputWidget{Bool} signal::Signal{Bool} label::AbstractString value::Bool end togglebutton(args...) = ToggleButton(args...) togglebutton(; label="", value=nothing, signal=nothing) = begin signal, value = init_wsigval(signal, value; default=false) ToggleButton(signal, label, value) end """ togglebutton(label=""; value=false, signal) Create a toggle button. Optionally specify the `label`, the initial state (`value=false` is off, `value=true` is on), and/or provide the (Reactive.jl) `signal` coupled to this button. """ togglebutton(label; kwargs...) = togglebutton(label=label; kwargs...) ######################### Button ########################### type Button{T} <: InputWidget{T} signal::Signal{T} label::AbstractString value::T end button(; value=nothing, label="", signal=Signal(value)) = Button(signal, label, value) """ button(label; value=nothing, signal) Create a push button. Optionally specify the `label`, the `value` emitted when then button is clicked, and/or the (Reactive.jl) `signal` coupled to this button. """ button(label; kwargs...) = button(label=label; kwargs...) ######################## Textbox ########################### type Textbox{T} <: InputWidget{T} signal::Signal{T} label::String @compat range::Union{Empty, Range} value::T end function empty(t::Type) if is(t, Number) zero(t) elseif is(t, AbstractString) "" end end function Textbox(; label="", value=nothing, # Allow unicode characters even if initiated with ASCII typ=Void, range=nothing, signal=nothing, syncsig=true) if isa(value, AbstractString) && range != nothing throw(ArgumentError( "You cannot set a range on a string textbox" )) end signal, value = init_wsigval(signal, value; typ=typ, default="") t = Textbox(signal, label, range, value) if syncsig #keep the Textbox updated if the signal changes keep_updated(val) = begin if val != t.value t.value = val update_view(t) end nothing end preserve(map(keep_updated, signal; typ=Void)) end t end textbox(;kwargs...) = Textbox(;kwargs...) """ textbox(value=""; label="", typ=typeof(value), range=nothing, signal) Create a box for entering text. `value` is the starting value; if you don't want to provide an initial value, you can constrain the type with `typ`. Optionally provide a `label`, specify the allowed range (e.g., `-10.0:10.0`) for numeric entries, and/or provide the (Reactive.jl) `signal` coupled to this text box. """ textbox(val; kwargs...) = Textbox(value=val; kwargs...) textbox(val::String; kwargs...) = Textbox(value=val; kwargs...) parse_msg{T<:Number}(w::Textbox{T}, val::AbstractString) = parse_msg(w, parse(T, val)) function parse_msg{T<:Number}(w::Textbox{T}, val::Number) v = convert(T, val) if isa(w.range, Range) # force value to stay in range v = max(first(w.range), min(last(w.range), v)) end v end ######################### Textarea ########################### type Textarea{AbstractString} <: InputWidget{AbstractString} signal::Signal{AbstractString} label::AbstractString value::AbstractString end textarea(args...) = Textarea(args...) textarea(; label="", value=nothing, signal=nothing) = begin signal, value = init_wsigval(signal, value; default="") Textarea(signal, label, value) end """ textarea(value=""; label="", signal) Creates an extended text-entry area. Optionally provide a `label` and/or the (Reactive.jl) `signal` associated with this widget. The `signal` updates when you type. """ textarea(val; kwargs...) = textarea(value=val; kwargs...) ##################### SelectionWidgets ###################### immutable OptionDict dict::OrderedDict invdict::Dict end OptionDict(d::OrderedDict) = begin T1 = eltype([keys(d)...]) T2 = eltype([values(d)...]) OptionDict(OrderedDict{T1,T2}(d), Dict{T2,T1}(zip(values(d), keys(d)))) end Base.getindex(x::OptionDict, y) = getindex(x.dict, y) Base.haskey(x::OptionDict, y) = haskey(x.dict, y) Base.keys(x::OptionDict) = keys(x.dict) Base.values(x::OptionDict) = values(x.dict) Base.length(x::OptionDict) = length(keys(x)) type Options{view, T} <: InputWidget{T} signal::Signal label::AbstractString value::T value_label::AbstractString options::OptionDict icons::AbstractArray tooltips::AbstractArray readout::Bool orientation::AbstractString end Options(view::Symbol, options::OptionDict; label = "", value_label=first(keys(options)), value=nothing, icons=[], tooltips=[], typ=valtype(options.dict), signal=nothing, readout=true, orientation="horizontal", syncsig=true, syncnearest=true, sel_mid_idx=0) = begin #sel_mid_idx set in selection_slider(...) so default value_label is middle of range sel_mid_idx != 0 && (value_label = collect(keys(options.dict))[sel_mid_idx]) signal, value = init_wsigval(signal, value; typ=typ, default=options[value_label]) typ = eltype(signal) ow = Options{view, typ}(signal, label, value, value_label, options, icons, tooltips, readout, orientation) if syncsig syncselnearest = view == :SelectionSlider && typ <: Real && syncnearest if view != :SelectMultiple #set up map that keeps the value_label in sync with the value #TODO handle SelectMultiple. Need something similar to handle_msg keep_label_updated(val) = begin if syncselnearest val = nearest_val(keys(ow.options.invdict), val) end if haskey(ow.options.invdict, val) && ow.value_label != ow.options.invdict[val] ow.value_label = ow.options.invdict[val] update_view(ow) end nothing end preserve(map(keep_label_updated, signal; typ=Void)) end push!(signal, value) end ow end function Options(view::Symbol, options::Union{Associative, AbstractArray}; kwargs...) Options(view, getoptions(options); kwargs...) end function getoptions(options) opts = OrderedDict() for el in options addoption!(opts, el) end optdict = OptionDict(opts) end addoption!(opts, v::NTuple{2}) = opts[string(v[1])] = v[2] addoption!(opts, v) = opts[string(v)] = v """ dropdown(choices; label="", value, typ, icons, tooltips, signal) Create a "dropdown" widget. `choices` can be a vector of options. Optionally specify the starting `value` (defaults to the first choice), the `typ` of elements in `choices`, supply custom `icons`, provide `tooltips`, and/or specify the (Reactive.jl) `signal` coupled to this widget. # Examples a = dropdown(["one", "two", "three"]) To link a callback to the dropdown, use f = dropdown(["turn red"=>colorize_red, "turn green"=>colorize_green]) map(g->g(image), signal(f)) """ dropdown(opts; kwargs...) = Options(:Dropdown, opts; kwargs...) """ radiobuttons: see the help for `dropdown` """ radiobuttons(opts; kwargs...) = Options(:RadioButtons, opts; kwargs...) """ selection: see the help for `dropdown` """ function selection(opts; multi=false, kwargs...) if multi signal = Signal(collect(opts)[1:1]) Options(:SelectMultiple, opts; signal=signal, kwargs...) else Options(:Select, opts; kwargs...) end end Base.@deprecate select(opts; kwargs...) selection(opts, kwargs...) """ togglebuttons: see the help for `dropdown` """ togglebuttons(opts; kwargs...) = Options(:ToggleButtons, opts; kwargs...) """ selection_slider: see the help for `dropdown` If the slider has numeric (<:Real) values, and its signal is updated, it will update to the nearest value from the range/choices provided. To disable this behaviour, so that the widget state will only update if an exact match for signal value is found in the range/choice, use `syncnearest=false`. """ selection_slider(opts; kwargs...) = begin if !haskey(Dict(kwargs), :value_label) #default to middle of slider mid_idx = length(opts)÷2 + 1 # +1 to round up. push!(kwargs, (:sel_mid_idx, mid_idx)) end Options(:SelectionSlider, opts; kwargs...) end function nearest_val(x, val) local valbest local dxbest = typemax(Float64) for v in x dx = abs(v-val) if dx < dxbest dxbest = dx valbest = v end end valbest end ### Output Widgets export Latex, Progress Base.@deprecate html(value; label="") HTML(value) type Latex <: Widget label::AbstractString value::AbstractString end latex(label, value::AbstractString) = Latex(label, value) latex(value::AbstractString; label="") = Latex(label, value) latex(value; label="") = Latex(label, mimewritable("application/x-latex", value) ? stringmime("application/x-latex", value) : stringmime("text/latex", value)) ## # assume we already have Latex ## writemime(io::IO, m::MIME{symbol("application/x-latex")}, l::Latex) = ## write(io, l.value) type Progress <: Widget label::AbstractString value::Int range::Range orientation::String readout::Bool readout_format::String continuous_update::Bool end progress(args...) = Progress(args...) progress(;label="", value=0, range=0:100, orientation="horizontal", readout=true, readout_format="d", continuous_update=true) = Progress(label, value, range, orientation, readout, readout_format, continuous_update) # Make a widget out of a domain widget(x::Signal, label="") = x widget(x::Widget, label="") = x widget(x::Range, label="") = selection_slider(x, label=label) widget(x::AbstractVector, label="") = togglebuttons(x, label=label) widget(x::Associative, label="") = togglebuttons(x, label=label) widget(x::Bool, label="") = checkbox(x, label=label) widget(x::AbstractString, label="") = textbox(x, label=label, typ=AbstractString) widget{T <: Number}(x::T, label="") = textbox(typ=T, value=x, label=label) ### Set! """ `set!(w::Widget, fld::Symbol, val)` Set the value of a widget property and update all displayed instances of the widget. If `val` is a `Signal`, then updates to that signal will be reflected in widget instances/views. If `fld` is `:value`, `val` is also `push!`ed to `signal(w)` """ function set!(w::Widget, fld::Symbol, val) fld == :value && push!(signal(w), val) setfield!(w, fld, val) update_view(w) w end set!(w::Widget, fld::Symbol, valsig::Signal) = begin map(val -> set!(w, fld, val), valsig) |> preserve end set!{T<:Options}(w::T, fld::Symbol, val::Union{Signal,Any}) = begin fld == :options && (val = getoptions(val)) invoke(set!, (Widget, Symbol, typeof(val)), w, fld, val) end
{ "content_hash": "76e5ebe3c666d499a4b621083bc59375", "timestamp": "", "source": "github", "line_count": 504, "max_line_length": 158, "avg_line_length": 29.45436507936508, "alnum_prop": 0.6221623442236444, "repo_name": "JobJob/Interact.jl", "id": "4d6550474f3db508c873d7caba28fd07a166f7ec", "size": "14846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/widgets.jl", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3007" }, { "name": "Julia", "bytes": "33729" }, { "name": "Jupyter Notebook", "bytes": "13499" } ], "symlink_target": "" }
package org.pikater.core.options.recommend; import org.pikater.core.agents.experiment.recommend.Agent_Basic; import org.pikater.core.ontology.subtrees.agentinfo.AgentInfo; import org.pikater.core.ontology.subtrees.batchdescription.Recommend; import org.pikater.core.options.SlotsHelper; public class BasicRecommend_Box { public static AgentInfo get() { AgentInfo agentInfo = new AgentInfo(); agentInfo.importAgentClass(Agent_Basic.class); agentInfo.importOntologyClass(Recommend.class); agentInfo.setName("Basic"); agentInfo.setDescription("Basic Recommend"); agentInfo.setInputSlots(SlotsHelper.getInputSlots_Recommend()); agentInfo.setOutputSlots(SlotsHelper.getOutputSlots_Recommend()); return agentInfo; } }
{ "content_hash": "5e18e00881120a5fc5224a743036a259", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 69, "avg_line_length": 29.72, "alnum_prop": 0.7994616419919246, "repo_name": "tomkren/pikater", "id": "97e7949e48d0f13ecd02483432afb00971920789", "size": "743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/pikater/core/options/recommend/BasicRecommend_Box.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2720" }, { "name": "CLIPS", "bytes": "8093" }, { "name": "CSS", "bytes": "17962" }, { "name": "HTML", "bytes": "14268583" }, { "name": "Haskell", "bytes": "1632" }, { "name": "Java", "bytes": "17530800" }, { "name": "Makefile", "bytes": "3240" }, { "name": "Shell", "bytes": "1665" } ], "symlink_target": "" }
@interface JSONFetcher () @property (strong) NSOperationQueue *jsonOperationQueue; @property (strong) AFHTTPRequestOperation *operation; @end @implementation JSONFetcher @synthesize document = _document; @synthesize jsonOperationQueue = _jsonOperationQueue; @synthesize operation = _operation; - (id)init { self = [super init]; if (!self) { return nil; } self.jsonOperationQueue = [[NSOperationQueue alloc] init]; self.jsonOperationQueue.maxConcurrentOperationCount = 8; self.operation = [[AFHTTPRequestOperation alloc] init]; return self; } - (void) downloadJSONFromLocation: (NSString *) location withSuccess: (void (^)(id object))success andFailure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:location]]; NSString *method = nil; NSString *variables = @""; NSString *headerValue = nil; NSString *keyValue = nil; // Build the request string for(NSDictionary *header in self.document.httpHeaders) { if(![variables isEqualToString:@""]) { variables = [variables stringByAppendingString:@"&"]; } headerValue = header[@"headerValue"]; keyValue = header[@"headerKey"]; headerValue = [headerValue stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; keyValue = [keyValue stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; variables = [variables stringByAppendingString:[NSString stringWithFormat:@"%@=%@", keyValue, headerValue]]; } switch (self.document.httpMethod) { case HTTPMethodGet: { method = @"GET"; NSArray *array = [location componentsSeparatedByString:@"?"]; if([array count] == 1) { // There are no post parameters [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", location, variables]]]; } else if ([array count] == 2) { if([array[1] isEqualToString:@""]) { // Try to fake me out with a fake url? How dare you [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", location, variables]]]; } else { // Let's just keep appending stuff [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@&%@", location, variables]]]; } } else { // Forget about it } break; } case HTTPMethodPut: { method = @"PUT"; [ request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; NSData *postData = [NSData dataWithBytes: [variables UTF8String] length: [variables length]]; [ request setHTTPBody: postData ]; break; } case HTTPMethodPost: method = @"POST"; break; case HTTPMethodHead: method = @"HEAD"; break; default: method = @"GET"; break; } [request setHTTPMethod:method]; self.operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; __block AFHTTPRequestOperation *blockOperation = self.operation; self.operation.completionBlock = ^ { if ([blockOperation isCancelled]) { return; } if (blockOperation.error) { if (failure) { dispatch_async(dispatch_get_main_queue(), ^(void) { failure(blockOperation.response, blockOperation.error); }); } } else { if (success) { dispatch_async(dispatch_get_main_queue(), ^(void) { success(blockOperation.responseData); }); } } }; [self.jsonOperationQueue addOperation:self.operation]; } @end
{ "content_hash": "c5c36fbb96122fb4f0168019ee59388e", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 117, "avg_line_length": 34.02479338842975, "alnum_prop": 0.5761476803497693, "repo_name": "azu/JSONAccelerator", "id": "4e64adf37802874fc123d96e1ee7a96fa181ef39", "size": "4331", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "JSONModeler/ModelController/JSONFetcher.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Groff", "bytes": "3060" }, { "name": "Objective-C", "bytes": "250478" }, { "name": "Ruby", "bytes": "135" } ], "symlink_target": "" }
 // This file was automatically generated by the code gen tool - do not modify. using System ; using scg = System.Collections.Generic ; using sd = System.Data ; using sds = System.Data.SqlClient ; using sr = System.Reflection ; using mst = Microsoft.SqlServer.Types ; using mss = Microsoft.SqlServer.Server ; using acr = alby.codegen.runtime ; using ns = alby.pantheon.codegen; namespace alby.pantheon.codegen.storedProcedure { public partial class SolicitorWebServiceGet٠rs2 : acr.RowBase { public const string column٠SolicitorWebServiceGuid = "SolicitorWebServiceGuid" ; public const string column٠Name = "Name" ; public const string column٠DevUrl = "DevUrl" ; public const string column٠IntgUrl = "IntgUrl" ; public const string column٠TestUrl = "TestUrl" ; public const string column٠StagUrl = "StagUrl" ; public const string column٠ProdUrl = "ProdUrl" ; public const string column٠DRUrl = "DRUrl" ; public const string column٠DevCertFilename = "DevCertFilename" ; public const string column٠IntgCertFilename = "IntgCertFilename" ; public const string column٠TestCertFilename = "TestCertFilename" ; public const string column٠StagCertFilename = "StagCertFilename" ; public const string column٠ProdCertFilename = "ProdCertFilename" ; public const string column٠DRCertFilename = "DRCertFilename" ; public const string column٠UpdateUserCode = "UpdateUserCode" ; public const string column٠UpdateDateTime = "UpdateDateTime" ; public const string column٠RowTimestamp = "RowTimestamp" ; public Guid? SolicitorWebServiceGuid { get { return base.GetValueˡ<Guid?>( _dicˡ, column٠SolicitorWebServiceGuid ) ; } set { base.SetValueˡ<Guid?>( _dicˡ, column٠SolicitorWebServiceGuid, value, ref _dirtyˡ ) ; } } public string Name { get { return base.GetValueˡ<string>( _dicˡ, column٠Name ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠Name, value, ref _dirtyˡ ) ; } } public string DevUrl { get { return base.GetValueˡ<string>( _dicˡ, column٠DevUrl ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠DevUrl, value, ref _dirtyˡ ) ; } } public string IntgUrl { get { return base.GetValueˡ<string>( _dicˡ, column٠IntgUrl ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠IntgUrl, value, ref _dirtyˡ ) ; } } public string TestUrl { get { return base.GetValueˡ<string>( _dicˡ, column٠TestUrl ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠TestUrl, value, ref _dirtyˡ ) ; } } public string StagUrl { get { return base.GetValueˡ<string>( _dicˡ, column٠StagUrl ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠StagUrl, value, ref _dirtyˡ ) ; } } public string ProdUrl { get { return base.GetValueˡ<string>( _dicˡ, column٠ProdUrl ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠ProdUrl, value, ref _dirtyˡ ) ; } } public string DRUrl { get { return base.GetValueˡ<string>( _dicˡ, column٠DRUrl ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠DRUrl, value, ref _dirtyˡ ) ; } } public string DevCertFilename { get { return base.GetValueˡ<string>( _dicˡ, column٠DevCertFilename ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠DevCertFilename, value, ref _dirtyˡ ) ; } } public string IntgCertFilename { get { return base.GetValueˡ<string>( _dicˡ, column٠IntgCertFilename ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠IntgCertFilename, value, ref _dirtyˡ ) ; } } public string TestCertFilename { get { return base.GetValueˡ<string>( _dicˡ, column٠TestCertFilename ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠TestCertFilename, value, ref _dirtyˡ ) ; } } public string StagCertFilename { get { return base.GetValueˡ<string>( _dicˡ, column٠StagCertFilename ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠StagCertFilename, value, ref _dirtyˡ ) ; } } public string ProdCertFilename { get { return base.GetValueˡ<string>( _dicˡ, column٠ProdCertFilename ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠ProdCertFilename, value, ref _dirtyˡ ) ; } } public string DRCertFilename { get { return base.GetValueˡ<string>( _dicˡ, column٠DRCertFilename ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠DRCertFilename, value, ref _dirtyˡ ) ; } } public string UpdateUserCode { get { return base.GetValueˡ<string>( _dicˡ, column٠UpdateUserCode ) ; } set { base.SetValueˡ<string>( _dicˡ, column٠UpdateUserCode, value, ref _dirtyˡ ) ; } } public DateTime? UpdateDateTime { get { return base.GetValueˡ<DateTime?>( _dicˡ, column٠UpdateDateTime ) ; } set { base.SetValueˡ<DateTime?>( _dicˡ, column٠UpdateDateTime, value, ref _dirtyˡ ) ; } } public byte[] RowTimestamp { get { return base.GetValueˡ<byte[]>( _dicˡ, column٠RowTimestamp ) ; } set { base.SetValueˡ<byte[]>( _dicˡ, column٠RowTimestamp, value, ref _dirtyˡ ) ; } } public SolicitorWebServiceGet٠rs2() : base() { base._dicˡ[ column٠SolicitorWebServiceGuid ] = null ; base._dicˡ[ column٠Name ] = null ; base._dicˡ[ column٠DevUrl ] = null ; base._dicˡ[ column٠IntgUrl ] = null ; base._dicˡ[ column٠TestUrl ] = null ; base._dicˡ[ column٠StagUrl ] = null ; base._dicˡ[ column٠ProdUrl ] = null ; base._dicˡ[ column٠DRUrl ] = null ; base._dicˡ[ column٠DevCertFilename ] = null ; base._dicˡ[ column٠IntgCertFilename ] = null ; base._dicˡ[ column٠TestCertFilename ] = null ; base._dicˡ[ column٠StagCertFilename ] = null ; base._dicˡ[ column٠ProdCertFilename ] = null ; base._dicˡ[ column٠DRCertFilename ] = null ; base._dicˡ[ column٠UpdateUserCode ] = null ; base._dicˡ[ column٠UpdateDateTime ] = null ; base._dicˡ[ column٠RowTimestamp ] = null ; } } }
{ "content_hash": "b2d0090643ce32a8d3ae466f1fdda9a5", "timestamp": "", "source": "github", "line_count": 265, "max_line_length": 89, "avg_line_length": 24.222641509433963, "alnum_prop": 0.623617385885652, "repo_name": "casaletto/alby.pantheon.2015", "id": "1a10694184162c8a9575566f4776550a3d525008", "size": "6593", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "alby.pantheon.codegen/storedProcedure/SolicitorWebServiceGet.rs2.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "252" }, { "name": "C#", "bytes": "1946908" } ], "symlink_target": "" }
import React from 'react' import { StyleSheet, StyleResolver } from 'style-sheet' const cls = StyleResolver.resolve export default () => ( <div className={cls([styles.root, styles.color])}> <div> Hello from <span className={cls(styles.brand)}>Next.js</span> </div> </div> ) const styles = StyleSheet.create({ root: { fontSize: 30, fontFamily: 'sans-serif', display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh', backgroundImage: 'radial-gradient(circle, #D7D7D7, #D7D7D7 1px, #FFF 1px, #FFF)', backgroundSize: '1em 1em' }, color: { // showcasing dynamic styles color: Math.random() > 0.5 ? '#111' : '#222' }, brand: { fontWeight: 'bold' } })
{ "content_hash": "bd1fc5f0919c68da1f8cc13360d0ff45", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 70, "avg_line_length": 23.5625, "alnum_prop": 0.616710875331565, "repo_name": "BlancheXu/test", "id": "320abc68f1e6a0abdb3cd8b6b70c2869ad30cd98", "size": "754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/with-style-sheet/pages/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1007" }, { "name": "JavaScript", "bytes": "681828" }, { "name": "Shell", "bytes": "1294" }, { "name": "TypeScript", "bytes": "445811" } ], "symlink_target": "" }
var center = document.getElementById("center"); var citizen_me = document.getElementById("citizen_me"); var citizen_unknown = document.getElementById("citizen_unknown"); var citizen_friend = document.getElementById("citizen_friend"); var citizen_enemy = document.getElementById("citizen_enemy"); var canvas = document.getElementById("map_canvas"); var radius = Math.min(canvas.width,canvas.height) * 0.5; var radiusOuter = radius * 0.8; var drawSize = 64; var ctx = canvas.getContext("2d"); String.prototype.hashCode = function() { var hash = 0, i, chr, len; if (this.length === 0) return hash; for (i = 0, len = this.length; i < len; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; function getMap() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.arc(canvas.width * 0.5, canvas.height * 0.5, radius, 0, 2 * Math.PI, false); ctx.fillStyle = '#00C0CC'; ctx.fill(); ctx.lineWidth = 5; ctx.strokeStyle = '#D6FDFF'; ctx.stroke(); ctx.beginPath(); ctx.arc(canvas.width * 0.5, canvas.height * 0.5, radius * 0.05, 0, 2 * Math.PI, false); ctx.fillStyle = '#267A7F'; ctx.fill(); ctx.lineWidth = 5; ctx.strokeStyle = '#00C0CC'; ctx.stroke(); $.getJSON("/_getMap?citizen=" + localStorage.myName, { format: "json" }).done(function( data ){ if(data.error) { console.error("Failed to get map", data.error); return; } var myDistanceToNorm = data.distanceFromNorm.__me__; var img = new Image(); console.log("img:", img); img.onload = function(){ ctx.drawImage(img, canvas.width * 0.5 -drawSize, canvas.height * 0.5 + radius * myDistanceToNorm-drawSize, drawSize*2, drawSize*2); }; img.src = '/images/profilepics/'+localStorage.myName+'.jpg'; var imgArray = []; var i = 0; for(var name in data.distanceFromOther) { imgArray[i] = new Image(); /* if (data.Judgement == "positive") { imgArray[i].style.border='2px solid #8EFF58'; } else if (data.Judgement == "negative") { style.border='2px solid #8EFF58'; } else break;*/ var ox = canvas.width * 0.5; var oy = canvas.height * 0.5; imgArray[i].onload = function(){ var direction = (this.src.hashCode() % 2) ? -1 : 1 var distance = data.distanceFromNorm[this.id] * radius; console.log(data.distanceFromOther[this.id]) var angle = data.distanceFromOther[this.id] * Math.PI * direction + Math.PI*0.5; var x = distance * Math.cos(angle); var y = distance * Math.sin(angle); ctx.drawImage(this, ox + x - drawSize*0.5, oy + y - drawSize*0.5, drawSize, drawSize); }; imgArray[i].id = name; imgArray[i] .src = "/images/profilepics/"+name+".jpg"; i++; } }); }
{ "content_hash": "108061d83ea1af0dd2a3985d7ee31c13", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 133, "avg_line_length": 28.138613861386137, "alnum_prop": 0.6217452498240675, "repo_name": "wilbefast/socinder-html5-game", "id": "978b659221451d0f9cbe5a5a7bb60abe6615b149", "size": "2842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/js/map.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4164" }, { "name": "HTML", "bytes": "3003" }, { "name": "JavaScript", "bytes": "25777" } ], "symlink_target": "" }
import { setSort, setDuration } from "../../../../source/iml/job-stats/job-stats-actions.js"; describe("job stats actions", () => { it("should set duration", () => { const resp = setDuration(5); expect(resp).toEqual({ type: "SET_DURATION", payload: { duration: 5 } }); }); it("should set sort", () => { const resp = setSort("read_bytes_average", true); expect(resp).toEqual({ type: "SET_SORT", payload: { orderBy: "read_bytes_average", desc: true } }); }); });
{ "content_hash": "2067f85ce01df1470f4f878507118525", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 93, "avg_line_length": 21.423076923076923, "alnum_prop": 0.5206463195691203, "repo_name": "intel-hpdd/GUI", "id": "a99fb365f4367c59fa310207119e47613347b542", "size": "567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/spec/iml/job-stats/job-stats-actions-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "45410" }, { "name": "HTML", "bytes": "2784" }, { "name": "JavaScript", "bytes": "1690243" }, { "name": "Makefile", "bytes": "15807" }, { "name": "Shell", "bytes": "3721" } ], "symlink_target": "" }
title: "2022 AES conference accommodation" css: /css/index.css layout: page bigimg: - /img/big-imgs/Canberra_twilight.jpeg: Canberra at twilight --- We have sourced some cheaper accommodation options on Campus (<10min walk from our conference venue). If you would like to stay at these places, contact them directly. **Burgmann College**: $70 pp/pn, includes all meals! (Not that you’ll need them with our yummy conference catering), and has shared bathrooms. Please contact Margaret Cadman. Margaret.Cadman@burgmann.anu.edu.au **John III College**: $100 pp/pn, includes breakfast. Please contact enquiries@johnxxiii.anu.edu.au There also are plenty of other hotel options around, pick something near the ANU campus for easy access. Canberra has E-scooters, making it quick and easy to get around the city.
{ "content_hash": "df89ba6559b04326c58cb60d3bf07e51", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 210, "avg_line_length": 57.92857142857143, "alnum_prop": 0.7805178791615289, "repo_name": "ausevo/ausevo.github.io", "id": "317d7aaf7a7fa73846741f311639a5b5eb8018e7", "size": "817", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "accommodation.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "55063" }, { "name": "HTML", "bytes": "22063" }, { "name": "JavaScript", "bytes": "3373" }, { "name": "Ruby", "bytes": "85" } ], "symlink_target": "" }
import './typedefs' import {meetsCondition} from './utils/conditionals' import {ValueWrapper} from './utils/path' import _ from 'lodash' function isNotUndefined (item) { return item !== undefined } function checkConditions (value, formValue) { return function (condition) { const metCondition = conditionItem => _.every(conditionItem, (condition, propName) => meetsCondition(value.get(propName), condition, formValue) ) if (condition.unless) { const unless = condition.unless.find(metCondition) if (unless !== undefined) { return false } } if (condition.if) { return isNotUndefined(condition.if.find(metCondition)) } else { return true } } } function checkRootCells (view, value, formValue) { return function (cell) { return checkCell(view, value, cell, formValue) } } function checkCellConditions (view, value, cell, formValue) { // Find a condition that has been met const meetsCondition = checkConditions(value, formValue) const condition = cell.conditions.find(meetsCondition) if (condition === undefined) { // Returns undefined if conditions aren't met so we can filter return } if (condition.then) { // Cell has conditional properties, so add them cell = Object.assign({}, cell, condition.then) } return cell } function expandArrayOptions (view, extendedCell) { const arrayOptions = {} if (extendedCell.arrayOptions.itemCell && extendedCell.arrayOptions.itemCell.extends) { arrayOptions.itemCell = expandExtendedCell(view, extendedCell.itemCell) } if (extendedCell.arrayOptions.tupleCells) { arrayOptions.tupleCells = extendedCell.arrayOptions.tupleCells.map(child => { if (child.extends) { return expandExtendedCell(view, child) } return child }) } return arrayOptions } function expandExtendedCell (view, cell) { const cellProps = {} let extendedCell = _.get(view.cellDefinitions, cell.extends) if (extendedCell.extends) { extendedCell = _.omit(expandExtendedCell(view, extendedCell), ['extends']) } if (extendedCell.arrayOptions) { cellProps.arrayOptions = expandArrayOptions(view, extendedCell) } if (extendedCell.children) { cellProps.children = extendedCell.children.map(child => { if (child.extends) { return expandExtendedCell(view, child) } return child }) } return Object.assign({}, cell, extendedCell, cellProps) } function getItemCell (itemCell, index) { if (Array.isArray(itemCell)) { return itemCell[index] } return itemCell } function cellFromArrayValues (view, value, cell, formValue) { const val = value.get() if (val && val.length > 0) { const possibleCellSchema = val.map((val, index) => { const indexedCell = getItemCell(cell, index) const evaluatedCell = checkCell(view, value.pushPath(String(index)), indexedCell, formValue) return _.omit(evaluatedCell || cell, ['conditions', 'extends']) }) const first = possibleCellSchema[0] const isHeterogenous = possibleCellSchema.some((cell) => !_.isEqual(cell, first)) if (isHeterogenous) { return possibleCellSchema } else { return possibleCellSchema[0] } } else { return _.omit( checkCell(view, value.pushPath('0'), getItemCell(cell, 0), formValue) || cell, ['conditions', 'extends'] ) } } function checkArrayOptions (view, value, cell, formValue) { if (!cell.arrayOptions) { return cell } const arrayOptions = _.clone(cell.arrayOptions) let itemCell = _.get(arrayOptions, 'itemCell') if (itemCell) { arrayOptions.itemCell = cellFromArrayValues(view, value, itemCell, formValue) } let tupleCells = _.get(arrayOptions, 'tupleCells') if (tupleCells) { const itemsCells = tupleCells.map((cell, index) => _.omit( checkCell(view, value.pushPath(index + ''), cell, formValue) || cell, ['conditions', 'extends'] ) ) arrayOptions.tupleCells = itemsCells } return Object.assign({}, cell, {arrayOptions}) } function pushModel (value, cell) { if (typeof cell.model === 'object') { const id = cell.internal ? '_internal.' + cell.id : cell.id return new ValueWrapper(value.value, id) } return value.pushPath(cell.model) } function checkCell (view, value, cell, formValue) { if (cell.extends) { cell = expandExtendedCell(view, cell) } value = pushModel(value, cell) if (cell.conditions) { // This cell has conditions cell = checkCellConditions(view, value, cell, formValue) if (cell === undefined) { return } } if (cell.children) { cell = checkChildren(view, value, cell, formValue) } cell = checkArrayOptions(view, value, cell, formValue) return _.omit(cell, ['conditions', 'extends']) } function checkChildren (view, value, cell, formValue) { const children = cell.children.map((child) => { return checkCell(view, value, child, formValue) }) .filter(isNotUndefined) return Object.assign({}, cell, {children}) } export default function evaluateView (view, value) { const wrappedValue = new ValueWrapper(value, []) if (view.cells === undefined) { return view } try { const cells = view.cells .map(checkRootCells(view, wrappedValue, value)) .filter(isNotUndefined) return Object.assign({}, view, {cells}) } catch (e) { // Unfortunately this is necessary because view validation happens outside of the reducer, // so we have no guarantee that the view is valid and it may cause run time errors. Returning return view } }
{ "content_hash": "d38dca3f0511b0e6ded84d4d9b10878c", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 98, "avg_line_length": 28.12, "alnum_prop": 0.6731863442389758, "repo_name": "ciena-blueplanet/bunsen-core", "id": "5642fab37fa696c274ae4e07978ea3a647b33272", "size": "5624", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/view-conditions.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "472789" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('songs', '0005_auto_20180513_2320'), ] operations = [ migrations.AlterField( model_name='song', name='id', field=models.CharField(db_index=True, default='5fb7044c571b11e881f2b9463adf3ccc', max_length=255, primary_key=True, serialize=False, unique=True), ), ]
{ "content_hash": "df7ce059473c22a7058b811988f04126", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 158, "avg_line_length": 26.555555555555557, "alnum_prop": 0.6359832635983264, "repo_name": "DiegoCorrea/ouvidoMusical", "id": "58b6d2f6215d4771355ea690ceef1ba18859fd55", "size": "551", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/data/songs/migrations/0006_auto_20180514_0206.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "182332" }, { "name": "Shell", "bytes": "51486" } ], "symlink_target": "" }
package org.apache.geode.management.internal.cli.commands; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.test.junit.categories.RegionsTest; import org.apache.geode.test.junit.rules.GfshCommandRule; import org.apache.geode.test.junit.rules.GfshCommandRule.PortType; import org.apache.geode.test.junit.rules.ServerStarterRule; @Category({RegionsTest.class}) public class DescribeRegionIntegrationTest { private static final String MEMBER_NAME = "test-server"; private static final String REGION_NAME = "test-region"; private static final String GROUP_NAME = "test-group"; @ClassRule public static ServerStarterRule server = new ServerStarterRule() .withRegion(RegionShortcut.REPLICATE, REGION_NAME).withName(MEMBER_NAME) .withProperty("groups", GROUP_NAME).withJMXManager().withAutoStart(); @Rule public GfshCommandRule gfsh = new GfshCommandRule(server::getJmxPort, PortType.jmxManager).withTimeout(2); @Test public void commandFailsWhenNotConnected() throws Exception { gfsh.disconnect(); gfsh.executeAndAssertThat("describe region").statusIsError() .containsOutput("was found but is not currently available"); } @Test public void commandFailsWithBadNameOption() throws Exception { String cmd = "describe region --name=invalid-region-name"; gfsh.executeAndAssertThat(cmd).statusIsError().containsOutput("invalid-region-name not found"); } @Test public void commandSucceedsWithGoodNameOption() throws Exception { String cmd = "describe region --name=" + REGION_NAME; gfsh.executeAndAssertThat(cmd).statusIsSuccess().containsOutput("Name", "Data Policy", "Hosting Members"); } }
{ "content_hash": "3a6e171fac4cf3080933ebaa0fe8a9e2", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 99, "avg_line_length": 36.52, "alnum_prop": 0.7661555312157722, "repo_name": "smgoller/geode", "id": "312330355549b87bcd1f478c7abac49a3c3fc07b", "size": "2615", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "geode-gfsh/src/integrationTest/java/org/apache/geode/management/internal/cli/commands/DescribeRegionIntegrationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "104031" }, { "name": "Dockerfile", "bytes": "15956" }, { "name": "Go", "bytes": "40709" }, { "name": "Groovy", "bytes": "41926" }, { "name": "HTML", "bytes": "4037528" }, { "name": "Java", "bytes": "33124128" }, { "name": "JavaScript", "bytes": "1780821" }, { "name": "Python", "bytes": "29801" }, { "name": "Ruby", "bytes": "1801" }, { "name": "SCSS", "bytes": "2677" }, { "name": "Shell", "bytes": "274196" } ], "symlink_target": "" }
/** * Gen Name Human component class. * * @export * @class GenNamePascal */ import React from "react"; import "./gen-name-snake.css"; export class GenNamePascal extends React.Component<any, { message: string }> { /** * Creates an instance of GenNamePascal. */ constructor(props?: any, context?: any) { super(props, context); this.state = { message: "Hello Gen Name Human" }; } /** * Render the component. * @returns {JSX.Element} */ public render(): JSX.Element { return <span className="gen-name-snake">{this.state.message}</span>; } }
{ "content_hash": "251b7b0643bef58c5b28832b50f81dc8", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 78, "avg_line_length": 23.73076923076923, "alnum_prop": 0.6012965964343598, "repo_name": "unitejs/core", "id": "29bafaa32f1e562832f4d6922bf742e61adc555a", "size": "617", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "assets/appFramework/react/generate/component/src/gen-name-snake.tsx", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php $strQuery = sprintf("select s.*,sp.seq as publish_seq,sp.start_date,sp.finish_date,unix_timestamp(sp.start_date) as start_time,unix_timestamp(sp.finish_date) as finish_time from test_published as sp join test as s on sp.test_seq=s.seq where sp.seq=%d",$intPublishedSeq); ?>
{ "content_hash": "44e903c12eb18b7d2d38ea7b3fc3b49f", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 270, "avg_line_length": 93.66666666666667, "alnum_prop": 0.7473309608540926, "repo_name": "inkukyang/MamaOMR", "id": "7d3beafda7e0afbdc697c755df7f69cff51fd91c", "size": "281", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Model/Tests/SQL/MySQL/Tests/getTestsByPublishedSeq.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "721406" }, { "name": "HTML", "bytes": "5867" }, { "name": "JavaScript", "bytes": "711879" }, { "name": "PHP", "bytes": "646163" } ], "symlink_target": "" }
package org.apereo.cas.throttle; import org.apache.commons.lang3.StringUtils; /** * This is {@link AuthenticationThrottlingExecutionPlanConfigurer}. * * @author Misagh Moayyed * @since 5.3.0 */ public interface AuthenticationThrottlingExecutionPlanConfigurer { /** * Configure authentication throttling execution plan. * * @param plan the plan */ default void configureAuthenticationThrottlingExecutionPlan(final AuthenticationThrottlingExecutionPlan plan) { } /** * Gets name. * * @return the name */ default String getName() { return StringUtils.defaultIfBlank(this.getClass().getSimpleName(), "Default"); } }
{ "content_hash": "71e7dcf60aea24419d91821b07058570", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 115, "avg_line_length": 24.714285714285715, "alnum_prop": 0.6936416184971098, "repo_name": "philliprower/cas", "id": "a8f6d607237034ba0e5d9acbd342932a3b1fb853", "size": "692", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "core/cas-server-core-authentication-throttle/src/main/java/org/apereo/cas/throttle/AuthenticationThrottlingExecutionPlanConfigurer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "750333" }, { "name": "Dockerfile", "bytes": "2544" }, { "name": "Groovy", "bytes": "19040" }, { "name": "HTML", "bytes": "408841" }, { "name": "Java", "bytes": "15178582" }, { "name": "JavaScript", "bytes": "206200" }, { "name": "Python", "bytes": "140" }, { "name": "Ruby", "bytes": "1417" }, { "name": "Shell", "bytes": "131196" }, { "name": "TypeScript", "bytes": "251817" } ], "symlink_target": "" }
package parser import ( "fmt" "errors" "strings" "github.com/xrash/gonf/tokens" ) type state func(p *Parser) error func err(got tokens.Token, expected ...string) error { msg := "Expected %s at line %d:%d. Got %s." for k, e := range(expected) { expected[k] = "'" + e + "'" } return errors.New(fmt.Sprintf(msg, strings.Join(expected, " OR "), got.Line(), got.Column(), got)) } func pairState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_STRING: p.stack.push(buildPairNode) p.stack.push(pairState) p.stack.push(valueState) p.stack.push(keyState) case tokens.T_QUOTE: p.stack.push(buildPairNode) p.stack.push(pairState) p.stack.push(valueState) p.stack.push(keyState) case tokens.T_TABLE_END: case tokens.T_EOF: default: return err(token, "STRING", "{", "EOF", "\"") } return nil } func keyState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_STRING: p.stack.push(buildKeyNode) p.stack.push(stringState) case tokens.T_QUOTE: p.stack.push(buildKeyNode) p.stack.push(stringState) default: return err(token, "STRING", "\"") } return nil } func valueState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_STRING: p.stack.push(buildValueStringNode) p.stack.push(stringState) case tokens.T_QUOTE: p.stack.push(buildValueStringNode) p.stack.push(stringState) case tokens.T_ARRAY_START: p.stack.push(buildValueArrayNode) p.stack.push(arrayState) case tokens.T_TABLE_START: p.stack.push(buildValueTableNode) p.stack.push(tableState) default: return err(token, "STRING", "[", "{", "\"") } return nil } func arrayState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_ARRAY_START: p.stack.push(buildArrayNode) p.stack.push(arrayEndState) p.stack.push(valuesState) p.stack.push(arrayStartState) default: return err(token, "[") } return nil } func valuesState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_STRING: p.stack.push(buildValuesNode) p.stack.push(valuesState) p.stack.push(valueState) case tokens.T_QUOTE: p.stack.push(buildValuesNode) p.stack.push(valuesState) p.stack.push(valueState) case tokens.T_ARRAY_START: p.stack.push(buildValuesNode) p.stack.push(valuesState) p.stack.push(valueState) case tokens.T_TABLE_START: p.stack.push(buildValuesNode) p.stack.push(valuesState) p.stack.push(valueState) case tokens.T_ARRAY_END: default: return err(token, "STRING", "[", "{", "]", "\"") } return nil } func tableState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_TABLE_START: p.stack.push(buildTableNode) p.stack.push(tableEndState) p.stack.push(pairState) p.stack.push(tableStartState) default: return err(token, "{") } return nil } func stringState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_STRING: p.stack.push(unquotedStringState) case tokens.T_QUOTE: p.stack.push(quotedStringState) default: return err(token, "STRING", "\"") } return nil } func unquotedStringState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_STRING: p.stack.push(literalState) default: return err(token, "STRING") } return nil } func quotedStringState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_QUOTE: p.stack.push(quoteState) p.stack.push(literalState) p.stack.push(quoteState) default: return err(token, "STRING") } return nil } func literalState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_STRING: p.next() default: return err(token, "STRING") } p.nodeStack.push(NewStringNode(token.Value())) return nil } func quoteState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_QUOTE: p.next() default: return err(token, "\"") } return nil } func arrayStartState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_ARRAY_START: p.next() default: return err(token, "[") } return nil } func arrayEndState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_ARRAY_END: p.next() default: return err(token, "]") } return nil } func tableStartState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_TABLE_START: p.next() default: return err(token, "{") } return nil } func tableEndState(p *Parser) error { token := p.lookup() switch token.Type() { case tokens.T_TABLE_END: p.next() default: return err(token, "}") } return nil } func buildPairNode(p *Parser) error { var pn *PairNode if node := p.nodeStack.pop(); node.Kind() == PAIR_NODE { pn = node.(*PairNode) } else { p.nodeStack.push(node) } vn := p.nodeStack.pop().(*ValueNode) kn := p.nodeStack.pop().(*KeyNode) p.nodeStack.push(NewPairNode(kn, vn, pn)) return nil } func buildValueStringNode(p *Parser) error { sn := p.nodeStack.pop().(*StringNode) p.nodeStack.push(NewValueNode(sn, nil, nil)) return nil } func buildValueArrayNode(p *Parser) error { vn := p.nodeStack.pop().(*ValuesNode) an := NewArrayNode(vn) p.nodeStack.push(NewValueNode(nil, nil, an)) return nil } func buildKeyNode(p *Parser) error { sn := p.nodeStack.pop().(*StringNode) p.nodeStack.push(NewKeyNode(sn)) return nil } func buildValuesNode(p *Parser) error { var values *ValuesNode if node := p.nodeStack.pop(); node.Kind() == VALUES_NODE { values = node.(*ValuesNode) } else { p.nodeStack.push(node) } vn := p.nodeStack.pop().(*ValueNode) p.nodeStack.push(NewValuesNode(vn, values)) return nil } func buildArrayNode(p *Parser) error { return nil } func buildValueTableNode(p *Parser) error { tn := p.nodeStack.pop().(*TableNode) p.nodeStack.push(NewValueNode(nil, tn, nil)) return nil } func buildTableNode(p *Parser) error { pn := p.nodeStack.pop().(*PairNode) p.nodeStack.push(NewTableNode(pn)) return nil }
{ "content_hash": "dae83d955fc8f08fb6f0a50afa6766b8", "timestamp": "", "source": "github", "line_count": 338, "max_line_length": 99, "avg_line_length": 17.90532544378698, "alnum_prop": 0.6776272306675479, "repo_name": "huuzkee-foundation/go-config", "id": "db0d8f86c61440795bde5951c5296d6e7d524940", "size": "6052", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "parser/states.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "28224" }, { "name": "Makefile", "bytes": "89" } ], "symlink_target": "" }
import shutil import tempfile from contextlib import contextmanager from pathlib import Path @contextmanager def temp_directory_with_files(*paths): """A context manager that creates a temporary directory and copies all paths to it. The temporary directory is unlinked when the context is exited. """ temp = tempfile.mkdtemp() try: temp = Path(temp) for p in paths: shutil.copy(str(p), str(temp / Path(p).name)) yield temp finally: shutil.rmtree(str(temp))
{ "content_hash": "4726df49007744a254cda154d11f1e44", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 80, "avg_line_length": 26.35, "alnum_prop": 0.6717267552182163, "repo_name": "NaturalHistoryMuseum/gouda", "id": "2ec7955347ca285ee68bf1e8359ae9e73718db98", "size": "527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gouda/tests/utils.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "873" }, { "name": "Java", "bytes": "1630" }, { "name": "Python", "bytes": "72625" }, { "name": "Shell", "bytes": "904" } ], "symlink_target": "" }
package cherry.fundamental.spring.webmvc; public class NotFoundException extends RuntimeException { private static final long serialVersionUID = 1L; public NotFoundException() { super(); } public NotFoundException(String message) { super(message); } public NotFoundException(Throwable cause) { super(cause); } public NotFoundException(String message, Throwable cause) { super(message, cause); } }
{ "content_hash": "b9232af9aeb151c69121de54884fcab2", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 60, "avg_line_length": 17.92, "alnum_prop": 0.7075892857142857, "repo_name": "agwlvssainokuni/springapp2", "id": "d96c82b657c46acd04f47192e83f8793bd506d9d", "size": "1065", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "corelib/fundamental/src/webmvc/java/cherry/fundamental/spring/webmvc/NotFoundException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1200" }, { "name": "CSS", "bytes": "1652" }, { "name": "FreeMarker", "bytes": "17499" }, { "name": "Java", "bytes": "3266437" }, { "name": "JavaScript", "bytes": "143752" }, { "name": "Shell", "bytes": "31985" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_17) on Sat Feb 06 17:11:29 CET 2010 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> org.apache.xmlrpc.server Class Hierarchy (Apache XML-RPC 3.1.3 API) </TITLE> <META NAME="date" CONTENT="2010-02-06"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.xmlrpc.server Class Hierarchy (Apache XML-RPC 3.1.3 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/xmlrpc/serializer/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/xmlrpc/util/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/xmlrpc/server/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package org.apache.xmlrpc.server </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.Object<UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/AbstractReflectiveHandlerMapping.html" title="class in org.apache.xmlrpc.server"><B>AbstractReflectiveHandlerMapping</B></A> (implements org.apache.xmlrpc.metadata.<A HREF="../../../../org/apache/xmlrpc/metadata/XmlRpcListableHandlerMapping.html" title="interface in org.apache.xmlrpc.metadata">XmlRpcListableHandlerMapping</A>) <UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/PropertyHandlerMapping.html" title="class in org.apache.xmlrpc.server"><B>PropertyHandlerMapping</B></A></UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/ReflectiveXmlRpcHandler.html" title="class in org.apache.xmlrpc.server"><B>ReflectiveXmlRpcHandler</B></A> (implements org.apache.xmlrpc.<A HREF="../../../../org/apache/xmlrpc/XmlRpcHandler.html" title="interface in org.apache.xmlrpc">XmlRpcHandler</A>) <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/RequestProcessorFactoryFactory.RequestSpecificProcessorFactoryFactory.html" title="class in org.apache.xmlrpc.server"><B>RequestProcessorFactoryFactory.RequestSpecificProcessorFactoryFactory</B></A> (implements org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/RequestProcessorFactoryFactory.html" title="interface in org.apache.xmlrpc.server">RequestProcessorFactoryFactory</A>) <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/RequestProcessorFactoryFactory.StatelessProcessorFactoryFactory.html" title="class in org.apache.xmlrpc.server"><B>RequestProcessorFactoryFactory.StatelessProcessorFactoryFactory</B></A> (implements org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/RequestProcessorFactoryFactory.html" title="interface in org.apache.xmlrpc.server">RequestProcessorFactoryFactory</A>) <LI TYPE="circle">java.lang.Throwable (implements java.io.Serializable) <UL> <LI TYPE="circle">java.lang.Exception<UL> <LI TYPE="circle">org.apache.xmlrpc.<A HREF="../../../../org/apache/xmlrpc/XmlRpcException.html" title="class in org.apache.xmlrpc"><B>XmlRpcException</B></A><UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcNoSuchHandlerException.html" title="class in org.apache.xmlrpc.server"><B>XmlRpcNoSuchHandlerException</B></A></UL> </UL> </UL> <LI TYPE="circle">org.apache.xmlrpc.<A HREF="../../../../org/apache/xmlrpc/XmlRpcConfigImpl.html" title="class in org.apache.xmlrpc"><B>XmlRpcConfigImpl</B></A> (implements org.apache.xmlrpc.<A HREF="../../../../org/apache/xmlrpc/XmlRpcConfig.html" title="interface in org.apache.xmlrpc">XmlRpcConfig</A>, org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/XmlRpcHttpConfig.html" title="interface in org.apache.xmlrpc.common">XmlRpcHttpConfig</A>) <UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcServerConfigImpl.html" title="class in org.apache.xmlrpc.server"><B>XmlRpcServerConfigImpl</B></A> (implements org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcHttpServerConfig.html" title="interface in org.apache.xmlrpc.server">XmlRpcHttpServerConfig</A>, org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcServerConfig.html" title="interface in org.apache.xmlrpc.server">XmlRpcServerConfig</A>) </UL> <LI TYPE="circle">org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/XmlRpcController.html" title="class in org.apache.xmlrpc.common"><B>XmlRpcController</B></A><UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcServer.html" title="class in org.apache.xmlrpc.server"><B>XmlRpcServer</B></A> (implements org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/XmlRpcRequestProcessor.html" title="interface in org.apache.xmlrpc.common">XmlRpcRequestProcessor</A>) <UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcStreamServer.html" title="class in org.apache.xmlrpc.server"><B>XmlRpcStreamServer</B></A> (implements org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/XmlRpcStreamRequestProcessor.html" title="interface in org.apache.xmlrpc.common">XmlRpcStreamRequestProcessor</A>) <UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcHttpServer.html" title="class in org.apache.xmlrpc.server"><B>XmlRpcHttpServer</B></A><LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcLocalStreamServer.html" title="class in org.apache.xmlrpc.server"><B>XmlRpcLocalStreamServer</B></A></UL> </UL> </UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcErrorLogger.html" title="class in org.apache.xmlrpc.server"><B>XmlRpcErrorLogger</B></A><LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcServerWorker.html" title="class in org.apache.xmlrpc.server"><B>XmlRpcServerWorker</B></A> (implements org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/XmlRpcWorker.html" title="interface in org.apache.xmlrpc.common">XmlRpcWorker</A>) <LI TYPE="circle">org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/XmlRpcWorkerFactory.html" title="class in org.apache.xmlrpc.common"><B>XmlRpcWorkerFactory</B></A><UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcServerWorkerFactory.html" title="class in org.apache.xmlrpc.server"><B>XmlRpcServerWorkerFactory</B></A></UL> </UL> </UL> <H2> Interface Hierarchy </H2> <UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/AbstractReflectiveHandlerMapping.AuthenticationHandler.html" title="interface in org.apache.xmlrpc.server"><B>AbstractReflectiveHandlerMapping.AuthenticationHandler</B></A><LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/RequestProcessorFactoryFactory.html" title="interface in org.apache.xmlrpc.server"><B>RequestProcessorFactoryFactory</B></A><LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/RequestProcessorFactoryFactory.RequestProcessorFactory.html" title="interface in org.apache.xmlrpc.server"><B>RequestProcessorFactoryFactory.RequestProcessorFactory</B></A><LI TYPE="circle">org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/ServerStreamConnection.html" title="interface in org.apache.xmlrpc.common"><B>ServerStreamConnection</B></A><UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/ServerHttpConnection.html" title="interface in org.apache.xmlrpc.server"><B>ServerHttpConnection</B></A></UL> <LI TYPE="circle">org.apache.xmlrpc.<A HREF="../../../../org/apache/xmlrpc/XmlRpcConfig.html" title="interface in org.apache.xmlrpc"><B>XmlRpcConfig</B></A><UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcServerConfig.html" title="interface in org.apache.xmlrpc.server"><B>XmlRpcServerConfig</B></A><UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcHttpServerConfig.html" title="interface in org.apache.xmlrpc.server"><B>XmlRpcHttpServerConfig</B></A> (also extends org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/XmlRpcHttpConfig.html" title="interface in org.apache.xmlrpc.common">XmlRpcHttpConfig</A>) </UL> <LI TYPE="circle">org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/XmlRpcStreamConfig.html" title="interface in org.apache.xmlrpc.common"><B>XmlRpcStreamConfig</B></A><UL> <LI TYPE="circle">org.apache.xmlrpc.common.<A HREF="../../../../org/apache/xmlrpc/common/XmlRpcHttpConfig.html" title="interface in org.apache.xmlrpc.common"><B>XmlRpcHttpConfig</B></A><UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcHttpServerConfig.html" title="interface in org.apache.xmlrpc.server"><B>XmlRpcHttpServerConfig</B></A> (also extends org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcServerConfig.html" title="interface in org.apache.xmlrpc.server">XmlRpcServerConfig</A>) </UL> </UL> </UL> <LI TYPE="circle">org.apache.xmlrpc.server.<A HREF="../../../../org/apache/xmlrpc/server/XmlRpcHandlerMapping.html" title="interface in org.apache.xmlrpc.server"><B>XmlRpcHandlerMapping</B></A></UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/xmlrpc/serializer/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../org/apache/xmlrpc/util/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/xmlrpc/server/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2001-2010 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "5b62e84ee85f385bf0b1dc0d12bf3aa6", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 936, "avg_line_length": 75.16582914572864, "alnum_prop": 0.6825778847439498, "repo_name": "asudhak/One-Button-App---Android", "id": "b1ef65798c7171eb926db81b7a8682de6b72eb4e", "size": "14958", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/apache-xmlrpc-3.1.3/docs/apidocs/org/apache/xmlrpc/server/package-tree.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "300786" }, { "name": "Python", "bytes": "2176" } ], "symlink_target": "" }
module Sidekiq module Benchmark VERSION = "0.7.2" end end
{ "content_hash": "c31171c04b14d2fe9f28a7658c02f874", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 21, "avg_line_length": 13.2, "alnum_prop": 0.6666666666666666, "repo_name": "kosmatov/sidekiq-benchmark", "id": "09b3881e1ae6ab6dee535d69d9af39c2c6678dd6", "size": "66", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/sidekiq-benchmark/version.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1579" }, { "name": "JavaScript", "bytes": "69080" }, { "name": "Makefile", "bytes": "742" }, { "name": "Ruby", "bytes": "13438" } ], "symlink_target": "" }
package eu.chargetime.ocpp; /** Interface to handle connections by a server. */ public interface Receiver extends Radio { /** * Accept an incoming connection request. * * @param events connection related events. */ void accept(RadioEvents events); }
{ "content_hash": "f2664ff5721800745abb81185b879035", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 51, "avg_line_length": 20.692307692307693, "alnum_prop": 0.7026022304832714, "repo_name": "ChangeTimeEU/Java-OCA-OCPP", "id": "44098543c108a36dcadbb3a242777746bcdb53ad", "size": "1453", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ocpp-common/src/main/java/eu/chargetime/ocpp/Receiver.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "6846" }, { "name": "Java", "bytes": "187631" } ], "symlink_target": "" }
<span class="post-meta"> {{ post.date | date: "%b %-d, %Y" }} </span> <h2> <a class="post-link" href="{{ post.url | prepend: site.baseurl }}">{{ post.title }}</a> </h2> <div class="post-content" itemprop="articleBody"> {{ post.content | markdownify | html_truncatewords: site.post_preview_words }} <a href="{{ post.url | prepend: site.baseurl }}">Continue reading</a> </div> {% if post.comments %} {% if post.nid > 0 %} {% comment %} This post was imported from Drupal. {% endcomment %} {% assign comments_url = post.redirect_from %} {% else %} {% comment %} This is a native Jekyll post. {% endcomment %} {% assign comments_url = post.url %} {% endif %} <div class="post-comment-count"> <a href="{{ comments_url | prepend: site.url }}#disqus_thread">View Comments</a> </div> {% endif %}
{ "content_hash": "7438c6399ca0c7dc622fded450e0aaaf", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 89, "avg_line_length": 32.92, "alnum_prop": 0.6099635479951397, "repo_name": "opensourcecatholic/opensourcecatholic.github.io", "id": "37c790329f8e1cb23f2e208c0cfe8720dc2e5234", "size": "823", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/post_preview.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "9635" }, { "name": "Ruby", "bytes": "1166" }, { "name": "SCSS", "bytes": "12054" } ], "symlink_target": "" }
.. _autocomplete: .. py:module:: walrus Autocomplete ============ Provide suggestions based on partial string search. Walrus' autocomplete library is based on the implementation from `redis-completion <https://github.com/coleifer/redis-completion>`_. .. note:: The walrus implementation of autocomplete relies on the ``HSCAN`` command and therefore requires Redis >= 2.8.0. Overview -------- The :py:class:`Autocomplete` engine works by storing substrings and mapping them to user-defined data. Features * Perform searches using partial words or phrases. * Store rich metadata along with substrings. * Boosting. Simple example -------------- Walrus :py:class:`Autocomplete` can be used to index words and phrases, and then make suggestions based on user searches. To begin, call :py:meth:`Database.autocomplete` to create an instance of the autocomplete index. .. code-block:: pycon >>> database = Database() >>> ac = database.autocomplete() Phrases can be stored by calling :py:meth:`Autocomplete.store`: .. code-block:: pycon >>> phrases = [ ... 'the walrus and the carpenter', ... 'walrus tusks', ... 'the eye of the walrus'] >>> for phrase in phrases: ... ac.store(phrase) To search for results, use :py:meth:`Autocomplete.search`. .. code-block:: pycon >>> ac.search('wal') ['the walrus and the carpenter', 'walrus tusks', 'the eye of the walrus'] >>> ac.search('wal car') ['the walrus and the carpenter'] To boost a result, we can specify one or more *boosts* when searching: .. code-block:: pycon >>> ac.search('wal', boosts={'walrus tusks': 2}) ['walrus tusks', 'the walrus and the carpenter', 'the eye of the walrus'] To remove a phrase from the index, use :py:meth:`Autocomplete.remove`: .. code-block:: pycon >>> ac.remove('walrus tusks') We can also check for the existence of a phrase in the index using :py:meth:`Autocomplete.exists`: .. code-block:: pycon >>> ac.exists('the walrus and the carpenter') True >>> ac.exists('walrus tusks') False Complete example ---------------- While walrus can work with just simple words and phrases, the :py:class:`Autocomplete` index was really developed to be able to provide meaningful typeahead suggestions for sites containing rich content. To this end, the autocomplete search allows you to store arbitrary metadata in the index, which will then be returned when a search is performed. .. code-block:: pycon >>> database = Database() >>> ac = database.autocomplete() Suppose we have a blog site and wish to add search for the entries. We'll use the blog entry's title for the search, and return, along with title, a thumbnail image and a link to the entry's detail page. That way when we display results we have all the information we need to display a nice-looking link: .. code-block:: pycon >>> for blog_entry in Entry.select(): ... metadata = { ... 'image': blog_entry.get_primary_thumbnail(), ... 'title': blog_entry.title, ... 'url': url_for('entry_detail', entry_id=blog_entry.id)} ... ... ac.store( ... obj_id=blog_entry.id, ... title=blog_entry.title, ... data=metadata, ... obj_type='entry') When we search we receive the metadata that was stored in the index: .. code-block:: pycon >>> ac.search('walrus') [{'image': '/images/walrus-logo.jpg', 'title': 'Walrus: Lightweight Python utilities for working with Redis', 'url': '/blog/walrus-lightweight-python-utilities-for-working-with-redis/'}, {'image': '/images/walrus-tusk.jpg', 'title': 'Building Autocomplete with Walrus', 'url': '/blog/building-autocomplete-with-redis/'}] Whenever an entry is created or updated, we will want to update the index. By keying off the entry's primary key and object type (*'entry'*), walrus will handle this correctly: .. code-block:: python def save_entry(entry): entry.save_to_db() # Save entry to relational database, etc. ac.store( obj_id=entry.id, title=entry.title, data={ 'image': entry.get_primary_thumbnail(), 'title': entry.title, 'url': url_for('entry_detail', entry_id=entry.id)}, obj_type='entry') Suppose we have a very popular blog entry that is frequently searched for. We can *boost* that entry's score by calling :py:meth:`~Autocomplete.boost_object`: .. code-block:: pycon >>> popular_entry = Entry.get(Entry.title == 'Some popular entry') >>> ac.boost_object( ... obj_id=popular_entry.id, ... obj_type='entry', ... multiplier=2.0) To perform boosts on a one-off basis while searching, we can specify a dictionary mapping object IDs or types to a particular multiplier: .. code-block:: pycon >>> ac.search( ... 'some phrase', ... boosts={popular_entry.id: 2.0, unpopular_entry.id, 0.5}) ... [ list of matching entry's metadata ] To remove an entry from the index, we just need to specify the object's id and type: .. code-block:: python def delete_entry(entry): entry.delete_from_db() # Remove from relational database, etc. ac.remove( obj_id=entry.id, obj_type='entry') We can also check whether an entry exists in the index: .. code-block:: pycon >>> entry = Entry.get(Entry.title == 'Building Autocomplete with Walrus') >>> ac.exists(entry.id, 'entry') True Scoring ------- Walrus implements a scoring algorithm that considers the words and also their position relative to the entire phrase. Let's look at some simple searches. We'll index the following strings: * ``"aa bb"`` * ``"aa cc"`` * ``"bb cc"`` * ``"bb aa cc"`` * ``"cc aa bb"`` .. code-block:: pycon >>> phrases = ['aa bb', 'aa cc', 'bb cc', 'bb aa cc', 'cc aa bb'] >>> for phrase in phrases: ... ac.store(phrase) Note how when we search for *aa* that the results with *aa* towards the front of the string score higher: .. code-block:: pycon >>> ac.search('aa') ['aa bb', 'aa cc', 'bb aa cc', 'cc aa bb'] This is even more clear when we search for *bb* and *cc*: .. code-block:: pycon >>> ac.search('bb') ['bb aa cc', 'bb cc', 'aa bb', 'cc aa bb'] >>> ac.search('cc') ['cc aa bb', 'aa cc', 'bb cc', 'bb aa cc'] As you can see, results are scored by the proximity of the match to the front of the string, then alphabetically. Boosting ^^^^^^^^ To modify the score of certain words or phrases, we can apply *boosts* when searching. Boosts consist of a dictionary mapping identifiers to multipliers. Multipliers greater than 1 will move results to the top, while multipliers between 0 and 1 will push results to the bottom. In this example, we'll take the 3rd result, *bb cc* and bring it to the top: .. code-block:: pycon >>> ac.search('cc', boosts={'bb cc': 2}) ['bb cc', 'cc aa bb', 'aa cc', 'bb aa cc'] In this example, we'll take the best result, *cc aa bb*, and push it back a spot: .. code-block:: pycon >>> ac.search('cc', boosts={'cc aa bb': .75}) ['aa cc', 'cc aa bb', 'bb cc', 'bb aa cc'] Persisting boosts ^^^^^^^^^^^^^^^^^ While boosts can be specified on a one-off basis while searching, we can also permanently store boosts that will be applied to *all* searches. To store a boost for a particular object or object type, call the :py:meth:`~Autocomplete.boost_object` method: .. code-block:: pycon >>> ac.boost_object(obj_id='bb cc', multiplier=2.0) >>> ac.boost_object(obj_id='cc aa bb', multiplier=.75) Now we can search and our boosts will automatically be in effect: .. code-block:: pycon >>> ac.search('cc') ['bb cc', 'aa cc', 'cc aa bb', 'bb aa cc'] ZRANGEBYLEX ----------- Because I wanted to implement a slightly more complex scoring algorithm, I chose not to use the ``ZRANGEBYLEX`` command while implementing autocomplete. For very simple use-cases, though, ``ZRANGEBYLEX`` will certainly offer better performance. Depending on your application's needs, you may be able to get by just storing your words in a sorted set and calling ``ZRANGEBYLEX`` on that set.
{ "content_hash": "776dd5829172c85ca519c9c38ba32cd0", "timestamp": "", "source": "github", "line_count": 270, "max_line_length": 390, "avg_line_length": 30.988888888888887, "alnum_prop": 0.6445559937851082, "repo_name": "johndlong/walrus", "id": "1b32aad0973d5c62513787d3b7b5e72ae154bf43", "size": "8367", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/autocomplete.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "2141" }, { "name": "Python", "bytes": "238083" } ], "symlink_target": "" }
REGISTER_REDUCE_OP_WITHOUT_GRAD(reduce_all, UseInputPlace); REGISTER_OP_CPU_KERNEL(reduce_all, ops::ReduceKernel<paddle::platform::CPUDeviceContext, bool, ops::AllFunctor>);
{ "content_hash": "187ec6ea74fe92ecc230122f7de52a40", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 76, "avg_line_length": 59.5, "alnum_prop": 0.5840336134453782, "repo_name": "chengduoZH/Paddle", "id": "49d6e72988ee00edc947e1a3fe8bc16067627193", "size": "1031", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "paddle/fluid/operators/reduce_ops/reduce_all_op.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "32490" }, { "name": "C++", "bytes": "10146609" }, { "name": "CMake", "bytes": "291349" }, { "name": "Cuda", "bytes": "1192566" }, { "name": "Dockerfile", "bytes": "10002" }, { "name": "Python", "bytes": "7124331" }, { "name": "Ruby", "bytes": "353" }, { "name": "Shell", "bytes": "200906" } ], "symlink_target": "" }
<?php use Orchestra\Testbench\TestCase; use Dimsav\Translatable\Test\Model\Country; class TestsBase extends TestCase { protected $queriesCount; public function setUp() { parent::setUp(); App::register('Dimsav\Translatable\TranslatableServiceProvider'); $this->resetDatabase(); $this->countQueries(); } public function testRunningMigration() { $country = Country::find(1); $this->assertEquals('gr', $country->iso); } protected function getEnvironmentSetUp($app) { $app['path.base'] = __DIR__ . '/../src'; $app['config']->set('database.default', 'mysql'); $app['config']->set('database.connections.mysql', array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'translatable_test', 'username' => 'homestead', 'password' => 'secret', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', )); $app['config']->set('translatable::locales', array('el', 'en', 'fr', 'de', 'id')); } protected function getPackageAliases() { return array('Eloquent' => 'Illuminate\Database\Eloquent\Model'); } protected function countQueries() { $that = $this; $event = App::make('events'); $event->listen('illuminate.query', function() use ($that) { $that->queriesCount++; }); } private function resetDatabase() { $artisan = $this->app->make('artisan'); // This creates the "migrations" table if not existing $artisan->call('migrate', [ '--database' => 'mysql', '--path' => '../tests/migrations', ]); // We empty the tables $artisan->call('migrate:reset', [ '--database' => 'mysql', ]); // We fill the tables $artisan->call('migrate', [ '--database' => 'mysql', '--path' => '../tests/migrations', ]); } }
{ "content_hash": "b7bc4e54ff3b6a1b85acd0c6d21fdf6a", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 90, "avg_line_length": 26.294871794871796, "alnum_prop": 0.5187713310580204, "repo_name": "WebStra/translatable", "id": "fe309ceb9dbe2c50efaec85c9362f0d551ccfefb", "size": "2051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/TestsBase.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "45200" } ], "symlink_target": "" }
import {AppManagementStore, updateSelectedAppId} from 'chrome://os-settings/chromeos/os_settings.js'; import {flushTasks} from 'chrome://test/test_util.js'; import {replaceBody, replaceStore, setupFakeHandler} from './test_util.js'; suite('<app-management-app-details-item>', () => { let appDetailsItem; let fakeHandler; setup(async function() { fakeHandler = setupFakeHandler(); replaceStore(); appDetailsItem = document.createElement('app-management-app-details-item'); replaceBody(appDetailsItem); flushTasks(); }); test('PWA type', async function() { const options = { type: apps.mojom.AppType.kWeb, installSource: apps.mojom.InstallSource.kUnknown, }; // Add PWA app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#type-and-source')); assertEquals( appDetailsItem.shadowRoot.querySelector('#type-and-source') .textContent.trim(), 'Web App'); }); test('Android type', async function() { const options = { type: apps.mojom.AppType.kArc, installSource: apps.mojom.InstallSource.kUnknown, }; // Add Android app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#type-and-source')); assertEquals( appDetailsItem.shadowRoot.querySelector('#type-and-source') .textContent.trim(), 'Android App'); }); test('Chrome type', async function() { const options = { type: apps.mojom.AppType.kChromeApp, installSource: apps.mojom.InstallSource.kUnknown, }; // Add Chrome app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#type-and-source')); assertEquals( appDetailsItem.shadowRoot.querySelector('#type-and-source') .textContent.trim(), 'Chrome App'); }); test('Chrome App from web store', async function() { const options = { type: apps.mojom.AppType.kChromeApp, installSource: apps.mojom.InstallSource.kChromeWebStore, }; // Add Chrome app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#type-and-source')); assertEquals( appDetailsItem.shadowRoot.querySelector('#type-and-source') .textContent.trim(), 'Chrome App installed from <a href="#">Chrome Web Store</a>'); }); test('Android App from play store', async function() { const options = { type: apps.mojom.AppType.kArc, installSource: apps.mojom.InstallSource.kPlayStore, }; // Add Chrome app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#type-and-source')); assertEquals( appDetailsItem.shadowRoot.querySelector('#type-and-source') .textContent.trim(), 'Android App installed from <a href="#">Google Play Store</a>'); }); test('System type', async function() { const options = { type: apps.mojom.AppType.kSystemWeb, }; // Add System app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#type-and-source')); assertEquals( appDetailsItem.shadowRoot.querySelector('#type-and-source') .textContent.trim(), 'System App'); }); test('system install source', async function() { const options = { installSource: apps.mojom.InstallSource.kSystem, }; // Add System app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#type-and-source')); assertEquals( appDetailsItem.shadowRoot.querySelector('#type-and-source') .textContent.trim(), 'ChromeOS System App'); }); test('Chrome app version', async function() { const options = { type: apps.mojom.AppType.kChromeApp, version: '17.2', }; // Add Chrome app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertEquals( appDetailsItem.shadowRoot.querySelector('#version').textContent.trim(), 'Version: 17.2'); }); test('Android app version', async function() { const options = { type: apps.mojom.AppType.kArc, version: '13.1.52', }; // Add Android app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertEquals( appDetailsItem.shadowRoot.querySelector('#version').innerText.trim(), 'Version: 13.1.52'); }); test('Android type storage', async function() { const options = { type: apps.mojom.AppType.kArc, installSource: apps.mojom.InstallSource.kUnknown, appSize: '17 MB', }; const options2 = { type: apps.mojom.AppType.kArc, installSource: apps.mojom.InstallSource.kUnknown, appSize: '17 MB', dataSize: '124.6 GB', }; // Add Android app, and make it the currently selected app. const app = await fakeHandler.addApp('app', options); const app2 = await fakeHandler.addApp('app2', options2); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app.id]); appDetailsItem.app = app; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#storage-title')); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#app-size')); assertFalse(!!appDetailsItem.shadowRoot.querySelector('#data-size')); assertEquals( appDetailsItem.shadowRoot.querySelector('#app-size').textContent.trim(), 'App size: 17 MB'); AppManagementStore.getInstance().dispatch(updateSelectedAppId(app2.id)); await fakeHandler.flushPipesForTesting(); assertTrue(!!AppManagementStore.getInstance().data.apps[app2.id]); appDetailsItem.app = app2; replaceBody(appDetailsItem); fakeHandler.flushPipesForTesting(); flushTasks(); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#storage-title')); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#app-size')); assertTrue(!!appDetailsItem.shadowRoot.querySelector('#data-size')); assertEquals( appDetailsItem.shadowRoot.querySelector('#app-size').textContent.trim(), 'App size: 17 MB'); assertEquals( appDetailsItem.shadowRoot.querySelector('#data-size') .textContent.trim(), 'Data stored in app: 124.6 GB'); }); });
{ "content_hash": "d8e1292efc669a6b7ec6bf7ddec0a255", "timestamp": "", "source": "github", "line_count": 328, "max_line_length": 101, "avg_line_length": 30.3140243902439, "alnum_prop": 0.6890274565020618, "repo_name": "nwjs/chromium.src", "id": "ef932e34ede09f4f75451277d41b9ff1ac948534", "size": "10087", "binary": false, "copies": "1", "ref": "refs/heads/nw70", "path": "chrome/test/data/webui/settings/chromeos/app_management/app_details_item_test.js", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import users.models class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contenttypes', '0002_remove_content_type_name'), ] operations = [ migrations.CreateModel( name='Invite', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('key', models.CharField(default=users.models.generate_invite_key, help_text='The key for the invite.', max_length=64, unique=True)), ('email', models.EmailField(help_text='The email address of the person you are inviting.', max_length=2048)), ('message', models.TextField(blank=True, help_text='An optional message to send to the invitee.', null=True)), ('created', models.DateTimeField(auto_now_add=True, help_text='When the invite was created.')), ('sent', models.DateTimeField(blank=True, help_text='When the invite was sent.', null=True)), ('accepted', models.BooleanField(default=False, help_text='Whether the invite has been accepted. Will only be true if the user has clicked on the invitation AND authenticated.')), ('completed', models.DateTimeField(blank=True, help_text='When the invite action was completed', null=True)), ('action', models.CharField(blank=True, choices=[('join_account', 'Join account'), ('join_team', 'Join team'), ('join_project', 'Join project'), ('take_tour', 'Take tour')], help_text='The action to perform when the invitee signs up.', max_length=64, null=True)), ('subject_id', models.IntegerField(blank=True, help_text='The id of the target of the action.', null=True)), ('arguments', models.JSONField(blank=True, help_text='Any additional arguments to pass to the action.', null=True)), ('inviter', models.ForeignKey(blank=True, help_text='The user who created the invite.', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='invites', to=settings.AUTH_USER_MODEL)), ('subject_type', models.ForeignKey(blank=True, help_text='The type of the target of the action. e.g Team, Account', null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ], ), migrations.CreateModel( name='Flag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(help_text='The human/computer readable name.', max_length=100, unique=True, verbose_name='Name')), ('everyone', models.NullBooleanField(help_text='Flip this flag on (Yes) or off (No) for everyone, overriding all other settings. Leave as Unknown to use normally.', verbose_name='Everyone')), ('percent', models.DecimalField(blank=True, decimal_places=1, help_text='A number between 0.0 and 99.9 to indicate a percentage of users for whom this flag will be active.', max_digits=3, null=True, verbose_name='Percent')), ('testing', models.BooleanField(default=False, help_text='Allow this flag to be set for a session for user testing', verbose_name='Testing')), ('superusers', models.BooleanField(default=True, help_text='Flag always active for superusers?', verbose_name='Superusers')), ('staff', models.BooleanField(default=False, help_text='Flag always active for staff?', verbose_name='Staff')), ('authenticated', models.BooleanField(default=False, help_text='Flag always active for authenticated users?', verbose_name='Authenticated')), ('languages', models.TextField(blank=True, default='', help_text='Activate this flag for users with one of these languages (comma-separated list)', verbose_name='Languages')), ('rollout', models.BooleanField(default=False, help_text='Activate roll-out mode?', verbose_name='Rollout')), ('note', models.TextField(blank=True, help_text='Note where this Flag is used.', verbose_name='Note')), ('created', models.DateTimeField(db_index=True, default=django.utils.timezone.now, help_text='Date when this Flag was created.', verbose_name='Created')), ('modified', models.DateTimeField(default=django.utils.timezone.now, help_text='Date when this Flag was last modified.', verbose_name='Modified')), ('groups', models.ManyToManyField(blank=True, help_text='Activate this flag for these user groups.', to='auth.Group', verbose_name='Groups')), ('users', models.ManyToManyField(blank=True, help_text='Activate this flag for these users.', to=settings.AUTH_USER_MODEL, verbose_name='Users')), ], options={ 'verbose_name': 'Flag', 'verbose_name_plural': 'Flags', 'abstract': False, }, ), ]
{ "content_hash": "fd61466c7b10bc06c3eb9d60b8c1e0ba", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 279, "avg_line_length": 84.53225806451613, "alnum_prop": 0.6517840106849838, "repo_name": "stencila/hub", "id": "e7a411d0407201c5a02cd1d18f8c1d89748c5a55", "size": "5290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "manager/users/migrations/0001_initial.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "5505" }, { "name": "HTML", "bytes": "274142" }, { "name": "JavaScript", "bytes": "18731" }, { "name": "Makefile", "bytes": "14959" }, { "name": "Mustache", "bytes": "1137" }, { "name": "Python", "bytes": "1262375" }, { "name": "SCSS", "bytes": "31993" }, { "name": "Shell", "bytes": "8726" }, { "name": "TypeScript", "bytes": "5270" } ], "symlink_target": "" }
package com.fanxin.huangfangyi.main.uvod.ui.base; import android.content.Context; /** * * @author leewen * */ public abstract class UBaseHelper { public interface ChangeListener { void onUpdateUI(); } //当前进度 protected int mCurrentLevel; //最大进度 protected int mMaxLevel; //历史进度 protected int mHistoryLevel; //每次增加的粒度 protected int mLevel; protected ChangeListener mListener; protected Context mContext; public abstract void init(Context context); public abstract void setValue(int level, boolean isTouch); public abstract int getSystemValueLevel(); public UBaseHelper(Context context) { mContext = context; init(context); } public int getCurrentLevel() { return mCurrentLevel; } public void setCurrentLevel(int currentLevel) { mCurrentLevel = currentLevel; } public int getMaxLevel() { return mMaxLevel; } public void setMaxLevel(int maxLevel) { mMaxLevel = maxLevel; } public int getHistoryLevel() { return mHistoryLevel; } public void setHistoryLevel(int historyLevel) { mHistoryLevel = historyLevel; } public int getLevel() { return mLevel; } public void setLevel(int level) { mLevel = level; } public ChangeListener getChanageListener() { return mListener; } public void setOnChangeListener(ChangeListener l) { mListener = l; } public void increaseValue() { setValue(mCurrentLevel + mLevel, false); } public void decreaseValue() { setValue(mCurrentLevel - mLevel, false); } public boolean isZero() { return mCurrentLevel == 0; } public void setToZero() { setValue(0, false); } public void updateValue() { mCurrentLevel = getSystemValueLevel(); } public void setVauleTouch(int level) { setValue(level, true); } }
{ "content_hash": "9cea35c546a97019b002e685f5c6c2aa", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 59, "avg_line_length": 18.239583333333332, "alnum_prop": 0.7138777841233581, "repo_name": "cowthan/Ayo2022", "id": "b2f6970ebb5a2685fca689a47ecbbe6838ab93d8", "size": "1789", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ProjWechat/src/com/fanxin/huangfangyi/main/uvod/ui/base/UBaseHelper.java", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "5114" }, { "name": "HTML", "bytes": "2365" }, { "name": "Java", "bytes": "9575777" }, { "name": "JavaScript", "bytes": "27653" }, { "name": "Makefile", "bytes": "891" } ], "symlink_target": "" }
'use strict'; import { isLinux, isWindows } from 'vs/base/common/platform'; import { fill } from 'vs/base/common/arrays'; import { rtrim } from 'vs/base/common/strings'; import { CharCode } from 'vs/base/common/charCode'; /** * The forward slash path separator. */ export const sep = '/'; /** * The native path separator depending on the OS. */ export const nativeSep = isWindows ? '\\' : '/'; export function relative(from: string, to: string): string { // ignore trailing slashes const originalNormalizedFrom = rtrim(normalize(from), sep); const originalNormalizedTo = rtrim(normalize(to), sep); // we're assuming here that any non=linux OS is case insensitive // so we must compare each part in its lowercase form const normalizedFrom = isLinux ? originalNormalizedFrom : originalNormalizedFrom.toLowerCase(); const normalizedTo = isLinux ? originalNormalizedTo : originalNormalizedTo.toLowerCase(); const fromParts = normalizedFrom.split(sep); const toParts = normalizedTo.split(sep); let i = 0, max = Math.min(fromParts.length, toParts.length); for (; i < max; i++) { if (fromParts[i] !== toParts[i]) { break; } } const result = [ ...fill(fromParts.length - i, () => '..'), ...originalNormalizedTo.split(sep).slice(i) ]; return result.join(sep); } /** * @returns the directory name of a path. */ export function dirname(path: string): string { const idx = ~path.lastIndexOf('/') || ~path.lastIndexOf('\\'); if (idx === 0) { return '.'; } else if (~idx === 0) { return path[0]; } else { let res = path.substring(0, ~idx); if (isWindows && res[res.length - 1] === ':') { res += nativeSep; // make sure drive letters end with backslash } return res; } } /** * @returns the base name of a path. */ export function basename(path: string): string { const idx = ~path.lastIndexOf('/') || ~path.lastIndexOf('\\'); if (idx === 0) { return path; } else if (~idx === path.length - 1) { return basename(path.substring(0, path.length - 1)); } else { return path.substr(~idx + 1); } } /** * @returns {{.far}} from boo.far or the empty string. */ export function extname(path: string): string { path = basename(path); const idx = ~path.lastIndexOf('.'); return idx ? path.substring(~idx) : ''; } const _posixBadPath = /(\/\.\.?\/)|(\/\.\.?)$|^(\.\.?\/)|(\/\/+)|(\\)/; const _winBadPath = /(\\\.\.?\\)|(\\\.\.?)$|^(\.\.?\\)|(\\\\+)|(\/)/; function _isNormal(path: string, win: boolean): boolean { return win ? !_winBadPath.test(path) : !_posixBadPath.test(path); } export function normalize(path: string, toOSPath?: boolean): string { if (path === null || path === void 0) { return path; } const len = path.length; if (len === 0) { return '.'; } const wantsBackslash = isWindows && toOSPath; if (_isNormal(path, wantsBackslash)) { return path; } const sep = wantsBackslash ? '\\' : '/'; const root = getRoot(path, sep); // skip the root-portion of the path let start = root.length; let skip = false; let res = ''; for (let end = root.length; end <= len; end++) { // either at the end or at a path-separator character if (end === len || path.charCodeAt(end) === CharCode.Slash || path.charCodeAt(end) === CharCode.Backslash) { if (streql(path, start, end, '..')) { // skip current and remove parent (if there is already something) let prev_start = res.lastIndexOf(sep); let prev_part = res.slice(prev_start + 1); if ((root || prev_part.length > 0) && prev_part !== '..') { res = prev_start === -1 ? '' : res.slice(0, prev_start); skip = true; } } else if (streql(path, start, end, '.') && (root || res || end < len - 1)) { // skip current (if there is already something or if there is more to come) skip = true; } if (!skip) { let part = path.slice(start, end); if (res !== '' && res[res.length - 1] !== sep) { res += sep; } res += part; } start = end + 1; skip = false; } } return root + res; } function streql(value: string, start: number, end: number, other: string): boolean { return start + other.length === end && value.indexOf(other, start) === start; } /** * Computes the _root_ this path, like `getRoot('c:\files') === c:\`, * `getRoot('files:///files/path') === files:///`, * or `getRoot('\\server\shares\path') === \\server\shares\` */ export function getRoot(path: string, sep: string = '/'): string { if (!path) { return ''; } let len = path.length; let code = path.charCodeAt(0); if (code === CharCode.Slash || code === CharCode.Backslash) { code = path.charCodeAt(1); if (code === CharCode.Slash || code === CharCode.Backslash) { // UNC candidate \\localhost\shares\ddd // ^^^^^^^^^^^^^^^^^^^ code = path.charCodeAt(2); if (code !== CharCode.Slash && code !== CharCode.Backslash) { let pos = 3; let start = pos; for (; pos < len; pos++) { code = path.charCodeAt(pos); if (code === CharCode.Slash || code === CharCode.Backslash) { break; } } code = path.charCodeAt(pos + 1); if (start !== pos && code !== CharCode.Slash && code !== CharCode.Backslash) { pos += 1; for (; pos < len; pos++) { code = path.charCodeAt(pos); if (code === CharCode.Slash || code === CharCode.Backslash) { return path.slice(0, pos + 1) // consume this separator .replace(/[\\/]/g, sep); } } } } } // /user/far // ^ return sep; } else if ((code >= CharCode.A && code <= CharCode.Z) || (code >= CharCode.a && code <= CharCode.z)) { // check for windows drive letter c:\ or c: if (path.charCodeAt(1) === CharCode.Colon) { code = path.charCodeAt(2); if (code === CharCode.Slash || code === CharCode.Backslash) { // C:\fff // ^^^ return path.slice(0, 2) + sep; } else { // C: // ^^ return path.slice(0, 2); } } } // check for URI // scheme://authority/path // ^^^^^^^^^^^^^^^^^^^ let pos = path.indexOf('://'); if (pos !== -1) { pos += 3; // 3 -> "://".length for (; pos < len; pos++) { code = path.charCodeAt(pos); if (code === CharCode.Slash || code === CharCode.Backslash) { return path.slice(0, pos + 1); // consume this separator } } } return ''; } export const join: (...parts: string[]) => string = function () { // Not using a function with var-args because of how TS compiles // them to JS - it would result in 2*n runtime cost instead // of 1*n, where n is parts.length. let value = ''; for (let i = 0; i < arguments.length; i++) { let part = arguments[i]; if (i > 0) { // add the separater between two parts unless // there already is one let last = value.charCodeAt(value.length - 1); if (last !== CharCode.Slash && last !== CharCode.Backslash) { let next = part.charCodeAt(0); if (next !== CharCode.Slash && next !== CharCode.Backslash) { value += sep; } } } value += part; } return normalize(value); }; /** * Check if the path follows this pattern: `\\hostname\sharename`. * * @see https://msdn.microsoft.com/en-us/library/gg465305.aspx * @return A boolean indication if the path is a UNC path, on none-windows * always false. */ export function isUNC(path: string): boolean { if (!isWindows) { // UNC is a windows concept return false; } if (!path || path.length < 5) { // at least \\a\b return false; } let code = path.charCodeAt(0); if (code !== CharCode.Backslash) { return false; } code = path.charCodeAt(1); if (code !== CharCode.Backslash) { return false; } let pos = 2; let start = pos; for (; pos < path.length; pos++) { code = path.charCodeAt(pos); if (code === CharCode.Backslash) { break; } } if (start === pos) { return false; } code = path.charCodeAt(pos + 1); if (isNaN(code) || code === CharCode.Backslash) { return false; } return true; } // Reference: https://en.wikipedia.org/wiki/Filename const INVALID_FILE_CHARS = isWindows ? /[\\/:\*\?"<>\|]/g : /[\\/]/g; const WINDOWS_FORBIDDEN_NAMES = /^(con|prn|aux|clock\$|nul|lpt[0-9]|com[0-9])$/i; export function isValidBasename(name: string): boolean { if (!name || name.length === 0 || /^\s+$/.test(name)) { return false; // require a name that is not just whitespace } INVALID_FILE_CHARS.lastIndex = 0; // the holy grail of software development if (INVALID_FILE_CHARS.test(name)) { return false; // check for certain invalid file characters } if (isWindows && WINDOWS_FORBIDDEN_NAMES.test(name)) { return false; // check for certain invalid file names } if (name === '.' || name === '..') { return false; // check for reserved values } if (isWindows && name[name.length - 1] === '.') { return false; // Windows: file cannot end with a "." } if (isWindows && name.length !== name.trim().length) { return false; // Windows: file cannot end with a whitespace } return true; }
{ "content_hash": "ff0c5cce96a92d91ed10ca44c2db747e", "timestamp": "", "source": "github", "line_count": 341, "max_line_length": 110, "avg_line_length": 26.117302052785924, "alnum_prop": 0.5969009656411408, "repo_name": "matthewshirley/vscode", "id": "3ad625b365305bd1978ef91e5462c131bbfa3b5d", "size": "9257", "binary": false, "copies": "6", "ref": "refs/heads/git-pull-from", "path": "src/vs/base/common/paths.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5668" }, { "name": "C", "bytes": "818" }, { "name": "C#", "bytes": "1640" }, { "name": "C++", "bytes": "1000" }, { "name": "CSS", "bytes": "433840" }, { "name": "Clojure", "bytes": "1206" }, { "name": "CoffeeScript", "bytes": "590" }, { "name": "F#", "bytes": "634" }, { "name": "Go", "bytes": "628" }, { "name": "Groovy", "bytes": "3928" }, { "name": "HLSL", "bytes": "184" }, { "name": "HTML", "bytes": "28846" }, { "name": "Inno Setup", "bytes": "107772" }, { "name": "Java", "bytes": "599" }, { "name": "JavaScript", "bytes": "3267615" }, { "name": "Lua", "bytes": "252" }, { "name": "Makefile", "bytes": "553" }, { "name": "Objective-C", "bytes": "1387" }, { "name": "PHP", "bytes": "802" }, { "name": "Perl", "bytes": "857" }, { "name": "Perl6", "bytes": "1065" }, { "name": "PowerShell", "bytes": "5372" }, { "name": "Python", "bytes": "2119" }, { "name": "R", "bytes": "362" }, { "name": "Ruby", "bytes": "1703" }, { "name": "Rust", "bytes": "532" }, { "name": "ShaderLab", "bytes": "330" }, { "name": "Shell", "bytes": "29219" }, { "name": "Swift", "bytes": "220" }, { "name": "TypeScript", "bytes": "12660119" }, { "name": "Visual Basic", "bytes": "893" } ], "symlink_target": "" }
[![Travis Widget](http://travis-ci.org/flori/json.svg?branch=master)](https://travis-ci.org/flori/json) ## Description This is a implementation of the JSON specification according to RFC 7159 http://www.ietf.org/rfc/rfc7159.txt . Starting from version 1.0.0 on there will be two variants available: * A pure ruby variant, that relies on the iconv and the stringscan extensions, which are both part of the ruby standard library. * The quite a bit faster native extension variant, which is in parts implemented in C or Java and comes with its own unicode conversion functions and a parser generated by the ragel state machine compiler http://www.complang.org/ragel/ . Both variants of the JSON generator generate UTF-8 character sequences by default. If an :ascii\_only option with a true value is given, they escape all non-ASCII and control characters with \uXXXX escape sequences, and support UTF-16 surrogate pairs in order to be able to generate the whole range of unicode code points. All strings, that are to be encoded as JSON strings, should be UTF-8 byte sequences on the Ruby side. To encode raw binary strings, that aren't UTF-8 encoded, please use the to\_json\_raw\_object method of String (which produces an object, that contains a byte array) and decode the result on the receiving endpoint. ## Installation It's recommended to use the extension variant of JSON, because it's faster than the pure ruby variant. If you cannot build it on your system, you can settle for the latter. Just type into the command line as root: ``` # rake install ``` The above command will build the extensions and install them on your system. ``` # rake install_pure ``` or ``` # ruby install.rb ``` will just install the pure ruby implementation of JSON. If you use Rubygems you can type ``` # gem install json ``` instead, to install the newest JSON version. There is also a pure ruby json only variant of the gem, that can be installed with: ``` # gem install json_pure ``` ## Compiling the extensions yourself If you want to create the `parser.c` file from its `parser.rl` file or draw nice graphviz images of the state machines, you need ragel from: http://www.complang.org/ragel/ ## Usage To use JSON you can ```ruby require 'json' ``` to load the installed variant (either the extension `'json'` or the pure variant `'json_pure'`). If you have installed the extension variant, you can pick either the extension variant or the pure variant by typing ```ruby require 'json/ext' ``` or ```ruby require 'json/pure' ``` Now you can parse a JSON document into a ruby data structure by calling ```ruby JSON.parse(document) ``` If you want to generate a JSON document from a ruby data structure call ```ruby JSON.generate(data) ``` You can also use the `pretty_generate` method (which formats the output more verbosely and nicely) or `fast_generate` (which doesn't do any of the security checks generate performs, e. g. nesting deepness checks). There are also the JSON and JSON[] methods which use parse on a String or generate a JSON document from an array or hash: ```ruby document = JSON 'test' => 23 # => "{\"test\":23}" document = JSON['test' => 23] # => "{\"test\":23}" ``` and ```ruby data = JSON '{"test":23}' # => {"test"=>23} data = JSON['{"test":23}'] # => {"test"=>23} ``` You can choose to load a set of common additions to ruby core's objects if you ```ruby require 'json/add/core' ``` After requiring this you can, e. g., serialise/deserialise Ruby ranges: ```ruby JSON JSON(1..10) # => 1..10 ``` To find out how to add JSON support to other or your own classes, read the section "More Examples" below. To get the best compatibility to rails' JSON implementation, you can ```ruby require 'json/add/rails' ``` Both of the additions attempt to require `'json'` (like above) first, if it has not been required yet. ## Serializing exceptions The JSON module doesn't extend `Exception` by default. If you convert an `Exception` object to JSON, it will by default only include the exception message. To include the full details, you must either load the `json/add/core` mentioned above, or specifically load the exception addition: ```ruby require 'json/add/exception' ``` ## More Examples To create a JSON document from a ruby data structure, you can call `JSON.generate` like that: ```ruby json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10] # => "[1,2,{\"a\":3.141},false,true,null,\"4..10\"]" ``` To get back a ruby data structure from a JSON document, you have to call JSON.parse on it: ```ruby JSON.parse json # => [1, 2, {"a"=>3.141}, false, true, nil, "4..10"] ``` Note, that the range from the original data structure is a simple string now. The reason for this is, that JSON doesn't support ranges or arbitrary classes. In this case the json library falls back to call `Object#to_json`, which is the same as `#to_s.to_json`. It's possible to add JSON support serialization to arbitrary classes by simply implementing a more specialized version of the `#to_json method`, that should return a JSON object (a hash converted to JSON with `#to_json`) like this (don't forget the `*a` for all the arguments): ```ruby class Range def to_json(*a) { 'json_class' => self.class.name, # = 'Range' 'data' => [ first, last, exclude_end? ] }.to_json(*a) end end ``` The hash key `json_class` is the class, that will be asked to deserialise the JSON representation later. In this case it's `Range`, but any namespace of the form `A::B` or `::A::B` will do. All other keys are arbitrary and can be used to store the necessary data to configure the object to be deserialised. If the key `json_class` is found in a JSON object, the JSON parser checks if the given class responds to the `json_create` class method. If so, it is called with the JSON object converted to a Ruby hash. So a range can be deserialised by implementing `Range.json_create` like this: ```ruby class Range def self.json_create(o) new(*o['data']) end end ``` Now it possible to serialise/deserialise ranges as well: ```ruby json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10] # => "[1,2,{\"a\":3.141},false,true,null,{\"json_class\":\"Range\",\"data\":[4,10,false]}]" JSON.parse json # => [1, 2, {"a"=>3.141}, false, true, nil, 4..10] json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10] # => "[1,2,{\"a\":3.141},false,true,null,{\"json_class\":\"Range\",\"data\":[4,10,false]}]" JSON.parse json, :create_additions => true # => [1, 2, {"a"=>3.141}, false, true, nil, 4..10] ``` `JSON.generate` always creates the shortest possible string representation of a ruby data structure in one line. This is good for data storage or network protocols, but not so good for humans to read. Fortunately there's also `JSON.pretty_generate` (or `JSON.pretty_generate`) that creates a more readable output: ```ruby puts JSON.pretty_generate([1, 2, {"a"=>3.141}, false, true, nil, 4..10]) [ 1, 2, { "a": 3.141 }, false, true, null, { "json_class": "Range", "data": [ 4, 10, false ] } ] ``` There are also the methods `Kernel#j` for generate, and `Kernel#jj` for `pretty_generate` output to the console, that work analogous to Core Ruby's `p` and the `pp` library's `pp` methods. The script `tools/server.rb` contains a small example if you want to test, how receiving a JSON object from a webrick server in your browser with the javasript prototype library http://www.prototypejs.org works. ## Speed Comparisons I have created some benchmark results (see the benchmarks/data-p4-3Ghz subdir of the package) for the JSON-parser to estimate the speed up in the C extension: ``` Comparing times (call_time_mean): 1 ParserBenchmarkExt#parser 900 repeats: 553.922304770 ( real) -> 21.500x 0.001805307 2 ParserBenchmarkYAML#parser 1000 repeats: 224.513358139 ( real) -> 8.714x 0.004454078 3 ParserBenchmarkPure#parser 1000 repeats: 26.755020642 ( real) -> 1.038x 0.037376163 4 ParserBenchmarkRails#parser 1000 repeats: 25.763381731 ( real) -> 1.000x 0.038814780 calls/sec ( time) -> speed covers secs/call ``` In the table above 1 is `JSON::Ext::Parser`, 2 is `YAML.load` with YAML compatbile JSON document, 3 is is `JSON::Pure::Parser`, and 4 is `ActiveSupport::JSON.decode`. The ActiveSupport JSON-decoder converts the input first to YAML and then uses the YAML-parser, the conversion seems to slow it down so much that it is only as fast as the `JSON::Pure::Parser`! If you look at the benchmark data you can see that this is mostly caused by the frequent high outliers - the median of the Rails-parser runs is still overall smaller than the median of the `JSON::Pure::Parser` runs: ``` Comparing times (call_time_median): 1 ParserBenchmarkExt#parser 900 repeats: 800.592479481 ( real) -> 26.936x 0.001249075 2 ParserBenchmarkYAML#parser 1000 repeats: 271.002390644 ( real) -> 9.118x 0.003690004 3 ParserBenchmarkRails#parser 1000 repeats: 30.227910865 ( real) -> 1.017x 0.033082008 4 ParserBenchmarkPure#parser 1000 repeats: 29.722384421 ( real) -> 1.000x 0.033644676 calls/sec ( time) -> speed covers secs/call ``` I have benchmarked the `JSON-Generator` as well. This generated a few more values, because there are different modes that also influence the achieved speed: ``` Comparing times (call_time_mean): 1 GeneratorBenchmarkExt#generator_fast 1000 repeats: 547.354332608 ( real) -> 15.090x 0.001826970 2 GeneratorBenchmarkExt#generator_safe 1000 repeats: 443.968212317 ( real) -> 12.240x 0.002252414 3 GeneratorBenchmarkExt#generator_pretty 900 repeats: 375.104545883 ( real) -> 10.341x 0.002665923 4 GeneratorBenchmarkPure#generator_fast 1000 repeats: 49.978706968 ( real) -> 1.378x 0.020008521 5 GeneratorBenchmarkRails#generator 1000 repeats: 38.531868759 ( real) -> 1.062x 0.025952543 6 GeneratorBenchmarkPure#generator_safe 1000 repeats: 36.927649925 ( real) -> 1.018x 7 (>=3859) 0.027079979 7 GeneratorBenchmarkPure#generator_pretty 1000 repeats: 36.272134441 ( real) -> 1.000x 6 (>=3859) 0.027569373 calls/sec ( time) -> speed covers secs/call ``` In the table above 1-3 are `JSON::Ext::Generator` methods. 4, 6, and 7 are `JSON::Pure::Generator` methods and 5 is the Rails JSON generator. It is now a bit faster than the `generator_safe` and `generator_pretty` methods of the pure variant but slower than the others. To achieve the fastest JSON document output, you can use the `fast_generate` method. Beware, that this will disable the checking for circular Ruby data structures, which may cause JSON to go into an infinite loop. Here are the median comparisons for completeness' sake: ``` Comparing times (call_time_median): 1 GeneratorBenchmarkExt#generator_fast 1000 repeats: 708.258020939 ( real) -> 16.547x 0.001411915 2 GeneratorBenchmarkExt#generator_safe 1000 repeats: 569.105020353 ( real) -> 13.296x 0.001757145 3 GeneratorBenchmarkExt#generator_pretty 900 repeats: 482.825371244 ( real) -> 11.280x 0.002071142 4 GeneratorBenchmarkPure#generator_fast 1000 repeats: 62.717626652 ( real) -> 1.465x 0.015944481 5 GeneratorBenchmarkRails#generator 1000 repeats: 43.965681162 ( real) -> 1.027x 0.022745013 6 GeneratorBenchmarkPure#generator_safe 1000 repeats: 43.929073409 ( real) -> 1.026x 7 (>=3859) 0.022763968 7 GeneratorBenchmarkPure#generator_pretty 1000 repeats: 42.802514491 ( real) -> 1.000x 6 (>=3859) 0.023363113 calls/sec ( time) -> speed covers secs/call ``` ## Author Florian Frank <mailto:flori@ping.de> ## License Ruby License, see https://www.ruby-lang.org/en/about/license.txt. ## Download The latest version of this library can be downloaded at * https://rubygems.org/gems/json Online Documentation should be located at * http://json.rubyforge.org
{ "content_hash": "4b1dc940984edef1683ea6b14bdfd2dc", "timestamp": "", "source": "github", "line_count": 407, "max_line_length": 103, "avg_line_length": 30.668304668304668, "alnum_prop": 0.6861079955135395, "repo_name": "devcycle/devcycle.github.io", "id": "1b15cf104acb9969cfb7b0f4b7c7c74a7708612e", "size": "12514", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/bundle/gems/json-2.2.0/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "93132" }, { "name": "JavaScript", "bytes": "4776" }, { "name": "Ruby", "bytes": "3625" }, { "name": "SCSS", "bytes": "97011" } ], "symlink_target": "" }
package com.vc.adapter; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; import com.vc.ui.Activity_BigPicture; import com.vc.ui.R; import common.Constants; import common.LocalStorage; import com.vc.api.OkHttpConnection; import com.vc.db.ActionDB; import dto.ActionSimple; import dto.AttendanceStatus; import dto.LikeStatus; public class ActivityAdapter extends ArrayAdapter { private int resourceId; private List<ActionSimple> activityList; private LayoutInflater inflater; private final int a = 0; private int position; private Context context; DisplayImageOptions options; protected ImageLoader imageLoader; public ActivityAdapter(Context context, int textViewResourceId, List<ActionSimple> ac_list) { super(context, textViewResourceId); inflater = LayoutInflater.from(context); this.context = context; this.activityList = ac_list; resourceId = textViewResourceId; // item璧勬簮id imageLoader = ImageLoader.getInstance(); imageLoader.init(ImageLoaderConfiguration.createDefault(context)); } @Override public int getCount() { return activityList.size(); } @Override public Object getItem(int position) { return activityList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; if (convertView == null) { convertView = inflater.inflate(resourceId, null); viewHolder = new ViewHolder(); viewHolder.imageView = (ImageView) convertView .findViewById(R.id.ac_pic_Iv); viewHolder.themeText = (TextView) convertView .findViewById(R.id.theme_tv); viewHolder.timeText = (TextView) convertView .findViewById(R.id.time_Tv); viewHolder.hostText = (TextView) convertView .findViewById(R.id.host_Tv); viewHolder.activitySiteText = (TextView) convertView .findViewById(R.id.site_Tv); viewHolder.attendanceText = (TextView) convertView .findViewById(R.id.rb_join); viewHolder.likeText = (TextView) convertView .findViewById(R.id.rb_like); viewHolder.a_ll = (RelativeLayout) convertView .findViewById(R.id.a_ll); viewHolder.l_ll = (RelativeLayout) convertView .findViewById(R.id.l_ll); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } this.position = position; loadPicture(viewHolder); viewHolder.themeText.setText(activityList.get(position) .getAction_theme()); viewHolder.hostText .setText(activityList.get(position).getAction_host()); viewHolder.timeText .setText(activityList.get(position).getAction_time()); viewHolder.activitySiteText.setText(activityList.get(position) .getAction_site()); viewHolder.attendanceText.setText(activityList.get(position) .getAttendance_nums() == 0 ? "参与" : activityList.get(position) .getAttendance_nums() + ""); viewHolder.likeText .setText(activityList.get(position).getLike_nums() == 0 ? "赞" : activityList.get(position).getLike_nums() + ""); final TextView a_tv = viewHolder.attendanceText; final TextView l_tv = viewHolder.likeText; final ImageView big_imageview = viewHolder.imageView; final int position_1 = position; viewHolder.a_ll.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(LocalStorage.getString(context,"userId") == ""){ Toast.makeText(context, "请先登录",Toast.LENGTH_SHORT).show(); }else{ ActionDB actionDB =ActionDB.getInstance(context); List<AttendanceStatus> list = actionDB.getAttendance(); int isAttendance = 0; int s = 0; if(a_tv.getText().toString() == "参与"){ s = 0; }else{ s = Integer.parseInt(a_tv.getText().toString()); } for(int i = 0; i < list.size();i++){ if(list.get(i).getIsAttendance() == 3){ isAttendance = 1; break; } } if(isAttendance != 1){ a_tv.setText(String.valueOf(s + 1)); activityList.get(position_1).setAttendance_nums(s + 1); //存储到数据库 AttendanceStatus as = new AttendanceStatus(); as.setActionId(activityList.get(position_1).getAction_id()); as.setIsAttendance(1); int userId = Integer.parseInt(LocalStorage.getString(context,"userId")); as.setUserId(userId); actionDB.saveAttendanceStatus(as); postMessageToServer("addAttendance", String.valueOf(activityList.get(position_1).getAction_id()), LocalStorage.getString(context,"userId")); }else{ if(s == 1){ a_tv.setText("参与"); activityList.get(position_1).setAttendance_nums(0); actionDB.deleteAttendance(String.valueOf(activityList.get(position_1).getAction_id())); postMessageToServer("deleteAttendance", String.valueOf(activityList.get(position_1).getAction_id()), LocalStorage.getString(context,"userId")); }else{ a_tv.setText(String.valueOf(s-1)); activityList.get(position_1).setAttendance_nums(s-1); actionDB.deleteAttendance(String.valueOf(activityList.get(position_1).getAction_id())); postMessageToServer("deleteAttendance", String.valueOf(activityList.get(position_1).getAction_id()), LocalStorage.getString(context,"userId")); } } } } }); viewHolder.l_ll.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(LocalStorage.getString(context,"userId") == ""){ Toast.makeText(context,"请先登录",Toast.LENGTH_SHORT).show(); }else{ ActionDB actionDB =ActionDB.getInstance(context); List<LikeStatus> list = actionDB.getLike(); int isLike = 0; int s = 0; if(l_tv.getText().toString() == "赞"){ s = 0; }else{ s = Integer.parseInt(l_tv.getText().toString()); } for(int i = 0; i < list.size();i++){ if(list.get(i).getIsLike() == 3){ isLike = 1; break; } } if(isLike != 1){ l_tv.setText(String.valueOf(s + 1)); activityList.get(position_1).setLike_nums(s + 1); //存储到数据库 LikeStatus ls = new LikeStatus(); ls.setActionId(activityList.get(position_1).getAction_id()); ls.setIsLike(1); ls.setUserId(Integer.parseInt(LocalStorage.getString(context,"userId"))); actionDB.saveLikeStatus(ls); postMessageToServer("addLike", String.valueOf(activityList.get(position_1).getAction_id()), LocalStorage.getString(context,"userId")); }else{ if(s == 1){ l_tv.setText("赞"); activityList.get(position_1).setLike_nums(0); actionDB.deleteLike(String.valueOf(activityList.get(position_1).getAction_id())); postMessageToServer("deleteLike", String.valueOf(activityList.get(position_1).getAction_id()), LocalStorage.getString(context,"userId")); }else{ l_tv.setText(String.valueOf(s-1)); activityList.get(position_1).setLike_nums(s-1); actionDB.deleteLike(String.valueOf(activityList.get(position_1).getAction_id())); postMessageToServer("deleteLike", String.valueOf(activityList.get(position_1).getAction_id()), LocalStorage.getString(context,"userId")); } } } } }); viewHolder.imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(context,Activity_BigPicture.class); intent.putExtra("picURL",activityList.get(position_1).getAction_picPath()); intent.putExtra("picType","action"); context.startActivity(intent); } }); return convertView; } private void loadPicture(ViewHolder viewHolder) { options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.icon_onloading) .showImageForEmptyUri(R.drawable.ic_launcher) .showImageOnFail(R.drawable.icon_loadfail) .cacheInMemory(true) .cacheOnDisk(true) .displayer(new RoundedBitmapDisplayer(2)) .build(); imageLoader.displayImage(Constants.SERVERADDRESS + "/file/image/get?imageUrl=" + activityList.get(position).getAction_picPath(), viewHolder.imageView, options); } private void postMessageToServer(final String type,final String activityId,final String userId){ new Thread(new Runnable() { @Override public void run() { List<NameValuePair> params; JSONObject json = new JSONObject(); if(type == "addAttendance"){ params = new ArrayList<NameValuePair>(); String dateTime = MessageFormat.format("{0,date,yyyy-MM-dd-HH-mm:ss}" , new Object[]{ new java.sql.Date(System.currentTimeMillis()) }); params.add(new BasicNameValuePair("attendance_userId",userId)); params.add(new BasicNameValuePair("attendance_activityId",activityId)); params.add(new BasicNameValuePair("attendance_time",dateTime)); json = OkHttpConnection.execute(context, "/attendance/addAttendance", params); }else if(type == "deleteAttendance"){ params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("attendance_userId",userId)); params.add(new BasicNameValuePair("attendance_activityId",activityId)); json = OkHttpConnection.execute(context, "/attendance/deleteAttendance", params); }else if(type == "addLike"){ params = new ArrayList<NameValuePair>(); String dateTime = MessageFormat.format("{0,date,yyyy-MM-dd-HH-mm:ss}" , new Object[]{ new java.sql.Date(System.currentTimeMillis()) }); params.add(new BasicNameValuePair("like_userId",userId)); params.add(new BasicNameValuePair("like_activityId",activityId)); params.add(new BasicNameValuePair("like_time",dateTime)); json = OkHttpConnection.execute(context, "/like/addLike", params); }else{ params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("like_userId",userId)); params.add(new BasicNameValuePair("like_activityId",activityId)); json = OkHttpConnection.execute(context, "/like/deleteLike", params); } } }).start(); } public static class ViewHolder { ImageView imageView; TextView themeText; TextView hostText; TextView timeText; TextView activitySiteText; TextView attendanceText; TextView likeText; RelativeLayout a_ll; RelativeLayout l_ll; } }
{ "content_hash": "d057a2a029a748706c8ebcf3b58e518c", "timestamp": "", "source": "github", "line_count": 375, "max_line_length": 97, "avg_line_length": 32.093333333333334, "alnum_prop": 0.6568342334856668, "repo_name": "ydc201211/VirtualCampus", "id": "ef5d1664dd82206aa331fee75cf5097e285a3311", "size": "12099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/vc/adapter/ActivityAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "636509" } ], "symlink_target": "" }
package com.codeabovelab.dm.gateway.proxy.common; import org.junit.Test; import static org.junit.Assert.assertNotNull; /** * Created by pronto on 1/18/16. */ public class HttpProxyTest { @Test public void testCookies() { String realCookie = HttpProxy.getRealCookie("" + "!Proxy!JSESSIONID=AE94F00CA87DB8576DBC00F824819F93;" + "!Proxy!JSESSIONID=AE94F00CA87DB8576DBC00F824819F93;" + "!Proxy!JSESSIONID=400C1F87D505AD2C04541B72F1DEA57E;"); assertNotNull(realCookie); } }
{ "content_hash": "2843d3a4dfce87e8c25bea7d25365ce5", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 71, "avg_line_length": 25.09090909090909, "alnum_prop": 0.6739130434782609, "repo_name": "codeabovelab/haven-platform", "id": "520e0fb15453c8eda34ed715cb9c48a45b3bfc1f", "size": "552", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/gateway-balancer-common/src/test/java/com.codeabovelab.dm.gateway.proxy.common/HttpProxyTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "35317" }, { "name": "HTML", "bytes": "8161" }, { "name": "Java", "bytes": "2880360" }, { "name": "JavaScript", "bytes": "156208" }, { "name": "Shell", "bytes": "244" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.includehack.fashionspot"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:name=".App" android:allowBackup="true" android:icon="@drawable/logo_icon" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".RouterActivity" android:noHistory="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".activities.IntroActivity" android:windowSoftInputMode="adjustPan" android:screenOrientation="portrait" android:theme="@style/IntroTheme" /> <activity android:name=".activities.HomeActivity" android:launchMode="singleTask" android:screenOrientation="portrait" android:theme="@style/HomeTheme" /> <activity android:name=".activities.ProfileActivity" android:parentActivityName=".activities.HomeActivity" android:screenOrientation="portrait" /> <activity android:name=".activities.FeedDetailActivity" android:parentActivityName=".activities.HomeActivity" android:screenOrientation="portrait" /> </application> </manifest>
{ "content_hash": "1e3e8a1673173a893c10afbf5cee92d3", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 78, "avg_line_length": 38.044444444444444, "alnum_prop": 0.6244158878504673, "repo_name": "JRSosa/FashionSpot", "id": "d344804b9503bc4f2585e869d1b3f0e8ebdee207", "size": "1712", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/FashionSpot/app/src/main/AndroidManifest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "779" }, { "name": "Java", "bytes": "39405" }, { "name": "JavaScript", "bytes": "1170" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>org.wso2.ei</groupId> <artifactId>wso2bps-integration-common</artifactId> <version>6.7.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <name>WSO2 BPS - Integration UI Pages</name> <artifactId>org.wso2.ei.businessprocess.integration.ui.pages</artifactId> <modelVersion>4.0.0</modelVersion> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.wso2.carbon.automation</groupId> <artifactId>org.wso2.carbon.automation.engine</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.wso2.carbon.automationutils</groupId> <artifactId>org.wso2.carbon.integration.common.utils</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.wso2.carbon</groupId> <artifactId>org.wso2.carbon.authenticator.stub</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.wso2.carbon.automation</groupId> <artifactId>org.wso2.carbon.automation.extensions</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.axis2.wso2</groupId> <artifactId>axis2-client</artifactId> <exclusions> <exclusion> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </exclusion> <exclusion> <artifactId>org.wso2.securevault</artifactId> <groupId>org.wso2.securevault</groupId> </exclusion> </exclusions> </dependency> </dependencies> </project>
{ "content_hash": "d2d1bd092f2971c1fc3f9da5297fcf0c", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 204, "avg_line_length": 38.10909090909091, "alnum_prop": 0.5949427480916031, "repo_name": "milindaperera/product-ei", "id": "6b28c6dd32031a2149641878168bb2198019fbaa", "size": "2096", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "integration/business-process-tests/tests-common/ui-pages/pom.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Ballerina", "bytes": "22977" }, { "name": "Batchfile", "bytes": "147995" }, { "name": "CSS", "bytes": "233470" }, { "name": "HTML", "bytes": "110657" }, { "name": "Java", "bytes": "8882160" }, { "name": "JavaScript", "bytes": "5980272" }, { "name": "PLSQL", "bytes": "16634" }, { "name": "PLpgSQL", "bytes": "12825" }, { "name": "Ruby", "bytes": "11897" }, { "name": "Shell", "bytes": "378668" }, { "name": "TSQL", "bytes": "308110" }, { "name": "XSLT", "bytes": "38219" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "85d6273759b95654ef02829cfd76fa7d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "ddf04c8ecaa551497d275b2864a5aeb225cc0504", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fagales/Fagaceae/Quercus/Quercus diversifolia/ Syn. Quercus bonplandiana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace suggestions { // An interface to fetch server suggestions asynchronously. class SuggestionsService : public KeyedService { public: using ResponseCallback = base::RepeatingCallback<void(const SuggestionsProfile&)>; using ResponseCallbackList = base::CallbackList<void(const SuggestionsProfile&)>; // Initiates a network request for suggestions if sync state allows and there // is no pending request. Returns true iff sync state allowed for a request, // whether a new request was actually sent or not. virtual bool FetchSuggestionsData() = 0; // Returns the current set of suggestions from the cache. virtual base::Optional<SuggestionsProfile> GetSuggestionsDataFromCache() const = 0; // Adds a callback that is called when the suggestions are updated. virtual std::unique_ptr<ResponseCallbackList::Subscription> AddCallback( const ResponseCallback& callback) WARN_UNUSED_RESULT = 0; // Adds a URL to the blacklist cache, returning true on success or false on // failure. The URL will eventually be uploaded to the server. virtual bool BlacklistURL(const GURL& candidate_url) = 0; // Removes a URL from the local blacklist, returning true on success or false // on failure. virtual bool UndoBlacklistURL(const GURL& url) = 0; // Removes all URLs from the blacklist. virtual void ClearBlacklist() = 0; }; } // namespace suggestions #endif // COMPONENTS_SUGGESTIONS_SUGGESTIONS_SERVICE_H_
{ "content_hash": "d6a39a422f71621f56c69303f41e77f7", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 79, "avg_line_length": 37.69230769230769, "alnum_prop": 0.7503401360544217, "repo_name": "endlessm/chromium-browser", "id": "bb9940fe8022bfd12a8b3e4c7cfcb8f5e0344742", "size": "2012", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/suggestions/suggestions_service.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.vzome.core.editor; import org.w3c.dom.Element; import com.vzome.core.algebra.AlgebraicField; import com.vzome.core.algebra.AlgebraicMatrix; import com.vzome.core.algebra.AlgebraicNumber; import com.vzome.core.algebra.AlgebraicVector; import com.vzome.core.commands.Command.Failure; import com.vzome.core.commands.XmlSaveFormat; import com.vzome.core.construction.MatrixTransformation; import com.vzome.core.construction.Point; import com.vzome.core.construction.Scaling; import com.vzome.core.construction.Segment; import com.vzome.core.construction.Transformation; import com.vzome.core.math.symmetry.Axis; import com.vzome.core.math.symmetry.Direction; import com.vzome.core.math.symmetry.Symmetry; import com.vzome.core.model.Connector; import com.vzome.core.model.Manifestation; import com.vzome.core.model.Panel; import com.vzome.core.model.Strut; public class ScalingTool extends SymmetryTool { private static final String ID = "scaling"; private static final String LABEL = "Create a scaling tool"; private static final String TOOLTIP = "<p>" + "Each tool enlarges or shrinks the selected objects,<br>" + "relative to a central point. To create a tool,<br>" + "select a ball representing the central point, and<br>" + "two struts from the same orbit (color) with different<br>" + "sizes.<br>" + "<br>" + "The selection order matters. First select a strut<br>" + "that you want to enlarge or shrink, then select a<br>" + "strut that has the desired target size.<br>" + "</p>"; public static class Factory extends AbstractToolFactory { public Factory( ToolsModel tools, Symmetry symmetry ) { super( tools, symmetry, ID, LABEL, TOOLTIP ); } @Override protected boolean countsAreValid( int total, int balls, int struts, int panels ) { return ( total == 3 && balls == 1 && struts == 2 ); } @Override public Tool createToolInternal( String id ) { ScalingTool tool = new ScalingTool( id, getSymmetry(), this .getToolsModel() ); int scalePower = 0;; switch ( id ) { case "scaling.builtin/scale up": scalePower = 1; break; case "scaling.builtin/scale down": scalePower = -1; break; default: return tool; // non-predefined, no scale factor set } AlgebraicField field = this .getToolsModel() .getEditorModel() .getRealizedModel() .getField(); tool .setScaleFactor( field .createPower( scalePower ) ); return tool; } // This is never called for the predefined tool, so symmetry can be null. @Override protected boolean bindParameters( Selection selection ) { Symmetry symmetry = getSymmetry(); AlgebraicVector offset1 = null; AlgebraicVector offset2 = null; for ( Manifestation man : selection ) if ( man instanceof Strut ) { Strut strut = (Strut) man; if ( offset1 == null ) offset1 = strut .getOffset(); else offset2 = strut .getOffset(); } Axis zone1 = symmetry .getAxis( offset1 ); Axis zone2 = symmetry .getAxis( offset2 ); if ( zone1 == null || zone2 == null ) return false; Direction orbit1 = zone1 .getDirection(); Direction orbit2 = zone2 .getDirection(); if ( orbit1 != orbit2 ) return false; if ( orbit1 .isAutomatic() ) return false; AlgebraicNumber l1 = zone1 .getLength( offset1 ); AlgebraicNumber l2 = zone2 .getLength( offset2 ); if ( l1 .equals( l2 ) ) return false; return true; } } private AlgebraicNumber scaleFactor; @Override public String getCategory() { return ID; } public ScalingTool( String id, Symmetry symmetry, ToolsModel tools ) { super( id, symmetry, tools ); this .scaleFactor = null; } void setScaleFactor( AlgebraicNumber scaleFactor ) { this.scaleFactor = scaleFactor; } @Override protected String checkSelection( boolean prepareTool ) { if ( this .scaleFactor != null ) { // a predefined tool; does not use this .symmetry AlgebraicField field = this .scaleFactor .getField(); this .transforms = new Transformation[ 1 ]; AlgebraicMatrix transform = new AlgebraicMatrix( field .basisVector( 3, AlgebraicVector.X ) .scale( this .scaleFactor ), field .basisVector( 3, AlgebraicVector.Y ) .scale( this .scaleFactor ), field .basisVector( 3, AlgebraicVector.Z ) .scale( this .scaleFactor ) ); transforms[ 0 ] = new MatrixTransformation( transform, this .originPoint .getLocation() ); return null; } Segment s1 = null, s2 = null; Point center = null; boolean correct = true; boolean hasPanels = false; for (Manifestation man : mSelection) { if ( prepareTool ) unselect( man ); if ( man instanceof Connector ) { if ( center != null ) { correct = false; break; } center = (Point) ((Connector) man) .getConstructions() .next(); } else if ( man instanceof Strut ) { if ( s2 != null ) { correct = false; break; } if ( s1 == null ) s1 = (Segment) ((Strut) man) .getConstructions() .next(); else s2 = (Segment) ((Strut) man) .getConstructions() .next(); } else if ( man instanceof Panel ) hasPanels = true; } if ( center == null ) { if ( prepareTool ) // after validation, or when loading from a file center = originPoint; else // just validating the selection, not really creating a tool return "No symmetry center selected"; } correct = correct && s2 != null; if ( !prepareTool && hasPanels ) correct = false; // panels must be allowed when opening legacy files (prepareTool) if ( !correct ) return "scaling tool requires before and after struts, and a single center"; Axis zone1 = symmetry .getAxis( s1 .getOffset() ); Axis zone2 = symmetry .getAxis( s2 .getOffset() ); if(zone1 == null || zone2 == null) return "struts cannot be automatic"; Direction orbit = zone1 .getDirection(); if ( orbit != zone2 .getDirection() ) return "before and after struts must be from the same orbit"; if ( prepareTool ) { this .transforms = new Transformation[ 1 ]; transforms[ 0 ] = new Scaling( s1, s2, center, symmetry ); } return null; } @Override protected String getXmlElementName() { return "ScalingTool"; } @Override protected void setXmlAttributes( Element element, XmlSaveFormat format ) throws Failure { String symmName = element .getAttribute( "symmetry" ); if ( symmName == null || symmName .isEmpty() ) { element .setAttribute( "symmetry", "icosahedral" ); logBugAccommodation( "scaling tool serialized with no symmetry; assuming icosahedral" ); } super .setXmlAttributes( element, format ); } }
{ "content_hash": "7c4ceebecf318f7c46ab484f8070c8ef", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 100, "avg_line_length": 33.591928251121075, "alnum_prop": 0.6039247096515818, "repo_name": "david-hall/vzome-core", "id": "47495311f842868a0cb2d799c21e61439692bc43", "size": "7554", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/vzome/core/editor/ScalingTool.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "7685" }, { "name": "GAP", "bytes": "23893" }, { "name": "Java", "bytes": "1628886" }, { "name": "POV-Ray SDL", "bytes": "789" }, { "name": "Shell", "bytes": "717" } ], "symlink_target": "" }
module Quickteller end require 'quickteller/version'
{ "content_hash": "33e27064330b2a67d2f2241076382314", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 29, "avg_line_length": 11, "alnum_prop": 0.8181818181818182, "repo_name": "krzysztofbialek/quickteller", "id": "06369134042bce18439c912273946d2de8f8db82", "size": "55", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/quickteller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "0" } ], "symlink_target": "" }
package no.kantega.publishing.controls.sitemap; import no.kantega.publishing.common.Aksess; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * User: tarkil * Date: Mar 11, 2008 * Time: 10:07:44 AM */ public class CrawlerSiteMapController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mav; Map model = new HashMap(); boolean enabled = Aksess.getConfiguration().getBoolean("crawler.sitemap.enabled", false); String associationcategory = Aksess.getConfiguration().getString("crawler.sitemap.associationcategory", null); int depth = Aksess.getConfiguration().getInt("crawler.sitemap.depth", -1); if (enabled) { model.put("associationcategory", associationcategory); model.put("depth", depth); mav = new ModelAndView("/WEB-INF/jsp/sitemap/sitemap.jsp", model); } else { response.sendError(404); mav = new ModelAndView(); } return mav; } }
{ "content_hash": "bb03ae1e35735463726d4aa41e86d396", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 118, "avg_line_length": 31.5609756097561, "alnum_prop": 0.6993817619783617, "repo_name": "kantega/Flyt-cms", "id": "9227abae69f515110be6bdca1a22b539ea73893f", "size": "1886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/core/src/main/java/no/kantega/publishing/controls/sitemap/CrawlerSiteMapController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "102415" }, { "name": "Groovy", "bytes": "9509" }, { "name": "HTML", "bytes": "1484" }, { "name": "Java", "bytes": "4322582" }, { "name": "JavaScript", "bytes": "562456" }, { "name": "XSLT", "bytes": "3705" } ], "symlink_target": "" }
// Load Environment variables require('dotenv').load(); // paystack module is required to make charge token call var paystack = require('paystack')(process.env.PAYSTACK_SECRET_KEY); // uuid module is required to create a random reference number var uuid = require('node-uuid'); var express = require('express'); var app = require('express')(); var bodyParser = require('body-parser'); app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); app.use(bodyParser.json()); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); app.get('/', function(req, res) { res.send('<body><head><link href="favicon.ico" rel="shortcut icon" />\ </head><body><h1>Awesome!</h1><p>Your server is set up. \ Go ahead and configure your Paystack sample apps to make calls to: \ <ul><li> <a href="#">https://'+req.headers.host+'</a></li></ul> \ </p></body></html>'); }); app.get('/new-access-code', function(req, res) { var customerid = req.params.customerid; var cartid = req.params.cartid; var email = req.query.email; var amountinkobo = req.query.amount; //var email = 'hendykombat@gmail.com'; //var amountinkobo = 5100; // you can then look up customer and cart details in a db etc // I'm hardcoding an email here for simplicity /* amountinkobo = process.env.TEST_AMOUNT * 100; if(isNaN(amountinkobo) || (amountinkobo < 2500)){ amountinkobo = 2500; } email = process.env.SAMPLE_EMAIL; */ // all fields supported by this call can be gleaned from // https://developers.paystack.co/reference#initialize-a-transaction paystack.transaction.initialize({ email: email, // a valid email address amount: amountinkobo, // only kobo and must be integer metadata: { custom_fields:[ { "display_name":"Started From", "variable_name":"started_from", "value":"ulearn charge card backend" }, { "display_name":"Requested by", "variable_name":"requested_by", "value": req.headers['user-agent'] }, { "display_name":"Server", "variable_name":"server", "value": req.headers.host }, { "display_name":"Product Purchased", "variable_name":"product", "value": req.query.item } ] } },function(error, body) { if(error){ res.send({error:error}); return; } res.send(body.data.access_code); }); }); app.get('/verify/:reference', function(req, res) { var reference = req.params.reference; paystack.transaction.verify(reference, function(error, body) { if(error){ res.send({error:error}); return; } if(body.data.success){ // save authorization var auth = body.authorization; } res.send(body.data.gateway_response); }); }); //The 404 Route (ALWAYS Keep this as the last route) app.get('/*', function(req, res){ res.status(404).send('Only GET /new-access-code \ or GET /verify/{reference} is allowed'); }); app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')) })
{ "content_hash": "633e913a25befd0a2c7a4ee0a7a8935d", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 72, "avg_line_length": 32.5945945945946, "alnum_prop": 0.5572139303482587, "repo_name": "hendy-ejegi/ulearn-charge-card-backend", "id": "4b663fc74319913a135fecd968a034787754d13a", "size": "3618", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3434" } ], "symlink_target": "" }
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Geocrest.Web.Mvc.EmbeddedViews { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; using System.Web.Helpers; using System.Web.Mvc; using System.Web.Mvc.Ajax; using System.Web.Mvc.Html; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.UI; using System.Web.WebPages; using Geocrest.Web.Mvc; [System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "2.0.0.0")] [System.Web.WebPages.PageVirtualPathAttribute("~/Views/Help/DisplayTemplates/ImageSample.cshtml")] public partial class ImageSample_ : System.Web.Mvc.WebViewPage<Geocrest.Web.Mvc.Documentation.ImageSample> { public ImageSample_() { } public override void Execute() { WriteLiteral("<img"); WriteAttribute("src", Tuple.Create(" src=\"", 57), Tuple.Create("\"", 73) #line 3 "..\..\Views\Help\DisplayTemplates\ImageSample.cshtml" , Tuple.Create(Tuple.Create("", 63), Tuple.Create<System.Object, System.Int32>(Model.Src #line default #line hidden , 63), false) ); WriteLiteral(" />"); } } } #pragma warning restore 1591
{ "content_hash": "fe84633d22684f25554f7f8d34d79d0a", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 110, "avg_line_length": 30.448275862068964, "alnum_prop": 0.5928652321630804, "repo_name": "geocrest/mvcpluggedin", "id": "0086ae290b39386bb0c9eaef3a0452ea980e5654", "size": "1768", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Geocrest.Web.Mvc/Views/Help/DisplayTemplates/ImageSample.generated.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1650744" }, { "name": "Pascal", "bytes": "3140" } ], "symlink_target": "" }
// Generated with http://www.jsonschema2pojo.org/ package biz.dfch.j.clickatell.rest.message; import java.util.HashMap; import java.util.Map; import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "data" }) public class MessageResponse { @JsonProperty("data") private Data data; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * * @return * The data */ @JsonProperty("data") public Data getData() { return data; } /** * * @param data * The data */ @JsonProperty("data") public void setData(Data data) { this.data = data; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
{ "content_hash": "37140af0bec904804773a73e2df47d53", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 85, "avg_line_length": 24.05263157894737, "alnum_prop": 0.6973012399708242, "repo_name": "dfch/biz.dfch.j.graylog.plugin.output.clickatell", "id": "349fcb7b7bdb9f6e1ad592e0fa96133574f9b0f7", "size": "1371", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/biz/dfch/j/clickatell/rest/message/MessageResponse.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "46915" } ], "symlink_target": "" }
package cofh.api.transport; import gnu.trove.map.hash.THashMap; import net.minecraftforge.common.config.Configuration; import java.util.*; public final class RegistryEnderAttuned { public static Map<String, Map<Integer, List<IEnderItemHandler>>> inputItem = new THashMap<String, Map<Integer, List<IEnderItemHandler>>>(); public static Map<String, Map<Integer, List<IEnderFluidHandler>>> inputFluid = new THashMap<String, Map<Integer, List<IEnderFluidHandler>>>(); public static Map<String, Map<Integer, List<IEnderEnergyHandler>>> inputEnergy = new THashMap<String, Map<Integer, List<IEnderEnergyHandler>>>(); public static Map<String, Map<Integer, List<IEnderItemHandler>>> outputItem = new THashMap<String, Map<Integer, List<IEnderItemHandler>>>(); public static Map<String, Map<Integer, List<IEnderFluidHandler>>> outputFluid = new THashMap<String, Map<Integer, List<IEnderFluidHandler>>>(); public static Map<String, Map<Integer, List<IEnderEnergyHandler>>> outputEnergy = new THashMap<String, Map<Integer, List<IEnderEnergyHandler>>>(); public static Configuration linkConf; public static Map<String, String> clientFrequencyNames = new LinkedHashMap<String, String>(); public static Map<String, String> clientFrequencyNamesReversed = new LinkedHashMap<String, String>(); public static void clear() { inputItem.clear(); inputFluid.clear(); inputEnergy.clear(); outputItem.clear(); outputFluid.clear(); outputEnergy.clear(); } public static List<IEnderItemHandler> getLinkedItemInputs(IEnderItemHandler theAttuned) { if (inputItem.get(theAttuned.getChannelString()) == null) { return null; } return inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); } public static List<IEnderItemHandler> getLinkedItemOutputs(IEnderItemHandler theAttuned) { if (outputItem.get(theAttuned.getChannelString()) == null) { return null; } return outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); } public static List<IEnderFluidHandler> getLinkedFluidInputs(IEnderFluidHandler theAttuned) { if (inputFluid.get(theAttuned.getChannelString()) == null) { return null; } return inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); } public static List<IEnderFluidHandler> getLinkedFluidOutputs(IEnderFluidHandler theAttuned) { if (outputFluid.get(theAttuned.getChannelString()) == null) { return null; } return outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); } public static List<IEnderEnergyHandler> getLinkedEnergyInputs(IEnderEnergyHandler theAttuned) { if (inputEnergy.get(theAttuned.getChannelString()) == null) { return null; } return inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); } public static List<IEnderEnergyHandler> getLinkedEnergyOutputs(IEnderEnergyHandler theAttuned) { if (outputEnergy.get(theAttuned.getChannelString()) == null) { return null; } return outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()); } /* HELPER FUNCTIONS */ public static void addItemHandler(IEnderItemHandler theAttuned) { if (theAttuned.canSendItems()) { if (inputItem.get(theAttuned.getChannelString()) == null) { inputItem.put(theAttuned.getChannelString(), new HashMap<Integer, List<IEnderItemHandler>>()); } if (inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { inputItem.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList<IEnderItemHandler>()); } if (!inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); } } if (theAttuned.canReceiveItems()) { if (outputItem.get(theAttuned.getChannelString()) == null) { outputItem.put(theAttuned.getChannelString(), new HashMap<Integer, List<IEnderItemHandler>>()); } if (outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { outputItem.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList<IEnderItemHandler>()); } if (!outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); } } } public static void addFluidHandler(IEnderFluidHandler theAttuned) { if (theAttuned.canSendFluid()) { if (inputFluid.get(theAttuned.getChannelString()) == null) { inputFluid.put(theAttuned.getChannelString(), new HashMap<Integer, List<IEnderFluidHandler>>()); } if (inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { inputFluid.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList<IEnderFluidHandler>()); } if (!inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); } } if (theAttuned.canReceiveFluid()) { if (outputFluid.get(theAttuned.getChannelString()) == null) { outputFluid.put(theAttuned.getChannelString(), new HashMap<Integer, List<IEnderFluidHandler>>()); } if (outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { outputFluid.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList<IEnderFluidHandler>()); } if (!outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); } } } public static void addEnergyHandler(IEnderEnergyHandler theAttuned) { if (theAttuned.canSendEnergy()) { if (inputEnergy.get(theAttuned.getChannelString()) == null) { inputEnergy.put(theAttuned.getChannelString(), new HashMap<Integer, List<IEnderEnergyHandler>>()); } if (inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { inputEnergy.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList<IEnderEnergyHandler>()); } if (!inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); } } if (theAttuned.canReceiveEnergy()) { if (outputEnergy.get(theAttuned.getChannelString()) == null) { outputEnergy.put(theAttuned.getChannelString(), new HashMap<Integer, List<IEnderEnergyHandler>>()); } if (outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) == null) { outputEnergy.get(theAttuned.getChannelString()).put(theAttuned.getFrequency(), new ArrayList<IEnderEnergyHandler>()); } if (!outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).contains(theAttuned)) { outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).add(theAttuned); } } } public static void removeItemHandler(IEnderItemHandler theAttuned) { if (inputItem.get(theAttuned.getChannelString()) != null) { if (inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); if (inputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { inputItem.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); } } } if (outputItem.get(theAttuned.getChannelString()) != null) { if (outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); if (outputItem.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { outputItem.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); } } } } public static void removeFluidHandler(IEnderFluidHandler theAttuned) { if (inputFluid.get(theAttuned.getChannelString()) != null) { if (inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); if (inputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { inputFluid.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); } } } if (outputFluid.get(theAttuned.getChannelString()) != null) { if (outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); if (outputFluid.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { outputFluid.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); } } } } public static void removeEnergyHandler(IEnderEnergyHandler theAttuned) { if (inputEnergy.get(theAttuned.getChannelString()) != null) { if (inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); if (inputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { inputEnergy.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); } } } if (outputEnergy.get(theAttuned.getChannelString()) != null) { if (outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()) != null) { outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).remove(theAttuned); if (outputEnergy.get(theAttuned.getChannelString()).get(theAttuned.getFrequency()).size() == 0) { outputEnergy.get(theAttuned.getChannelString()).remove(theAttuned.getFrequency()); } } } } public static void add(IEnderAttuned theAttuned) { if (theAttuned instanceof IEnderItemHandler) { addItemHandler((IEnderItemHandler) theAttuned); } if (theAttuned instanceof IEnderFluidHandler) { addFluidHandler((IEnderFluidHandler) theAttuned); } if (theAttuned instanceof IEnderEnergyHandler) { addEnergyHandler((IEnderEnergyHandler) theAttuned); } } public static void remove(IEnderAttuned theAttuned) { if (theAttuned instanceof IEnderItemHandler) { removeItemHandler((IEnderItemHandler) theAttuned); } if (theAttuned instanceof IEnderFluidHandler) { removeFluidHandler((IEnderFluidHandler) theAttuned); } if (theAttuned instanceof IEnderEnergyHandler) { removeEnergyHandler((IEnderEnergyHandler) theAttuned); } } public static void sortClientNames() { List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(clientFrequencyNames.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, String>>() { @Override public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { int int1 = Integer.valueOf(clientFrequencyNamesReversed.get(o1.getValue())); int int2 = Integer.valueOf(clientFrequencyNamesReversed.get(o2.getValue())); return int1 > int2 ? 1 : int1 == int2 ? 0 : -1; } }); Map<String, String> result = new LinkedHashMap<String, String>(); for (Map.Entry<String, String> entry : list) { result.put(entry.getKey(), entry.getValue()); } clientFrequencyNames = result; } public static void clearClientNames() { clientFrequencyNames.clear(); clientFrequencyNamesReversed.clear(); } public static void addClientNames(String owner, String name) { if (!owner.isEmpty()) { clientFrequencyNames.put(owner, name); clientFrequencyNamesReversed.put(name, owner); } } }
{ "content_hash": "5b52f6281a746464b27f6c609f8a8fb5", "timestamp": "", "source": "github", "line_count": 280, "max_line_length": 150, "avg_line_length": 49.14642857142857, "alnum_prop": 0.6527141922825376, "repo_name": "pixlepix/TinkersArmory", "id": "3c2b832b789170a096a649739455fb73ec8bf340", "size": "13761", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/api/java/cofh/api/transport/RegistryEnderAttuned.java", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "330126" } ], "symlink_target": "" }
from __future__ import absolute_import, print_function, unicode_literals import collections import msgpack import six from six.moves import xrange RawDoc = collections.namedtuple('RawDoc', ('version', 'klasses', 'stores', 'doc', 'instances')) class RawDoc(object): __slots__ = ('version', 'klasses', 'stores', '_doc', '_instances', '_doc_packed', '_instances_packed') def __init__(self, version, klasses, stores, doc, instances, packed=True): self.version = version self.klasses = klasses self.stores = stores if packed: self._doc_packed = doc self._instances_packed = instances self._doc = self._instances = None else: self._doc = doc self._instances = instances self._doc_packed = self._instances_packed = None @classmethod def from_stream(cls, unpacker, on_end='error', encoding='utf-8'): if on_end not in ('error', 'break'): raise ValueError('on_end must be "error" or "break"') if not hasattr(unpacker, 'unpack'): if six.PY2 and isinstance(encoding, six.text_type): encoding = encoding.encode('utf-8') unpacker = msgpack.Unpacker(unpacker, use_list=True, encoding=encoding) try: while True: try: klasses = unpacker.unpack() except msgpack.OutOfData: return if isinstance(klasses, int): version = klasses klasses = unpacker.unpack() else: version = 1 stores = unpacker.unpack() doc = unpacker.read_bytes(unpacker.unpack()) instances = [unpacker.read_bytes(unpacker.unpack()) for i in xrange(len(stores))] yield cls(version, klasses, stores, doc, instances, packed=True) except msgpack.OutOfData: if on_end == 'error': raise def write(self, out): if self.version != 1: msgpack.pack(self.version, out) msgpack.pack(self.klasses, out) msgpack.pack(self.stores, out) doc = self.doc_packed msgpack.pack(len(doc), out) out.write(doc) for insts in self.instances_packed: msgpack.pack(len(insts), out) out.write(insts) def _get_doc(self): if self._doc is None: self._doc = msgpack.unpackb(self._doc_packed) return self._doc def _set_doc(self, doc): self._doc = doc self._doc_packed = None doc = property(_get_doc, _set_doc) def _get_instances(self): if self._instances is None: self._instances = [msgpack.unpackb(store) for store in self._instances_packed] return self._instances def _set_instances(self, instances): self._instances = instances self._instances_packed = None instances = property(_get_instances, _set_instances) def _get_doc_packed(self): if self._doc_packed is None: self._doc_packed = msgpack.packb(self._doc) return self._doc_packed def _set_doc_packed(self, doc): self._doc_packed = doc self._doc = None doc_packed = property(_get_doc_packed, _set_doc_packed) def _get_instances_packed(self): if self._instances_packed is None: self._instances_packed = [msgpack.packb(store) for store in self._instances] return self._instances_packed def _set_instances_packed(self, instances): self._instances_packed = instances self._instances = None instances_packed = property(_get_instances_packed, _set_instances_packed) def read_raw_docs(unpacker, on_end='error'): return RawDoc.from_stream(unpacker, on_end=on_end) def write_raw_doc(out, doc): doc.write(out) class RawDocWriter(object): def __init__(self, out): self.out = out def write(self, doc): doc.write(self.out) def import_string(name): path, base = name.rsplit('.', 1) return getattr(__import__(path, globals=None, fromlist=[base]), base)
{ "content_hash": "7b3f44eaa625a41a863afca2f920bb25", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 104, "avg_line_length": 28.6793893129771, "alnum_prop": 0.6475911631620974, "repo_name": "schwa-lab/dr-apps-python", "id": "8ba96c8c411ef9dfbee57d89b58fc17b8f8f7e78", "size": "3820", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "drapps/util.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "70931" }, { "name": "VimL", "bytes": "23" } ], "symlink_target": "" }
function ensure_tooling_available() { local required_tools=("lsblk" "cut" "udevadm" "grep" "badblocks" "fdisk" "mkfs.ext4") local are_tools_missing=0 local tool for tool in ${required_tools[@]} do local tool_path tool_path=$(which "$tool") if [ $? -ne 0 ] then echo "$tool is required by this script but is not available." are_tools_missing=1 fi done if [ "$are_tools_missing" -eq "1" ] then exit 1 fi } function ensure_running_as_root() { if [ "$EUID" -ne 0 ] then echo "This script must be run as root." 1>&2 exit 1 fi } function ensure_two_arguments_provided() { local argument_count=$# if [ $argument_count -ne 2 ] then echo "This script expects two arguments." 1>&2 exit 1 fi } function ensure_first_argument_is_block_device() { local block_device="$1" if [ ! -b "$block_device" ] then echo "The first script argument must be an existent block device." 1>&2 exit 1 fi } function ensure_first_argument_is_an_ide_or_scsi_disk() { local block_device="$1" local block_device_type=$(lsblk --noheadings --nodeps --raw "$1" --output TYPE) if [ "$block_device_type" != "disk" ] then echo "The first script argument must be an IDE or SCSI disk." 1>&2 exit 1 fi local block_device_major_number=$(lsblk --noheadings --nodeps --raw --output MAJ:MIN "$1" | cut --delimiter=: --fields=1) # MAJ=3 is an IDE disk if [ "$block_device_major_number" != "3" ] then # MAJ=8 is a SCSI (or SATA) disk if [ "$block_device_major_number" != "8" ] then echo "The first script argument must be an IDE or SCSI disk device." 1>&2 exit 1 fi fi } function ensure_first_argument_is_a_usb_disk() { local block_device="$1" local block_device_identifier=$(lsblk --noheadings --nodeps --raw --output KNAME "$block_device") udevadm info --query=all --path="/sys/block/$block_device_identifier" | grep ID_PATH=.*usb.* > /dev/null if [ $? -ne 0 ] then echo "The first script argument must be a USB disk device." 1>&2 exit 1 fi } function type_y_to_continue() { local block_device="$1" echo -n "This will destructively test and repartition USB disk device ""$block_device"". Are you sure (Y/N)?" local confirmation while read -r -n 1 confirmation do if [ "${confirmation,,}" = "n" ] then echo -e "\nConfirmation declined." exit 1 elif [ "${confirmation,,}" = "y" ] then echo -e "" break fi done } function test_block_device_for_bad_blocks() { local block_device="$1" badblocks -w -s -v -b 4096 "$block_device" if [ $? -ne 0 ] then echo "Device $block_device has bad blocks!" 1>&2 exit 1 fi } function create_new_mbr_partition_table() { local block_device="$1" echo -e "o\nw" | fdisk "$block_device" &> /dev/null } function create_data_partition() { local block_device="$1" local partition_number="$2" local partition_label="$3" echo -e "n\np\n$partition_number\n\n\nt\n83\nw" | fdisk "$block_device" &> /dev/null mkfs.ext4 -m0 -L "$partition_label" "$block_device$partition_number" &> /dev/null } ensure_tooling_available ensure_running_as_root ensure_two_arguments_provided "$@" ensure_first_argument_is_block_device "$1" ensure_first_argument_is_an_ide_or_scsi_disk "$1" ensure_first_argument_is_a_usb_disk "$1" type_y_to_continue "$1" test_block_device_for_bad_blocks "$1" create_new_mbr_partition_table "$1" create_data_partition "$1" 1 "$2" echo "Finished." exit 0
{ "content_hash": "b01412464a09fb69c9976d0ce80da69b", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 125, "avg_line_length": 25.60135135135135, "alnum_prop": 0.5943520717867511, "repo_name": "sjwood/provisioning", "id": "91fdcb61e29a25335aaf851ed626aaa3510d7e93", "size": "4377", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "usb_disk_preparation.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Shell", "bytes": "23141" } ], "symlink_target": "" }
#ifndef BOOST_MPL_LIST_AUX_POP_FRONT_HPP_INCLUDED #define BOOST_MPL_LIST_AUX_POP_FRONT_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source$ // $Date: 2004-10-24 04:18:08 -0400 (Sun, 24 Oct 2004) $ // $Revision: 25850 $ #include <boost/mpl/pop_front_fwd.hpp> #include <boost/mpl/next_prior.hpp> #include <boost/mpl/list/aux_/tag.hpp> namespace boost { namespace mpl { template<> struct pop_front_impl< aux::list_tag > { template< typename List > struct apply { typedef typename mpl::next<List>::type type; }; }; }} #endif // BOOST_MPL_LIST_AUX_POP_FRONT_HPP_INCLUDED
{ "content_hash": "9cc5a3bc4fbff0a218ad0ad2c80375fc", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 62, "avg_line_length": 25.294117647058822, "alnum_prop": 0.6627906976744186, "repo_name": "jaredhoberock/gotham", "id": "a38ff06008a2868fbac50a5c85bc544d2af87b69", "size": "860", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "windows/include/boost/mpl/list/aux_/pop_front.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3000328" }, { "name": "C++", "bytes": "43171616" }, { "name": "Perl", "bytes": "6275" }, { "name": "Python", "bytes": "2200222" }, { "name": "Shell", "bytes": "2497" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="Servicios" table="servicios"> <id name="intServicioId" type="integer" column="int_servicio_id"> <generator strategy="SEQUENCE"/> </id> <field name="varServicioNombre" type="string" column="var_servicio_nombre" length="150" nullable="true"/> <field name="intServicioTipo" type="integer" column="int_servicio_tipo" nullable="true"/> <field name="varTurnoHorainicio" type="string" column="var_turno_horainicio" length="10" nullable="true"/> <field name="varTurnoHorafin" type="string" column="var_turno_horafin" length="10" nullable="true"/> <field name="intTurnoDia" type="integer" column="int_turno_dia" nullable="true"/> </entity> </doctrine-mapping>
{ "content_hash": "0b1b6628b9b51150a2e2ae78f4db343c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 276, "avg_line_length": 78.38461538461539, "alnum_prop": 0.7262021589793916, "repo_name": "marx8926/actumbesfinal", "id": "34023f53a5847280951bca69330f9913a052241a", "size": "1019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AE/DataBundle/Resources/config/doctrine/metadata/orm/Servicios.orm.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "471856" }, { "name": "JavaScript", "bytes": "1864071" }, { "name": "PHP", "bytes": "4879680" } ], "symlink_target": "" }
/** * Imports */ import {Menu, Text, Icon, Block} from 'vdux-ui' import {MenuItem, Avatar} from 'vdux-containers' import Link from 'components/Link' import ImagePicker from 'components/ImagePicker' import {component, element} from 'vdux' /** * <Left Nav/> */ export default component({ render ({props, children, context}) { const {thisProfile, isMine} = props const {username, displayName, drafts = {}, photoURL} = thisProfile.value const numDrafts = Object.keys(drafts).length const imgProps = isMine ? { onClick: context.openModal(() => <ImagePicker/>), pointer: true, transition: 'opacity .25s', hoverProps: {opacity: .2} } : {} const imageSize = '80px' return ( <Block tall align='start'> <Block borderRight='1px solid grey'> <Menu column overflowY='auto' w={180} pt='s' px='s'> <Block py={10} borderBottom='1px solid divider'> <Block bgColor='blue' circle={imageSize} m='0 auto 6px' relative> <Icon name='edit' color='white' fs='28' textAlign='center' lh={imageSize} circle={imageSize}/> <Avatar absolute top left display='block' circle={imageSize} src={photoURL} {...imgProps} /> </Block> <Block whiteSpace='nowrap' ellipsis textAlign='center'> <Block ellipsis mb='s'>{displayName}</Block> <Block color='blue' ellipsis fs={11} fontFamily='"Press Start 2P"'>{username}</Block> </Block> </Block> <Item color='red' mt='s' icon='collections' href={`/${username}/gallery`}> Showcase </Item> <Block hide={!isMine}> <Block px mt='s' pt pb='s' fs='xxs' borderTop='1px solid divider'>Play</Block> <Item color='blue' icon='check_circle' href={`/${username}/studio/completed`}> Completed </Item> <Item color='green' icon='access_time' href={`/${username}/studio/inProgress`}> In Progress </Item> </Block> <Block hide={!isMine} px mt='s' pt pb='s' fs='xxs' borderTop='1px solid divider'>Created</Block> <Item color='blue' href={`/${username}/authored/playlists`} icon='view_list'> Playlists </Item> <Item color='green' icon='stars' href={`/${username}/authored/challenges`}> Challenges </Item> <Item hide={!isMine} color='yellow' icon='edit' href={`/${username}/authored/drafts`}> Drafts <Block italic ml='s' color='#888' fs='13' lh='17px'> ({numDrafts}) </Block> </Item> </Menu> </Block> <Block flex bg='#F0F0F0'> {children} </Block> </Block> ) } }) const Item = component({ render({props, children, context}) { const {icon, color, ...rest} = props return ( <Link bgColor='#FAFAFA' color='primary' fs='xs' align='start center' ui={MenuItem} currentProps={{bgColor: '#EEE'}} {...rest}> { icon && <Icon name={icon} mr={10} color={color} /> } { children } </Link> ) } })
{ "content_hash": "639f161f24d3c5364e6cc4d332830315", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 129, "avg_line_length": 32.10989010989011, "alnum_prop": 0.6013004791238877, "repo_name": "danleavitt0/artbot", "id": "b4c6e13927ecbdf7736ab601559d45efa41439ef", "size": "2922", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/layouts/LeftNav/LeftNav.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1085" }, { "name": "HTML", "bytes": "488" }, { "name": "JavaScript", "bytes": "186702" } ], "symlink_target": "" }
#define _ZLIB_SUPPORT 1 #define MD6_SUPPORT 1 #if defined(_WIN32) #ifdef _ZLIB_SUPPORT #if !defined(WINRT) #pragma comment(lib, "libzlib.lib") #else #pragma comment(lib, "zlib.lib") #endif #else #include "zlib.h" #endif #endif #include <assert.h> #include "crypto_wrapper.h" #if defined(MD6_SUPPORT) #include "md6.h" #endif #include <algorithm> #include <fstream> #include "xxfsutility.h" #define HASH_FILE_BUFF_SIZE 1024 #ifdef _ZLIB_SUPPORT #include <zlib.h> #endif using namespace purelib; template<typename _ByteSeqCont> _ByteSeqCont zlib_compress(const unmanaged_string& in, int level) { // calc destLen auto destLen = ::compressBound(in.size()); _ByteSeqCont out(destLen, '\0'); // do compress int ret = ::compress2((Bytef*)(&out.front()), &destLen, (const Bytef*)in.c_str(), in.size(), level); if (ret == Z_OK) { out.resize(destLen); } return std::move(out); } template<typename _ByteSeqCont> _ByteSeqCont zlib_deflate(const unmanaged_string& in, int level) { int err; Bytef buffer[128]; z_stream d_stream; /* compression stream */ // strcpy((char*)buffer, "garbage"); d_stream.zalloc = nullptr; d_stream.zfree = nullptr; d_stream.opaque = (voidpf)0; d_stream.next_in = (Bytef*)in.c_str(); d_stream.avail_in = in.size(); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); _ByteSeqCont output; err = deflateInit(&d_stream, level); if (err != Z_OK) // TODO: log somthing return std::move(output); output.reserve(in.size()); for (;;) { err = deflate(&d_stream, Z_FINISH); if (err == Z_STREAM_END) { output.insert(output.end(), buffer, buffer + sizeof(buffer) - d_stream.avail_out); break; } switch (err) { case Z_NEED_DICT: err = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: deflateEnd(&d_stream); output.clear(); return std::move(output); } // not enough buffer ? if (err != Z_STREAM_END) { output.insert(output.end(), buffer, buffer + sizeof(buffer)); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); } } deflateEnd(&d_stream); if (err != Z_STREAM_END) { output.clear(); } return std::move(output); } template<typename _ByteSeqCont> _ByteSeqCont zlib_inflate(const unmanaged_string& compr) { // inflate int err; Bytef buffer[128]; z_stream d_stream; /* decompression stream */ // strcpy((char*)buffer, "garbage"); d_stream.zalloc = nullptr; d_stream.zfree = nullptr; d_stream.opaque = (voidpf)0; d_stream.next_in = (Bytef*)compr.c_str(); d_stream.avail_in = compr.size(); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); _ByteSeqCont output; err = inflateInit(&d_stream); if (err != Z_OK) // TODO: log somthing return std::move(output); // CHECK_ERR(err, "inflateInit"); output.reserve(compr.size() << 2); for (;;) { err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) { output.insert(output.end(), buffer, buffer + sizeof(buffer) - d_stream.avail_out); break; } switch (err) { case Z_NEED_DICT: err = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: goto _L_end; } // not enough memory ? if (err != Z_STREAM_END) { // *out = (unsigned char*)realloc(*out, bufferSize * BUFFER_INC_FACTOR); output.insert(output.end(), buffer, buffer + sizeof(buffer)); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); } } _L_end: inflateEnd(&d_stream); if (err != Z_STREAM_END) { output.clear(); } return std::move(output); } // inflate alias template<typename _ByteSeqCont> _ByteSeqCont zlib_uncompress(const unmanaged_string& in) { return zlib_inflate<_ByteSeqCont>(in); } // gzip template<typename _ByteSeqCont> _ByteSeqCont zlib_gzcompr(const unmanaged_string& in, int level) { int err; Bytef buffer[128]; z_stream d_stream; /* compression stream */ // strcpy((char*)buffer, "garbage"); d_stream.zalloc = nullptr; d_stream.zfree = nullptr; d_stream.opaque = (voidpf)0; d_stream.next_in = (Bytef*)in.c_str(); d_stream.avail_in = in.size(); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); _ByteSeqCont output; err = deflateInit2(&d_stream, level, Z_DEFLATED, MAX_WBITS + 16, MAX_MEM_LEVEL - 1, Z_DEFAULT_STRATEGY); if (err != Z_OK) // TODO: log somthing return std::move(output); for (;;) { err = deflate(&d_stream, Z_FINISH); if (err == Z_STREAM_END) { output.insert(output.end(), buffer, buffer + sizeof(buffer) - d_stream.avail_out); break; } switch (err) { case Z_NEED_DICT: err = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: goto _L_end; } // not enough buffer ? if (err != Z_STREAM_END) { output.insert(output.end(), buffer, buffer + sizeof(buffer)); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); } } _L_end: deflateEnd(&d_stream); if (err != Z_STREAM_END) { output.clear(); } return std::move(output); } template<typename _ByteSeqCont> _ByteSeqCont zlib_gzuncompr(const unmanaged_string& compr) { // inflate int err; Bytef buffer[128]; z_stream d_stream; /* decompression stream */ // strcpy((char*)buffer, "garbage"); d_stream.zalloc = nullptr; d_stream.zfree = nullptr; d_stream.opaque = (voidpf)0; d_stream.next_in = (Bytef*)compr.c_str(); d_stream.avail_in = compr.size(); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); _ByteSeqCont output; err = inflateInit2(&d_stream, MAX_WBITS + 16); if (err != Z_OK) // TODO: log somthing return std::move(output); // CHECK_ERR(err, "inflateInit"); output.reserve(compr.size() << 2); for (;;) { err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) { output.insert(output.end(), buffer, buffer + sizeof(buffer) - d_stream.avail_out); break; } switch (err) { case Z_NEED_DICT: err = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: goto _L_end; } // not enough memory ? if (err != Z_STREAM_END) { // *out = (unsigned char*)realloc(*out, bufferSize * BUFFER_INC_FACTOR); output.insert(output.end(), buffer, buffer + sizeof(buffer)); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); } } _L_end: inflateEnd(&d_stream); if (err != Z_STREAM_END) { output.clear(); } return std::move(output); } std::string crypto::zlib::compress(const unmanaged_string& in, int level) { return zlib_compress<std::string>(in, level); } std::string crypto::zlib::uncompress(const unmanaged_string& in) { return zlib_uncompress<std::string>(in); } std::string crypto::zlib::deflate(const unmanaged_string& in, int level) { return zlib_deflate<std::string>(in, level); } std::string crypto::zlib::inflate(const unmanaged_string& in) { return zlib_inflate<std::string>(in); } std::string crypto::zlib::gzcompr(const unmanaged_string& in, int level) { return zlib_gzcompr<std::string>(in, level); } std::string crypto::zlib::gzuncompr(const unmanaged_string& in) { return zlib_gzuncompr<std::string>(in); } std::vector<char> crypto::zlib::abi::compress(const unmanaged_string& in, int level) { return zlib_compress<std::vector<char>>(in, level); } std::vector<char> crypto::zlib::abi::uncompress(const unmanaged_string& in) { return zlib_uncompress<std::vector<char>>(in); } std::vector<char> crypto::zlib::abi::deflate(const unmanaged_string& in, int level) { return zlib_deflate<std::vector<char>>(in, level); } std::vector<char> crypto::zlib::abi::inflate(const unmanaged_string& in) { return zlib_inflate<std::vector<char>>(in); } std::vector<char> crypto::zlib::abi::gzcompr(const unmanaged_string& in, int level) { return zlib_gzcompr<std::vector<char>>(in, level); } std::vector<char> crypto::zlib::abi::gzuncompr(const unmanaged_string& in) { return zlib_gzuncompr<std::vector<char>>(in); } std::string crypto::hash::md5(const unmanaged_string& plaintext) { char ciphertext[32]; md5chars(plaintext.c_str(), plaintext.length(), ciphertext); return std::string(ciphertext, sizeof(ciphertext)); } std::string crypto::hash::md5raw(const unmanaged_string& plaintext) { char ciphertext[16]; ::md5(plaintext.c_str(), plaintext.length(), ciphertext); return std::string(ciphertext, sizeof(ciphertext)); } std::string crypto::hash::fmd5(const char* filename) { FILE* fp = fopen(filename, "rb"); // std::ifstream fin(filename, std::ios_base::binary); if (fp == NULL) { // std::cout << "Transmission Client: open failed!\n"; return ""; } //fin.seekg(0, std::ios_base::end); //std::streamsize bytes_left = fin.tellg(); // filesize initialized //fin.seekg(0, std::ios_base::beg); auto bytes_left = fsutil::get_file_size(fp); char buffer[HASH_FILE_BUFF_SIZE]; md5_state_t state; char hash[16] = { 0 }; std::string result(32, '\0'); md5_init(&state); while (bytes_left > 0) { auto n = (std::min)((std::streamsize)sizeof(buffer), (std::streamsize)bytes_left); // fin.read(buffer, bytes_read); auto bytes_read = fread(buffer, 1, n, fp); md5_append(&state, (unsigned char*)buffer, bytes_read); bytes_left -= bytes_read; } fclose(fp); md5_finish(&state, (unsigned char*)hash); hexs2chars(hash, sizeof(hash), &result.front(), result.size()); return std::move(result); } #if defined(MD6_SUPPORT) std::string crypto::hash::md6(const std::string& plaintext) { // char ciphertext[128]; std::string result(128, '\0'); ::md6chars(plaintext.c_str(), plaintext.length(), &result.front(), 64); return std::move(result); // std::string(ciphertext, sizeof(ciphertext)); } std::string crypto::hash::md6raw(const std::string& plaintext) { std::string result(64, '\0'); ::md6(plaintext.c_str(), plaintext.length(), &result.front(), 64); return std::move(result); } std::string crypto::hash::fmd6(const char* filename, int hashByteLen) { std::ifstream fin; fin.open(filename, std::ios_base::binary); if (!fin.is_open()) { // std::cout << "Transmission Client: open failed!\n"; return ""; } fin.seekg(0, std::ios_base::end); std::streamsize bytes_left = fin.tellg(); // filesize initialized fin.seekg(0, std::ios_base::beg); char buffer[HASH_FILE_BUFF_SIZE]; md6_state state; if (hashByteLen > 64) hashByteLen = 64; // int hashByteLen = 64; // assert(hashByteLen <= 64); char hash[64] = { 0 }; std::string result(hashByteLen << 1, '\0'); md6_init(&state, hashByteLen << 3); while (bytes_left > 0) { int bytes_read = (std::min)((std::streamsize)sizeof(buffer), bytes_left); fin.read(buffer, bytes_read); md6_update(&state, (unsigned char*)buffer, bytes_read << 3); bytes_left -= bytes_read; } fin.close(); md6_final(&state, (unsigned char*)hash); hexs2chars(hash, hashByteLen, &result.front(), result.size()); return std::move(result); } #endif /* MD6_SUPPORT */ std::string crypto::http::b64dec(const unmanaged_string& ciphertext) { std::string plaintext( ciphertext.length(), '\0' ); base64_decodestate state; base64_init_decodestate(&state); int r1 = base64_decode_block(ciphertext.c_str(), ciphertext.length(), &plaintext.front(), &state); plaintext.resize(r1); return std::move(plaintext); } std::string crypto::http::b64enc(const unmanaged_string& plaintext) { std::string ciphertext( (plaintext.length() * 2), '\0' ); char* wrptr = &ciphertext.front(); base64_encodestate state; base64_init_encodestate(&state); int r1 = base64_encode_block(plaintext.c_str(), plaintext.length(), wrptr, &state); int r2 = base64_encode_blockend(wrptr + r1, &state); ciphertext.resize(r1 + r2); return std::move(ciphertext); } std::string crypto::http::urlencode(const unmanaged_string& input) { std::string output; for( size_t ix = 0; ix < input.size(); ix++ ) { uint8_t buf[4]; memset( buf, 0, 4 ); if( isalnum( (uint8_t)input[ix] ) ) { buf[0] = input[ix]; } //else if ( isspace( (BYTE)sIn[ix] ) ) //{ // buf[0] = '+'; //} else { buf[0] = '%'; buf[1] = ::hex2uchr( (uint8_t)input[ix] >> 4 ); buf[2] = ::hex2uchr( (uint8_t)input[ix] % 16); } output += (char *)buf; } return std::move(output); }; std::string crypto::http::urldecode(const unmanaged_string& ciphertext) { std::string result = ""; for( size_t ix = 0; ix < ciphertext.size(); ix++ ) { uint8_t ch = 0; if(ciphertext[ix]=='%') { ch = (::uchr2hex(ciphertext[ix+1])<<4); ch |= ::uchr2hex(ciphertext[ix+2]); ix += 2; } else if(ciphertext[ix] == '+') { ch = ' '; } else { ch = ciphertext[ix]; } result += (char)ch; } return std::move(result); } // appended zlib_inflate func managed_cstring crypto::zlib::abi::_inflate(const unmanaged_string& compr) { // inflate int err; Bytef buffer[128]; z_stream d_stream; /* decompression stream */ // strcpy((char*)buffer, "garbage"); d_stream.zalloc = nullptr; d_stream.zfree = nullptr; d_stream.opaque = (voidpf)0; d_stream.next_in = (Bytef*)compr.c_str(); d_stream.avail_in = compr.size(); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); managed_cstring output; err = inflateInit(&d_stream); if (err != Z_OK) // TODO: log somthing return std::move(output); // CHECK_ERR(err, "inflateInit"); output.reserve(compr.size() << 2); for (;;) { err = inflate(&d_stream, Z_NO_FLUSH); if (err == Z_STREAM_END) { output.cappend((const char*)buffer, sizeof(buffer) - d_stream.avail_out); break; } switch (err) { case Z_NEED_DICT: err = Z_DATA_ERROR; case Z_DATA_ERROR: case Z_MEM_ERROR: goto _L_end; } // not enough memory ? if (err != Z_STREAM_END) { // *out = (unsigned char*)realloc(*out, bufferSize * BUFFER_INC_FACTOR); output.cappend((const char*)buffer, sizeof(buffer)); d_stream.next_out = buffer; d_stream.avail_out = sizeof(buffer); } } _L_end: inflateEnd(&d_stream); if (err != Z_STREAM_END) { output.clear(); } return std::move(output); }
{ "content_hash": "25b35e23a0495498b2a0a8b61d1a3880", "timestamp": "", "source": "github", "line_count": 626, "max_line_length": 108, "avg_line_length": 25.984025559105433, "alnum_prop": 0.5541005778925365, "repo_name": "halx99/cocos2d-x-pc-port", "id": "1d42f2b400c384300d83912a8c8ae7c28ee4c2f8", "size": "16266", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "crypto-support/crypto_wrapper.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "118979" }, { "name": "C++", "bytes": "1637292" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace YAF.Pages.Admin { public partial class forums { /// <summary> /// PageLinks control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::VZF.Controls.PageLinks PageLinks; /// <summary> /// LocalizedLabel1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::VZF.Controls.LocalizedLabel LocalizedLabel1; /// <summary> /// tviewcontainer control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlGenericControl tviewcontainer; /// <summary> /// TreeMenuTip control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::VZF.Controls.LocalizedLabel TreeMenuTip; /// <summary> /// PageLinks1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::VZF.Controls.PageLinks PageLinks1; /// <summary> /// CategoryList control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Repeater CategoryList; /// <summary> /// NewCategory control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button NewCategory; /// <summary> /// NewForum control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button NewForum; /// <summary> /// SmartScroller1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::VZF.Controls.SmartScroller SmartScroller1; } }
{ "content_hash": "98de5bb6861d7876b0f2efb88070e767", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 87, "avg_line_length": 34.75, "alnum_prop": 0.532673860911271, "repo_name": "vzrus/VZF", "id": "c452c789489e3c00d0697709b47ef4e78ddab7e4", "size": "3338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vzfsrc/VZF.NET/pages/admin/forums.ascx.designer.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "1892975" }, { "name": "Batchfile", "bytes": "2894" }, { "name": "C#", "bytes": "8971363" }, { "name": "CSS", "bytes": "1682229" }, { "name": "HTML", "bytes": "46740" }, { "name": "JavaScript", "bytes": "5407447" }, { "name": "PLpgSQL", "bytes": "1799027" }, { "name": "SQLPL", "bytes": "4870" }, { "name": "XSLT", "bytes": "7052" } ], "symlink_target": "" }
namespace webkit { // A special implementation of WebLayerImpl for layers that its contents // need to be automatically scaled when the bounds changes. The compositor // can efficiently handle the bounds change of such layers if the bounds // is fixed to a given value and the change of bounds are converted to // transformation scales. class WebLayerImplFixedBounds : public WebLayerImpl { public: WEBKIT_COMPOSITOR_BINDINGS_EXPORT WebLayerImplFixedBounds(); WEBKIT_COMPOSITOR_BINDINGS_EXPORT explicit WebLayerImplFixedBounds( scoped_refptr<cc::Layer>); virtual ~WebLayerImplFixedBounds(); // WebLayerImpl overrides. virtual void invalidateRect(const blink::WebFloatRect& rect); virtual void setAnchorPoint(const blink::WebFloatPoint& anchor_point); virtual void setBounds(const blink::WebSize& bounds); virtual blink::WebSize bounds() const; virtual void setTransform(const SkMatrix44& transform); virtual SkMatrix44 transform() const; WEBKIT_COMPOSITOR_BINDINGS_EXPORT void SetFixedBounds(gfx::Size bounds); protected: void SetTransformInternal(const gfx::Transform& transform); void UpdateLayerBoundsAndTransform(); gfx::Transform original_transform_; gfx::Size original_bounds_; gfx::Size fixed_bounds_; private: DISALLOW_COPY_AND_ASSIGN(WebLayerImplFixedBounds); }; } // namespace webkit #endif // WEBKIT_RENDERER_COMPOSITOR_BINDINGS_WEB_LAYER_IMPL_FIXED_BOUNDS_H_
{ "content_hash": "2205beded89bda53e8ec0fbf8f015ece", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 77, "avg_line_length": 36.51282051282051, "alnum_prop": 0.7808988764044944, "repo_name": "anirudhSK/chromium", "id": "f338cdead7a6d64a7346f4212becd364c6f3ddf3", "size": "1861", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "webkit/renderer/compositor_bindings/web_layer_impl_fixed_bounds.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "52960" }, { "name": "Awk", "bytes": "8660" }, { "name": "C", "bytes": "42502191" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "201859263" }, { "name": "CSS", "bytes": "946557" }, { "name": "DOT", "bytes": "2984" }, { "name": "Java", "bytes": "5687122" }, { "name": "JavaScript", "bytes": "22163714" }, { "name": "M", "bytes": "2190" }, { "name": "Matlab", "bytes": "2496" }, { "name": "Objective-C", "bytes": "7670589" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "672770" }, { "name": "Python", "bytes": "10873885" }, { "name": "R", "bytes": "262" }, { "name": "Shell", "bytes": "1315894" }, { "name": "Tcl", "bytes": "277091" }, { "name": "TypeScript", "bytes": "1560024" }, { "name": "XSLT", "bytes": "13493" }, { "name": "nesC", "bytes": "15206" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FlipListSides")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FlipListSides")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b30f84d9-82bf-459f-9ff1-850e286e77cb")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "a007f90e1e8ffd5480a0e7251e219d37", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.861111111111114, "alnum_prop": 0.7455325232308792, "repo_name": "Shtereva/Fundamentals-with-CSharp", "id": "25ed8cb3838616374532016883455f7740de90e3", "size": "1402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lists-ProcessingVariable-LengthSequences/FlipListSides/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "201" }, { "name": "C#", "bytes": "1263790" }, { "name": "CSS", "bytes": "1026" }, { "name": "HTML", "bytes": "10254" }, { "name": "JavaScript", "bytes": "42472" }, { "name": "PowerShell", "bytes": "264844" } ], "symlink_target": "" }
package langinfo var CAPI = map[string]struct{}{ "__darwin_check_fd_set_overflow": {}, }
{ "content_hash": "fb921392b06f54a62ddf95da9acb1618", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 38, "avg_line_length": 18.2, "alnum_prop": 0.6703296703296703, "repo_name": "42wim/matterbridge", "id": "a7a9ae844acd20ea67d2bd39c17ee9bd0f78f7cb", "size": "407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/modernc.org/libc/langinfo/capi_darwin_arm64.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2029" }, { "name": "Go", "bytes": "456275" }, { "name": "Shell", "bytes": "513" } ], "symlink_target": "" }
<p style="margin-top: -2px; margin-bottom: -2px;" align="center"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b> <font color="#008000">Department of Mathematics</font></b></font></p> <p style="margin-top: -2px; margin-bottom: -2px;" align="center"><b> <font color="#008000" face="Verdana, Arial, Helvetica, sans-serif" size="2"> Indian Institute of Science</font></b></p> <p style="margin-top: -2px; margin-bottom: -2px;" align="center"><b> <font color="#008000" face="Verdana, Arial, Helvetica, sans-serif" size="2"> Bangalore 560 012</font></b></p> <p style="margin-top: -2px; margin-bottom: -2px;" align="center">&nbsp;</p> <p style="margin-top: -2px; margin-bottom: -2px;" align="center"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b> <font color="#ff00ff">SEMINAR</font></b></font></p> <p>&nbsp;</p> <table style="border-collapse: collapse;" id="AutoNumber1" border="0" bordercolor="#111111" cellspacing="1" height="201" width="136%"> <tbody><tr> <td align="left" height="35" valign="top" width="11%"> <p style="margin-top: -2px; margin-bottom: -2px;"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b> Speaker</b> </font> </p></td> <td align="left" height="35" valign="top" width="2%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2"><b> :</b> </font> </p></td> <td align="left" height="35" width="141%"> <pre><font face="Verdana"> Ms. Jotsaroop</font></pre> </td> </tr> <tr> <td align="left" height="35" valign="top" width="11%"> <b><font face="Verdana, Arial, Helvetica, sans-serif" size="2">Affiliation</font></b></td> <td align="left" height="35" valign="top" width="2%"> <b><font face="Verdana" size="2">:</font></b></td> <td align="left" height="35" valign="top" width="141%"> <font face="Verdana" size="2"> IISc, Bangalore.</font></td> </tr> <tr> <td align="left" height="31" valign="top" width="11%"> <p style="margin-top: -2px; margin-bottom: -2px;"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b> Subject Area</b></font></p></td> <td align="left" height="31" valign="top" width="2%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2"><b> :</b> </font> </p></td> <td align="left" height="31" width="141%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2">Mathematics</font></p> <p style="margin-top: -2px; margin-bottom: -2px;">&nbsp;</p></td> </tr> <tr> <td align="left" height="31" valign="top" width="11%"> <p style="margin-top: -2px; margin-bottom: -2px;"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b> Venue</b></font></p></td> <td align="left" height="31" valign="top" width="2%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2"><b> :</b> </font> </p></td> <td align="left" height="31" width="141%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2"> Department of Mathematics, Lecture Hall I</font></p> <p style="margin-top: -2px; margin-bottom: -2px;">&nbsp;</p></td> </tr> <tr> <td align="left" height="31" valign="top" width="11%"> <p style="margin-top: -2px; margin-bottom: -2px;"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b> Time</b> </font> </p></td> <td align="left" height="31" valign="top" width="2%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2"><b> :</b> </font> </p></td> <td align="left" height="31" width="141%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2">4.00 p.m.-5.00 p.m.</font></p> <p style="margin-top: -2px; margin-bottom: -2px;">&nbsp;</p></td> </tr> <tr> <td align="left" height="35" valign="top" width="11%"> <p style="margin-top: -2px; margin-bottom: -2px;"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b> Date</b> &nbsp;</font></p></td> <td align="left" height="35" valign="top" width="2%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2"><b> :</b> </font> </p></td> <td align="left" height="35" width="141%"> <pre><font face="Verdana">May</font><font face="Verdana" size="2">31, 2012 (</font><font face="Verdana">Thursday</font><font face="Verdana" size="2">)</font></pre> </td> </tr> <tr> <td align="left" height="1" valign="top" width="11%"> <p style="margin-top: -2px; margin-bottom: -2px;"><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b> Title</b></font></p></td> <td align="left" height="1" valign="top" width="2%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2"><b> :</b> </font> </p></td> <td align="left" height="1" width="141%"> <pre><font face="Verdana">"Grushin multipliers and Toeplitz operators"</font></pre> </td> </tr> <tr> <td align="left" height="1" valign="top" width="11%"> <b> <font face="Verdana, Arial, Helvetica, sans-serif" size="2">Abstract</font></b></td> <td align="left" height="1" valign="top" width="2%"> <p style="margin-top: -2px; margin-bottom: -2px;"> <font face="Verdana" size="2"><b> :</b> </font> </p></td> <td align="left" height="1" width="141%"> <div align="justify"> <pre><font face="Verdana"><p align="justify"> The Grushin operator is defined as $G:=-\triangle-|x|^2\partial_t^2$ on R^{n+1}. We study the boundedness of the multipliers $m(G)$ of $G$ on $L^p(R^{n+1})$. We prove the analogue of the Hormander-Mihlin theorem for $m(G)$. We also study the boundedness of the solution of the wave equation corresponding to $G$ on $L^p(R^{n+1})$. The main tool in studying the above is the operator-valued Fourier multiplier theorem by Lutz Weis. Next we look at Toeplitz operators on some Segal-Bargmann spaces. Let $T_g$ be the Toeplitz operator corresponding to g. We study the boundedness of $T_g$ by transferring them to the underlying $L^2$ spaces. We make use of the above transference to get some sufficient conditions on $g$ for the boundedness of $T_g$. </p> </font><font face="Verdana" size="2"> </font></pre> </div> <pre>&nbsp;</pre> </td> </tr> </tbody></table> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //--> </script> <script language="JavaScript"> <!-- var SymRealOnLoad; var SymRealOnUnload; function SymOnUnload() { window.open = SymWinOpen; if(SymRealOnUnload != null) SymRealOnUnload(); } function SymOnLoad() { if(SymRealOnLoad != null) SymRealOnLoad(); window.open = SymRealWinOpen; SymRealOnUnload = window.onunload; window.onunload = SymOnUnload; } SymRealOnLoad = window.onload; window.onload = SymOnLoad; //-->
{ "content_hash": "971ce6d4b8f3d70362305c87c9118bbe", "timestamp": "", "source": "github", "line_count": 523, "max_line_length": 191, "avg_line_length": 24.8604206500956, "alnum_prop": 0.6566682048915552, "repo_name": "siddhartha-gadgil/www.math.iisc.ernet.in", "id": "49a2b505ae92b7f29bfc9f2c4fea1b8b44ac4973", "size": "13010", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/seminars2012/may311.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16646" }, { "name": "HTML", "bytes": "7363807" }, { "name": "JavaScript", "bytes": "14188" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="dev.paytrack.paytrack"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.USE_CREDENTIALS" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <application android:allowBackup="true" android:icon="@mipmap/ic_paytrack" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <meta-data android:name="com.google.android.geo.API_KEY" android:value="AIzaSyAdg424oFe5fqVHKOFAMA4KaFfEKwVwlMg" /> <activity android:name=".activity.TripListActivity"> </activity> <activity android:name=".activity.CreateTripActivity" /> <activity android:name=".activity.TripActivity" /> <activity android:name=".activity.RecommendVenuesActivity" /> <activity android:name=".activity.MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".activity.AuthenticationActivity"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="bienepaytrack.dev" android:scheme="http" /> </intent-filter> </activity> </application> </manifest>
{ "content_hash": "34a68588b7ad205f60b2e9134b7515f1", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 80, "avg_line_length": 38.95918367346939, "alnum_prop": 0.6165531691985333, "repo_name": "victorpm5/paytrack", "id": "dd3796105fc5ebc97ee3db221d4e782df247e5c1", "size": "1909", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/AndroidManifest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "66455" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- ~ Copyright 2016 Red Hat, Inc. and/or its affiliates ~ and other contributors as indicated by the @author tags. ~ ~ 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <artifactId>keycloak-parent</artifactId> <groupId>org.keycloak</groupId> <version>1.9.0.Final-SNAPSHOT</version> <relativePath>../../../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>keycloak-jaxrs-oauth-client</artifactId> <name>Keycloak JAX-RS OAuth Client</name> <description/> <dependencies> <dependency> <groupId>org.jboss.spec.javax.ws.rs</groupId> <artifactId>jboss-jaxrs-api_2.0_spec</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-client</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.keycloak</groupId> <artifactId>keycloak-core</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.keycloak</groupId> <artifactId>keycloak-adapter-spi</artifactId> </dependency> <dependency> <groupId>org.keycloak</groupId> <artifactId>keycloak-adapter-core</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jackson2-provider</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.spec.javax.servlet</groupId> <artifactId>jboss-servlet-api_3.1_spec</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>org.osgi.core</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "0b8cf224be700e24aff8e7c614e3b467", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 105, "avg_line_length": 36.48543689320388, "alnum_prop": 0.5968600319318786, "repo_name": "jean-merelis/keycloak", "id": "eac0f49ce44224364daea8e1a9151875074981e5", "size": "3758", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "adapters/oidc/jaxrs-oauth-client/pom.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "3104" }, { "name": "ApacheConf", "bytes": "22819" }, { "name": "Batchfile", "bytes": "2114" }, { "name": "CSS", "bytes": "345395" }, { "name": "FreeMarker", "bytes": "63757" }, { "name": "HTML", "bytes": "452064" }, { "name": "Java", "bytes": "10984710" }, { "name": "JavaScript", "bytes": "737973" }, { "name": "Shell", "bytes": "11085" }, { "name": "XSLT", "bytes": "116830" } ], "symlink_target": "" }
import { Component, ChangeDetectionStrategy, Input, Output, EventEmitter, OnInit, TemplateRef, OnChanges, SimpleChanges, ContentChild, forwardRef, ChangeDetectorRef } from '@angular/core'; import {NgbRatingConfig} from './rating-config'; import {getValueInRange} from '../util/util'; import {Key} from '../util/key'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; /** * Context for the custom star display template */ export interface StarTemplateContext { /** * Star fill percentage. An integer value between 0 and 100 */ fill: number; /** * Index of the star. */ index: number; } const NGB_RATING_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NgbRating), multi: true }; /** * Rating directive that will take care of visualising a star rating bar. */ @Component({ selector: 'ngb-rating', changeDetection: ChangeDetectionStrategy.OnPush, host: { 'class': 'd-inline-flex', 'tabindex': '0', 'role': 'slider', 'aria-valuemin': '0', '[attr.aria-valuemax]': 'max', '[attr.aria-valuenow]': 'nextRate', '[attr.aria-valuetext]': 'ariaValueText()', '[attr.aria-disabled]': 'readonly ? true : null', '(blur)': 'handleBlur()', '(keydown)': 'handleKeyDown($event)', '(mouseleave)': 'reset()' }, template: ` <ng-template #t let-fill="fill">{{ fill === 100 ? '&#9733;' : '&#9734;' }}</ng-template> <ng-template ngFor [ngForOf]="contexts" let-index="index"> <span class="sr-only">({{ index < nextRate ? '*' : ' ' }})</span> <span (mouseenter)="enter(index + 1)" (click)="handleClick(index + 1)" [style.cursor]="readonly || disabled ? 'default' : 'pointer'"> <ng-template [ngTemplateOutlet]="starTemplate || starTemplateFromContent || t" [ngTemplateOutletContext]="contexts[index]"> </ng-template> </span> </ng-template> `, providers: [NGB_RATING_VALUE_ACCESSOR] }) export class NgbRating implements ControlValueAccessor, OnInit, OnChanges { contexts: StarTemplateContext[] = []; disabled = false; nextRate: number; /** * Maximal rating that can be given using this widget. */ @Input() max: number; /** * Current rating. Can be a decimal value like 3.75 */ @Input() rate: number; /** * A flag indicating if rating can be updated. */ @Input() readonly: boolean; /** * A flag indicating if rating can be reset to 0 on mouse click */ @Input() resettable: boolean; /** * A template to override star display. * Alternatively put a <ng-template> as the only child of <ngb-rating> element */ @Input() starTemplate: TemplateRef<StarTemplateContext>; @ContentChild(TemplateRef) starTemplateFromContent: TemplateRef<StarTemplateContext>; /** * An event fired when a user is hovering over a given rating. * Event's payload equals to the rating being hovered over. */ @Output() hover = new EventEmitter<number>(); /** * An event fired when a user stops hovering over a given rating. * Event's payload equals to the rating of the last item being hovered over. */ @Output() leave = new EventEmitter<number>(); /** * An event fired when a user selects a new rating. * Event's payload equals to the newly selected rating. */ @Output() rateChange = new EventEmitter<number>(true); onChange = (_: any) => {}; onTouched = () => {}; constructor(config: NgbRatingConfig, private _changeDetectorRef: ChangeDetectorRef) { this.max = config.max; this.readonly = config.readonly; } ariaValueText() { return `${this.nextRate} out of ${this.max}`; } enter(value: number): void { if (!this.readonly && !this.disabled) { this._updateState(value); } this.hover.emit(value); } handleBlur() { this.onTouched(); } handleClick(value: number) { this.update(this.resettable && this.rate === value ? 0 : value); } handleKeyDown(event: KeyboardEvent) { // tslint:disable-next-line:deprecation switch (event.which) { case Key.ArrowDown: case Key.ArrowLeft: this.update(this.rate - 1); break; case Key.ArrowUp: case Key.ArrowRight: this.update(this.rate + 1); break; case Key.Home: this.update(0); break; case Key.End: this.update(this.max); break; default: return; } // note 'return' in default case event.preventDefault(); } ngOnChanges(changes: SimpleChanges) { if (changes['rate']) { this.update(this.rate); } } ngOnInit(): void { this.contexts = Array.from({length: this.max}, (v, k) => ({fill: 0, index: k})); this._updateState(this.rate); } registerOnChange(fn: (value: any) => any): void { this.onChange = fn; } registerOnTouched(fn: () => any): void { this.onTouched = fn; } reset(): void { this.leave.emit(this.nextRate); this._updateState(this.rate); } setDisabledState(isDisabled: boolean) { this.disabled = isDisabled; } update(value: number, internalChange = true): void { const newRate = getValueInRange(value, this.max, 0); if (!this.readonly && !this.disabled && this.rate !== newRate) { this.rate = newRate; this.rateChange.emit(this.rate); } if (internalChange) { this.onChange(this.rate); this.onTouched(); } this._updateState(this.rate); } writeValue(value) { this.update(value, false); this._changeDetectorRef.markForCheck(); } private _getFillValue(index: number): number { const diff = this.nextRate - index; if (diff >= 1) { return 100; } if (diff < 1 && diff > 0) { return parseInt((diff * 100).toFixed(2), 10); } return 0; } private _updateState(nextValue: number) { this.nextRate = nextValue; this.contexts.forEach((context, index) => context.fill = this._getFillValue(index)); } }
{ "content_hash": "de4215049315c9adea390be3835327de", "timestamp": "", "source": "github", "line_count": 227, "max_line_length": 139, "avg_line_length": 26.215859030837006, "alnum_prop": 0.6299781549319442, "repo_name": "ng-bootstrap/core", "id": "7722a9e0742851c54327d0320d906fc2e51e6742", "size": "5951", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/rating/rating.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3033" }, { "name": "HTML", "bytes": "32637" }, { "name": "JavaScript", "bytes": "32488" }, { "name": "TypeScript", "bytes": "225626" } ], "symlink_target": "" }
require 'coop_scraper/credit_card' require 'coop_scraper/current_account'
{ "content_hash": "a36c9a004af0b5966a31b1db75c2d9fa", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 38, "avg_line_length": 36.5, "alnum_prop": 0.821917808219178, "repo_name": "fidothe/coop_to_ofx", "id": "54a92aeb7003b2a99157c8727ef41e0bd2cff572", "size": "73", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/coop_scraper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "60857" } ], "symlink_target": "" }
package importalias import ( srcclient "github.com/matryer/moq/pkg/moq/testpackages/importalias/source/client" tgtclient "github.com/matryer/moq/pkg/moq/testpackages/importalias/target/client" ) type MiddleMan interface { Connect(src srcclient.Client, tgt tgtclient.Client) }
{ "content_hash": "ef5da3dfd6fbde9294f2db2e1e3740d7", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 82, "avg_line_length": 28.1, "alnum_prop": 0.8078291814946619, "repo_name": "matryer/moq", "id": "831394fdaaa6308ce62fb0d05dccdd2dead80b47", "size": "281", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pkg/moq/testpackages/importalias/middleman.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "63935" } ], "symlink_target": "" }
/* * Decompiled with CFR 0_119. */ package script.systemCalls; import script.InternalScriptError; import script.Script; import script.dataObjects.DataObject; import script.dataObjects.StringObject; import script.patterns.PatternHandler; import script.systemCalls.Trap; public class Trap_ReplaceAll extends Trap { public Trap_ReplaceAll(Script s) { super(s); } @Override public DataObject apply() throws InternalScriptError { return this.owner.getPatternHandler().replaceAll(this.getStrParam(0, true), this.getStrParam(1, true), this.getStrParam(2, true)); } }
{ "content_hash": "7ce3a03fe3a44cf46238aca6fd9ad738", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 138, "avg_line_length": 25.083333333333332, "alnum_prop": 0.7441860465116279, "repo_name": "eeveorg/GMSI", "id": "7888d60633642788e3269b1e160c22406a9b5309", "size": "602", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "script/systemCalls/Trap_ReplaceAll.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "56" }, { "name": "Java", "bytes": "814233" } ], "symlink_target": "" }
import { Component, Input, OnInit } from '@angular/core'; import { CommonService } from '../../shared/common.service'; @Component({ selector: 'stacked-bar-chart', styleUrls: ['./stacked-bar-chart.css'], template: `<div id="stacked-bar-div"></div>` }) export class StackedBarChartComponent implements OnInit { private uv: any; private data: any; private metaData: {}; @Input() compress: boolean; constructor(private commonService: CommonService) { this.uv = commonService.uv; } ngOnInit() { this.commonService.getForestAreaCover('stacked-bar-chart').subscribe((data) => { this.data = data; this.makeChart(this.data); }); } makeChart(data: {}) { this.metaData = { meta: { position: '#stacked-bar-div', caption: 'Forest Cover', hlabel: 'Area', hsublabel: 'in \'00 kms' }, dimension: { height: 200, width: 400 } }; if (this.compress) { this.metaData = { margin: { left: 10, right: 10, bottom: 10 }, dimension: { height: 200, width: 200 }, meta: { position: '#stacked-bar-div', }, axis: { showtext: false } }; } this.uv.chart('StackedBar', data, this.metaData); this.commonService.setCachedMetaData('stacked-bar-chart', this.metaData); } }
{ "content_hash": "77dbcff8a74a7dc17a2ad79b365cbd0c", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 137, "avg_line_length": 28.770491803278688, "alnum_prop": 0.45071225071225074, "repo_name": "prakritisaxena/prakritisaxena.github.io", "id": "b540b9dcebc605dc22f86f21904d1dbf061bdaf8", "size": "1755", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/app/components/stacked-bar-chart/stacked-bar-chart.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3893" }, { "name": "HTML", "bytes": "7938" }, { "name": "JavaScript", "bytes": "5145" }, { "name": "TypeScript", "bytes": "87001" } ], "symlink_target": "" }
<?php namespace Ffm\Hookdocs\Console\Commands\Magento1; use Ffm\Hookdocs\Display\TableInterface; use Ffm\Hookdocs\FileHandler; use Ffm\Hookdocs\Linktypes\None; use Ffm\Hookdocs\Magento1\EventType; use Ffm\Hookdocs\PhpFilterIterator; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ObserversCommand extends Command { protected function configure() { $this->setName('magento1:observers') ->setDescription('Read observer documentation') ->setHelp('Reads doc comments to get observer documentation'); $this->addArgument('path', InputArgument::REQUIRED, 'path to files to test'); $this->addArgument('linkType', InputArgument::REQUIRED, 'type of link'); $this->addArgument( 'linkProject', InputArgument::REQUIRED, 'slug in url for project. Usually something like `owner/project-name`' ); $this->addArgument( 'linkBranch', InputArgument::REQUIRED, 'branch used for the link. Usually something like `develop` or `master`' ); $this->addArgument('output', InputArgument::REQUIRED, 'Type of output (Markdown, Html)'); } protected function execute(InputInterface $input, OutputInterface $output) { $path = DOCUMENTER_PROJECT_ROOT_DIR . $input->getArgument('path'); $link = $input->getArgument('linkType'); $project = $input->getArgument('linkProject'); $branch = $input->getArgument('linkBranch'); $outputType = $input->getArgument('output'); $linkType = "\Ffm\Hookdocs\Linktypes\\" . ucfirst((string)$link); $linkClass = class_exists($linkType, true) ? new $linkType($project, $branch) : new None($project, $branch) ; $records = []; if (is_file($path)) { $file = new FileHandler(new \SplFileObject($path), EventType::class, $linkClass); $records = $file->getDocComments(); } elseif (is_dir($path)) { $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path)); $Regex = new \RegexIterator($iterator, '/^.+\.php$/i', \RecursiveRegexIterator::GET_MATCH); foreach ($Regex as $fileInfo) { $fileInfo = new \SplFileObject($fileInfo[0]); $file = new FileHandler($fileInfo, EventType::class, $linkClass); $records = array_merge($records, $file->getDocComments()); } } else { throw new InvalidArgumentException('Path not readable'); } $outputClass = "\Ffm\Hookdocs\Display\\" . ucfirst((string)$outputType); /** @var TableInterface $outputInstance */ $outputInstance = new $outputClass(EventType::HEADER_NAMES, $records); $output->write($outputInstance->getHeader().$outputInstance->getBody().$outputInstance->getFooter()); } }
{ "content_hash": "963a3b7ccf9dc331ac4f7bda2110c2d1", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 117, "avg_line_length": 42.64383561643836, "alnum_prop": 0.6460006424670736, "repo_name": "ffmengineering/hookdocumenter", "id": "088f3b4f0863e923f1322657dd6e2db47005fd0a", "size": "3113", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ffm/Hookdocs/Console/Commands/Magento1/ObserversCommand.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "24186" } ], "symlink_target": "" }
describe('Prettify', function() { 'use strict'; var prettify, mockSce, mockWindow, mockHighlight, mockObjectToPrettify, mockJsonFormattedObject; beforeEach(function() { module('apinterest.visualization'); mockSce = { trustAsHtml: function(value) { return value; } }; mockHighlight = { highlightAuto: function(value) { return { value: value }; } }; mockWindow = { hljs: mockHighlight }; mockObjectToPrettify = { key: 'value' }; mockJsonFormattedObject = '{\n' + ' "key": "value"\n' + '}'; spyOn(mockSce, 'trustAsHtml').and.callThrough(); spyOn(mockHighlight, 'highlightAuto').and.callThrough(); module(function($provide) { $provide.value('$sce', mockSce); $provide.value('$window', mockWindow); }); inject(function($injector, $filter) { prettify = $filter('prettify'); }); }); it('should handle null values', function() { var prettified = prettify(null); expect(prettified).toBeNull(); }); it('should handle empty strings', function() { var prettified = prettify(''); expect(prettified).toEqual(''); }); it('should format object literals as json', function() { var prettified = prettify(mockObjectToPrettify); expect(prettified).toEqual(mockJsonFormattedObject); }); it('should replace linebreak literals with real linebreaks', function() { var prettified = prettify('row1\\nrow2'); expect(prettified).toEqual('row1\nrow2'); }); it('should replace windows linebreak literals with real linebreaks', function() { var prettified = prettify('row1\\r\\nrow2'); expect(prettified).toEqual('row1\nrow2'); }); it('should unescape escaped double quotes', function() { var prettified = prettify('\\"'); expect(prettified).toEqual('"'); }); it('should unescape escaped slashes', function() { var prettified = prettify('\\\\'); expect(prettified).toEqual('\\'); }); it('should syntax highlight', function() { prettify(mockObjectToPrettify); expect(mockHighlight.highlightAuto).toHaveBeenCalledWith(mockJsonFormattedObject); }); it('should trust value as html', function() { prettify(mockObjectToPrettify); expect(mockSce.trustAsHtml).toHaveBeenCalledWith(mockJsonFormattedObject); }); });
{ "content_hash": "0ef239f6c4d9fe781c9a2c84e19ab10b", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 90, "avg_line_length": 23.384615384615383, "alnum_prop": 0.5548245614035088, "repo_name": "erikbarke/apinterest", "id": "d0c75ddb14b796a13ecc58c76d9746d64ecda80b", "size": "2736", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/js/app/visualization/prettify.filter.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "116" }, { "name": "C#", "bytes": "111173" }, { "name": "CSS", "bytes": "10344" }, { "name": "HTML", "bytes": "20282" }, { "name": "JavaScript", "bytes": "203451" }, { "name": "Smalltalk", "bytes": "320" } ], "symlink_target": "" }
/* * This is not the original file distributed by the Apache Software Foundation * It has been modified by the Hipparchus project */ package org.hipparchus.analysis.differentiation; import org.hipparchus.analysis.MultivariateMatrixFunction; /** Class representing the Jacobian of a multivariate vector function. * <p> * The rows iterate on the model functions while the columns iterate on the parameters; thus, * the numbers of rows is equal to the dimension of the underlying function vector * value and the number of columns is equal to the number of free parameters of * the underlying function. * </p> */ public class JacobianFunction implements MultivariateMatrixFunction { /** Underlying vector-valued function. */ private final MultivariateDifferentiableVectorFunction f; /** Simple constructor. * @param f underlying vector-valued function */ public JacobianFunction(final MultivariateDifferentiableVectorFunction f) { this.f = f; } /** {@inheritDoc} */ @Override public double[][] value(double[] point) { // set up parameters final DSFactory factory = new DSFactory(point.length, 1); final DerivativeStructure[] dsX = new DerivativeStructure[point.length]; for (int i = 0; i < point.length; ++i) { dsX[i] = factory.variable(i, point[i]); } // compute the derivatives final DerivativeStructure[] dsY = f.value(dsX); // extract the Jacobian final double[][] y = new double[dsY.length][point.length]; final int[] orders = new int[point.length]; for (int i = 0; i < dsY.length; ++i) { for (int j = 0; j < point.length; ++j) { orders[j] = 1; y[i][j] = dsY[i].getPartialDerivative(orders); orders[j] = 0; } } return y; } }
{ "content_hash": "cfe526a216a395594513174548d56014", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 93, "avg_line_length": 31.516666666666666, "alnum_prop": 0.6398730830248546, "repo_name": "Hipparchus-Math/hipparchus", "id": "899669717256f83bd872e7ddeafc26e2e0116a8c", "size": "2693", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hipparchus-core/src/main/java/org/hipparchus/analysis/differentiation/JacobianFunction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "67" }, { "name": "Java", "bytes": "15801055" }, { "name": "Python", "bytes": "7212" }, { "name": "R", "bytes": "57047" }, { "name": "Shell", "bytes": "4024" } ], "symlink_target": "" }
import {describe, ddescribe, it, iit, xit, xdescribe, expect, beforeEach, SpyObject, proxy} from 'angular2/test_lib'; import {isBlank, isPresent, FIELD, IMPLEMENTS} from 'angular2/src/facade/lang'; import {ListWrapper, MapWrapper, List} from 'angular2/src/facade/collection'; import {ProtoElementInjector, PreBuiltObjects, DirectiveBinding} from 'angular2/src/core/compiler/element_injector'; import {Parent, Ancestor} from 'angular2/src/core/annotations/visibility'; import {EventEmitter} from 'angular2/src/core/annotations/events'; import {onDestroy} from 'angular2/src/core/annotations/annotations'; import {Optional, Injector, Inject, bind} from 'angular2/di'; import {View} from 'angular2/src/core/compiler/view'; import {ViewContainer} from 'angular2/src/core/compiler/view_container'; import {NgElement} from 'angular2/src/core/dom/element'; import {LightDom, SourceLightDom, DestinationLightDom} from 'angular2/src/core/compiler/shadow_dom_emulation/light_dom'; import {Directive} from 'angular2/src/core/annotations/annotations'; import {BindingPropagationConfig} from 'angular2/src/core/compiler/binding_propagation_config'; @proxy @IMPLEMENTS(View) class DummyView extends SpyObject {noSuchMethod(m){super.noSuchMethod(m)}} @proxy @IMPLEMENTS(LightDom) class DummyLightDom extends SpyObject {noSuchMethod(m){super.noSuchMethod(m)}} class SimpleDirective { } class SomeOtherDirective { } class NeedsDirective { dependency:SimpleDirective; constructor(dependency:SimpleDirective){ this.dependency = dependency; } } class OptionallyNeedsDirective { dependency:SimpleDirective; constructor(@Optional() dependency:SimpleDirective){ this.dependency = dependency; } } class NeedDirectiveFromParent { dependency:SimpleDirective; constructor(@Parent() dependency:SimpleDirective){ this.dependency = dependency; } } class NeedDirectiveFromAncestor { dependency:SimpleDirective; constructor(@Ancestor() dependency:SimpleDirective){ this.dependency = dependency; } } class NeedsService { service:any; constructor(@Inject("service") service) { this.service = service; } } class NeedsEventEmitter { clickEmitter; constructor(@EventEmitter('click') clickEmitter:Function) { this.clickEmitter = clickEmitter; } click() { this.clickEmitter(null); } } class A_Needs_B { constructor(dep){} } class B_Needs_A { constructor(dep){} } class NeedsView { view:any; constructor(@Inject(View) view) { this.view = view; } } class DirectiveWithDestroy { onDestroyCounter:number; constructor(){ this.onDestroyCounter = 0; } onDestroy() { this.onDestroyCounter ++; } } export function main() { var defaultPreBuiltObjects = new PreBuiltObjects(null, null, null, null, null); function humanize(tree, names:List) { var lookupName = (item) => ListWrapper.last( ListWrapper.find(names, (pair) => pair[0] === item)); if (tree.children.length == 0) return lookupName(tree); var children = tree.children.map(m => humanize(m, names)); return [lookupName(tree), children]; } function injector(bindings, lightDomAppInjector = null, shadowDomAppInjector = null, preBuiltObjects = null) { if (isBlank(lightDomAppInjector)) lightDomAppInjector = new Injector([]); var proto = new ProtoElementInjector(null, 0, bindings, isPresent(shadowDomAppInjector)); var inj = proto.instantiate(null, null, null); var preBuilt = isPresent(preBuiltObjects) ? preBuiltObjects : defaultPreBuiltObjects; inj.instantiateDirectives(lightDomAppInjector, shadowDomAppInjector, preBuilt); return inj; } function parentChildInjectors(parentBindings, childBindings, parentPreBuildObjects = null) { if (isBlank(parentPreBuildObjects)) parentPreBuildObjects = defaultPreBuiltObjects; var inj = new Injector([]); var protoParent = new ProtoElementInjector(null, 0, parentBindings); var parent = protoParent.instantiate(null, null, null); parent.instantiateDirectives(inj, null, parentPreBuildObjects); var protoChild = new ProtoElementInjector(protoParent, 1, childBindings, false, 1); var child = protoChild.instantiate(parent, null, null); child.instantiateDirectives(inj, null, defaultPreBuiltObjects); return child; } function hostShadowInjectors(hostBindings, shadowBindings, hostPreBuildObjects = null) { if (isBlank(hostPreBuildObjects)) hostPreBuildObjects = defaultPreBuiltObjects; var inj = new Injector([]); var shadowInj = inj.createChild([]); var protoParent = new ProtoElementInjector(null, 0, hostBindings, true); var host = protoParent.instantiate(null, null, null); host.instantiateDirectives(inj, shadowInj, hostPreBuildObjects); var protoChild = new ProtoElementInjector(protoParent, 0, shadowBindings, false, 1); var shadow = protoChild.instantiate(null, host, null); shadow.instantiateDirectives(shadowInj, null, null); return shadow; } describe("ProtoElementInjector", () => { describe("direct parent", () => { it("should return parent proto injector when distance is 1", () => { var distance = 1; var protoParent = new ProtoElementInjector(null, 0, []); var protoChild = new ProtoElementInjector(protoParent, 1, [], false, distance); expect(protoChild.directParent()).toEqual(protoParent); }); it("should return null otherwise", () => { var distance = 2; var protoParent = new ProtoElementInjector(null, 0, []); var protoChild = new ProtoElementInjector(protoParent, 1, [], false, distance); expect(protoChild.directParent()).toEqual(null); }); }); }); describe("ElementInjector", function () { describe("instantiate", function () { it("should create an element injector", function () { var protoParent = new ProtoElementInjector(null, 0, []); var protoChild1 = new ProtoElementInjector(protoParent, 1, []); var protoChild2 = new ProtoElementInjector(protoParent, 2, []); var p = protoParent.instantiate(null, null, null); var c1 = protoChild1.instantiate(p, null, null); var c2 = protoChild2.instantiate(p, null, null); expect(humanize(p, [ [p, 'parent'], [c1, 'child1'], [c2, 'child2'] ])).toEqual(["parent", ["child1", "child2"]]); }); describe("direct parent", () => { it("should return parent injector when distance is 1", () => { var distance = 1; var protoParent = new ProtoElementInjector(null, 0, []); var protoChild = new ProtoElementInjector(protoParent, 1, [], false, distance); var p = protoParent.instantiate(null, null, null); var c = protoChild.instantiate(p, null, null); expect(c.directParent()).toEqual(p); }); it("should return null otherwise", () => { var distance = 2; var protoParent = new ProtoElementInjector(null, 0, []); var protoChild = new ProtoElementInjector(protoParent, 1, [], false, distance); var p = protoParent.instantiate(null, null, null); var c = protoChild.instantiate(p, null, null); expect(c.directParent()).toEqual(null); }); }); }); describe("hasBindings", function () { it("should be true when there are bindings", function () { var p = new ProtoElementInjector(null, 0, [SimpleDirective]); expect(p.hasBindings).toBeTruthy(); }); it("should be false otherwise", function () { var p = new ProtoElementInjector(null, 0, []); expect(p.hasBindings).toBeFalsy(); }); }); describe("hasInstances", function () { it("should be false when no directives are instantiated", function () { expect(injector([]).hasInstances()).toBe(false); }); it("should be true when directives are instantiated", function () { expect(injector([SimpleDirective]).hasInstances()).toBe(true); }); }); describe("instantiateDirectives", function () { it("should instantiate directives that have no dependencies", function () { var inj = injector([SimpleDirective]); expect(inj.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective); }); it("should instantiate directives that depend on other directives", function () { var inj = injector([SimpleDirective, NeedsDirective]); var d = inj.get(NeedsDirective); expect(d).toBeAnInstanceOf(NeedsDirective); expect(d.dependency).toBeAnInstanceOf(SimpleDirective); }); it("should instantiate directives that depend on app services", function () { var appInjector = new Injector([ bind("service").toValue("service") ]); var inj = injector([NeedsService], appInjector); var d = inj.get(NeedsService); expect(d).toBeAnInstanceOf(NeedsService); expect(d.service).toEqual("service"); }); it("should instantiate directives that depend on pre built objects", function () { var view = new DummyView(); var inj = injector([NeedsView], null, null, new PreBuiltObjects(view, null, null, null, null)); expect(inj.get(NeedsView).view).toBe(view); }); it("should instantiate directives that depend on the containing component", function () { var shadow = hostShadowInjectors([SimpleDirective], [NeedsDirective]); var d = shadow.get(NeedsDirective); expect(d).toBeAnInstanceOf(NeedsDirective); expect(d.dependency).toBeAnInstanceOf(SimpleDirective); }); it("should not instantiate directives that depend on other directives in the containing component's ElementInjector", () => { expect( () => { hostShadowInjectors([SomeOtherDirective, SimpleDirective], [NeedsDirective]); }).toThrowError('No provider for SimpleDirective! (NeedsDirective -> SimpleDirective)') }); it("should instantiate component directives that depend on app services in the shadow app injector", () => { var shadowAppInjector = new Injector([ bind("service").toValue("service") ]); var inj = injector([NeedsService], null, shadowAppInjector); var d = inj.get(NeedsService); expect(d).toBeAnInstanceOf(NeedsService); expect(d.service).toEqual("service"); }); it("should not instantiate other directives that depend on app services in the shadow app injector", () => { var shadowAppInjector = new Injector([ bind("service").toValue("service") ]); expect( () => { injector([SomeOtherDirective, NeedsService], null, shadowAppInjector); }).toThrowError('No provider for service! (NeedsService -> service)'); }); it("should return app services", function () { var appInjector = new Injector([ bind("service").toValue("service") ]); var inj = injector([], appInjector); expect(inj.get('service')).toEqual('service'); }); it("should get directives from parent", function () { var child = parentChildInjectors([SimpleDirective], [NeedDirectiveFromParent]); var d = child.get(NeedDirectiveFromParent); expect(d).toBeAnInstanceOf(NeedDirectiveFromParent); expect(d.dependency).toBeAnInstanceOf(SimpleDirective); }); it("should not return parent's directives on self", function () { expect(() => { injector([SimpleDirective, NeedDirectiveFromParent]); }).toThrowError(); }); it("should get directives from ancestor", function () { var child = parentChildInjectors([SimpleDirective], [NeedDirectiveFromAncestor]); var d = child.get(NeedDirectiveFromAncestor); expect(d).toBeAnInstanceOf(NeedDirectiveFromAncestor); expect(d.dependency).toBeAnInstanceOf(SimpleDirective); }); it("should throw when no SimpleDirective found", function () { expect(() => injector([NeedDirectiveFromParent])). toThrowError('No provider for SimpleDirective! (NeedDirectiveFromParent -> SimpleDirective)'); }); it("should inject null when no directive found", function () { var inj = injector([OptionallyNeedsDirective]); var d = inj.get(OptionallyNeedsDirective); expect(d.dependency).toEqual(null); }); it("should accept SimpleDirective bindings instead of SimpleDirective types", function () { var inj = injector([ DirectiveBinding.createFromBinding(bind(SimpleDirective).toClass(SimpleDirective), null) ]); expect(inj.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective); }); it("should allow for direct access using getDirectiveAtIndex", function () { var inj = injector([ DirectiveBinding.createFromBinding(bind(SimpleDirective).toClass(SimpleDirective), null) ]); expect(inj.getDirectiveAtIndex(0)).toBeAnInstanceOf(SimpleDirective); expect(() => inj.getDirectiveAtIndex(-1)).toThrowError( 'Index -1 is out-of-bounds.'); expect(() => inj.getDirectiveAtIndex(10)).toThrowError( 'Index 10 is out-of-bounds.'); }); it("should allow for direct access using getBindingAtIndex", function () { var inj = injector([ DirectiveBinding.createFromBinding(bind(SimpleDirective).toClass(SimpleDirective), null) ]); expect(inj.getDirectiveBindingAtIndex(0)).toBeAnInstanceOf(DirectiveBinding); expect(() => inj.getDirectiveBindingAtIndex(-1)).toThrowError( 'Index -1 is out-of-bounds.'); expect(() => inj.getDirectiveBindingAtIndex(10)).toThrowError( 'Index 10 is out-of-bounds.'); }); it("should handle cyclic dependencies", function () { expect(() => { var bAneedsB = bind(A_Needs_B).toFactory((a) => new A_Needs_B(a), [B_Needs_A]); var bBneedsA = bind(B_Needs_A).toFactory((a) => new B_Needs_A(a), [A_Needs_B]); injector([ DirectiveBinding.createFromBinding(bAneedsB, null), DirectiveBinding.createFromBinding(bBneedsA, null) ]); }).toThrowError('Cannot instantiate cyclic dependency! ' + '(A_Needs_B -> B_Needs_A -> A_Needs_B)'); }); it("should call onDestroy on directives subscribed to this event", function () { var inj = injector([ DirectiveBinding.createFromType(DirectiveWithDestroy, new Directive({lifecycle: [onDestroy]})) ]); var destroy = inj.get(DirectiveWithDestroy); inj.clearDirectives(); expect(destroy.onDestroyCounter).toBe(1); }); }); describe("pre built objects", function () { it("should return view", function () { var view = new DummyView(); var inj = injector([], null, null, new PreBuiltObjects(view, null, null, null, null)); expect(inj.get(View)).toEqual(view); }); it("should return element", function () { var element = new NgElement(null); var inj = injector([], null, null, new PreBuiltObjects(null, element, null, null, null)); expect(inj.get(NgElement)).toEqual(element); }); it('should return viewContainer', function () { var viewContainer = new ViewContainer(null, null, null, null, null); var inj = injector([], null, null, new PreBuiltObjects(null, null, viewContainer, null, null)); expect(inj.get(ViewContainer)).toEqual(viewContainer); }); it('should return bindingPropagationConfig', function () { var config = new BindingPropagationConfig(null); var inj = injector([], null, null, new PreBuiltObjects(null, null, null, null, config)); expect(inj.get(BindingPropagationConfig)).toEqual(config); }); describe("light DOM", () => { var lightDom, parentPreBuiltObjects; beforeEach(() => { lightDom = new DummyLightDom(); parentPreBuiltObjects = new PreBuiltObjects(null, null, null, lightDom, null); }); it("should return destination light DOM from the parent's injector", function () { var child = parentChildInjectors([], [], parentPreBuiltObjects); expect(child.get(DestinationLightDom)).toEqual(lightDom); }); it("should return null when parent's injector is a component boundary", function () { var child = hostShadowInjectors([], [], parentPreBuiltObjects); expect(child.get(DestinationLightDom)).toBeNull(); }); it("should return source light DOM from the closest component boundary", function () { var child = hostShadowInjectors([], [], parentPreBuiltObjects); expect(child.get(SourceLightDom)).toEqual(lightDom); }); }); }); describe('event emitters', () => { it('should be injectable and callable', () => { var inj = injector([NeedsEventEmitter]); inj.get(NeedsEventEmitter).click(); }); it('should be queryable through hasEventEmitter', () => { var inj = injector([NeedsEventEmitter]); expect(inj.hasEventEmitter('click')).toBe(true); expect(inj.hasEventEmitter('move')).toBe(false); }); }); }); }
{ "content_hash": "c37b38563a5ebafa2cf2c0ccfbc80cbe", "timestamp": "", "source": "github", "line_count": 479, "max_line_length": 131, "avg_line_length": 36.407098121085596, "alnum_prop": 0.6566316875967658, "repo_name": "lgalfaso/angular", "id": "490397e4e2290dc6787ac00e596b0b7381de366e", "size": "17439", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/angular2/test/core/compiler/element_injector_spec.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dart", "bytes": "97287" }, { "name": "HTML", "bytes": "26614" }, { "name": "JavaScript", "bytes": "298366" }, { "name": "Shell", "bytes": "11801" } ], "symlink_target": "" }
using System; using System.Drawing; using System.Collections.Generic; using Rimss.GraphicsProcessing.Palette.Helpers; using Rimss.GraphicsProcessing.Palette.ColorCaches.Common; namespace Rimss.GraphicsProcessing.Palette.ColorCaches.EuclideanDistance { public class EuclideanDistanceColorCache : BaseColorCache { #region | Fields | private IList<Color> palette; #endregion #region | Properties | /// <summary> /// Gets a value indicating whether this instance is color model supported. /// </summary> /// <value> /// <c>true</c> if this instance is color model supported; otherwise, <c>false</c>. /// </value> public override Boolean IsColorModelSupported { get { return true; } } #endregion #region | Constructors | /// <summary> /// Initializes a new instance of the <see cref="EuclideanDistanceColorCache"/> class. /// </summary> public EuclideanDistanceColorCache() { ColorModel = ColorModel.RedGreenBlue; } /// <summary> /// Initializes a new instance of the <see cref="EuclideanDistanceColorCache"/> class. /// </summary> /// <param name="colorModel">The color model.</param> public EuclideanDistanceColorCache(ColorModel colorModel) { ColorModel = colorModel; } #endregion #region << BaseColorCache >> /// <summary> /// See <see cref="BaseColorCache.OnCachePalette"/> for more details. /// </summary> protected override void OnCachePalette(IList<Color> palette) { this.palette = palette; } /// <summary> /// See <see cref="BaseColorCache.OnGetColorPaletteIndex"/> for more details. /// </summary> protected override void OnGetColorPaletteIndex(Color color, out Int32 paletteIndex) { paletteIndex = ColorModelHelper.GetEuclideanDistance(color, ColorModel, palette); } #endregion } }
{ "content_hash": "1f544560f162ba8933ca13dca801b92d", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 94, "avg_line_length": 29.027397260273972, "alnum_prop": 0.6054742803209061, "repo_name": "lerwine/RIMSS", "id": "b5b923215a88a9d085a8e7ade3aaf357fcea15d9", "size": "2119", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GraphicsProcessing/Palette/ColorCaches/EuclideanDistance/EuclideanDistanceColorCache.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "100" }, { "name": "C#", "bytes": "446059" }, { "name": "CSS", "bytes": "513" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "10714" } ], "symlink_target": "" }
package application.core.model.dr; import lombok.*; import javax.persistence.*; import java.io.Serializable; @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor @ToString @Entity @Table(name = "drHousingCosts") public class DRHousingCosts implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "drHousingCostsId") private Integer drHousingCostsId; @Column(name = "housing3_1Amount") private String housing3_1Amount; @Column(name = "housing3_1Days") private String housing3_1Days; @Column(name = "housing3_1Total") private String housing3_1Total; @Column(name = "housing3_1Currency") private String housing3_1Currency; @Column(name = "housing3_1Funding") private String housing3_1Funding; @Column(name = "housing3_2Amount") private String housing3_2Amount; @Column(name = "housing3_2Days") private String housing3_2Days; @Column(name = "housing3_2Total") private String housing3_2Total; @Column(name = "housing3_2Currency") private String housing3_2Currency; @Column(name = "housing3_2Funding") private String housing3_2Funding; }
{ "content_hash": "af5c51b5a734226df8e8551687fdf3e5", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 55, "avg_line_length": 23.49019607843137, "alnum_prop": 0.7153589315525877, "repo_name": "paladin952/cwmd", "id": "73cd9c423bcf38e14224f93badaf17f6c848068f", "size": "1198", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "cwmd_core/src/main/java/application/core/model/dr/DRHousingCosts.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "16438" }, { "name": "HTML", "bytes": "28383" }, { "name": "Java", "bytes": "206511" }, { "name": "JavaScript", "bytes": "48536" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "1098a0cfb12de59373fe42d91e616535", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "cb869ce52538ee99773fc39846b716327c001dd7", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Sapotaceae/Manilkara/Manilkara dissecta/ Syn. Manilkara dissecta pancheri/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using AsterNET.Manager.Event; namespace AsterNET.Manager.Action { /// <summary> /// Retrieves a the details about a given SIP peer.<br /> /// For a PeerEntryEvent is sent by Asterisk containing the details of the peer /// followed by a PeerlistCompleteEvent.<br /> /// Available since Asterisk 1.2 /// </summary> /// <seealso cref="Manager.Event.PeerEntryEvent" /> /// <seealso cref="Manager.Event.PeerlistCompleteEvent" /> public class SIPShowPeerAction : ManagerActionEvent { /// <summary> Creates a new empty SIPShowPeerAction.</summary> public SIPShowPeerAction() { } /// <summary> /// Creates a new SIPShowPeerAction that requests the details about the given SIP peer. /// </summary> public SIPShowPeerAction(string peer) { this.Peer = peer; } public override string Action { get { return "SIPShowPeer"; } } /// <summary> /// Get/Set the name of the peer to retrieve.<br /> /// This parameter is mandatory. /// </summary> public string Peer { get; set; } public override Type ActionCompleteEventClass() { return typeof (PeerlistCompleteEvent); } } }
{ "content_hash": "4af2c7365dd2b14f1d8d90c4163907c6", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 99, "avg_line_length": 30.955555555555556, "alnum_prop": 0.5613783201722901, "repo_name": "AsterNET/AsterNET", "id": "137fe8ca3b4a79cf1c891d5241678739d0a2b387", "size": "1393", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Asterisk.2013/Asterisk.NET/Manager/Action/SIPShowPeerAction.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "699876" } ], "symlink_target": "" }
package jdk.internal.jrtfs; import java.io.*; import java.nio.channels.*; import java.nio.file.*; import java.nio.file.DirectoryStream.Filter; import java.nio.file.attribute.*; import java.nio.file.spi.FileSystemProvider; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutorService; public final class JrtFileSystemProvider extends FileSystemProvider { private volatile FileSystem theFileSystem; public JrtFileSystemProvider() { } @Override public String getScheme() { return "jrt"; } /** * Need FilePermission ${java.home}/-", "read" to create or get jrt:/ */ private void checkPermission() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { String home = SystemImages.RUNTIME_HOME; FilePermission perm = new FilePermission(home + File.separator + "-", "read"); sm.checkPermission(perm); } } private void checkUri(URI uri) { if (!uri.getScheme().equalsIgnoreCase(getScheme())) throw new IllegalArgumentException("URI does not match this provider"); if (uri.getAuthority() != null) throw new IllegalArgumentException("Authority component present"); if (uri.getPath() == null) throw new IllegalArgumentException("Path component is undefined"); if (!uri.getPath().equals("/")) throw new IllegalArgumentException("Path component should be '/'"); if (uri.getQuery() != null) throw new IllegalArgumentException("Query component present"); if (uri.getFragment() != null) throw new IllegalArgumentException("Fragment component present"); } @Override public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException { checkPermission(); checkUri(uri); return new JrtFileSystem(this, env); } @Override public Path getPath(URI uri) { checkPermission(); if (!uri.getScheme().equalsIgnoreCase(getScheme())) throw new IllegalArgumentException("URI does not match this provider"); if (uri.getAuthority() != null) throw new IllegalArgumentException("Authority component present"); if (uri.getQuery() != null) throw new IllegalArgumentException("Query component present"); if (uri.getFragment() != null) throw new IllegalArgumentException("Fragment component present"); String path = uri.getPath(); if (path == null || path.charAt(0) != '/') throw new IllegalArgumentException("Invalid path component"); return getTheFileSystem().getPath(path); } private FileSystem getTheFileSystem() { checkPermission(); FileSystem fs = this.theFileSystem; if (fs == null) { synchronized (this) { fs = this.theFileSystem; if (fs == null) { try { fs = new JrtFileSystem(this, null) { @Override public void close() { throw new UnsupportedOperationException(); } }; } catch (IOException ioe) { throw new InternalError(ioe); } } this.theFileSystem = fs; } } return fs; } @Override public FileSystem getFileSystem(URI uri) { checkPermission(); checkUri(uri); return getTheFileSystem(); } // Checks that the given file is a JrtPath static final JrtPath toJrtPath(Path path) { if (path == null) throw new NullPointerException(); if (!(path instanceof JrtPath)) throw new ProviderMismatchException(); return (JrtPath)path; } @Override public void checkAccess(Path path, AccessMode... modes) throws IOException { toJrtPath(path).checkAccess(modes); } @Override public void copy(Path src, Path target, CopyOption... options) throws IOException { toJrtPath(src).copy(toJrtPath(target), options); } @Override public void createDirectory(Path path, FileAttribute<?>... attrs) throws IOException { toJrtPath(path).createDirectory(attrs); } @Override public final void delete(Path path) throws IOException { toJrtPath(path).delete(); } @Override @SuppressWarnings("unchecked") public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) { return JrtFileAttributeView.get(toJrtPath(path), type); } @Override public FileStore getFileStore(Path path) throws IOException { return toJrtPath(path).getFileStore(); } @Override public boolean isHidden(Path path) { return toJrtPath(path).isHidden(); } @Override public boolean isSameFile(Path path, Path other) throws IOException { return toJrtPath(path).isSameFile(other); } @Override public void move(Path src, Path target, CopyOption... options) throws IOException { toJrtPath(src).move(toJrtPath(target), options); } @Override public AsynchronousFileChannel newAsynchronousFileChannel(Path path, Set<? extends OpenOption> options, ExecutorService exec, FileAttribute<?>... attrs) throws IOException { throw new UnsupportedOperationException(); } @Override public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { return toJrtPath(path).newByteChannel(options, attrs); } @Override public DirectoryStream<Path> newDirectoryStream( Path path, Filter<? super Path> filter) throws IOException { return toJrtPath(path).newDirectoryStream(filter); } @Override public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { return toJrtPath(path).newFileChannel(options, attrs); } @Override public InputStream newInputStream(Path path, OpenOption... options) throws IOException { return toJrtPath(path).newInputStream(options); } @Override public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException { return toJrtPath(path).newOutputStream(options); } @Override @SuppressWarnings("unchecked") // Cast to A public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException { if (type == BasicFileAttributes.class || type == JrtFileAttributes.class) return (A)toJrtPath(path).getAttributes(); return null; } @Override public Map<String, Object> readAttributes(Path path, String attribute, LinkOption... options) throws IOException { return toJrtPath(path).readAttributes(attribute, options); } @Override public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException { toJrtPath(path).setAttribute(attribute, value, options); } }
{ "content_hash": "b3142ef9f5974e634c361ccd35d8f0df", "timestamp": "", "source": "github", "line_count": 250, "max_line_length": 83, "avg_line_length": 31.244, "alnum_prop": 0.6046600947381897, "repo_name": "forax/jigsaw-jrtfs", "id": "76e7832d97ec862ce6080403f6ca0e8e3db5ec0d", "size": "9017", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/jdk/internal/jrtfs/JrtFileSystemProvider.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "200064" }, { "name": "JavaScript", "bytes": "1719" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8' /> <title>VisualPHPUnit</title> <link rel="stylesheet" href="ui/css/index.css" media="screen" /> <link rel="stylesheet" href="ui/css/jqueryFileTree.css" media="screen" /> <link rel='stylesheet' href='ui/css/jquery-ui-1.8.11.custom.css' /> </head> <body> <div id='container'> <div id='browser'> <div class="wrap" style="position: fixed;"> <h1>VisualPHPUnit</h1> <fieldset> <legend id='legend_tests'>Tests</legend> <ul class="show"> <li> <div id='file_tree'></div> <input type='hidden' name='test_files' id='test_files' /> </li> <li style="text-align: center"> <small><a href="#" id="select_all">Select All</a></small> </li> <li> <input type='submit' id='run_tests' value='Run Tests' /> </li> </ul> </fieldset> <fieldset> <legend id='legend_options'>Options</legend> <ul> <li> <label for='store_statistics'>Store Statistics:</label> <select name='store_statistics' id='store_statistics'> <option value='0' <?php if ( !STORE_STATISTICS ) echo 'selected';?>>No</option> <option value='1' <?php if ( STORE_STATISTICS ) echo 'selected';?>>Yes</option> </select> </li> <li> <label for='create_snapshots'>Create Snapshots:</label> <select name='create_snapshots' id='create_snapshots'> <option value='0' <?php if ( !CREATE_SNAPSHOTS ) echo 'selected';?>>No</option> <option value='1' <?php if ( CREATE_SNAPSHOTS ) echo 'selected';?>>Yes</option> </select> </li> <li> <label for='snapshot_directory'>Snapshot Directory:</label> <input type='text' name='snapshot_directory' id='snapshot_directory' value='<?php echo SNAPSHOT_DIRECTORY;?>' /> </li> <li> <label for='sandbox_errors'>Sandbox Errors:</label> <select name='sandbox_errors' id='sandbox_errors'> <option value='0' <?php if ( !SANDBOX_ERRORS ) echo 'selected';?>>No</option> <option value='1' <?php if ( SANDBOX_ERRORS ) echo 'selected';?>>Yes</option> </select> </li> <li class='sandbox'> <label for='sandbox_filename'>Sandbox Filename:</label> <input type='text' name='sandbox_filename' id='sandbox_filename' value='<?php echo SANDBOX_FILENAME;?>' /> </li> <li class='sandbox'> <label>Sandbox Ignore:</label> <div id='sandbox_inputs'> <input type='checkbox' name='sandbox_ignore[]' id='e_notice' value='E_NOTICE' /> <label for='e_notice'>E_NOTICE</label> <input type='checkbox' name='sandbox_ignore[]' id='e_warning' value='E_WARNING' /> <label for='e_warning'>E_WARNING</label> <input type='checkbox' name='sandbox_ignore[]' id='e_error' value='E_ERROR' /> <label for='e_error'>E_ERROR</label> <input type='checkbox' name='sandbox_ignore[]' id='e_parse' value='E_PARSE' /> <label for='e_parse'>E_PARSE</label> <input type='checkbox' name='sandbox_ignore[]' id='e_strict' value='E_STRICT' /> <label for='e_strict'>E_STRICT</label> </div> </li> </ul> </fieldset> <fieldset> <legend id='legend_archives'>Archives</legend> <ul> <li> <label for='select_snapshot'>Select Snapshot:</label> <select name='select_snapshot' id='select_snapshot'> <?php foreach ( $results as $file ) { ?> <option value='<?php echo $file;?>'><?php echo $file;?></option> <?php } ?> </select> <input type='hidden' id='view_snapshot' name='view_snapshot' value='0' /> </li> <li> <input type='submit' id='view_archive' value='View' /> </li> </ul> </fieldset> <fieldset> <legend id='legend_graphs'>Graphs</legend> <ul> <li> <label for='graph_type'>Type:</label> <select id='graph_type'> <option value='Suite'>Suites</option> <option value='Test'>Tests</option> </select> </li> <li> <label for='time_frame'>Time Frame:</label> <select id='time_frame'> <option value='Daily'>Daily</option> <option value='Weekly'>Weekly</option> <option value='Monthly'>Monthly</option> </select> </li> <li> <label for='start_date'>Start Date:</label> <input type='text' id='start_date' /> </li> <li> <label for='end_date'>End Date:</label> <input type='text' id='end_date' /> </li> <li> <input type='submit' id='draw_graph' value='Draw Graph' disabled /> </li> </ul> </fieldset> </div> </div> <div id='output'> </div> </div> <script src="ui/js/jquery-1.5.1.min.js"></script> <script src="ui/js/listprint.js"></script> <script src="ui/js/jquery.sortElements.js"></script> <script src="ui/js/jqueryFileTree/jqueryFileTree.js"></script> <script src='ui/js/jquery-ui-1.8.11.custom.min.js'></script> <script src="ui/js/Highcharts-2.1.4/highcharts.js"></script> <script src="ui/js/Highcharts-2.1.4/themes/gray.js"></script> <script> $(document).ready(function() { var expanded = {}; $("#browser, #browser > .wrap").width(300); $("#output").width($("#container").width()-350); function updateTests() { var tests = ''; $('.selected_file').each(function() { tests += $(this).children().attr('rel') + '|'; }); return tests; } $('#file_tree').fileTree({ /* fix for Windows filepaths */ root: '<?php echo str_replace('\\', '/', realpath(TEST_DIRECTORY));?>', script: 'ui/js/jqueryFileTree/connectors/jqueryFileTree.php', callback: function() { $('#file_tree li:first-child a').trigger('click'); } }, function(file) { $('#test_files').val(updateTests()); }); $("#select_all").click(function(e) { $('#file_tree li a').trigger('click'); e.preventDefault(); return false; }); function handleSubmit() { if ( !$('.error_message').length ) { $('#run_tests').removeAttr('disabled'); } else { $('#run_tests').attr('disabled', 'disabled'); } } function getError(selector, ajaxType) { $.get('index.php', { dir: selector.val(), type: ajaxType }, function(data) { selector.siblings('.error_message').remove(); if ( data != 'OK' ) { selector.after("<span class='error_message'>" + data + "</span>"); } handleSubmit(); }); } function updateBrowser() { setTimeout(function() { $('#container').css('height', $(document).height()); }, 100) } $('#create_snapshots').change(function() { if ( $(this).val() == 1 ) { $(this).parent().next().show(); getError($('#snapshot_directory'), 'dir'); } else { $(this).parent().next().hide().children('.error_message').remove(); handleSubmit(); } updateBrowser(); }); $('#sandbox_errors').change(function() { if ( $(this).val() == 1 ) { $(this).parent().nextAll('.sandbox').show(); getError($('#sandbox_filename'), 'file'); } else { $(this).parent().nextAll('.sandbox').hide().children('.error_message').remove(); handleSubmit(); } updateBrowser(); }); $('#snapshot_directory').blur(function() { getError($(this), 'dir'); }); $('#sandbox_filename').blur(function() { getError($(this), 'file'); }); function updateIgnore(ignoreErrors) { if ( ignoreErrors != '' ) { var ignore = ignoreErrors.split('|'); for ( var i = 0; i < ignore.length; i++ ) { $('#' + ignore[i].toLowerCase()).attr('checked', 'checked'); } } } $('#legend_tests').click(function() { $('#legend_tests').next().slideToggle(); $('#view_snapshot').val(0); $('#legend_archives, #legend_graphs').next().slideUp(300, function() { updateBrowser(); }); }); $('#legend_options').click(function() { $('#legend_options').next().slideToggle(); $('#view_snapshot').val(0); $('#legend_archives, #legend_graphs').next().slideUp(300, function() { updateBrowser(); }); }); $('#legend_archives').click(function() { $(this).next().slideToggle(); $('#view_snapshot').val(1); $('#legend_tests, #legend_options, #legend_graphs').next().slideUp(300, function() { updateBrowser(); }); }); $('#legend_graphs').click(function() { $(this).next().slideToggle(); $('#legend_tests, #legend_options, #legend_archives').next().slideUp(300, function() { updateBrowser(); }); }); function updateOutput() { $('#sort_type').unbind(); $('#sort_type').bind('change', function() { var type = $(this).val(); switch ( type ) { case 'Results (asc)': $('.box.rounded:not(.error)').sortElements(function(a, b) { return $(a).attr('data-suite-status') > $(b).attr('data-suite-status'); }); break; case 'Results (desc)': $('.box.rounded:not(.error)').sortElements(function(a, b) { return $(a).attr('data-suite-status') < $(b).attr('data-suite-status'); }); break; case 'Time (asc)': $('.box.rounded:not(.error)').sortElements(function(a, b) { return $(a).attr('data-suite-time') > $(b).attr('data-suite-time'); }); break; case 'Time (desc)': $('.box.rounded:not(.error)').sortElements(function(a, b) { return $(a).attr('data-suite-time') < $(b).attr('data-suite-time'); }); break; } }); $('#sort_type').trigger('change'); $('.display').unbind(); $('.display').bind('click', function() { var checkbox = $(this); var suites = $('.suite_' + checkbox.attr('target')); if ( checkbox.is(':checked') ) { suites.fadeIn(); } else { suites.fadeOut(); } }); $('.expand.button').each(function(index) { $(this).click(function(e) { console.log(this); if ( $(this).text() == '-' ) { if ( $(this).parent().hasClass('test') ) { var id = $(this).parent().attr("id"); delete expanded[id]; $(this).next('.more').slideUp(); } else { $(this).parent().next('.more').slideUp(); } $(this).text('+'); } else { if ( $(this).parent().hasClass('test') ) { var id = $(this).parent().attr("id"); expanded[id] = true; $(this).next('.more').slideDown(); } else { $(this).parent().next('.more').slideDown(); } $(this).text('-'); } }); }); $('ul li div span').each(function() { var width = $(this).attr('data-percent'); $(this).css({ 'width': width + '%' }); }); } $('#draw_graph').click(function(event) { event.preventDefault(); $('#output').html("<div class='loader'><img src='ui/images/loading.gif' /></div>"); $.post('index.php', { 'graph_type' : $('#graph_type').val(), 'time_frame' : $('#time_frame').val(), 'start_date' : $('#start_date').val(), 'end_date' : $('#end_date').val() }, function(data) { var chart = $.parseJSON(data); $('#output').fadeOut(300, function() { $(this).html("<div id='graph_container' class='highcharts-container'></div>"); new Highcharts.Chart(chart); $(this).fadeIn(300, function() { updateBrowser(); }); }); }); }); $('#view_archive').click(function(event) { event.preventDefault(); $('#output').html("<div class='loader'><img src='ui/images/loading.gif' /></div>"); $.post('index.php', { 'select_snapshot' : $('#select_snapshot').val(), 'view_snapshot' : $('#view_snapshot').val() }, function(data) { $('#output').fadeOut(300, function() { $(this).html(data).fadeIn(300, function() { updateBrowser(); updateOutput(); }); }); }); }); $('#run_tests').click(function(event) { event.preventDefault(); $('#output').html("<div class='loader'><img src='ui/images/loading.gif' /></div>"); var sandboxIgnore = []; $(":checked").each(function() { sandboxIgnore.push($(this).val()); }); $.post('index.php', { 'store_statistics' : $('#store_statistics').val(), 'create_snapshots' : $('#create_snapshots').val(), 'snapshot_directory' : $('#snapshot_directory').val(), 'sandbox_errors' : $('#sandbox_errors').val(), 'sandbox_filename' : $('#sandbox_filename').val(), 'sandbox_ignore' : sandboxIgnore, 'test_files' : $('#test_files').val(), }, function(data) { $('#output').fadeOut(300, function() { $(this).html(data).fadeIn(300, function() { updateBrowser(); updateOutput(); expandImportant(); ob_dump(); }); }); // Update the snapshot list $.get('index.php', { 'snapshots' : '1' }, function(data) { var snapshots = $.parseJSON(data); $('#select_snapshot').html(''); $.each(snapshots, function(key, snapshot) { $('#select_snapshot').append($('<option></option>').attr('value', snapshot).text(snapshot)); }); }); }); }); function ob_dump() { $(".more.test.hide > .variables > pre").each(function() { var ob = $(this).html(); $(this).html(''); try { var bits = JSON.parse(ob); for (var k in bits) { $("<h3>").text(k).appendTo(this); listPrint(bits[k]).appendTo(this); } } catch (e) { $(this).append(ob+"\n\n"); } }); } function expandImportant() { if ($("#output > .box").length==1) { $("#output > .box > .more").slideDown('fast'); } for (var k in expanded) { if (k != '') { $("#" + k + ' > .more').show(); } } } function constrainDates() { var startDate = $('#start_date').datepicker('getDate'); var endDate = $('#end_date').datepicker('getDate'); if ( endDate < startDate ) { $('#end_date').datepicker('setDate', startDate); } if (startDate != null) { var timeFrame = $('#time_frame').val(); switch ( timeFrame ) { case 'Daily': var endDateMax = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + 12); break; case 'Weekly': var endDateMax = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + 84); break; case 'Monthly': var endDateMax = new Date(startDate.getFullYear(), startDate.getMonth() + 12, startDate.getDate()); break; } $('#end_date').datepicker('option', { 'maxDate': endDateMax, 'minDate': startDate }); $('#end_date').trigger('change'); } } $('#start_date').datepicker({ onSelect: function(dateText, inst) { constrainDates(); } }); $('#end_date').datepicker(); $('#time_frame').change(function() { constrainDates(); }); $('#start_date, #end_date').change(function() { if ( $('#start_date').val().length && $('#end_date').val().length ) { $('#draw_graph').removeAttr('disabled'); } else { $('#draw_graph').attr('disabled', 'disabled'); } }); $('#create_snapshots').trigger('change'); $('#sandbox_errors').trigger('change'); updateIgnore('<?php echo SANDBOX_IGNORE; ?>'); $('#legend_options, #legend_archives, #legend_graphs').next().css('display', 'none'); }); </script> </body> </html>
{ "content_hash": "c3f000a90aab2671e2ec900f04fa07e1", "timestamp": "", "source": "github", "line_count": 532, "max_line_length": 140, "avg_line_length": 40.24248120300752, "alnum_prop": 0.39058339950488113, "repo_name": "Naatan/VisualPHPUnit", "id": "b519a71dbabc43f0f0bd6e77bfc6bc080d55e64a", "size": "21409", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui/index.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "290465" }, { "name": "PHP", "bytes": "57249" } ], "symlink_target": "" }
import org.specs2._ import org.specs2.matcher._ import com.twitter.finagle.builder.{ ServerBuilder, ClientBuilder } import com.twitter.finagle.thrift._ import ca.stevenskelton.thrift.testservice._ import org.apache.thrift.protocol.TBinaryProtocol class FixedSizeCacheSpec extends mutable.SpecificationWithJUnit { sequential val socket = com.twitter.util.RandomSocket() val clientService = ClientBuilder().codec(ThriftClientFramedCodec()).hosts(socket).hostConnectionLimit(2).build() val client = new TestApi$FinagleClient(clientService) val filter = new BinaryProtocolToJsonLoggingFilter(TestApi, println) andThen new FixedSizeCache(Seq("w1sDelay", "w200msDelay")) val service = ServerBuilder().codec(ThriftServerFramedCodec()).bindTo(socket).name("test") .build(filter andThen new TestApi$FinagleService(new TestService, new TBinaryProtocol.Factory)) "not cache methods not in list" in { var start = System.currentTimeMillis client.w100msDelay(1).get.name === "Id1" System.currentTimeMillis - start must beGreaterThanOrEqualTo(100L) start = System.currentTimeMillis client.w100msDelay(1).get.name === "Id1" System.currentTimeMillis - start must beGreaterThanOrEqualTo(100L) } "cache methods in list" in { var start = System.currentTimeMillis client.w200msDelay(1).get.name === "Id1" System.currentTimeMillis - start must beGreaterThanOrEqualTo(200L) start = System.currentTimeMillis client.w200msDelay(1).get.name === "Id1" System.currentTimeMillis - start must beLessThan(200L) } "mixed" in { var start = System.currentTimeMillis client.w200msDelay(1).get.name === "Id1" start = System.currentTimeMillis client.w200msDelay(10).get.name === "Id10" System.currentTimeMillis - start must beGreaterThanOrEqualTo(200L) start = System.currentTimeMillis client.w200msDelay(1).get.name === "Id1" System.currentTimeMillis - start must beLessThan(200L) start = System.currentTimeMillis client.w200msDelay(100).get.name === "Id100" System.currentTimeMillis - start must beGreaterThanOrEqualTo(200L) } "do not cache exceptions" in { client.w200msDelay(1).get.name == "Id1" client.w200msDelay(2).get must throwA[NotFoundException] client.w200msDelay(3).get must throwA[DisabledException] var start = System.currentTimeMillis client.w200msDelay(1).get.name == "Id1" System.currentTimeMillis - start must beLessThan(175L) start = System.currentTimeMillis client.w200msDelay(2).get must throwA[NotFoundException] System.currentTimeMillis - start must beGreaterThanOrEqualTo(200L) start = System.currentTimeMillis client.w200msDelay(3).get must throwA[DisabledException] System.currentTimeMillis - start must beGreaterThanOrEqualTo(200L) } "do not cache unhandled exceptions" in { var start = System.currentTimeMillis client.w200msDelay(4).get must throwA[Exception] System.currentTimeMillis - start must beGreaterThanOrEqualTo(200L) start = System.currentTimeMillis client.w200msDelay(4).get must throwA[Exception] System.currentTimeMillis - start must beGreaterThanOrEqualTo(200L) } }
{ "content_hash": "4dd65e0086138a3f1ace15c4d2a93d80", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 129, "avg_line_length": 36.29545454545455, "alnum_prop": 0.7532874139010645, "repo_name": "stevenrskelton/Blog", "id": "38f6513bbcf9415379b2033c99bc77f29a10e223", "size": "3194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/scala/FixedSizeCacheSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "136514" } ], "symlink_target": "" }