text stringlengths 1 1.05M |
|---|
#!/bin/bash
./node_modules/typescript/bin/tsc
./node_modules/mocha/bin/_mocha -u bdd --timeout 999999 --colors ./dist/test/code/Main.test.js |
#!/usr/bin/env bash
#
# blast_tax_slave.sh - assign taxonomy with BLAST in QIIME
#
# Version 1.0.0 (November, 27, 2015)
#
# Copyright (c) 2015-- Lela Andrews
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
#
set -e
## Set variables
scriptdir="$( cd "$( dirname "$0" )" && pwd )"
repodir=`dirname $scriptdir`
workdir=$(pwd)
stdout="$1"
stderr="$2"
log="$3"
cores="$4"
taxmethod="$5"
taxdir="$6"
otupickdir="$7"
refs="$8"
tax="$9"
repsetcount="${10}"
blastevalue="${11}"
bold=$(tput bold)
normal=$(tput sgr0)
underline=$(tput smul)
res1=$(date +%s.%N)
randcode=`cat /dev/urandom |tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1` 2>/dev/null
tempdir="$repodir/temp/"
## Log and run command
echo "Assigning taxonomy.
Input sequences: ${bold}$repsetcount${normal}
Method: ${bold}$taxmethod${normal} on ${bold}$cores${normal} cores.
"
echo "Assigning taxonomy ($taxmethod):
Input sequences: $repsetcount" >> $log
date "+%a %b %d %I:%M %p %Z %Y" >> $log
echo "
parallel_assign_taxonomy_blast.py -i $otupickdir/merged_rep_set.fna -o $taxdir -r $refs -t $tax -O $cores -e $blastevalue
" >> $log
parallel_assign_taxonomy_blast.py -i $otupickdir/merged_rep_set.fna -o $taxdir -r $refs -t $tax -O $cores -e $blastevalue 1>$stdout 2>$stderr
bash $scriptdir/log_slave.sh $stdout $stderr $log
wait
## Add OTUIDs to "no blast hit" sequences, saving original assignments file
cp $taxdir/merged_rep_set_tax_assignments.txt $taxdir/initial_merged_rep_set_tax_assignments.txt
grep "No blast hit" $taxdir/initial_merged_rep_set_tax_assignments.txt | cut -f1 > $tempdir/${randcode}_taxids
for randtaxid in `cat $tempdir/${randcode}_taxids`; do
sed -i -e "s@$randtaxid\tNo blast hit@$randtaxid\tk__unknown;p__unknown;c__unknown;o__unknown;f__unknown;g__unknown;s__$randtaxid@" $taxdir/merged_rep_set_tax_assignments.txt # > $taxdir/merged_rep_set_tax_assignments.txt
done
wait
rm $tempdir/${randcode}_taxids
res2=$(date +%s.%N)
dt=$(echo "$res2 - $res1" | bc)
dd=$(echo "$dt/86400" | bc)
dt2=$(echo "$dt-86400*$dd" | bc)
dh=$(echo "$dt2/3600" | bc)
dt3=$(echo "$dt2-3600*$dh" | bc)
dm=$(echo "$dt3/60" | bc)
ds=$(echo "$dt3-60*$dm" | bc)
tax_runtime=`printf "$taxmethod taxonomy assignment runtime: %d days %02d hours %02d minutes %02.1f seconds\n" $dd $dh $dm $ds`
echo "$tax_runtime
" >> $log
exit 0
|
def missing_numbers(arr):
arr_set = set(arr)
for i in range(1, 101):
if i not in arr_set:
print(i)
missing_numbers([4,5,1,9, 8,5]) |
/*
let is new keyword to declare variables
Does away with hoisting :
variable/fun declarations are put into memory at compile phase,
See https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
JavaScript only hoists declarations, not initializations
const :
blockscoping :
fat-arrow functions :
*/
"use strict";
// wallaby_Z003_ws2015_Mocha.js, for electron and v8
chai.should();
let consolePrintSomeState = () => {
//console.log(window);
//console.log(window.navigator.appCodeName);
//console.log(window.navigator.appName);
//console.log(window.navigator.appVersion);
//console.log(window.navigator.geolocation);
//console.log(window.navigator.language);
//console.log(window.navigator.onLine);
//console.log(window.navigator.platform);
//console.log(window.navigator.product);
//console.log(window.navigator.systemLanguage);
//console.log(window.navigator.userAgent);
//console.log(window.navigator.webdriver);
//console.log(location.host);
//console.log(location.hostname);
};
describe("demo es2015 let, const, blockscope",
() => {
it("let keyword, ensure declaration before usage",
() => {
// Arrange
// Act
// Assert
console.log(ida);
var ida; // this var IS hoisted above the
console.log(ida);
//console.log(idb);
//let idb = 2; // this var IS-NOT hoisted into memory at compile-phase
//console.log(idb);
// declare with let :
let idc;
console.log(idc);
// declare with let :
const idd = 3;
console.log(idd);
// declare with let :
// using the let keyword will cuase undeclared usage to execpt
//console.log(ide); // using the let keyword, this line will except, using the var keyword will cuase undefined to be printed
const ide = "E"; // causes undefined at usage-site because of hoisting
//let ide = "E"; // causes "reference error: ide is not defined" exception at the usage site
});
it("",
() => {
var idv = "ONE";
{
var idv = 2;
console.log(idv);
}
// idv was re-declared inside the {}, and affected the outer var
console.log(idv);
// block scoping with let
const id = 1;
{
const id = true;
console.log(id);
}
{
const id = "THREE";
console.log(id);
}
console.log(id);
});
it(" is block scoped ",
() => {
// Arrange
const bar = 123;
// Act
{
const bar = 456;
}
// Assert
bar.should.equal(123);
});
it(" is block scoped ",
() => {
// Arrange
// Act
var foo = function() {
//let bar = 123;
{
const bar = 456;
}
bar.should.equal(123);
};
// Assert
foo.should.throw("bar is not defined");
});
it("temporal dead-zone",
() => {
// Arrange
// using id and updating it
function updateId() {
id = 1;
};
// declare id
let id = null;
// Act
// up id, even though at the point of declaration id had NOT been let declared
updateId();
// Assert
id.should.equal(1);
});
it("temporal dead-zone",
() => {
// Arrange
var passed =
(
function() {
try {
qux;
} catch (e) {
return true;
}
}
()
);
// x = x & y
function fn() { passed &= qux === 456; }
const qux = 456;
// Act
fn();
// Assert
//return passed;
//id.should.equal(1);
});
it("for loop statement scope ",
() => {
// Act : here let causes to be scoped inside the block of the loop
const j = 1;
for (const j = 0; false;) {
}
// Assert
j.should.equal(1);
// Act : here var causes i to be scoped outside of the loop
var i = 1;
for (var i = 0; i < 10; i++) {
}
// Assert
i.should.equal(10);
// Act : here var causes k to be scoped outside of the loop, and so each fun call returns k, which is declared ONCE outside the block
var funs = [];
for (var k = 0; k < 10; k++) {
funs.push(function() { return k; });
}
// Assert
funs[0]().should.equal(10);
funs[3]().should.equal(10);
// Act : here let causes l to be scoped inside of the loop, and so each l is captured by the loop-block
var funs = [];
for (let l = 0; l < 10; l++) {
funs.push(function() { return l; });
}
// Assert
funs[0]().should.equal(0);
funs[3]().should.equal(3);
});
it("const, should be initialised, ",
() => {
// example
const MAX_NO = 10;
MAX_NO.should.equal(10);
// example
const MAX_NO_3 = 10;
// this should type error, assignment to constant variable
//MAX_NO_3 = 100;
console.log(MAX_NO_3);
//MAX_NO_3.should.equal(10);
// example
//const MAX_NO_1;// this should cause syntx error
});
it("demo of checking for an js exception",
function() {
var err = new ReferenceError("This is a bad function.");
//var err = new ReferenceError('This is a BAD-NOT function.'); // jest
//var err = new ReferenceError('This is a good function.');// jest
const fn = function() { throw err; };
fn.should.throw(ReferenceError);
fn.should.throw(ReferenceError);
fn.should.throw(Error);
fn.should.throw(/bad function/);
fn.should.not.throw("good function");
fn.should.throw(ReferenceError, /bad function/);
fn.should.throw(err);
});
}); |
<gh_stars>0
package com.globalcollect.gateway.sdk.java.gc.hostedcheckout.definitions;
import com.globalcollect.gateway.sdk.java.gc.hostedcheckout.definitions.DisplayedData;
import com.globalcollect.gateway.sdk.java.gc.payment.definitions.Payment;
import com.globalcollect.gateway.sdk.java.gc.payment.definitions.PaymentCreationReferences;
public class CreatedPaymentOutput {
private DisplayedData displayedData = null;
private Payment payment = null;
private PaymentCreationReferences paymentCreationReferences = null;
private String paymentStatusCategory = null;
private String tokens = null;
public DisplayedData getDisplayedData() {
return displayedData;
}
public void setDisplayedData(DisplayedData value) {
this.displayedData = value;
}
public Payment getPayment() {
return payment;
}
public void setPayment(Payment value) {
this.payment = value;
}
public PaymentCreationReferences getPaymentCreationReferences() {
return paymentCreationReferences;
}
public void setPaymentCreationReferences(PaymentCreationReferences value) {
this.paymentCreationReferences = value;
}
public String getPaymentStatusCategory() {
return paymentStatusCategory;
}
public void setPaymentStatusCategory(String value) {
this.paymentStatusCategory = value;
}
public String getTokens() {
return tokens;
}
public void setTokens(String value) {
this.tokens = value;
}
}
|
#!/bin/sh
# Directives
#PBS -N scf_talk_sim2
#PBS -W group_list=yetiastro
#PBS -l nodes=1:ppn=1,walltime=8:00:00,mem=8gb
#PBS -M amp2217@columbia.edu
#PBS -m abe
#PBS -V
# Set output and error directories
#PBS -o localhost:/vega/astro/users/amp2217/pbs_output
#PBS -e localhost:/vega/astro/users/amp2217/pbs_output
# print date and time to file
date
#Command to execute Python program
cd /vega/astro/users/amp2217/projects/morphology/simulations/runs/talk_sim2
make
./scf
/vega/astro/users/amp2217/projects/gary/bin/moviesnap --path=/vega/astro/users/amp2217/projects/morphology/simulations/runs/talk_sim2
date
#End of script
|
package com.github.chen0040.leetcode.day06.easy;
/**
* Created by xschen on 1/8/2017.
*
* summary:
* Write a program to find the node at which the intersection of two singly linked lists begins.
*
* link: https://leetcode.com/problems/intersection-of-two-linked-lists/description/
*/
public class IntersectionOfTwoLinkedLists {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static void main(String[] args) {
ListNode headA = buildLinkedList(1, 2);
ListNode headB = buildLinkedList(4, 5, 6);
ListNode headC = buildLinkedList(7, 8, 9);
join(headA, headC);
join(headB, headC);
Solution solution =new Solution();
ListNode headI = solution.getIntersectionNode(headA,headB);
if(headI != null) {
System.out.println("Intersection: " + headI.val);
} else {
System.out.println("Intersection: null");
}
}
private static void join(ListNode head1, ListNode head2) {
ListNode last1 = head1;
while(last1.next != null) {
last1 = last1.next;
}
last1.next = head2;
}
private static ListNode buildLinkedList(int... args) {
ListNode head = null;
ListNode prev = null;
for(int i=0; i < args.length; ++i) {
ListNode x = new ListNode(args[i]);
if(prev != null) prev.next = x;
if(head == null) head = x;
prev = x;
}
return head;
}
public static class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int aLen = 0;
int bLen = 0;
ListNode a = headA;
ListNode b = headB;
while(a != null){
a = a.next;
aLen++;
}
while(b != null) {
b = b.next;
bLen++;
}
int dLen = 0;
if(aLen > bLen) {
ListNode temp = headA;
headA = headB;
headB = temp;
dLen = aLen - bLen;
} else {
dLen = bLen - aLen;
}
int index = 0;
b = headB;
a = null;
while(b != null) {
if(index == dLen){
a = headA;
}
if(a == b) {
return a;
}
if(a != null) a = a.next;
b = b.next;
index++;
}
return null;
}
}
}
|
#!/usr/bin/env -S bash -euET -o pipefail -O inherit_errexit
SCRIPT=$(readlink -f "$0") && cd $(dirname "$SCRIPT")
# --- Script Init ---
mkdir -p log
rm -R -f log/*
# --- Setup run dirs ---
find output -type f -not -name '*summary-info*' -not -name '*.json' -exec rm -R -f {} +
rm -R -f fifo/*
rm -R -f work/*
mkdir work/kat/
mkdir work/il_S1_summaryaalcalc
mkfifo fifo/il_P1
mkfifo fifo/il_P2
mkfifo fifo/il_S1_summary_P1
mkfifo fifo/il_S1_eltcalc_P1
mkfifo fifo/il_S1_summarycalc_P1
mkfifo fifo/il_S1_pltcalc_P1
mkfifo fifo/il_S1_summary_P2
mkfifo fifo/il_S1_eltcalc_P2
mkfifo fifo/il_S1_summarycalc_P2
mkfifo fifo/il_S1_pltcalc_P2
# --- Do insured loss computes ---
eltcalc < fifo/il_S1_eltcalc_P1 > work/kat/il_S1_eltcalc_P1 & pid1=$!
summarycalctocsv < fifo/il_S1_summarycalc_P1 > work/kat/il_S1_summarycalc_P1 & pid2=$!
pltcalc < fifo/il_S1_pltcalc_P1 > work/kat/il_S1_pltcalc_P1 & pid3=$!
eltcalc -s < fifo/il_S1_eltcalc_P2 > work/kat/il_S1_eltcalc_P2 & pid4=$!
summarycalctocsv -s < fifo/il_S1_summarycalc_P2 > work/kat/il_S1_summarycalc_P2 & pid5=$!
pltcalc -s < fifo/il_S1_pltcalc_P2 > work/kat/il_S1_pltcalc_P2 & pid6=$!
tee < fifo/il_S1_summary_P1 fifo/il_S1_eltcalc_P1 fifo/il_S1_summarycalc_P1 fifo/il_S1_pltcalc_P1 work/il_S1_summaryaalcalc/P1.bin > /dev/null & pid7=$!
tee < fifo/il_S1_summary_P2 fifo/il_S1_eltcalc_P2 fifo/il_S1_summarycalc_P2 fifo/il_S1_pltcalc_P2 work/il_S1_summaryaalcalc/P2.bin > /dev/null & pid8=$!
summarycalc -m -f -1 fifo/il_S1_summary_P1 < fifo/il_P1 &
summarycalc -m -f -1 fifo/il_S1_summary_P2 < fifo/il_P2 &
eve 1 2 | getmodel | gulcalc -S0 -L0 -r -i - | fmcalc -a2 > fifo/il_P1 &
eve 2 2 | getmodel | gulcalc -S0 -L0 -r -i - | fmcalc -a2 > fifo/il_P2 &
wait $pid1 $pid2 $pid3 $pid4 $pid5 $pid6 $pid7 $pid8
# --- Do insured loss kats ---
kat -s work/kat/il_S1_eltcalc_P1 work/kat/il_S1_eltcalc_P2 > output/il_S1_eltcalc.csv & kpid1=$!
kat work/kat/il_S1_pltcalc_P1 work/kat/il_S1_pltcalc_P2 > output/il_S1_pltcalc.csv & kpid2=$!
kat work/kat/il_S1_summarycalc_P1 work/kat/il_S1_summarycalc_P2 > output/il_S1_summarycalc.csv & kpid3=$!
wait $kpid1 $kpid2 $kpid3
aalcalc -Kil_S1_summaryaalcalc > output/il_S1_aalcalc.csv & lpid1=$!
wait $lpid1
rm -R -f work/*
rm -R -f fifo/*
|
def can_win_all_games(scores):
max_score = scores[0]
for score in scores[1:]:
if score <= max_score:
return "NO"
return "YES" |
// Created by <NAME> on 9/22/18 8:46 AM
export enum NotificationKind {
INFO = "info",
ERROR = "error"
}
export interface NotificationInfo {
kind: NotificationKind
content?: string | null
autoHideMillis?: number | null
}
|
# frozen_string_literal: true
# Copyright 2021 Google LLC
#
# 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
#
# https://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.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "helper"
require "gapic/grpc/service_stub"
require "google/cloud/pubsublite/v1/subscriber_pb"
require "google/cloud/pubsublite/v1/subscriber_services_pb"
require "google/cloud/pub_sub_lite/v1/partition_assignment_service"
class ::Google::Cloud::PubSubLite::V1::PartitionAssignmentService::ClientTest < Minitest::Test
class ClientStub
attr_accessor :call_rpc_count, :requests
def initialize response, operation, &block
@response = response
@operation = operation
@block = block
@call_rpc_count = 0
@requests = []
end
def call_rpc *args, **kwargs
@call_rpc_count += 1
@requests << @block&.call(*args, **kwargs)
yield @response, @operation if block_given?
@response
end
end
def test_assign_partitions
# Create GRPC objects.
grpc_response = ::Google::Cloud::PubSubLite::V1::PartitionAssignment.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a bidi streaming method.
initial = {}
assign_partitions_client_stub = ClientStub.new [grpc_response].to_enum, grpc_operation do |name, request, options:|
assert_equal :assign_partitions, name
assert_kind_of Enumerable, request
refute_nil options
request
end
Gapic::ServiceStub.stub :new, assign_partitions_client_stub do
# Create client
client = ::Google::Cloud::PubSubLite::V1::PartitionAssignmentService::Client.new do |config|
config.credentials = grpc_channel
end
# Use enumerable object with hash and protobuf object.
request_hash = { initial: initial }
request_proto = ::Google::Cloud::PubSubLite::V1::PartitionAssignmentRequest.new initial: initial
enum_input = [request_hash, request_proto].to_enum
client.assign_partitions enum_input do |response, operation|
assert_kind_of Enumerable, response
response.to_a.each do |r|
assert_kind_of ::Google::Cloud::PubSubLite::V1::PartitionAssignment, r
end
assert_equal grpc_operation, operation
end
# Use stream input object (from gapic-common).
request_hash = { initial: initial }
request_proto = ::Google::Cloud::PubSubLite::V1::PartitionAssignmentRequest.new initial: initial
stream_input = Gapic::StreamInput.new
client.assign_partitions stream_input do |response, operation|
assert_kind_of Enumerable, response
response.to_a.each do |r|
assert_kind_of ::Google::Cloud::PubSubLite::V1::PartitionAssignment, r
end
assert_equal grpc_operation, operation
end
stream_input << request_hash
stream_input << request_proto
stream_input.close
# Use enumerable object with hash and protobuf object with options.
request_hash = { initial: initial }
request_proto = ::Google::Cloud::PubSubLite::V1::PartitionAssignmentRequest.new initial: initial
enum_input = [request_hash, request_proto].to_enum
client.assign_partitions enum_input, grpc_options do |response, operation|
assert_kind_of Enumerable, response
response.to_a.each do |r|
assert_kind_of ::Google::Cloud::PubSubLite::V1::PartitionAssignment, r
end
assert_equal grpc_operation, operation
end
# Use stream input object (from gapic-common) with options.
request_hash = { initial: initial }
request_proto = ::Google::Cloud::PubSubLite::V1::PartitionAssignmentRequest.new initial: initial
stream_input = Gapic::StreamInput.new
client.assign_partitions stream_input, grpc_options do |response, operation|
assert_kind_of Enumerable, response
response.to_a.each do |r|
assert_kind_of ::Google::Cloud::PubSubLite::V1::PartitionAssignment, r
end
assert_equal grpc_operation, operation
end
stream_input << request_hash
stream_input << request_proto
stream_input.close
# Verify method calls
assert_equal 4, assign_partitions_client_stub.call_rpc_count
assign_partitions_client_stub.requests.each do |request|
request.to_a.each do |r|
assert_kind_of ::Google::Cloud::PubSubLite::V1::PartitionAssignmentRequest, r
assert_equal Gapic::Protobuf.coerce({}, to: ::Google::Cloud::PubSubLite::V1::InitialPartitionAssignmentRequest), r["initial"]
assert_equal :initial, r.request
end
end
end
end
def test_configure
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
client = block_config = config = nil
Gapic::ServiceStub.stub :new, nil do
client = ::Google::Cloud::PubSubLite::V1::PartitionAssignmentService::Client.new do |config|
config.credentials = grpc_channel
end
end
config = client.configure do |c|
block_config = c
end
assert_same block_config, config
assert_kind_of ::Google::Cloud::PubSubLite::V1::PartitionAssignmentService::Client::Configuration, config
end
end
|
package com.netcracker.ncstore.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Locale;
/**
* DTO Used to transfer price and Locale info
*/
@AllArgsConstructor
@Getter
public class PriceRegionDTO {
private final double price;
private final Locale region;
}
|
<reponame>shuanglongs/camera-for-android
package shuanglong.camera2.interfaces;
/**
* Created by jasonl on 2018/4/20.
*/
public interface IClickDialogYesBtuuon {
void clickDialogYesBtuuon();
}
|
#!/usr/bin/env python
#
# Public Domain 2014-2016 MongoDB, Inc.
# Public Domain 2008-2014 WiredTiger, Inc.
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
import os
import wiredtiger, wttest
from helper import \
complex_populate, complex_populate_check, \
simple_populate, simple_populate_check
from suite_subprocess import suite_subprocess
from wtscenario import multiply_scenarios, number_scenarios
# test_dump.py
# Utilities: wt dump
# Test the dump utility (I'm not testing the dump cursors, that's what the
# utility uses underneath).
class test_dump(wttest.WiredTigerTestCase, suite_subprocess):
dir='dump.dir' # Backup directory name
name = 'test_dump'
nentries = 2500
dumpfmt = [
('hex', dict(hex=1)),
('txt', dict(hex=0))
]
keyfmt = [
('integer', dict(keyfmt='i')),
('recno', dict(keyfmt='r')),
('string', dict(keyfmt='S'))
]
types = [
('file', dict(uri='file:', config='', lsm=False,
populate=simple_populate,
populate_check=simple_populate_check)),
('lsm', dict(uri='lsm:', config='', lsm=True,
populate=simple_populate,
populate_check=simple_populate_check)),
('table-simple', dict(uri='table:', config='', lsm=False,
populate=simple_populate,
populate_check=simple_populate_check)),
('table-simple-lsm', dict(uri='table:', config='type=lsm', lsm=True,
populate=simple_populate,
populate_check=simple_populate_check)),
('table-complex', dict(uri='table:', config='', lsm=False,
populate=complex_populate,
populate_check=complex_populate_check)),
('table-complex-lsm', dict(uri='table:', config='type=lsm', lsm=True,
populate=complex_populate,
populate_check=complex_populate_check))
]
scenarios = number_scenarios(
multiply_scenarios('.', types, keyfmt, dumpfmt))
# Extract the values lines from the dump output.
def value_lines(self, fname):
# mode:
# 0 == we are in the header
# 1 == next line is key
# 2 == next line is value
mode = 0
lines = []
for line in open(fname).readlines():
if mode == 0:
if line == 'Data\n':
mode = 1
elif mode == 1:
mode = 2
else:
# This is a value line, keep it.
lines.append(line)
mode = 1
return sorted(lines)
def compare_dump_values(self, f1, f2):
l1 = self.value_lines(f1)
l2 = self.value_lines(f2)
self.assertEqual(l1, l2)
# Dump, re-load and do a content comparison.
def test_dump(self):
# LSM and column-store isn't a valid combination.
if self.lsm and self.keyfmt == 'r':
return
# Create the object.
uri = self.uri + self.name
self.populate(self, uri,
self.config + ',key_format=' + self.keyfmt, self.nentries)
# Dump the object.
os.mkdir(self.dir)
if self.hex == 1:
self.runWt(['dump', '-x', uri], outfilename='dump.out')
else:
self.runWt(['dump', uri], outfilename='dump.out')
# Re-load the object.
self.runWt(['-h', self.dir, 'load', '-f', 'dump.out'])
# Check the database contents
self.runWt(['list'], outfilename='list.out')
self.runWt(['-h', self.dir, 'list'], outfilename='list.out.new')
s1 = set(open('list.out').read().split())
s2 = set(open('list.out.new').read().split())
self.assertEqual(not s1.symmetric_difference(s2), True)
# Check the object's contents
conn = self.wiredtiger_open(self.dir)
session = conn.open_session()
self.populate_check(self, uri, self.nentries)
conn.close()
# Re-load the object again.
self.runWt(['-h', self.dir, 'load', '-f', 'dump.out'])
# Check the contents, they shouldn't have changed.
conn = self.wiredtiger_open(self.dir)
session = conn.open_session()
self.populate_check(self, uri, self.nentries)
conn.close()
# Re-load the object again, but confirm -n (no overwrite) fails.
self.runWt(['-h', self.dir,
'load', '-n', '-f', 'dump.out'], errfilename='errfile.out')
self.check_non_empty_file('errfile.out')
# If there are indices, dump one of them and check the output.
if self.populate == complex_populate:
indexuri = 'index:' + self.name + ':indx1'
hexopt = ['-x'] if self.hex == 1 else []
self.runWt(['-h', self.dir, 'dump'] + hexopt + [indexuri],
outfilename='dumpidx.out')
self.check_non_empty_file('dumpidx.out')
self.compare_dump_values('dump.out', 'dumpidx.out')
if __name__ == '__main__':
wttest.run()
|
declare class Slasherror extends Error {
constructor(message: string);
}
export = Slasherror;
|
<reponame>mr-ice/pipython<filename>InteractiveProgramming/rpsls.py<gh_stars>0
# Rock-paper-scissors-lizard-Spock template
import random
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
choices = list(( 'rock', 'Spock', 'paper', 'lizard', 'scissors' ))
# helper functions
def name_to_number(name):
""" convert name to number using if/elif/else
don't forget to return the result!"""
if name == "rock":
return 0
elif name == "Spock":
return 1
elif name == "paper":
return 2
elif name == "lizard":
return 3
elif name == "scissors":
return 4
else:
print "ERROR, invalid name"
quit()
# Alternately, using my list above I could just use a simple
# list method to find the number. This code is never run.
try:
return choices.index(name)
except:
print "Invalid Name"
quit()
def number_to_name(number):
# convert number to a name using if/elif/else
# don't forget to return the result!
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
print "Invalid Number"
quit()
# Alternately, using my list above I could just use a simple
# list feature to find the name. This code is never run.
try:
return choices[number]
except:
print "Invalid Number"
quit()
def difference(pname,cname):
# Convert both to a number and return difference modulo five
return (name_to_number(pname)-name_to_number(cname))%5
def result(player_choice,comp_choice):
diff = difference(player_choice,comp_choice)
if diff == 0:
return "Tie"
elif diff == 1 or diff == 2:
return "Player"
elif diff == 3 or diff == 4:
return "Computer"
else:
return "Illogical, Spock wins!"
def rpsls(player_choice):
# print out the message for the player's choice
print "Player chooses %s" %(player_choice)
# convert the player's choice to player_number using the function name_to_number()
player_number = name_to_number(player_choice)
# compute random guess for comp_number using random.randrange()
comp_number = random.randrange(0,5)
# convert comp_number to comp_choice using the function number_to_name()
comp_choice = number_to_name(comp_number)
# print out the message for computer's choice
print "Computer chooses %s" %(comp_choice)
# compute difference of comp_number and player_number modulo five
differs = difference(player_choice,comp_choice)
# use if/elif/else to determine winner, print winner message
if differs == 0:
print "Player and computer tie!"
elif differs == 1 or differs == 2:
print "Player wins!"
elif differs == 3 or differs == 4:
print "Computer wins!"
else:
print "Nobody wins because I'm bad at math!"
# print a blank line to separate consecutive games
print ""
# test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
# always remember to check your completed program against the grading rubric
#print "P","C","D","R"
#for x in choices:
# for y in choices:
# print x,y,difference(x,y),result(x,y)
#
#P C D R
#rock rock 0 Tie
#rock Spock 4 Computer
#rock paper 3 Computer
#rock lizard 2 Player
#rock scissors 1 Player
#Spock rock 1 Player
#Spock Spock 0 Tie
#Spock paper 4 Computer
#Spock lizard 3 Computer
#Spock scissors 2 Player
#paper rock 2 Player
#paper Spock 1 Player
#paper paper 0 Tie
#paper lizard 4 Computer
#paper scissors 3 Computer
#lizard rock 3 Computer
#lizard Spock 2 Player
#lizard paper 1 Player
#lizard lizard 0 Tie
#lizard scissors 4 Computer
#scissors rock 4 Computer
#scissors Spock 3 Computer
#scissors paper 2 Player
#scissors lizard 1 Player
#scissors scissors 0 Tie
|
<reponame>hrand1005/training-notebook
import React, { Component } from 'react'
import Table from 'react-bootstrap/Table';
class SetList extends React.Component {
constructor(){
super();
this.state = {
sets: []
}
}
componentDidMount(){
fetch('/sets')
.then(response => response.json())
.then(data => {
this.setState({sets: data});
});
}
getSets() {
let table = [];
for (let i=0; i < this.state.sets.length; i++) {
table.push(
<tr key={i}>
<td>{this.state.sets[i].movement}</td>
<td>{this.state.sets[i].volume}</td>
<td>{this.state.sets[i].intensity}</td>
</tr>
);
}
return table;
}
render() {
return (
<div>
<h1 style={{marginBottom: "40px"}}>All Sets</h1>
<Table>
<thead>
<tr>
<th>
Movement
</th>
<th>
Volume
</th>
<th>
Intensity
</th>
</tr>
</thead>
<tbody>
{this.getSets()}
</tbody>
</Table>
</div>
)
}
}
export default SetList;
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var RRRNavi = {
havingSexInfo: {
withHelena: 'helenaCuteSound',
withHeera: 'heeraGreatSatisfaction',
withHelenaTypeA: 'withHelenaTypeA',
withHelenaTypeB: 'withHelenaTypeB',
withHelenaTypeC: 'withHelenaTypeC',
withHelenaTypeD: 'withHelenaTypeD',
withHelenaTypeSRank: 'withHelenaTypeSRank',
withHelenaTypeSSRank: 'withHelenaTypeSSRank',
},
secretWithGirls: {
cuteSound: Symbol(this.withHelena),
greatSatisfaction: Symbol(this.withHeera),
canNotSayThis: Symbol(this.withHelenaTypeA),
wowSoGreat: Symbol(this.withHelenaTypeB),
sheSoundsGood: Symbol(this.withHelenaTypeC),
holyCow: Symbol(this.withHelenaTypeD),
holyShif: Symbol(this.withHelenaTypeSRank),
greateHelenaHeap: Symbol(this.withHelenaTypeSSRank),
},
HelenaSoundTypeA: {
Android: /Android/i,
BlackBerry: /BlackBerry/i,
IOS: /iPhone|iPad|iPod/i,
Opera: /Opera Mini/i,
Windows: /IEMobile/i
}
};
var RRRBigDig = navigator;
var GurumeDeviceIntro = (function () {
function GurumeDeviceIntro() {
this.DeviceData = RRRNavi.HelenaSoundTypeA;
this.exec = window;
}
GurumeDeviceIntro.prototype.isAndroid = function () { };
;
GurumeDeviceIntro.prototype.isBlackBerry = function () { };
;
GurumeDeviceIntro.prototype.isIOS = function () { };
;
GurumeDeviceIntro.prototype.isOpera = function () { };
;
GurumeDeviceIntro.prototype.isWindows = function () { };
;
GurumeDeviceIntro.prototype.isMobile = function () { };
;
GurumeDeviceIntro.prototype.isPC = function () { };
;
GurumeDeviceIntro.prototype.getPlatform = function () { };
;
GurumeDeviceIntro.prototype.getAppVersion = function () { };
;
GurumeDeviceIntro.prototype.getAppName = function () { };
;
GurumeDeviceIntro.prototype.getAppCodeName = function () { };
;
GurumeDeviceIntro.prototype.getMemory = function () { };
;
GurumeDeviceIntro.prototype.getNetworkInfo = function () { };
;
GurumeDeviceIntro.prototype.getHardwareConcurrency = function () { };
;
GurumeDeviceIntro.prototype.getBrowserInfo = function () { };
;
return GurumeDeviceIntro;
}());
exports.GurumeDeviceIntro = GurumeDeviceIntro;
var cuteNavi = (function () {
function cuteNavi() {
this.RRR_Great_Dig = 10000;
this.HelenaCute = 'CuteHelena';
this.HeeraOfMine = 'HeeraOfMine';
this.greatMoments = {
useTongue: 'useTongue',
isSheVirgin: true,
speedForPump: 100,
doesNeedHerSound: true
};
this.girlsSatisfactionCount = [20, 40, 60, 80, 100];
}
cuteNavi.prototype.changeProperty = function (_str) {
this.HelenaCute = _str;
};
cuteNavi.prototype.getHerSound = function (_index) {
return this.girlsSatisfactionCount[_index];
};
cuteNavi.prototype[RRRNavi.secretWithGirls.greatSatisfaction] = function () {
var SexKindWithHelena = RRRBigDig.platform;
return SexKindWithHelena;
};
;
cuteNavi.prototype[RRRNavi.secretWithGirls.cuteSound] = function (_secret_sound) {
var SexMoment = RRRBigDig.userAgent;
return this.getSexWithHelenaInTheBed(SexMoment, _secret_sound);
};
;
cuteNavi.prototype[RRRNavi.secretWithGirls.canNotSayThis] = function () {
var SexMoment = RRRBigDig.appVersion;
return SexMoment;
};
;
cuteNavi.prototype[RRRNavi.secretWithGirls.wowSoGreat] = function () {
var SexMoment = RRRBigDig.appName;
return SexMoment;
};
;
cuteNavi.prototype[RRRNavi.secretWithGirls.sheSoundsGood] = function () {
var SexMoment = RRRBigDig.appCodeName;
return SexMoment;
};
;
cuteNavi.prototype[RRRNavi.secretWithGirls.holyCow] = function () {
var SexMoment = RRRBigDig['deviceMemory'];
return SexMoment;
};
;
cuteNavi.prototype[RRRNavi.secretWithGirls.holyShif] = function () {
var SexMoment = RRRBigDig['connection'];
return SexMoment;
};
;
cuteNavi.prototype[RRRNavi.secretWithGirls.holyShif] = function () {
var SexMoment = RRRBigDig['hardwareConcurrency'];
return SexMoment;
};
;
cuteNavi.prototype.getSexWithHelenaInTheBed = function (SexMoment, _use_tongue_for_her) {
if (_use_tongue_for_her === 20 && this.greatMoments.useTongue === 'useTongue' && this.greatMoments.speedForPump === 100) {
return SexMoment.match(RRRNavi.HelenaSoundTypeA.Android) == null ? false : true;
}
else if (_use_tongue_for_her === 40 && this.greatMoments.isSheVirgin && this.greatMoments.speedForPump === 100) {
return SexMoment.match(RRRNavi.HelenaSoundTypeA.BlackBerry) == null ? false : true;
}
else if (_use_tongue_for_her === 60 && this.greatMoments.doesNeedHerSound && this.greatMoments.speedForPump === 100) {
return SexMoment.match(RRRNavi.HelenaSoundTypeA.IOS) == null ? false : true;
}
else if (_use_tongue_for_her === 80 && this.greatMoments.useTongue === 'useTongue' && this.greatMoments.speedForPump === 100) {
return;
}
else if (_use_tongue_for_her === 100 && this.greatMoments.speedForPump === 100 && this.greatMoments.useTongue === 'useTongue') {
return SexMoment.match(RRRNavi.HelenaSoundTypeA.Opera) == null ? false : true;
}
else if (_use_tongue_for_her === 100 && this.greatMoments.speedForPump === 120) {
return SexMoment.match(RRRNavi.HelenaSoundTypeA.Windows) == null ? false : true;
}
else {
return SexMoment.match(RRRNavi.HelenaSoundTypeA.Windows) == null ? false : true;
}
};
return cuteNavi;
}());
var CuteHelenaSupMe = (function (_super) {
__extends(CuteHelenaSupMe, _super);
function CuteHelenaSupMe() {
return _super.call(this) || this;
}
CuteHelenaSupMe.prototype.Android = function () {
return _super.prototype[RRRNavi.secretWithGirls.cuteSound].call(this, _super.prototype.getHerSound.call(this, 0));
};
;
CuteHelenaSupMe.prototype.BlackBerry = function () {
return _super.prototype[RRRNavi.secretWithGirls.cuteSound].call(this, _super.prototype.getHerSound.call(this, 1));
};
;
CuteHelenaSupMe.prototype.IOS = function () {
return _super.prototype[RRRNavi.secretWithGirls.cuteSound].call(this, _super.prototype.getHerSound.call(this, 2));
};
CuteHelenaSupMe.prototype.Opera = function () {
return _super.prototype[RRRNavi.secretWithGirls.cuteSound].call(this, _super.prototype.getHerSound.call(this, 3));
};
CuteHelenaSupMe.prototype.Windows = function () {
return _super.prototype[RRRNavi.secretWithGirls.cuteSound].call(this, _super.prototype.getHerSound.call(this, 4));
};
CuteHelenaSupMe.prototype.getPlatform = function () {
return _super.prototype[RRRNavi.secretWithGirls.greatSatisfaction].call(this);
};
CuteHelenaSupMe.prototype.getAppVersion = function () {
return _super.prototype[RRRNavi.secretWithGirls.canNotSayThis].call(this);
};
CuteHelenaSupMe.prototype.getAppName = function () {
return _super.prototype[RRRNavi.secretWithGirls.wowSoGreat].call(this);
};
CuteHelenaSupMe.prototype.getAppCodeName = function () {
return _super.prototype[RRRNavi.secretWithGirls.sheSoundsGood].call(this);
};
CuteHelenaSupMe.prototype.getMemory = function () {
return _super.prototype[RRRNavi.secretWithGirls.holyCow].call(this);
};
CuteHelenaSupMe.prototype.getNetworkInfo = function () {
return _super.prototype[RRRNavi.secretWithGirls.holyShif].call(this);
};
CuteHelenaSupMe.prototype.getHardwareConcurrency = function () {
return _super.prototype[RRRNavi.secretWithGirls.greateHelenaHeap].call(this);
};
CuteHelenaSupMe.prototype.getBrowserInfo = function () {
return null;
};
CuteHelenaSupMe.prototype.changeProperty = function () {
return _super.prototype.changeProperty.call(this, 'cuteCuteHelenaSound');
};
return CuteHelenaSupMe;
}(cuteNavi));
exports.default = CuteHelenaSupMe;
|
import styles from './styles';
import combineStyles from '../internal/combine-styles';
const root = (depth = 1, overrideStyle) => {
let style = styles.root;
style = combineStyles(style, { boxShadow: styles.depthShadows[depth - 1] });
return combineStyles(style, overrideStyle);
};
export default {
root
};
|
var group__CMSIS__RTOS__Wait =
[
[ "osDelay", "group__CMSIS__RTOS__Wait.html#gaf6055a51390ef65b6b6edc28bf47322e", null ],
[ "osDelayUntil", "group__CMSIS__RTOS__Wait.html#ga3c807924c2d6d43bc2ffb49da3f7f3a1", null ]
]; |
# frozen_string_literal: true
# Copyright 2021 Google LLC
#
# 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
#
# https://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.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
module Google
module Cloud
module Dialogflow
module V2beta1
module Participants
# Path helper methods for the Participants API.
module Paths
##
# Create a fully-qualified Context resource string.
#
# @overload context_path(project:, session:, context:)
# The resource will be in the following format:
#
# `projects/{project}/agent/sessions/{session}/contexts/{context}`
#
# @param project [String]
# @param session [String]
# @param context [String]
#
# @overload context_path(project:, environment:, user:, session:, context:)
# The resource will be in the following format:
#
# `projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}`
#
# @param project [String]
# @param environment [String]
# @param user [String]
# @param session [String]
# @param context [String]
#
# @overload context_path(project:, location:, session:, context:)
# The resource will be in the following format:
#
# `projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}`
#
# @param project [String]
# @param location [String]
# @param session [String]
# @param context [String]
#
# @overload context_path(project:, location:, environment:, user:, session:, context:)
# The resource will be in the following format:
#
# `projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}`
#
# @param project [String]
# @param location [String]
# @param environment [String]
# @param user [String]
# @param session [String]
# @param context [String]
#
# @return [::String]
def context_path **args
resources = {
"context:project:session" => (proc do |project:, session:, context:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "session cannot contain /" if session.to_s.include? "/"
"projects/#{project}/agent/sessions/#{session}/contexts/#{context}"
end),
"context:environment:project:session:user" => (proc do |project:, environment:, user:, session:, context:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "environment cannot contain /" if environment.to_s.include? "/"
raise ::ArgumentError, "user cannot contain /" if user.to_s.include? "/"
raise ::ArgumentError, "session cannot contain /" if session.to_s.include? "/"
"projects/#{project}/agent/environments/#{environment}/users/#{user}/sessions/#{session}/contexts/#{context}"
end),
"context:location:project:session" => (proc do |project:, location:, session:, context:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/"
raise ::ArgumentError, "session cannot contain /" if session.to_s.include? "/"
"projects/#{project}/locations/#{location}/agent/sessions/#{session}/contexts/#{context}"
end),
"context:environment:location:project:session:user" => (proc do |project:, location:, environment:, user:, session:, context:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/"
raise ::ArgumentError, "environment cannot contain /" if environment.to_s.include? "/"
raise ::ArgumentError, "user cannot contain /" if user.to_s.include? "/"
raise ::ArgumentError, "session cannot contain /" if session.to_s.include? "/"
"projects/#{project}/locations/#{location}/agent/environments/#{environment}/users/#{user}/sessions/#{session}/contexts/#{context}"
end)
}
resource = resources[args.keys.sort.join(":")]
raise ::ArgumentError, "no resource found for values #{args.keys}" if resource.nil?
resource.call(**args)
end
##
# Create a fully-qualified Conversation resource string.
#
# @overload conversation_path(project:, conversation:)
# The resource will be in the following format:
#
# `projects/{project}/conversations/{conversation}`
#
# @param project [String]
# @param conversation [String]
#
# @overload conversation_path(project:, location:, conversation:)
# The resource will be in the following format:
#
# `projects/{project}/locations/{location}/conversations/{conversation}`
#
# @param project [String]
# @param location [String]
# @param conversation [String]
#
# @return [::String]
def conversation_path **args
resources = {
"conversation:project" => (proc do |project:, conversation:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
"projects/#{project}/conversations/#{conversation}"
end),
"conversation:location:project" => (proc do |project:, location:, conversation:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/"
"projects/#{project}/locations/#{location}/conversations/#{conversation}"
end)
}
resource = resources[args.keys.sort.join(":")]
raise ::ArgumentError, "no resource found for values #{args.keys}" if resource.nil?
resource.call(**args)
end
##
# Create a fully-qualified Message resource string.
#
# @overload message_path(project:, conversation:, message:)
# The resource will be in the following format:
#
# `projects/{project}/conversations/{conversation}/messages/{message}`
#
# @param project [String]
# @param conversation [String]
# @param message [String]
#
# @overload message_path(project:, location:, conversation:, message:)
# The resource will be in the following format:
#
# `projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}`
#
# @param project [String]
# @param location [String]
# @param conversation [String]
# @param message [String]
#
# @return [::String]
def message_path **args
resources = {
"conversation:message:project" => (proc do |project:, conversation:, message:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "conversation cannot contain /" if conversation.to_s.include? "/"
"projects/#{project}/conversations/#{conversation}/messages/#{message}"
end),
"conversation:location:message:project" => (proc do |project:, location:, conversation:, message:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/"
raise ::ArgumentError, "conversation cannot contain /" if conversation.to_s.include? "/"
"projects/#{project}/locations/#{location}/conversations/#{conversation}/messages/#{message}"
end)
}
resource = resources[args.keys.sort.join(":")]
raise ::ArgumentError, "no resource found for values #{args.keys}" if resource.nil?
resource.call(**args)
end
##
# Create a fully-qualified Participant resource string.
#
# @overload participant_path(project:, conversation:, participant:)
# The resource will be in the following format:
#
# `projects/{project}/conversations/{conversation}/participants/{participant}`
#
# @param project [String]
# @param conversation [String]
# @param participant [String]
#
# @overload participant_path(project:, location:, conversation:, participant:)
# The resource will be in the following format:
#
# `projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}`
#
# @param project [String]
# @param location [String]
# @param conversation [String]
# @param participant [String]
#
# @return [::String]
def participant_path **args
resources = {
"conversation:participant:project" => (proc do |project:, conversation:, participant:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "conversation cannot contain /" if conversation.to_s.include? "/"
"projects/#{project}/conversations/#{conversation}/participants/#{participant}"
end),
"conversation:location:participant:project" => (proc do |project:, location:, conversation:, participant:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/"
raise ::ArgumentError, "conversation cannot contain /" if conversation.to_s.include? "/"
"projects/#{project}/locations/#{location}/conversations/#{conversation}/participants/#{participant}"
end)
}
resource = resources[args.keys.sort.join(":")]
raise ::ArgumentError, "no resource found for values #{args.keys}" if resource.nil?
resource.call(**args)
end
##
# Create a fully-qualified SessionEntityType resource string.
#
# @overload session_entity_type_path(project:, session:, entity_type:)
# The resource will be in the following format:
#
# `projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}`
#
# @param project [String]
# @param session [String]
# @param entity_type [String]
#
# @overload session_entity_type_path(project:, location:, session:, entity_type:)
# The resource will be in the following format:
#
# `projects/{project}/locations/{location}/agent/sessions/{session}/entityTypes/{entity_type}`
#
# @param project [String]
# @param location [String]
# @param session [String]
# @param entity_type [String]
#
# @overload session_entity_type_path(project:, environment:, user:, session:, entity_type:)
# The resource will be in the following format:
#
# `projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/entityTypes/{entity_type}`
#
# @param project [String]
# @param environment [String]
# @param user [String]
# @param session [String]
# @param entity_type [String]
#
# @overload session_entity_type_path(project:, location:, environment:, user:, session:, entity_type:)
# The resource will be in the following format:
#
# `projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/entityTypes/{entity_type}`
#
# @param project [String]
# @param location [String]
# @param environment [String]
# @param user [String]
# @param session [String]
# @param entity_type [String]
#
# @return [::String]
def session_entity_type_path **args
resources = {
"entity_type:project:session" => (proc do |project:, session:, entity_type:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "session cannot contain /" if session.to_s.include? "/"
"projects/#{project}/agent/sessions/#{session}/entityTypes/#{entity_type}"
end),
"entity_type:location:project:session" => (proc do |project:, location:, session:, entity_type:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/"
raise ::ArgumentError, "session cannot contain /" if session.to_s.include? "/"
"projects/#{project}/locations/#{location}/agent/sessions/#{session}/entityTypes/#{entity_type}"
end),
"entity_type:environment:project:session:user" => (proc do |project:, environment:, user:, session:, entity_type:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "environment cannot contain /" if environment.to_s.include? "/"
raise ::ArgumentError, "user cannot contain /" if user.to_s.include? "/"
raise ::ArgumentError, "session cannot contain /" if session.to_s.include? "/"
"projects/#{project}/agent/environments/#{environment}/users/#{user}/sessions/#{session}/entityTypes/#{entity_type}"
end),
"entity_type:environment:location:project:session:user" => (proc do |project:, location:, environment:, user:, session:, entity_type:|
raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/"
raise ::ArgumentError, "environment cannot contain /" if environment.to_s.include? "/"
raise ::ArgumentError, "user cannot contain /" if user.to_s.include? "/"
raise ::ArgumentError, "session cannot contain /" if session.to_s.include? "/"
"projects/#{project}/locations/#{location}/agent/environments/#{environment}/users/#{user}/sessions/#{session}/entityTypes/#{entity_type}"
end)
}
resource = resources[args.keys.sort.join(":")]
raise ::ArgumentError, "no resource found for values #{args.keys}" if resource.nil?
resource.call(**args)
end
extend self
end
end
end
end
end
end
|
import mongoose from 'mongoose';
const TransactionSchema = new mongoose.Schema({
text: {
type: String,
trim: true,
required: [true, 'Please add some text'],
},
amount: {
type: Number,
required: [true, 'Please add a positive or negative number'],
},
createdAt: {
type: Date,
default: Date.now,
},
});
const Transaction = mongoose.model('Transaction', TransactionSchema);
export default Transaction;
|
def calculate_area(base, height):
return (1/2) * base * height |
SELECT * FROM `users` WHERE `country` = 'United States' |
#!/bin/sh
set -e
ROOTDIR=dist
BUNDLE=${ROOTDIR}/Altair-Qt.app
CODESIGN=codesign
TEMPDIR=sign.temp
TEMPLIST=${TEMPDIR}/signatures.txt
OUT=signature.tar.gz
if [ ! -n "$1" ]; then
echo "usage: $0 <codesign args>"
echo "example: $0 -s MyIdentity"
exit 1
fi
rm -rf ${TEMPDIR} ${TEMPLIST}
mkdir -p ${TEMPDIR}
${CODESIGN} -f --file-list ${TEMPLIST} "$@" "${BUNDLE}"
for i in `grep -v CodeResources ${TEMPLIST}`; do
TARGETFILE="${BUNDLE}/`echo ${i} | sed "s|.*${BUNDLE}/||"`"
SIZE=`pagestuff $i -p | tail -2 | grep size | sed 's/[^0-9]*//g'`
OFFSET=`pagestuff $i -p | tail -2 | grep offset | sed 's/[^0-9]*//g'`
SIGNFILE="${TEMPDIR}/${TARGETFILE}.sign"
DIRNAME="`dirname ${SIGNFILE}`"
mkdir -p "${DIRNAME}"
echo "Adding detached signature for: ${TARGETFILE}. Size: ${SIZE}. Offset: ${OFFSET}"
dd if=$i of=${SIGNFILE} bs=1 skip=${OFFSET} count=${SIZE} 2>/dev/null
done
for i in `grep CodeResources ${TEMPLIST}`; do
TARGETFILE="${BUNDLE}/`echo ${i} | sed "s|.*${BUNDLE}/||"`"
RESOURCE="${TEMPDIR}/${TARGETFILE}"
DIRNAME="`dirname "${RESOURCE}"`"
mkdir -p "${DIRNAME}"
echo "Adding resource for: "${TARGETFILE}""
cp "${i}" "${RESOURCE}"
done
rm ${TEMPLIST}
tar -C ${TEMPDIR} -czf ${OUT} .
rm -rf ${TEMPDIR}
echo "Created ${OUT}"
|
#pragma once
class CExtendAudioFrameObserver :
public agora::media::IAudioFrameObserver
{
public:
CExtendAudioFrameObserver();
~CExtendAudioFrameObserver();
LPBYTE pPlayerData;
int nPlayerDataLen;
bool bDebug;
virtual bool onRecordAudioFrame(AudioFrame& audioFrame);
virtual bool onPlaybackAudioFrame(AudioFrame& audioFrame);
virtual bool onMixedAudioFrame(AudioFrame& audioFrame);
virtual bool onPlaybackAudioFrameBeforeMixing(unsigned int uid, AudioFrame& audioFrame);
};
|
from unihan_db.tables import (
UnhnLocation,
UnhnLocationkXHC1983,
UnhnReading,
kCantonese,
kCCCII,
kCheungBauer,
kCheungBauerIndex,
kCihaiT,
kDaeJaweon,
kDefinition,
kFenn,
kFennIndex,
kGSR,
kHanYu,
kHanyuPinlu,
kHanyuPinyin,
kHDZRadBreak,
kIICore,
kIICoreSource,
kUnihanCore2020,
kIRG_GSource,
kIRG_HSource,
kIRG_JSource,
kIRG_KPSource,
kIRG_KSource,
kIRG_MSource,
kIRG_TSource,
kIRG_USource,
kIRG_VSource,
kIRG_SSource,
kIRG_UKSource,
kIRGDaeJaweon,
kIRGHanyuDaZidian,
kIRGKangXi,
kMandarin,
kRSAdobe_Japan1_6,
kRSJapanese,
kRSKangXi,
kRSKanWa,
kRSKorean,
kRSUnicode,
kSBGY,
kTotalStrokes,
kXHC1983,
kTGHZ2013,
kSimplifiedVariant,
kTraditionalVariant,
kSpoofingVariant,
kZVariant,
kSemanticVariant,
kSpecializedSemanticVariant,
UnhnVariantSource,
SemanticVariantSource
)
def import_char(c, char): # NOQA: C901
if 'kDefinition' in char:
for d in char['kDefinition']:
c.kDefinition.append(kDefinition(definition=d))
if 'kCantonese' in char:
for d in char['kCantonese']:
c.kCantonese.append(kCantonese(definition=d))
if 'kCCCII' in char:
for d in char['kCCCII']:
c.kCCCII.append(kCCCII(hex=d))
if 'kMandarin' in char:
d = char['kMandarin']
c.kMandarin.append(kMandarin(hans=d['zh-Hans'], hant=d['zh-Hant']))
if 'kTotalStrokes' in char:
d = char['kTotalStrokes']
c.kTotalStrokes.append(kTotalStrokes(hans=d['zh-Hans'], hant=d['zh-Hant']))
if 'kHanyuPinyin' in char:
for d in char['kHanyuPinyin']:
k = kHanyuPinyin()
for loc in d['locations']:
k.locations.append(
UnhnLocation(
volume=loc['volume'],
page=loc['page'],
character=loc['character'],
virtual=loc['virtual'],
)
)
for reading in d['readings']:
k.readings.append(UnhnReading(reading=reading))
c.kHanyuPinyin.append(k)
if 'kHanYu' in char:
k = kHanYu()
for d in char['kHanYu']:
k.locations.append(
UnhnLocation(
volume=d['volume'],
page=d['page'],
character=d['character'],
virtual=d['virtual'],
)
)
c.kHanYu.append(k)
if 'kIRGHanyuDaZidian' in char:
for d in char['kIRGHanyuDaZidian']:
k = kIRGHanyuDaZidian()
k.locations.append(
UnhnLocation(
volume=d['volume'],
page=d['page'],
character=d['character'],
virtual=d['virtual'],
)
)
c.kIRGHanyuDaZidian.append(k)
if 'kXHC1983' in char:
for d in char['kXHC1983']:
k = kXHC1983()
for loc in d['locations']:
k.locations.append(
UnhnLocationkXHC1983(
page=loc['page'],
character=loc['character'],
entry=loc['entry'],
substituted=loc['substituted'],
)
)
k.readings.append(UnhnReading(reading=d['reading']))
c.kXHC1983.append(k)
if 'kTGHZ2013' in char:
for d in char['kTGHZ2013']:
k = kTGHZ2013()
for loc in d['locations']:
k.locations.append(
UnhnLocation(
page=loc['page'],
character=loc['character'],
)
)
k.readings.append(UnhnReading(reading=d['reading']))
c.kTGHZ2013.append(k)
if 'kCheungBauer' in char:
for d in char['kCheungBauer']:
k = kCheungBauer(
radical=d['radical'], strokes=d['strokes'], cangjie=d['cangjie']
)
for reading in d['readings']:
k.readings.append(UnhnReading(reading=reading))
c.kCheungBauer.append(k)
if 'kRSAdobe_Japan1_6' in char:
for d in char['kRSAdobe_Japan1_6']:
c.kRSAdobe_Japan1_6.append(
kRSAdobe_Japan1_6(
type=d['type'],
cid=d['cid'],
radical=d['radical'],
strokes=d['strokes'],
strokes_residue=d['strokes-residue'],
)
)
if 'kCihaiT' in char:
for d in char['kCihaiT']:
c.kCihaiT.append(
kCihaiT(page=d['page'], row=d['row'], character=d['character'])
)
if 'kIICore' in char:
for d in char['kIICore']:
k = kIICore(priority=d['priority'])
for s in d['sources']:
k.sources.append(kIICoreSource(source=s))
c.kIICore.append(k)
if 'kUnihanCore2020' in char:
for s in char['kUnihanCore2020']:
c.kUnihanCore2020.append(kUnihanCore2020(source=s))
if 'kDaeJaweon' in char:
k = kDaeJaweon()
d = char['kDaeJaweon']
k.locations.append(
UnhnLocation(page=d['page'], character=d['character'], virtual=d['virtual'])
)
c.kDaeJaweon.append(k)
if 'kIRGKangXi' in char:
k = kIRGKangXi()
for d in char['kIRGKangXi']:
k.locations.append(
UnhnLocation(
page=d['page'], character=d['character'], virtual=d['virtual']
)
)
c.kIRGKangXi.append(k)
if 'kIRGDaeJaweon' in char:
k = kIRGDaeJaweon()
for d in char['kIRGDaeJaweon']:
k.locations.append(
UnhnLocation(
page=d['page'], character=d['character'], virtual=d['virtual']
)
)
c.kIRGDaeJaweon.append(k)
if 'kFenn' in char:
for d in char['kFenn']:
c.kFenn.append(kFenn(phonetic=d['phonetic'], frequency=d['frequency']))
if 'kHanyuPinlu' in char:
for d in char['kHanyuPinlu']:
c.kHanyuPinlu.append(
kHanyuPinlu(phonetic=d['phonetic'], frequency=d['frequency'])
)
if 'kHDZRadBreak' in char:
d = char['kHDZRadBreak']
k = kHDZRadBreak(radical=d['radical'], ucn=d['ucn'])
k.locations.append(
UnhnLocation(
volume=d['location']['volume'],
page=d['location']['page'],
character=d['location']['character'],
virtual=d['location']['virtual'],
)
)
c.kHDZRadBreak.append(k)
if 'kSBGY' in char:
for d in char['kSBGY']:
k = kSBGY()
k.locations.append(UnhnLocation(page=d['page'], character=d['character']))
c.kSBGY.append(k)
rs_fields = ( # radical-stroke fields, since they're the same structure
('kRSUnicode', kRSUnicode, c.kRSUnicode),
('kRSJapanese', kRSJapanese, c.kRSJapanese),
('kRSKangXi', kRSKangXi, c.kRSKangXi),
('kRSKanWa', kRSKanWa, c.kRSKanWa),
('kRSKorean', kRSKorean, c.kRSKorean),
)
for f, model, column in rs_fields:
if f in char:
for d in char[f]:
k = model(
radical=d['radical'],
strokes=d['strokes'],
simplified=d['simplified'],
)
column.append(k)
irg_fields = ( # IRG, since they're the same structure
('kIRG_GSource', kIRG_GSource, c.kIRG_GSource),
('kIRG_HSource', kIRG_HSource, c.kIRG_HSource),
('kIRG_JSource', kIRG_JSource, c.kIRG_JSource),
('kIRG_KPSource', kIRG_KPSource, c.kIRG_KPSource),
('kIRG_KSource', kIRG_KSource, c.kIRG_KSource),
('kIRG_MSource', kIRG_MSource, c.kIRG_MSource),
('kIRG_TSource', kIRG_TSource, c.kIRG_TSource),
('kIRG_USource', kIRG_USource, c.kIRG_USource),
('kIRG_VSource', kIRG_VSource, c.kIRG_VSource),
('kIRG_SSource', kIRG_SSource, c.kIRG_SSource),
('kIRG_UKSource', kIRG_UKSource, c.kIRG_UKSource),
)
for f, model, column in irg_fields:
if f in char:
d = char[f]
k = model(source=d['source'], location=d['location'])
column.append(k)
if 'kGSR' in char:
for d in char['kGSR']:
k = kGSR(set=d['set'], letter=d['letter'], apostrophe=d['apostrophe'])
c.kGSR.append(k)
if 'kCheungBauerIndex' in char:
d = char['kCheungBauerIndex']
k = kCheungBauerIndex()
k.locations.append(
UnhnLocation(
page=d['location']['page'], character=d['location']['character']
)
)
c.kCheungBauerIndex.append(k)
if 'kFennIndex' in char:
d = char['kFennIndex']
k = kFennIndex()
k.locations.append(
UnhnLocation(
page=d['location']['page'], character=d['location']['character']
)
)
c.kFennIndex.append(k)
simple_variant_fields = (
('kSimplifiedVariant', kSimplifiedVariant, c.kSimplifiedVariant),
('kTraditionalVariant', kTraditionalVariant, c.kTraditionalVariant),
('kSpoofingVariant', kSpoofingVariant, c.kSpoofingVariant),
)
for f, model, column in simple_variant_fields:
if f in char:
for d in char[f]:
column.append(model(ucn=d))
sourced_variant_fields = (
('kZVariant', kZVariant, c.kZVariant, UnhnVariantSource),
('kSemanticVariant', kSemanticVariant, c.kSemanticVariant, SemanticVariantSource),
('kSpecializedSemanticVariant', kSpecializedSemanticVariant, c.kSpecializedSemanticVariant, SemanticVariantSource),
)
for f, model, column, source_model in sourced_variant_fields:
if f in char:
for d in char[f]:
m = model(ucn=d['ucn'])
for s in d.get('sources', []):
m.sources.append(source_model(**s))
column.append(m)
|
package com.datasift.client.pylon;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PylonSampleInteractionParent {
@JsonProperty
protected String subtype;
@JsonProperty
protected String content;
public PylonSampleInteractionParent() { }
public String getSubtype() { return this.subtype; }
public String getContent() { return this.content; }
}
|
import numpy as np
import scipy.spatial.distance
def compute_connection_matrix_and_edges(P0, n_neighbour):
D0 = scipy.spatial.distance.cdist(P0, P0)
C0 = np.zeros(D0.shape, dtype=int)
S0 = []
for i in range(len(P0)):
nearest_neighbors = np.argsort(D0[i])[1:n_neighbour+1]
for j in nearest_neighbors:
C0[i, j] = 1 # Set the connection between points i and j to 1
S0.append((i, j)) # Add the edge (i, j) to the list of edges
return C0, S0 |
/*!
* \file Peripheral.c
*
* copyright Revised BSD License, see section \ref LICENSE
*
* copyright (c) 2020, <NAME> <EMAIL>
*
**************************************************************************************/
#include <stdio.h>
#include <string.h>
#include "Peripheral.h"
#include "utilities.h"
#include "device.h"
#include "device-config.h"
#include "LoRaLink.h"
#if defined(ABZ78_R)
static Gpio_t EzGpios[7] = { 0 };
static PinNames EzPinNames[7] = { GPIO_0, GPIO_1, GPIO_2, GPIO_3, GPIO_4, SWCLK, SWDIO };
#else
static Gpio_t EzGpios[8] = { 0 };
static PinNames EzPinNames[8] = { GPIO_0, GPIO_1, GPIO_2, GPIO_3, GPIO_4, GPIO_5, SWCLK, SWDIO };
#endif
static I2c_t* pDeviceI2c;
static Spi_t* pDeviceSpi;
/**
* Calculate free SRAM
*/
int getFreeRam(void)
{
extern char __bss_end__;
int freeMemory;
freeMemory = ((int)&freeMemory) - ((int)&__bss_end__);
return freeMemory;
}
void PeriphInit(void)
{
pDeviceI2c = DeviceGetI2c();
pDeviceSpi = DeviceGetSpi();
}
void SetUartBaudrate( uint32_t baudrate )
{
DeviceSetBaudeRate(baudrate);
}
uint8_t WriteI2c( uint8_t deviceAddr, uint16_t addr, uint8_t *buffer, uint16_t size )
{
deviceAddr = deviceAddr << 1;
return I2cWriteBuffer( pDeviceI2c, deviceAddr, addr, buffer, size );
}
uint8_t ReadI2c( uint8_t deviceAddr, uint16_t addr, uint8_t *buffer, uint16_t size )
{
deviceAddr = deviceAddr << 1;
return I2cReadBuffer( pDeviceI2c, deviceAddr, addr, buffer, size );
}
uint16_t ReadWriteSpi( uint16_t outData )
{
return SpiInOut( pDeviceSpi, outData );
}
void InitGpio( PortNo_t no, PinModes mode, PinConfigs config, PinTypes type )
{
GpioInit( &EzGpios[no], EzPinNames[no], mode, config, type, 0 );
}
void WriteGpio( PortNo_t no, uint32_t value )
{
GpioWrite( &EzGpios[no], value );
}
void ToggleGpio( PortNo_t no )
{
GpioToggle( &EzGpios[no] );
}
uint32_t ReadGpio( PortNo_t no )
{
return GpioRead( &EzGpios[no] );
}
uint16_t ReadAdcVoltage( AdcCh_t ch )
{
uint32_t channel = ch == CH0 ? ADC_CHANNEL_2 : ADC_CHANNEL_3;
uint16_t millVolt = DeviceAdcMeasureVoltage(channel);
return (uint16_t)millVolt;
}
uint16_t ReadAdc( AdcCh_t ch )
{
uint32_t channel = ch == CH0 ? ADC_CHANNEL_2 : ADC_CHANNEL_3;
uint16_t millVolt = DeviceAdcMeasureValue(channel);
return (uint16_t)millVolt;
}
uint16_t ReadVdd( void )
{
return DeviceMeasureVdd();
}
int16_t GetRssi( void )
{
return LoRaLinkGetRssi();
}
int8_t GetSnr( void )
{
return LoRaLinkGetSnr();
}
|
<reponame>DispatchMe/meteor-bound-document<gh_stars>1-10
describe('BoundDocument', function () {
var c = new Mongo.Collection('widgets');
c.attachSchema({
name: {type: String},
one: {
type: Object,
optional: true
},
'one.two': {
type: Object,
optional: true
},
'one.two.three': {
type: String,
optional: true
}
});
c.allow({
insert: function () { return true; },
update: function () { return true; },
remove: function () { return true; }
});
beforeEach(function () {
c.remove({_id: '1'});
c.insert({_id: '1', name: 'foo'});
});
it('gets and sets property values', function () {
var doc = c.findOne('1', {bind: true});
expect(doc.name).toEqual('foo');
expect(doc.one.two.three).toBeUndefined();
doc.name = 'name';
doc.one.two.three = 'bar';
// immediately updated
expect(doc.name).toEqual('name');
expect(doc.one.two.three).toEqual('bar');
// still updated after another retrieve
doc = c.findOne('1');
expect(doc.name).toEqual('name');
expect(doc.one.two.three).toEqual('bar');
});
describe('collection.findOne', function () {
it('returns a normal document without bind option', function () {
var doc = c.findOne('1');
expect(doc instanceof BoundDocument).toEqual(false);
});
it('returns a bound document with bind option', function () {
var doc = c.findOne('1', {bind: true});
expect(doc instanceof BoundDocument).toEqual(true);
});
it('returns undefined when there is no document with bind option', function () {
var doc = c.findOne('2', {bind: true});
expect(doc).toBeUndefined();
});
});
describe('cursor.fetch', function () {
it('returns a normal document without bind option', function () {
var doc = c.find('1').fetch()[0];
expect(doc instanceof BoundDocument).toEqual(false);
});
it('returns a bound document with bind option', function () {
var doc = c.find('1', {bind: true}).fetch()[0];
expect(doc instanceof BoundDocument).toEqual(true);
});
});
describe('cursor.forEach', function () {
it('returns a normal document without bind option', function () {
c.find('1').forEach(function (doc) {
expect(doc instanceof BoundDocument).toEqual(false);
});
});
it('returns a bound document with bind option', function () {
c.find('1', {bind: true}).forEach(function (doc) {
expect(doc instanceof BoundDocument).toEqual(true);
});
});
});
describe('cursor.map', function () {
it('returns a normal document without bind option', function () {
c.find('1').map(function (doc) {
expect(doc instanceof BoundDocument).toEqual(false);
});
});
it('returns a bound document with bind option', function () {
c.find('1', {bind: true}).map(function (doc) {
expect(doc instanceof BoundDocument).toEqual(true);
});
});
});
});
|
#!/bin/bash
set -e
# Import Secret ##########
mkdir /root/.ssh
chmod 700 /root/.ssh
cat /etc/secret-volume/id_rsa > /root/.ssh/id_rsa
cat /etc/secret-volume/authorized_keys > /root/.ssh/authorized_keys
chmod 600 /root/.ssh/id_rsa
chmod 600 /root/.ssh/authorized_keys
chown -R root:root /root/.ssh
##########################
# Setup backgroud service #
/usr/bin/supervisord -c /etc/supervisor/supervisord.conf
sleep 2
x11vnc -display :11 -passwd "$VNCPASS" -xkb -forever &
sleep 2
###########################
exec "$@"
|
#!/bin/bash
docker-compose run --no-deps --rm wpcli "$@" |
def dec_to_binary(number):
return bin(number)[2:]
binary = dec_to_binary(17)
print(binary) # 10001 |
<filename>api_resources.py
# coding=utf-8
import csv
import json
import time
import treetagger
import treetagger_wordnet
class Resources:
"""Sentimentwordnet bindind class
This class provides a binding to lookup sentiment meassure for
English and Spanish words
"""
def __init__(self):
"""
Initialite datastructures
"""
self.map_lenguage = {"english": "en",
"spanish": "sp",
"italian": "it",
"portuguese": "pt",
"french": "fr",
"catalan": "ct"}
"""
Init TreeTagger
"""
# Init treetagger with a specific language
self.treetagger_english = treetagger.TreeTagger(encoding='latin-1', language="english")
self.treetagger_spanish = treetagger.TreeTagger(encoding='utf8', language="spanish")
self.treetagger_italian = treetagger.TreeTagger(encoding='utf8', language="italian")
self.treetagger_portuguese = treetagger.TreeTagger(encoding='latin-1', language="portuguese")
self.treetagger_french = treetagger.TreeTagger(encoding='utf8', language="french")
self.tt_to_wordnet = treetagger_wordnet.TreetaggerToWordnet()
"""
Load domains
"""
self.domains = {}
f_in = file("data/domains/wordnet-domains30.txt", "r")
for line in f_in:
line = line.replace("\n", "")
chunks = line.split("\t")
self.domains[chunks[0]] = chunks[1].split(' ')
f_in.close()
"""
Load affects
"""
self.affects = {}
f_in = file("data/affects/wn-affect-1.1-30.txt", "r")
for line in f_in:
line = line.replace("\n", "")
chunks = line.split("\t")
self.affects[chunks[0]] = chunks[1].split(' ')
f_in.close()
"""
Load senti
"""
self.senti = {}
f_in = file("data/senti/senti.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
chunks = line.split("\t")
self.senti[chunks[2] + '#' + chunks[0]] = {}
self.senti[chunks[2] + '#' + chunks[0]]["positive"] = chunks[3]
self.senti[chunks[2] + '#' + chunks[0]]["negative"] = chunks[1]
self.senti[chunks[2] + '#' + chunks[0]]["objective"] = 1 - abs(float(chunks[3][1:]) + float(chunks[1][1:]))
f_in.close()
"""
Load words_en
"""
self.words_en = {}
f_in = file("data/words/en.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
line = line.replace("\r", "")
chunks = line.split("\t")
self.words_en[chunks[0]] = {}
self.words_en[chunks[0]]["word"] = chunks[1]
self.words_en[chunks[0]]["pos"] = chunks[2]
self.words_en[chunks[0]]["synsets"] = chunks[3].split(' ')
f_in.close()
"""
Load words_sp
"""
self.words_sp = {}
f_in = file("data/words/sp.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
line = line.replace("\r", "")
chunks = line.split("\t")
self.words_sp[chunks[0]] = {}
self.words_sp[chunks[0]]["word"] = chunks[1]
self.words_sp[chunks[0]]["pos"] = chunks[2]
self.words_sp[chunks[0]]["synsets"] = chunks[3].split(' ')
f_in.close()
"""
Load words_it
"""
self.words_it = {}
f_in = file("data/words/it.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
line = line.replace("\r", "")
chunks = line.split("\t")
self.words_it[chunks[0]] = {}
self.words_it[chunks[0]]["word"] = chunks[1]
self.words_it[chunks[0]]["pos"] = chunks[2]
self.words_it[chunks[0]]["synsets"] = chunks[3].split(' ')
f_in.close()
"""
Load words_pt
"""
self.words_pt = {}
f_in = file("data/words/pt.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
line = line.replace("\r", "")
chunks = line.split("\t")
self.words_pt[chunks[0]] = {}
self.words_pt[chunks[0]]["word"] = chunks[1]
self.words_pt[chunks[0]]["pos"] = chunks[2]
self.words_pt[chunks[0]]["synsets"] = chunks[3].split(' ')
f_in.close()
"""
Load words_fr
"""
self.words_fr = {}
f_in = file("data/words/fr.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
line = line.replace("\r", "")
chunks = line.split("\t")
self.words_fr[chunks[0]] = {}
self.words_fr[chunks[0]]["word"] = chunks[1]
self.words_fr[chunks[0]]["pos"] = chunks[2]
self.words_fr[chunks[0]]["synsets"] = chunks[3].split(' ')
f_in.close()
"""
Load words_ct
"""
self.words_ct = {}
f_in = file("data/words/ct.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
line = line.replace("\r", "")
chunks = line.split("\t")
self.words_ct[chunks[0]] = {}
self.words_ct[chunks[0]]["word"] = chunks[1]
self.words_ct[chunks[0]]["pos"] = chunks[2]
self.words_ct[chunks[0]]["synsets"] = chunks[3].split(' ')
f_in.close()
"""
Load synsets_en
"""
self.synsets_en = {}
f_in = file("data/synsets/en.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
line = line.replace("\r", "")
chunks = line.split("\t")
self.synsets_en[chunks[0]] = {}
self.synsets_en[chunks[0]]["synset"] = chunks[1]
self.synsets_en[chunks[0]]["pos"] = chunks[2]
self.synsets_en[chunks[0]]["meaning"] = chunks[3]
self.synsets_en[chunks[0]]["words"] = chunks[4].split(' ')
f_in.close()
"""
Load synsets_sp
"""
self.synsets_sp = {}
f_in = file("data/synsets/sp.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
chunks = line.split("\t")
self.synsets_sp[chunks[0]] = chunks[1].split(' ')
f_in.close()
"""
Load synsets_it
"""
self.synsets_it = {}
f_in = file("data/synsets/it.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
chunks = line.split("\t")
self.synsets_it[chunks[0]] = chunks[1].split(' ')
f_in.close()
"""
Load synsets_pt
"""
self.synsets_pt = {}
f_in = file("data/synsets/pt.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
chunks = line.split("\t")
self.synsets_pt[chunks[0]] = chunks[1].split(' ')
f_in.close()
"""
Load synsets_fr
"""
self.synsets_fr = {}
f_in = file("data/synsets/fr.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
chunks = line.split("\t")
self.synsets_fr[chunks[0]] = chunks[1].split(' ')
f_in.close()
"""
Load synsets_ct
"""
self.synsets_ct = {}
f_in = file("data/synsets/ct.tsv", "r")
for line in f_in:
line = line.replace("\n", "")
chunks = line.split("\t")
self.synsets_ct[chunks[0]] = chunks[1].split(' ')
f_in.close()
def get_senti(self, synset, pos):
if pos + '#' + synset in self.senti:
return self.senti[pos + '#' + synset]
else:
return None
def get_domain(self, synset, pos):
if pos + '#' + synset in self.domains:
return self.domains[pos + '#' + synset]
else:
return None
def get_affect(self, synset, pos):
if pos + '#' + synset in self.affects:
return self.affects[pos + '#' + synset]
else:
return None
def get_meaning(self, synset, pos):
if pos + '#' + synset in self.synsets_en:
return self.synsets_en[pos + '#' + synset]["meaning"]
else:
return None
def has_senti(self, synset, pos):
if pos + '#' + synset in self.senti:
return True
else:
return False
def has_domain(self, synset, pos):
if pos + '#' + synset in self.domains:
return True
else:
return False
def has_affect(self, synset, pos):
if pos + '#' + synset in self.affects:
return True
else:
return False
def has_word(self, word, pos, language):
if pos + '#' + word in self.words_en:
return True
else:
return False
def get_first_synset(self, word, pos, language):
if pos is None or word is None:
return None
lan = self.map_lenguage[language]
if lan == "en":
if pos + '#' + word in self.words_en:
return self.words_en[pos + '#' + word]["synsets"][0]
else:
return None
if lan == "sp":
if pos + '#' + word in self.words_sp:
return self.words_sp[pos + '#' + word]["synsets"][0]
else:
return None
if lan == "it":
if pos + '#' + word in self.words_it:
return self.words_it[pos + '#' + word]["synsets"][0]
else:
return None
if lan == "pt":
if pos + '#' + word in self.words_pt:
return self.words_pt[pos + '#' + word]["synsets"][0]
else:
return None
if lan == "fr":
if pos + '#' + word in self.words_fr:
return self.words_fr[pos + '#' + word]["synsets"][0]
else:
return None
if lan == "ct":
if pos + '#' + word in self.words_ct:
return self.words_ct[pos + '#' + word]["synsets"][0]
else:
return None
else:
return None
def get_words(self, synset, pos, language):
lan = self.map_lenguage[language]
if lan == "en":
if pos + '#' + synset in self.synsets_en:
return self.synsets_en[pos + '#' + synset]["words"]
else:
return None
if lan == "sp":
if pos + '#' + synset in self.synsets_sp:
return self.synsets_sp[pos + '#' + synset]
else:
return None
if lan == "it":
if pos + '#' + synset in self.synsets_it:
return self.synsets_it[pos + '#' + synset]
else:
return None
if lan == "pt":
if pos + '#' + synset in self.synsets_pt:
return self.synsets_pt[pos + '#' + synset]
else:
return None
if lan == "fr":
if pos + '#' + synset in self.synsets_fr:
return self.synsets_fr[pos + '#' + synset]
else:
return None
if lan == "ct":
if pos + '#' + synset in self.synsets_ct:
return self.synsets_ct[pos + '#' + synset]
else:
return None
else:
return None
def get_info(self, synset, pos):
result = {}
result["meaning"] = self.get_meaning(synset, pos)
result["synset"] = synset
result["pos"] = pos
result["domain"] = self.get_domain(synset, pos)
result["affect"] = self.get_affect(synset, pos)
result["sentiment"] = self.get_senti(synset, pos)
result["english_words"] = self.get_words(synset, pos, "english")
result["spanish_words"] = self.get_words(synset, pos, "spanish")
result["italian_words"] = self.get_words(synset, pos, "italian")
result["portuguese_words"] = self.get_words(synset, pos, "portuguese")
result["french_words"] = self.get_words(synset, pos, "french")
result["catalan_words"] = self.get_words(synset, pos, "catalan")
return result
def get_postagging(self, text, language):
# Perform PosTagging
response = []
if language == "english":
for postag in self.treetagger_english.tag(text):
element = {}
# Word
element["word"] = postag[0]
# Postaging
element["postagging"] = postag[1]
# Wordnet postagging mapping
element["pos"] = self.tt_to_wordnet.wordnet_morph_category(self.map_lenguage[language], postag[1])
# Lemma
element["lemma"] = postag[2]
response.append(element)
if language == "spanish":
for postag in self.treetagger_spanish.tag(text):
element = {}
# Word
element["word"] = postag[0]
# Postaging
element["postagging"] = postag[1]
# Wordnet postagging mapping
element["pos"] = self.tt_to_wordnet.wordnet_morph_category(self.map_lenguage[language], postag[1])
# Lemma
element["lemma"] = postag[2]
response.append(element)
if language == "italian":
for postag in self.treetagger_italian.tag(text):
element = {}
# Word
element["word"] = postag[0]
# Postaging
element["postagging"] = postag[1]
# Wordnet postagging mapping
element["pos"] = self.tt_to_wordnet.wordnet_morph_category(self.map_lenguage[language], postag[1])
# Lemma
element["lemma"] = postag[2]
response.append(element)
if language == "portuguese":
for postag in self.treetagger_portuguese.tag(text):
element = {}
# Word
element["word"] = postag[0]
# Postaging
element["postagging"] = postag[1]
# Wordnet postagging mapping
element["pos"] = self.tt_to_wordnet.wordnet_morph_category(self.map_lenguage[language], postag[1])
# Lemma
element["lemma"] = postag[2]
response.append(element)
if language == "french":
for postag in self.treetagger_french.tag(text):
element = {}
# Word
element["word"] = postag[0]
# Postaging
element["postagging"] = postag[1]
# Wordnet postagging mapping
element["pos"] = self.tt_to_wordnet.wordnet_morph_category(self.map_lenguage[language], postag[1])
# Lemma
element["lemma"] = postag[2]
response.append(element)
if language == "catalan":
response.append("Sorry, we don't have a Catalan Treetagger")
return response
def get_translation(self, word, pos, from_language, to_language):
lang_from = self.map_lenguage[from_language]
lang_to = self.map_lenguage[to_language]
# Assert input params
assert (lang_from in ["sp", "en", "it", "pt", "fr", "ct"])
assert (lang_to in ["sp", "en", "it", "pt", "fr", "ct"])
synset = self.get_first_synset(word, pos, from_language)
if synset is not None:
return self.get_words(synset, pos, to_language)
else:
return None
def get_synonym(self, word, pos, language):
synset = self.get_first_synset(word, pos, language)
if synset is not None:
return self.get_words(synset, pos, language)
else:
return None
def get_affect_text(self, text, language):
affects = {}
affects["affects"] = {}
affects["words"] = {}
for word in text:
synset = self.get_first_synset(word["word"], word["pos"], language)
if synset is not None:
if self.has_affect(synset, word["pos"]):
affect = self.get_affect(synset, word["pos"])
element = {}
element["word"] = word["word"]
element["pos"] = word["pos"]
element["synset"] = synset
element["domains"] = affect
for af in affect:
if af not in affects["affects"].keys():
affects["affects"][af] = 1
else:
affects["affects"][af] += 1
affects["words"][word["word"]] = element
return affects
def get_affects(self, text, language):
posttext = self.get_postagging(text, language)
return self.get_affect_text(posttext, language)
def get_domains_text(self, text, language):
result = {}
result["dommains"] = {}
result["words"] = {}
for word in text:
synset = self.get_first_synset(word["word"], word["pos"], language)
if synset is not None:
if self.has_domain(synset, word["pos"]):
dommain = self.get_domain(synset, word["pos"])
element = {}
element["word"] = word["word"]
element["pos"] = word["pos"]
element["synset"] = synset
element["domains"] = dommain
for af in dommain:
if af not in result["dommains"].keys():
result["dommains"][af] = 1
else:
result["dommains"][af] += 1
result["words"][word["word"]] = element
return result
def get_domains(self, text, language):
posttext = self.get_postagging(text, language)
return self.get_domains_text(posttext, language)
def get_info_word(self, word, pos, language):
if pos is None or word is None:
return None
lan = self.map_lenguage[language]
if lan == "en":
if pos + '#' + word in self.words_en:
synsets = self.words_en[pos + '#' + word]["synsets"]
else:
return None
if lan == "sp":
if pos + '#' + word in self.words_sp:
synsets = self.words_sp[pos + '#' + word]["synsets"]
else:
return None
if lan == "it":
if pos + '#' + word in self.words_it:
synsets = self.words_it[pos + '#' + word]["synsets"]
else:
return None
if lan == "pt":
if pos + '#' + word in self.words_pt:
synsets = self.words_pt[pos + '#' + word]["synsets"]
else:
return None
if lan == "fr":
if pos + '#' + word in self.words_fr:
synsets = self.words_fr[pos + '#' + word]["synsets"]
else:
return None
if lan == "ct":
if pos + '#' + word in self.words_ct:
synsets = self.words_ct[pos + '#' + word]["synsets"]
else:
return None
results = {}
for synset in synsets:
results[synset+'#'+pos] = self.get_info(synset, pos)
return results
def get_sentiment_text(self, text, language):
sentiment = {}
sentiment["words"] = {}
sentiment["positive"] = 0
sentiment["negative"] = 0
for word in text:
synset = self.get_first_synset(word["lemma"], word["pos"], language)
if synset is not None:
if self.has_senti(synset, word["pos"]):
senti = self.get_senti(synset, word["pos"])
sentiment["positive"] = sentiment["positive"] + float(senti["positive"][1:])
sentiment["negative"] = sentiment["negative"] + float(senti["negative"][1:])
if senti["positive"] != "+0" or senti["negative"] != "-0":
senti["synset"] = synset
senti["pos"] = word["pos"]
sentiment["words"][word["lemma"]] = senti
return sentiment
def get_sentiment_and_emotion(self, text, language):
sentiment = {}
sentiment_result = self.get_sentiment(text, language)
affect_result = self.get_affects(text, language)
sentiment["sentiment"] = sentiment_result["positive"] - sentiment_result["negative"]
# sentiment["positive"] = sentiment_result["positive"]
# sentiment["negative"] = sentiment_result["negative"]
# sentiment["affects"] = affect_result["affects"] if 'affects' in affect_result.keys() else []
affects = affect_result.get("affects", {})
if affects:
max_affect = max(affects, key=affects.get)
sentiment["emotion"] = max_affect
else:
sentiment["emotion"] = ""
return sentiment
def get_sentiment(self, text, language):
posttext = self.get_postagging(text, language)
return self.get_sentiment_text(posttext, language)
def get_info_first_word(self, word, pos, language):
synset = self.get_first_synset(word, pos, language)
return self.get_info(synset, pos)
if __name__ == "__main__":
# Init class
time_start = time.time()
sentiwordnet = Resources()
print("Loaded time: %s\n" % (time.time() - time_start))
# Some lookups
# words = [("unfortunately", "r", "english"), ("desafortunadamente", "r", "spanish"),
# ("exuberant", "a", "english"), ("stressful", "a", "english"), ("comfortably", "r", "english"),
# ("violación", "n", "spanish")]
#
# for word, pos, language in words:
# time_start = time.time()
# a = sentiwordnet.get_info(word, pos)
# print("%s %s" % (word, a))
# print("Lookup time: %s \n" % (time.time() - time_start))
#
# print("***INFO DE UN SYNSET***")
# print(sentiwordnet.get_info("00042769", "r"))
# print("***TRADUCCION DE UNA PALABRA***")
# print(sentiwordnet.get_translation("good", "n", "english", "spanish"))
# print(sentiwordnet.get_translation("diorama", "n", "spanish", "english"))
# print("***SINÓNIMOS DE UNA PALABRA***")
# print(sentiwordnet.get_synonym("good", "n", "english"))
# print(sentiwordnet.get_synonym("diorama", "n", "spanish"))
# print(sentiwordnet.get_sentiment([{"word": "buy", "pos": "v"}, {"word": "new", "pos": "r"}], "english"))
# print(sentiwordnet.get_postagging("I am a good boy", "english"))
# print(sentiwordnet.get_affects("amado amado amado", "spanish"))
# print("***INFO DE UNA PALABRA***")
# print(sentiwordnet.get_info_word("good","n","english"))
print("***INFO DE UN SYNSET***")
print(sentiwordnet.get_info("14441825","n"))
# print(sentiwordnet.get_sentiment(
# "Cuando <NAME> se despertó una mañana después de un sueño intranquilo, se encontró sobre su cama convertido en un monstruoso insecto. Estaba tumbado sobre su espalda dura, y en forma de caparazón y, al levantar un poco la cabeza veía un vientre abombado, parduzco, dividido por partes duras en forma de arco, sobre cuya protuberancia apenas podía mantenerse el cobertor, a punto ya de resbalar al suelo. Sus muchas patas, ridículamente pequeñas en comparación con el resto de su tamaño, le vibraban desamparadas ante los ojos.",
# "spanish"))
# print(sentiwordnet.get_sentiment("Ogni individuo ha diritto all'istruzione. L'istruzione deve essere gratuita almeno per quanto riguarda le classi elementari e fondamentali. L'istruzione elementare deve essere obbligatoria. L'istruzione tecnica e professionale deve essere messa alla portata di tutti e l'istruzione superiore deve essere egualmente accessibile a tutti sulla base del merito.", "italian")) |
<reponame>ExternalRepositories/mesytec-mvlc
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/sock_diag.h>
#include <linux/inet_diag.h>
#include <arpa/inet.h>
#include <iostream>
using std::cerr;
using std::cout;
using std::endl;
static int
send_query(int fd)
{
struct sockaddr_nl nladdr = {
.nl_family = AF_NETLINK
};
struct NetlinkDiagMessage
{
struct nlmsghdr nlh;
struct inet_diag_req_v2 diagReq;
};
NetlinkDiagMessage req = {};
req.nlh.nlmsg_len = sizeof(req);
req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_MATCH;
req.diagReq.sdiag_family = AF_INET;
req.diagReq.sdiag_protocol = IPPROTO_UDP;
req.diagReq.idiag_ext = (1u << (INET_DIAG_SKMEMINFO - 1));
req.diagReq.pad = 0;
req.diagReq.idiag_states = 0xffffffffu; // All states (0 filters out all sockets).
// Filter by dest port to reduce the number of results.
req.diagReq.id.idiag_dport = htons(0x8001);
struct iovec iov = {
.iov_base = &req,
.iov_len = sizeof(req)
};
struct msghdr msg = {
.msg_name = (void *) &nladdr,
.msg_namelen = sizeof(nladdr),
.msg_iov = &iov,
.msg_iovlen = 1
};
for (;;) {
if (sendmsg(fd, &msg, 0) < 0) {
if (errno == EINTR)
continue;
perror("sendmsg");
return -1;
}
return 0;
}
}
static int
print_diag(const struct inet_diag_msg *diag, unsigned int len)
{
if (len < NLMSG_LENGTH(sizeof(*diag))) {
fputs("short response\n", stderr);
return -1;
}
if (diag->idiag_family != AF_INET) {
fprintf(stderr, "unexpected family %u\n", diag->idiag_family);
return -1;
}
printf("diag: state=%u, timer=%u, retrans=%u\n",
diag->idiag_state, diag->idiag_timer, diag->idiag_retrans);
printf(" id.sport=%u, id.dport=%u\n",
ntohs(diag->id.idiag_sport), ntohs(diag->id.idiag_dport));
char srcAddr[50] = { 0 };
char dstAddr[50] = { 0 };
strcpy(srcAddr, inet_ntoa(*(struct in_addr *)diag->id.idiag_src));
strcpy(dstAddr, inet_ntoa(*(struct in_addr *)diag->id.idiag_dst));
printf(" id.idiag_src=%s, id.idiag_dst=%s\n",
srcAddr, dstAddr);
printf(" rqueue=%u, wqueue=%u\n",
diag->idiag_rqueue, diag->idiag_wqueue);
printf(" uid=%u, inode=%u\n",
diag->idiag_uid, diag->idiag_inode);
struct rtattr *attr = nullptr;
unsigned int rta_len = len - NLMSG_LENGTH(sizeof(*diag));
unsigned int peer = 0;
size_t path_len = 0;
char path[sizeof(((struct sockaddr_un *) 0)->sun_path) + 1];
struct inet_diag_meminfo memInfo = {};
for (attr = (struct rtattr *) (diag + 1);
RTA_OK(attr, rta_len);
attr = RTA_NEXT(attr, rta_len))
{
printf("attr->rta_type=%u\n", attr->rta_type);
switch (attr->rta_type) {
case INET_DIAG_MEMINFO:
if (RTA_PAYLOAD(attr) >= sizeof(memInfo))
{
memInfo = *(const inet_diag_meminfo *) RTA_DATA(attr);
printf("INET_DIAG_MEMINFO: rmem=%u, wmem=%u, fmem=%u, tmem=%u\n",
memInfo.idiag_rmem,
memInfo.idiag_wmem,
memInfo.idiag_fmem,
memInfo.idiag_tmem);
}
break;
case INET_DIAG_SKMEMINFO:
if (RTA_PAYLOAD(attr) >= sizeof(uint32_t) * SK_MEMINFO_VARS)
{
const uint32_t *memInfo = (const uint32_t *) RTA_DATA(attr);
printf("INET_DIAG_SKMEMINFO: rmem_alloc=%u, rcvbuf=%u,"
"wmem_alloc=%u, sndbuf=%u, fwd_alloc=%u, wmem_queued=%u,"
"optmem=%u, backlog=%u\n",
memInfo[SK_MEMINFO_RMEM_ALLOC],
memInfo[SK_MEMINFO_RCVBUF],
memInfo[SK_MEMINFO_WMEM_ALLOC],
memInfo[SK_MEMINFO_SNDBUF],
memInfo[SK_MEMINFO_FWD_ALLOC],
memInfo[SK_MEMINFO_WMEM_QUEUED],
memInfo[SK_MEMINFO_OPTMEM],
memInfo[SK_MEMINFO_BACKLOG]);
}
break;
#if 0
case UNIX_DIAG_NAME:
if (!path_len) {
path_len = RTA_PAYLOAD(attr);
if (path_len > sizeof(path) - 1)
path_len = sizeof(path) - 1;
memcpy(path, RTA_DATA(attr), path_len);
path[path_len] = '\0';
}
break;
case UNIX_DIAG_PEER:
if (RTA_PAYLOAD(attr) >= sizeof(peer))
peer = *(unsigned int *) RTA_DATA(attr);
break;
#endif
}
}
//printf("inode=%u", diag->udiag_ino);
if (peer)
printf(", peer=%u", peer);
if (path_len)
printf(", name=%s%s", *path ? "" : "@",
*path ? path : path + 1);
putchar('\n');
return 0;
}
static int
receive_responses(int fd)
{
long buf[8192 / sizeof(long)];
struct sockaddr_nl nladdr = {
.nl_family = AF_NETLINK
};
struct iovec iov = {
.iov_base = buf,
.iov_len = sizeof(buf)
};
int flags = 0;
for (;;) {
struct msghdr msg = {
.msg_name = (void *) &nladdr,
.msg_namelen = sizeof(nladdr),
.msg_iov = &iov,
.msg_iovlen = 1
};
ssize_t ret = recvmsg(fd, &msg, flags);
if (ret < 0) {
if (errno == EINTR)
continue;
perror("recvmsg");
return -1;
}
if (ret == 0)
return 0;
const struct nlmsghdr *h = (struct nlmsghdr *) buf;
if (!NLMSG_OK(h, ret)) {
fputs("!NLMSG_OK\n", stderr);
return -1;
}
for (; NLMSG_OK(h, ret); h = NLMSG_NEXT(h, ret)) {
if (h->nlmsg_type == NLMSG_DONE)
{
fputs("NLMSG_DONE\n", stderr);
return 0;
}
if (h->nlmsg_type == NLMSG_ERROR) {
const struct nlmsgerr *err = (const struct nlmsgerr *) NLMSG_DATA(h);
if (h->nlmsg_len < NLMSG_LENGTH(sizeof(*err))) {
fputs("NLMSG_ERROR\n", stderr);
} else {
errno = -err->error;
perror("NLMSG_ERROR");
}
return -1;
}
if (h->nlmsg_type != SOCK_DIAG_BY_FAMILY) {
fprintf(stderr, "unexpected nlmsg_type %u\n",
(unsigned) h->nlmsg_type);
return -1;
}
if (print_diag((const inet_diag_msg *) NLMSG_DATA(h), h->nlmsg_len))
return -1;
}
}
}
int
main(void)
{
/*
printf("some rta_type values:"
"INET_DIAG_TOS=%u,"
"INET_DIAG_TCLASS=%u,"
"INET_DIAG_MEMINFO=%u,"
"INET_DIAG_SKMEMINFO=%u,"
"INET_DIAG_INFO=%u,"
"INET_DIAG_CONG=%u\n",
INET_DIAG_TOS,
INET_DIAG_TCLASS,
INET_DIAG_MEMINFO,
INET_DIAG_SKMEMINFO,
INET_DIAG_INFO,
INET_DIAG_CONG);
*/
int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_SOCK_DIAG);
if (fd < 0) {
perror("socket");
return 1;
}
int ret = send_query(fd) || receive_responses(fd);
close(fd);
return ret;
}
|
<filename>src/test/java/de/lmu/cis/ocrd/ml/test/MockBaseOCRToken.java<gh_stars>1-10
package de.lmu.cis.ocrd.ml.test;
import de.lmu.cis.ocrd.ml.BaseOCRToken;
import de.lmu.cis.ocrd.ml.OCRWord;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class MockBaseOCRToken implements BaseOCRToken {
private int nOCR;
private List<MockOCRWord> words;
public MockBaseOCRToken(int nOCR) {
this.nOCR = nOCR;
this.words = new ArrayList<>();
}
public MockBaseOCRToken addWord(MockOCRWord word) {
words.add(word);
return this;
}
@Override
public String getID() {
return "**MOCK**ID**";
}
@Override
public int getNOCR() {
return nOCR;
}
@Override
public OCRWord getMasterOCR() {
if (words.isEmpty()) {
throw new RuntimeException("cannot access master ocr word: empty");
}
return words.get(0);
}
@Override
public OCRWord getSlaveOCR(int i) {
if ((i+1) >= words.size()) {
throw new RuntimeException("cannot access master slave ocr: " + i);
}
return words.get(i+1);
}
@Override
public Optional<String> getGT() {
if (words.size() > nOCR) {
return Optional.of(words.get(nOCR).getWordRaw());
}
return Optional.empty();
}
@Override
public void correct(String correction, double confidence, boolean take) {
throw new RuntimeException("correct: not implemented");
}
}
|
#!/bin/bash
# Get the pid file's name.
PIDFILE="pidfile.pid"
# Kill the process running at pid.
if [ -e $PIDFILE ]; then
kill "$(cat $PIDFILE 2>/dev/null)"
fi
# Write our pid to file.
echo $$ >$PIDFILE
# Run command.
node bin/www > hotlink.log
|
package core.checker.linearizability;
import core.checker.checker.Operation;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.Locale;
import java.util.Objects;
@Slf4j
@Data
@NoArgsConstructor
public class Op extends Operation {
private int process;
private Type type;
private F f;
private Object value;
private int index = -1;
private int entryId = -1;
private Object m;
private double start;
private double end;
public Op(int process, F f, int value, double start, double end) {
this.process = process;
this.f = f;
this.value = value;
this.start = start;
this.end = end;
}
public Op(int process, F f, Type type, Object value) {
this.process = process;
this.f = f;
this.type = type;
this.value = value;
}
public Op(int process, F f, Type type, Object value, int index) {
this.process = process;
this.f = f;
this.type = type;
this.value = value;
this.index = index;
}
public Op(Object process, Object f, Object type, Object value) {
if (process instanceof Number) {
this.process = Integer.parseInt(process.toString());
} else {
this.process = -1;
}
this.f = F.valueOf(f.toString().substring(1).toUpperCase(Locale.ROOT));
this.type = Type.valueOf(type.toString().substring(1).toUpperCase(Locale.ROOT));
this.value = value;
}
public Op(Op op) {
this.process = op.getProcess();
this.f = op.getF();
this.type = op.getType();
this.value = op.getValue();
this.index = op.getIndex();
}
public Op(Operation op){
this.process = op.getProcess();
this.f = op.getF();
this.type = op.getType();
this.value = op.getValue();
this.index = op.getIndex();
}
// public Op(core.record.Operation op) {
// this.process = Integer.parseInt(op.getRequestId().toString() + op.getThreadId().toString());
// ActionEnum action = op.getAction();
// if (action == ActionEnum.InvokeOperation) {
// this.type = Type.INVOKE;
// RWRequest data = (RWRequest) op.getData();
// if (data.getAction().equals("read")) {
// this.f = F.READ;
// } else if (data.getAction().equals("write")) {
// this.f = F.WRITE;
// }
// this.value = data.getValue();
// } else if (action == ActionEnum.ResponseOperation) {
// ClientInvokeResponse data = (ClientInvokeResponse) op.getData();
// if (data.isSuccess()) {
// this.type = Type.OK;
// } else {
// this.type = Type.FAIL;
// }
// this.value = data.getNewState();
// }
// }
@Override
public String toString() {
return "Op{" +
"process=" + process +
", type=" + type +
", f=" + f +
", value=" + value +
", index=" + index +
", entryId=" + entryId +
", m=" + m +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Op op = (Op) o;
return process == op.process && index == op.index&& type == op.type && f == op.f && Objects.equals(value, op.value);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), process, type, f, value, index);
}
}
|
import React from "react";
import API from "../utils/API";
import SearchBar from "./SearchBar";
//Search Results table in Act 19 is = table.js -Namita
class Table extends React.Component {
state = {
employees: [],
search: "",
ascending: true
};
// When this component mounts, search the API for random users
componentDidMount() {
this.searchEmployee();
}
searchEmployee = () => {
API.search()
.then(res => {
// console.log("API results", res.data.results)
this.setState({ employees: res.data.results })
}
)
.catch(err => console.log(err));
};
handleInputChange = event => {
const name = event.target.name;
const value = event.target.value;
this.setState({ [name]: value });
};
//Filtering Employees
handleFormSubmit = event => {
// Preventing the default behavior of the form submit (which is to refresh the page)
event.preventDefault();
console.log(this.state.search)
const filteredEmp = this.state.employees.filter(employee =>
employee.name.first.toLowerCase() === this.state.search.toLowerCase() ||
employee.name.last.toLowerCase() === this.state.search.toLowerCase()
)
console.log("Filtered Emp", filteredEmp);
//updating the employee state variable with the new filtered value. The original employee state value came from the API call and componantDidMount()
this.setState({ employees: filteredEmp })
//reset Values
if (this.state.search === "") {
this.searchEmployee()
}
};
sortEmployees = event => {
event.preventDefault();
console.log(this.state.ascending)
if (this.state.ascending === true) {
this.setState({ ascending: false })
} else {
this.setState({ ascending: true })
}
const sortedList = this.state.employees.sort((a, b) => {
//In case of Ascending
if (this.state.ascending === true) {
if (a.name.first < b.name.first) {
return -1;
}
if (a.name.first > b.name.first) {
return 1;
}
return 0;
}else {
//In case of Descending
if (a.name.first < b.name.first) {
return 1;
}
if (a.name.first > b.name.first) {
return -1;
}
return 0;
}
})
console.log("Sort List:", sortedList)
}
render() {
return (
<div>
<SearchBar
search={this.state.search}
handleFormSubmit={this.handleFormSubmit}
handleInput={this.handleInputChange}
/>
<hr />
<table className="table table-dark">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">First<span onClick={this.sortEmployees}> ▽ </span></th>
<th scope="col">Last</th>
<th scope="col">Email</th>
<th scope="col">DOB</th>
</tr>
</thead>
<tbody>
{this.state.employees.map((employee, index) => (
<tr id={index} key={index}>
<th scope="row">{index + 1}</th>
<td>{employee.name.first}</td>
<td>{employee.name.last}</td>
<td>{employee.email}</td>
<td>{employee.dob.date.substring(0, 10)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default Table; |
def count_ways_to_reach_stair(n):
a = [0 for i in range(n + 1)]
a[0] = 1
a[1] = 1
a[2] = 2
for i in range(3, n + 1):
a[i] = a[i - 1] + a[i - 2] + a[i - 3]
return a[n] |
<reponame>maevic/atom-watcher
'use strict';
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var Task = require('atom').Task;
var Convert = require('ansi-to-html');
var convert;
var isWindows = /^win/.test(process.platform);
var WatcherView = require('./atom-watcher-view.js');
var CompositeDisposable = require('atom').CompositeDisposable;
var cwd = path.resolve(__dirname, '..');
var projectDirectory;
var Watcher = function() {
this.watcher = null;
this.watcherView = null;
this.subscriptions = null;
this.running = false;
this.configPath = '';
this.panel = null;
};
Watcher.prototype = {
activate: function(state) {
this.watcherView = new WatcherView(state.viewState);
this.panel = atom.workspace.addBottomPanel({
item: this.watcherView.getElement()
});
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.commands.add('atom-workspace', {
'atom-watcher:start': (function(self) {
return function() {
return self.start();
};
})(this)
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'atom-watcher:toggle': function(self) {
return function() {
return self.toggle();
};
}(this),
'atom-watcher:toggle-output': function(self) {
return function() {
return self.watcherView.toggle();
}
}(this)
}));
atom.emitter.on('atom-watcher:createConfig', (function(self) {
return function() {
var configPath = self.getConfigPath();
try {
fs.statSync(configPath);
} catch (e) {
fs.createReadStream(cwd + '/misc/defaultConfig.js').pipe(fs.createWriteStream(configPath));
atom.notifications.addSuccess('atom-watcher', {
detail: 'Configuration file was successfully created: ' + configPath,
dismissable: true
});
}
atom.workspace.open(configPath);
};
})(this));
atom.emitter.on('atom-watcher:shown', (function(self) {
return function() {
if (!convert) {
convert = new Convert({
fg: self.watcherView.getTextColor()
});
}
}
})(this));
atom.styles.onDidUpdateStyleElement((function(self) {
return function() {
convert = new Convert({
fg: self.watcherView.getTextColor()
});
}
})(this));
if (atom.config.get('atom-watcher.autoStart')) {
this.start();
}
if (this.watcherView.visible) {
this.watcherView.show();
} else {
this.watcherView.hide();
}
return this;
},
serialize: function() {
return {
viewState: this.watcherView.serialize()
};
},
deactivate: function() {
if (this.watcher && !this.watcher.killed) {
this.watcher.kill();
}
if (this.statusBarIcon) {
this.statusBarIcon.destroy();
}
if (this.panel) {
this.panel.destroy();
}
},
consumeStatusBar: function(statusBar) {
this.statusBarIcon = statusBar.addLeftTile({
item: this.watcherView.getStatusBarIcon(),
priority: 100
});
},
start: function() {
if (this.running) {
this.stop();
}
this.configPath = this.getConfigPath();
try {
fs.statSync(this.configPath);
} catch (e) {
this.watcherView.appendText('No configuration file was found. The searched path was »' + this.configPath + '«.');
return false;
}
process.chdir(projectDirectory); // Make sure that the spawned children operate in the right direcotry.
this.watcher = spawn(atom.config.get('atom-watcher.nodeExecutable'), [
cwd + '/bin/atom-watcher.js',
this.configPath,
'--color'
]);
var self = this;
this.watcher.on('error', function() {
var errorText = 'NodeJS could not be started. Please make sure you have node in your global path variable.';
self.watcherView.appendText(errorText);
atom.notifications.addError('atom-watcher', {
detail: errorText,
dismissable: true
});
self.running = true;
self.watcherView.setStatus('stopped');
});
this.watcher.stdout.on('data', function(buffer) {
self.watcherView.appendText('<pre>' + convert.toHtml(buffer.toString()) + '</pre>');
});
this.watcher.stderr.on('data', function(buffer) {
self.watcherView.appendText('<pre>' + convert.toHtml(buffer.toString()) + '</pre>');
});
this.watcher.on('error', function() {
console.log('ERROR', arguments);
});
this.watcher.on('exit', function(code) {
self.watcherView.appendText('<br />The watcher exited with code ' + code + '<br />');
self.watcher = null;
self.running = false;
self.watcherView.setStatus('stopped');
});
this.running = true;
this.watcherView.setStatus('started');
return true;
},
stop: function() {
if (this.watcher) {
this.watcher.kill();
}
this.watcher = null;
this.running = false;
this.watcherView.setStatus('stopped');
},
toggle: function() {
if (!this.running) {
if (!this.start()) {
atom.notifications.addWarning('atom-watcher', {
detail: 'No configuration file was found. The searched path was »' + this.configPath + '«.',
dismissable: true
});
}
} else {
this.stop();
}
},
getConfigPath: function() {
if (!projectDirectory) {
var paths = atom.project.getPaths();
if (!paths.length) {
return '';
}
projectDirectory = paths[0];
}
var configFileName = atom.config.get('atom-watcher.configFileName');
var configPath;
if (!isWindows && configFileName.indexOf('/') === 0 || isWindows && configFileName.indexOf(':') === 1) { // Path is absolute
configPath = configFileName;
} else { // Path is relative
configPath = projectDirectory + path.sep + configFileName;
}
return configPath;
}
};
module.exports = new Watcher();
module.exports.config = {
autoStart: {
title: 'Automatic start',
description: 'The watcher looks for a config file and starts automatically if it finds one.',
type: 'boolean',
default: false
},
configFileName: {
title: 'Configuration file name',
description: 'Either relative to the project directory or absolute.',
type: 'string',
default: 'watcherConfig.js'
},
nodeExecutable: {
title: 'Node executable',
description: 'Mac user please type the full path to your node executable.',
type: 'string',
default: 'node'
}
};
|
#!/bin/sh
# create image based jail in FreeBSD 7
# This script is obsolete
# Source: http://blog.sleeplessbeastie.eu/2011/03/16/how-to-do-some-work-in-each-active-jail/
ezjail="/usr/local/bin/ezjail-admin"
tail="/usr/bin/tail"
temp_file=`mktemp -q /tmp/jcreate.XXXXXX`
usage() {
echo "Usage:"
echo "jcreate.sh name ip size"
}
if [ "${#}" != "3" ]; then
usage
else
name=$1
ip=$2
size=$3
${ezjail} create -i -s ${size} -f default ${name} ${ip} > ${temp_file} 2>&1
if [ "${?}" -eq "0" ]; then
echo "Jail ${name} with address ${ip} and size ${size} created."
echo "Log filename: ${temp_file}"
else
echo "There was an error"
echo "Log filename: ${temp_file}"
tail ${temp_file}
fi
fi
|
tac ~/.surf/history* | dmenu -l 10 -b -i | cut -d ' ' -f 3
|
#!/usr/bin/env sh
# Script to export a release
set -e
mkdir -p ./release
space /_cmdline/ -e SPACE_MUTE_EXIT_MESSAGE=1 -d >./release/podc
chmod +x ./release/podc
space -f lib/podman-runtime.yaml /podman/ -e SPACE_MUTE_EXIT_MESSAGE=1 -d >./release/podc-podman-runtime
|
function configure_nomailcheck() {
local -n __var=$1
# stop bash from checking mail
# currently it is not needed anymore since by default
# bash doesn't do mail checking anymore
# References:
# - https://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html#index-MAILCHECK
if [ -n "${MAILCHECK}" ]
then
unset MAILCHECK
__var=0
return
fi
__var=1
}
register_interactive configure_no_mail_check
|
openInEnum = {
CURRENT_TAB : 0,
NEW_TAB : 1,
NEW_BGTAB : 2,
NEW_WINDOW : 3,
}
let openIn = openInEnum.CURRENT_TAB;
chrome.storage.local.get('openIn', item => {
if (item.openIn) {
openIn = item.openIn;
}
});
function logLastError() {
if (chrome.runtime.lastError) {
console.error('Resurrect error:', chrome.runtime.lastError);
}
}
function genGoogleUrl(url) {
return 'https://www.google.com/search?q=cache:' + encodeURIComponent(url);
}
function genGoogleTextUrl(url) {
return 'https://www.google.com/search?strip=1&q=cache:' + encodeURIComponent(url);
}
function genIaUrl(url) {
let dateStr = (new Date()).toISOString().replace(/-|T|:|\..*/g, '');
return 'https://web.archive.org/web/'+dateStr+'/'+url;
}
function genIaListUrl(url) {
let dateStr = (new Date()).toISOString().replace(/-|T|:|\..*/g, '');
return 'https://web.archive.org/web/*/'+url;
}
function genArchiveIsUrl(url) {
return 'https://archive.is/'+url;
}
function genWebCiteUrl(url) {
return 'http://webcitation.org/query.php?url='+encodeURIComponent(url);
}
function genMementoUrl(url) {
let dateStr = (new Date()).toISOString().replace(/-|T|:|\..*/g, '');
return 'http://timetravel.mementoweb.org/list/'
+ dateStr + '/' + encodeURIComponent(url);
}
function setOpenIn(where) {
openIn = where;
chrome.storage.local.set({openIn: openIn}, logLastError);
updateContextRadios();
}
function updateContextRadios() {
['page', 'link'].forEach(context => {
chrome.contextMenus.update(
'resurrect-current-tab-' + context,
{checked: openIn == openInEnum.CURRENT_TAB});
chrome.contextMenus.update(
'resurrect-new-tab-' + context,
{checked: openIn == openInEnum.NEW_TAB});
chrome.contextMenus.update(
'resurrect-bg-tab-' + context,
{checked: openIn == openInEnum.NEW_BGTAB});
chrome.contextMenus.update(
'resurrect-new-window-' + context,
{checked: openIn == openInEnum.NEW_WINDOW});
});
}
function goToUrl(url, where, openerTabId) {
switch(Number(where)) {
case openInEnum.CURRENT_TAB:
chrome.tabs.update({'url': url});
break;
case openInEnum.NEW_TAB:
chrome.tabs.create({'url': url, openerTabId});
break;
case openInEnum.NEW_BGTAB:
chrome.tabs.create({'url': url, 'active': false, openerTabId});
break;
case openInEnum.NEW_WINDOW:
chrome.windows.create({'url': url});
break;
}
}
|
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#! /bin/bash
set -ex
ZONE=us-central1-f
GROUP=frontend-group
TEMPLATE=$GROUP-tmpl
MACHINE_TYPE=f1-micro
STARTUP_SCRIPT=startup-script.sh
IMAGE_FAMILY=ubuntu-1804-lts
IMAGE_PROJECT=ubuntu-os-cloud
SCOPES="userinfo-email,\
logging-write,\
storage-full,\
datastore,\
https://www.googleapis.com/auth/projecthosting"
TAGS=http-server
MIN_INSTANCES=1
MAX_INSTANCES=10
TARGET_UTILIZATION=0.6
SERVICE=frontend-web-service
#
# Instance group setup
#
# First we have to create an instance template.
# This template will be used by the instance group
# to create new instances.
# [START create_template]
gcloud compute instance-templates create $TEMPLATE \
--machine-type $MACHINE_TYPE \
--scopes $SCOPES \
--metadata-from-file startup-script=$STARTUP_SCRIPT \
--image-family $IMAGE_FAMILY \
--image-project $IMAGE_PROJECT \
--tags $TAGS
# [END create_template]
# Create the managed instance group.
# [START create_group]
gcloud compute instance-groups managed \
create $GROUP \
--base-instance-name $GROUP \
--size $MIN_INSTANCES \
--template $TEMPLATE \
--zone $ZONE
# [END create_group]
# [START create_named_port]
gcloud compute instance-groups managed set-named-ports \
$GROUP \
--named-ports http:8080 \
--zone $ZONE
# [END create_named_port]
#
# Load Balancer Setup
#
# A complete HTTP load balancer is structured as follows:
#
# 1) A global forwarding rule directs incoming requests to a target HTTP proxy.
# 2) The target HTTP proxy checks each request against a URL map to determine the
# appropriate backend service for the request.
# 3) The backend service directs each request to an appropriate backend based on
# serving capacity, zone, and instance health of its attached backends. The
# health of each backend instance is verified using either a health check.
#
# We'll create these resources in reverse order:
# service, health check, backend service, url map, proxy.
# Create a health check
# The load balancer will use this check to keep track of which instances to send traffic to.
# Note that health checks will not cause the load balancer to shutdown any instances.
# [START create_health_check]
gcloud compute http-health-checks create ah-health-check \
--request-path /_ah/health
# [END create_health_check]
# Create a backend service, associate it with the health check and instance group.
# The backend service serves as a target for load balancing.
# [START create_backend_service]
gcloud compute backend-services create $SERVICE \
--http-health-checks ah-health-check \
--port-name http \
--global
# [END create_backend-service]
# [START add_backend_service]
gcloud compute backend-services add-backend $SERVICE \
--instance-group $GROUP \
--instance-group-zone $ZONE \
--global
# [END add_backend_service]
# Create a URL map and web Proxy. The URL map will send all requests to the
# backend service defined above.
# [START create_url_map]
gcloud compute url-maps create $SERVICE-map \
--default-service $SERVICE
# [END create_url_map]
# [START create_http_proxy]
gcloud compute target-http-proxies create $SERVICE-proxy \
--url-map $SERVICE-map
# [END create_http_proxy]
# Create a global forwarding rule to send all traffic to our proxy
# [START create_forwarding_rule]
gcloud compute forwarding-rules create $SERVICE-http-rule \
--global \
--target-http-proxy $SERVICE-proxy \
--ports 80
# [END create_forwarding_rule]
#
# Autoscaler configuration
#
# [START set_autoscaling]
gcloud compute instance-groups managed set-autoscaling \
$GROUP \
--max-num-replicas $MAX_INSTANCES \
--target-load-balancing-utilization $TARGET_UTILIZATION \
--zone $ZONE
# [END set_autoscaling]
# [START create_firewall]
gcloud compute firewall-rules create default-allow-http-8080 \
--allow tcp:8080 \
--source-ranges 0.0.0.0/0 \
--target-tags http-server \
--description "Allow port 8080 access to http-server"
# [END create_firewall]
|
cd ../doc
pdflatex annotation_gui.tex
bibtex annotation_gui
pdflatex annotation_gui.tex
pdflatex annotation_gui.tex
pdflatex administration_gui.tex
bibtex administration_gui
pdflatex administration_gui.tex
pdflatex administration_gui.tex
pdflatex installation.tex
bibtex installation
pdflatex installation.tex
pdflatex installation.tex
|
"""
Given a list of integers, create a function that calculates the sum of each integer and returns the sum.
"""
def calc_sum(list_int):
total = 0
for n in list_int:
total += n
return total
if __name__ == '__main__':
list_int = [1, 2, 3, 4, 5]
print(calc_sum(list_int)) # 15 |
<filename>ExtLib/Aurora/Examples/SimpleTest/PhysicsManager.cpp
//
// Copyright (c) 2010-2011 <NAME> and <NAME>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#include "IPhysicsManager.h"
#include "IGameManager.h"
#include "IGameObject.h"
#include "IObjectUtils.h"
#include "ICameraControl.h"
#include "GlobalParameters.h"
#include "../../Common/Math.inl"
#include "../../RuntimeObjectSystem/ObjectInterfacePerModule.h"
#include "../../RuntimeCompiler/IFileChangeNotifier.h"
#include "../../Systems/SystemTable.h"
#include "../../Systems/IEntitySystem.h"
#include "../../Systems/IAssetSystem.h"
#include "../../Systems/ILogSystem.h"
#include "../../RuntimeObjectSystem/ISimpleSerializer.h"
#include "../../Systems/IGUISystem.h"
#include "../../Systems/IGame.h"
#include <assert.h>
#include <limits>
#include <algorithm>
class PhysicsManager: public IPhysicsManager, public IGameEventListener
{
// We have two sets of typedefs here, one for fast access during runtime, and another
// that is used for safe storage during serialization
typedef std::vector<IGameObject*> TGameObjects;
typedef std::vector<ObjectId> TGameObjectIds;
public:
PhysicsManager()
{
m_Objects.resize(EGT_COUNT);
}
virtual ~PhysicsManager()
{
((IGameManager*)IObjectUtils::GetUniqueInterface( "GameManager", IID_IGAMEMANAGER ))->RemoveListener(this);
}
// IObject
virtual void Serialize(ISimpleSerializer *pSerializer)
{
AU_ASSERT(pSerializer);
SERIALIZE(m_fWorldCenteringDist);
SerializeObjectsList( pSerializer );
}
virtual void Init( bool isFirstInit )
{
IGameManager* pGameManager = (IGameManager*)IObjectUtils::GetUniqueInterface( "GameManager", IID_IGAMEMANAGER );
pGameManager->AddListener(this);
float height, width;
PerModuleInterface::g_pSystemTable->pGame->GetWindowSize( width, height );
// Slightly reduce dimensions so object never cross window edges (since their position is in the center of object
width -= 50;
height -= 50;
m_fWorldCenteringDist.SetX( width * width * 0.25f );
m_fWorldCenteringDist.SetZ( height * height * 0.25f );
}
// ~IObject
// IGameEventListener
virtual void OnGameReset()
{
for (int i=0; i<EGT_COUNT; ++i)
{
m_Objects[i].clear();
}
}
virtual void OnGameObjectCreated( IGameObject* pGameObject )
{
m_Objects[pGameObject->GetGameTeam()].push_back( pGameObject );
}
virtual void OnGameObjectAboutToDestroy( IGameObject* pGameObject )
{
TGameObjects& data = m_Objects[pGameObject->GetGameTeam()];
TGameObjects::iterator it = std::find(data.begin(), data.end(), pGameObject);
if (it != data.end())
{
data.erase(it);
}
}
// ~IGameEventListener
// IPhysicsManager
virtual void RequestPositionUpdate( IGameObject* pGameObject, const AUVec3f& desiredPosition, float frameDelta )
{
AUVec3f pos = desiredPosition;
ApplyGameAreaRepulsionField( pGameObject, pos, frameDelta );
ApplyTeamRepulsionFields( pGameObject, pos, frameDelta );
CheckForCollisions( pGameObject, pos, frameDelta );
pGameObject->GetEntity()->SetPosition(pos);
}
virtual bool IsHeadingToGameBounds( const AUVec3f& position, const AUVec3f& velocity ) const
{
float edgeProportion = (position.x * position.x) / m_fWorldCenteringDist.x +
(position.z * position.z) / m_fWorldCenteringDist.z;
return ( edgeProportion > 0.8f && position.Dot(velocity) > cos( M_PI_4 ) );
}
// ~IPhysicsManager
private:
void ApplyGameAreaRepulsionField( IGameObject* pGameObject, AUVec3f& desiredPosition, float frameDelta )
{
float edgeProportion = (desiredPosition.x * desiredPosition.x) / m_fWorldCenteringDist.x +
(desiredPosition.z * desiredPosition.z) / m_fWorldCenteringDist.z;
float forceStart = 0.9f;
if ( edgeProportion > forceStart )
{
float centeringMagnitude = (edgeProportion - forceStart) / (1.0f - forceStart);
AUVec3f dir = (-desiredPosition).GetNormalised(); // Towards center
desiredPosition += dir * pGameObject->GetMaxSpeed() * frameDelta * centeringMagnitude;
}
}
void ApplyTeamRepulsionFields( IGameObject* pGameObject, AUVec3f& desiredPosition, float frameDelta )
{
const AUVec3f& refPos = pGameObject->GetEntity()->GetPosition();
const float refDist = pGameObject->GetCollisionRadius();
const float forceStartMultiplier = 1.5f;
TGameObjects& data = m_Objects[pGameObject->GetGameTeam()];
TGameObjects::iterator it = data.begin();
TGameObjects::iterator itEnd = data.end();
while (it != itEnd)
{
IGameObject* pTeamObject = *it;
if (pTeamObject != pGameObject)
{
const AUVec3f& teamObjectPos = pTeamObject->GetEntity()->GetPosition();
const float minAllowedDist = refDist + pTeamObject->GetCollisionRadius();
const float distSqr = (refPos - teamObjectPos).MagnitudeSqr();
const float forceStart = minAllowedDist * forceStartMultiplier;
if ( distSqr < forceStart * forceStart )
{
float repulsionMagnitude = (forceStart - sqrt(distSqr)) / ( forceStart * ( 1.0f - 1.0f / forceStartMultiplier ) );
AUVec3f dir = (refPos - teamObjectPos).GetNormalised();
desiredPosition += dir * pGameObject->GetMaxSpeed() * frameDelta * repulsionMagnitude;
}
}
++it;
}
}
void CheckForCollisions( IGameObject* pGameObject, AUVec3f& desiredPosition, float frameDelta )
{
const AUVec3f& refPos = pGameObject->GetEntity()->GetPosition();
const float refDist = pGameObject->GetCollisionRadius();
for (int i=0; i<EGT_COUNT; ++i)
{
TGameObjects& data = m_Objects[i];
TGameObjects::iterator it = data.begin();
TGameObjects::iterator itEnd = data.end();
while (it != itEnd)
{
IGameObject* pTestObject = *it;
if (pTestObject != pGameObject)
{
const AUVec3f& testObjectPos = pTestObject->GetEntity()->GetPosition();
float distSqr = (refPos - testObjectPos).MagnitudeSqr();
float minAllowedDist = refDist + pTestObject->GetCollisionRadius();
if ( (distSqr <= minAllowedDist * minAllowedDist) && (pGameObject->GetGameTeam() != pTestObject->GetGameTeam()) )
{
// Set desired position to edge of collision radii
AUVec3f dir = (refPos - testObjectPos).GetNormalised();
desiredPosition = testObjectPos + dir * minAllowedDist;
pTestObject->OnCollision( pGameObject );
pGameObject->OnCollision( pTestObject );
}
}
++it;
}
}
}
void SerializeObjectsList( ISimpleSerializer *pSerializer )
{
std::vector<TGameObjectIds> m_ObjectIds;
if ( !pSerializer->IsLoading() )
{
// Create a collection of ObjectIds that matches m_Objects pointer collection
m_ObjectIds.resize(EGT_COUNT);
for (int i=0; i<EGT_COUNT; ++i)
{
size_t count = m_Objects[i].size();
m_ObjectIds[i].resize( count );
for (size_t j=0; j<count; ++j)
{
m_ObjectIds[i][j] = m_Objects[i][j]->GetObjectId();
}
}
}
SERIALIZE(m_ObjectIds);
if ( pSerializer->IsLoading() )
{
// Rebuild m_objects pointer collection
for (int i=0; i<EGT_COUNT; ++i)
{
size_t count = m_ObjectIds[i].size();
m_Objects[i].clear();
m_Objects[i].resize( count );
for (size_t j=0; j<count; ++j)
{
IGameObject* pGameObject = 0;
IObjectUtils::GetObject( &pGameObject, m_ObjectIds[i][j] );
m_Objects[i][j] = pGameObject;
}
}
}
}
// Private Members
std::vector<TGameObjects> m_Objects; // set of gameobjects separated by team (this is handy for potential field calculations)
AUVec3f m_fWorldCenteringDist;
};
REGISTERCLASS(PhysicsManager);
|
def isPalindrome(string):
left, right = 0, len(string)-1
while right >= left:
if not string[left] == string[right]:
return False
left += 1
right -= 1
return True |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.__PlaygroundIcon = void 0;
var _react = _interopRequireDefault(require("react"));
var _Icon = _interopRequireDefault(require("./Icon"));
var icons = _interopRequireWildcard(require("./md/"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var __PlaygroundIcon = function __PlaygroundIcon() {
return _react.default.createElement("div", {
style: {
color: 'green',
margin: 2,
padding: 4
}
}, Object.keys(icons).map(function (key) {
return _react.default.createElement(_Icon.default, {
icon: icons[key],
size: 42
});
}));
};
exports.__PlaygroundIcon = __PlaygroundIcon; |
<filename>internal/nodearmord/config.go
package nodearmord
import (
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"github.com/spf13/viper"
)
const (
appName = "nodearmor"
configFileName = "settings"
defaultControllerURL = "wss://api.nodearmor.net/"
)
// Config : global configuration store
var config = viper.New()
// LoadConfig : initializes defaults and loads configuration from file if present
func LoadConfig() {
// Config settings
config.SetConfigType("json")
config.SetConfigName(configFileName)
// Config dirs
usr, err := user.Current()
configDir := filepath.Join(usr.HomeDir, fmt.Sprintf(".%s", appName))
_ = os.Mkdir(configDir, os.ModeDir)
config.AddConfigPath(configDir)
// Set defaults
config.SetDefault("ControllerURL", defaultControllerURL)
err = config.ReadInConfig()
if err != nil {
log.Print("configuration file not found. Creating default.")
os.OpenFile(filepath.Join(configDir, fmt.Sprintf("%s.json", configFileName)), os.O_RDONLY|os.O_CREATE, 0666)
err = config.WriteConfig()
if err != nil {
log.Printf("error creating default config file: %s", err)
}
}
}
// WriteConfig : overwrites config file with current values
func WriteConfig() {
err := config.WriteConfig()
if err != nil {
log.Printf("error writing config file: %s", err)
return
}
log.Print("config file written")
}
|
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for RHSA-2015:1945
#
# Security announcement date: 2015-10-27 20:24:53 UTC
# Script generation date: 2017-01-01 21:16:42 UTC
#
# Operating System: Red Hat 7
# Architecture: x86_64
#
# Vulnerable packages fix on version:
# - openshift.x86_64:3.0.2.0-0.git.20.656dc3e.el7ose
# - openshift-clients.x86_64:3.0.2.0-0.git.20.656dc3e.el7ose
# - openshift-master.x86_64:3.0.2.0-0.git.20.656dc3e.el7ose
# - openshift-node.x86_64:3.0.2.0-0.git.20.656dc3e.el7ose
# - openshift-sdn-ovs.x86_64:3.0.2.0-0.git.20.656dc3e.el7ose
# - tuned-profiles-openshift-node.x86_64:3.0.2.0-0.git.20.656dc3e.el7ose
#
# Last versions recommanded by security team:
# - openshift.x86_64:3.0.2.0-0.git.45.423f434.el7ose
# - openshift-clients.x86_64:3.0.2.0-0.git.45.423f434.el7ose
# - openshift-master.x86_64:3.0.2.0-0.git.45.423f434.el7ose
# - openshift-node.x86_64:3.0.2.0-0.git.45.423f434.el7ose
# - openshift-sdn-ovs.x86_64:3.0.2.0-0.git.45.423f434.el7ose
# - tuned-profiles-openshift-node.x86_64:3.0.2.0-0.git.45.423f434.el7ose
#
# CVE List:
# - CVE-2015-5305
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo yum install openshift.x86_64-3.0.2.0 -y
sudo yum install openshift-clients.x86_64-3.0.2.0 -y
sudo yum install openshift-master.x86_64-3.0.2.0 -y
sudo yum install openshift-node.x86_64-3.0.2.0 -y
sudo yum install openshift-sdn-ovs.x86_64-3.0.2.0 -y
sudo yum install tuned-profiles-openshift-node.x86_64-3.0.2.0 -y
|
<gh_stars>1-10
// Utilities for creating global IDs in systems that don't have them.
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _nodeNodeJs = require('./node/node.js');
Object.defineProperty(exports, 'globalIdType', {
enumerable: true,
get: function get() {
return _nodeNodeJs.globalIdType;
}
}); |
import sys
import pygame
# Define constants
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 500
FPS = 60
# Create the window
window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('My Game')
# Create the game variables
is_game_over = False
# Initialize PyGame
pygame.init()
# Main loop
while not is_game_over:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_game_over = True
# Update the game
# Draw the game
# Flip the screen
pygame.display.flip()
# Clean up
pygame.quit()
sys.exit() |
const BACK_END_URL = 'http://localhost:3000/api';
export enum FETCH_STATUS {
ERROR = 1,
NEED_UMBRELLA,
DO_NOT_NEED_UMBRELLA,
}
export default class RequestInterceptor {
#fetchStatus = FETCH_STATUS.NEED_UMBRELLA;
#page = page;
#callBackOnUmbrellaFetch = async (): Promise<void> => Promise.resolve();
start = async (): Promise<void> => {
await this.#page.setRequestInterception(true);
this.#page.on('request', async (interceptedRequest) => {
if (
interceptedRequest.url() ===
`${BACK_END_URL}/needUmbrella?lat=1&lon=2`
) {
await this.#callBackOnUmbrellaFetch();
await interceptedRequest.respond({
headers: {
'access-control-allow-origin': '*',
},
status:
this.#fetchStatus !== FETCH_STATUS.ERROR ? 200 : 400,
body: JSON.stringify({
shouldUseUmbrella:
this.#fetchStatus === FETCH_STATUS.NEED_UMBRELLA,
}),
});
} else {
await interceptedRequest.continue();
}
});
};
setUmbrellaFetchStatus = (umbrellaFetchStatus: FETCH_STATUS): void => {
this.#fetchStatus = umbrellaFetchStatus;
};
setCallBackOnUmbrellaFetch(callback: () => Promise<void>): void {
this.#callBackOnUmbrellaFetch = callback;
}
}
|
<gh_stars>1-10
package com.starbucks.api.service;
import com.starbucks.domain.TbUser;
public interface TbUserService {
/**
* 根据用户名或者邮箱查找用户信息
* @param str
* @return
*/
TbUser get(String str);
/**
* 添加
*
*/
void add(TbUser tbUser);
}
|
<filename>src/main/java/patron/users/guis/edit/UserEditController.java
package patron.users.guis.edit;
import patron.users.guis.edit.controllerExtend._50_StageControllerExtend;
import patron.users.models.User;
/**
* The type User edit controller.
*/
public class UserEditController extends _50_StageControllerExtend {
/**
* Instantiates a new User edit controller.
*
* @param user the user
*/
public UserEditController(User user){
this.user = user;
}
}
|
rm test.txt.scores;
../src/fmpl -i test.txt 2>/dev/null ;
if ! cmp test.txt.scores test.txt.SCORES >/dev/null 2>&1; then
echo "test failed"
else
echo "test ok"
fi
|
<gh_stars>0
package main
import (
"time"
"github.com/YanickJair/intro/exclusion"
)
func main() {
mc := exclusion.New()
go exclusion.RunWriter(&mc, 20)
go exclusion.RunReader(&mc, 20)
go exclusion.RunReader(&mc, 20)
time.Sleep(15 * time.Second)
}
|
<?php
class InvoiceHandler {
private $title;
private $urlManager;
public function __construct($title, $urlManager) {
$this->title = $title;
$this->urlManager = $urlManager;
}
public function submitInvoice() {
return "Your invoice has been submitted, and someone will respond soon.";
}
public function sendEmailConfirmation() {
return "You should receive an email confirmation in a few minutes.";
}
public function generateSubmitAnotherInvoiceURL() {
return $this->urlManager->createURL(['invoice-sub/index']);
}
}
// Example usage
$title = "Invoice for Services";
$urlManager = new UrlManager(); // Assume the existence of the UrlManager class
$invoiceHandler = new InvoiceHandler($title, $urlManager);
echo $invoiceHandler->submitInvoice();
echo $invoiceHandler->sendEmailConfirmation();
echo "You may now close this window, or <a href='" . $invoiceHandler->generateSubmitAnotherInvoiceURL() . "'>submit another invoice</a>";
?> |
/*
UI地址:\\192.168.6.119\产品管理\2_数据支撑\03_UI\职位推荐
引用方法:<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
调用方法:csdn.position.show({
sourceType: "", //博客blog,论坛discussion_topic, 下载 download,问答ask_topic, 个人空间space??, 英雄会hero??, 在线培训 course, csto
tplType: "", //模板类型,
博客详情:blogDetail,
博客专栏:blogSpec,
论坛详情:bbsDetail,
问答详情:askDetail,
个人空间--我的空间:personalSpaceMy,
个人空间--首页:personalSpaceHome,
英雄会--首页:heroHome
英雄会--答题专家组:heroExpert
英雄会--挑战题目详情页:heroFightDetail
英雄会--我的英雄会:heroMy
在线培训--课程分类列表:无
在线培训--课程详情页:eduDetail
搜索:search
下载--我的资源:downMy
下载--下载页和下载详情页:downDetail
CSTO案例库列表:cstoCaseList
CSTO案例详情页:cstoCaseDetail
CSTO我的T台:cstoMy
CSTO项目列表页:cstoProjectList
CSTO项目详情页:cstoProjectDetail
searchType: "", //页面类型,用于搜索函数,detail(详情页) / list(列表页)。
searchKey: "", //搜索关键字,例如博客详情:博文ID,如果是博客专栏:分类字符串。
username: "", //当前登录用户名
containerId: "" //容器DIV的id。
});
举例:
博客详情页
<div id="job_blog_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "blog",
tplType: "blogDetail",
searchType: "detail",
searchKey: "博文ID",
username: "当前登录用户名",
containerId: "job_blog_reco" //容器DIV的id。
});
</script>
</div>
博客专栏页
<div id="job_blog_reco_spec">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "blog",
tplType: "blogSpec",
searchType: "list",
searchKey: "专栏分类字符串",
username: "当前登录用户名",
containerId: "job_blog_reco_spec" //容器DIV的id。
});
</script>
</div>
论坛详情页
<div id="job_bbs_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "discussion_topic",
tplType: "bbsDetail",
searchType: "detail",
searchKey: "贴子ID",
username: "当前登录用户名",
containerId: "job_bbs_reco" //容器DIV的id。
});
</script>
</div>
问答详情页
<div id="job_ask_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "ask_topic",
tplType: "askDetail",
searchType: "detail",
searchKey: "问题ID",
username: "当前登录用户名",
containerId: "job_ask_reco" //容器DIV的id。
});
</script>
</div>
个人空间--我的空间
<div id="job_myspace_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "my",
tplType: "personalSpaceMy",
searchType: "list",
searchKey: "NO",
username: "当前登录用户名",
containerId: "job_myspace_reco" //容器DIV的id。
});
</script>
</div>
个人空间--首页
<div id="job_myhome_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "my",
tplType: "personalSpaceHome",
searchType: "list",
searchKey: "NO",
username: "当前登录用户名",
containerId: "job_myhome_reco" //容器DIV的id。
});
</script>
</div>
英雄会-首页,正在发生的下面。
http://hero.csdn.net/
<div id="job_yx_home_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "hero",
tplType: "heroHome",
searchType: "list",
searchKey: "NO",
username: "当前登录用户名",
containerId: "job_yx_home_reco" //容器DIV的id。
});
</script>
</div>
英雄会--答题专家组,审题专家组下面。
http://hero.csdn.net/Examine/Apply
<div id="job_yx_expert_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "hero",
tplType: "heroExpert",
searchType: "list",
searchKey: "NO",
username: "当前登录用户名",
containerId: "job_yx_expert_reco" //容器DIV的id。
});
</script>
</div>
英雄会--挑战题目详情页,发布公司下面。
http://hero.csdn.net/OnlineCompiler/Index?ID=10646&ExamID=10649&from=4
<div id="job_yx_fight_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "hero",
tplType: "heroFightDetail",
searchType: "list",
searchKey: "NO",
username: "当前登录用户名",
containerId: "job_yx_fight_reco" //容器DIV的id。
});
</script>
</div>
英雄会--我的英雄会,列表的下面。
http://hero.csdn.net/Exam/List
<div id="job_yx_my_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "hero",
tplType: "heroMy",
searchType: "list",
searchKey: "NO",
username: "当前登录用户名",
containerId: "job_yx_my_reco" //容器DIV的id。
});
</script>
</div>
在线培训--课程分类列表
<div id="job_edu_detail_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "course",
tplType: "eduDetail",
searchType: "list",
searchKey: "页面上的搜索类型",
username: "当前登录用户名",
containerId: "job_edu_detail_reco" //容器DIV的id。
});
</script>
</div>
在线培训--课程详情页,在右侧推荐课程下边。
http://edu.csdn.net/course/detail/326
<div id="job_edu_detail_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "course",
tplType: "eduDetail",
searchType: "detail",
searchKey: "课程ID",
username: "当前登录用户名",
containerId: "job_edu_detail_reco" //容器DIV的id。
});
</script>
</div>
搜索
http://so.csdn.net/so/search/s.do?q=java
<div id="job_search_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "all(该关键字暂时不被使用)",
tplType: "search",
searchType: "list",
searchKey: "搜索关键字",
username: "当前登录用户名",
containerId: "job_search_reco" //容器DIV的id。
});
</script>
</div>
下载--我的资源
http://so.csdn.net/so/search/s.do?q=java
<div id="job_down_my_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "download",
tplType: "downMy",
searchType: "list",
searchKey: "NO",
username: "当前登录用户名",
containerId: "job_down_my_reco" //容器DIV的id。
});
</script>
</div>
下载--下载页和下载详情页
http://so.csdn.net/so/search/s.do?q=java
<div id="job_down_detail_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "download",
tplType: "downDetail",
searchType: "detail",
searchKey: "资源ID",
username: "当前登录用户名",
containerId: "job_down_detail_reco" //容器DIV的id。
});
</script>
</div>
CSTO-案例库列表,放在“上周最受欢迎”下边。
http://www.csto.com/case
<div id="job_csto_caselist_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "csto",
tplType: "cstoCaseList",
searchType: "list",
searchKey: "筛选条件里的热门分类和热门技术,逗号分隔",
username: "当前登录用户名",
containerId: "job_csto_caselist_reco" //容器DIV的id。
});
</script>
</div>
CSTO-案例详情页,放在“最近浏览过的人”下边。
http://www.csto.com/case/show/id:21740
<div id="job_csto_casedetail_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "csto",
tplType: "cstoCaseDetail",
searchType: "detail",
searchKey: "案例ID",
username: "当前登录用户名",
containerId: "job_csto_casedetail_reco" //容器DIV的id。
});
</script>
</div>
CSTO-我的T台,放在“我的资料”下边。
http://www.csto.com/my/info/edit
<div id="job_csto_my_reco1">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "csto",
tplType: "cstoMy",
searchType: "list",
searchKey: "NO",
username: "当前登录用户名",
containerId: "job_csto_my_reco1" //容器DIV的id。
});
</script>
</div>
CSTO-项目列表页
http://www.csto.com/project/list
<div id="job_csto_projlist_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "csto",
tplType: "cstoProjectList",
searchType: "list",
searchKey: "筛选条件里的热门分类和热门技术,逗号分隔",
username: "当前登录用户名",
containerId: "job_csto_projlist_reco" //容器DIV的id。
});
</script>
</div>
CSTO-项目详情页
http://www.csto.com/p/72969
<div id="job_csto_projdetail_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.show({
sourceType: "csto",
tplType: "cstoProjectDetail",
searchType: "detail",
searchKey: "项目ID",
username: "当前登录用户名",
containerId: "job_csto_projdetail_reco" //容器DIV的id。
});
</script>
</div>
//------------------------------------------------------------------------------------------------------------------
课程推荐
//------------------------------------------------------------------------------------------------------------------
搜索页的培训推荐
http://so.csdn.net/so/search/s.do?q=java
<div id="edu_so_reco">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.showEdu({
sourceType: "so",
searchType: "detail",
searchKey: "搜索关键字",
username: "当前登录用户名",
recordcount: "4",
containerId: "edu_so_reco" //容器DIV的id。
});
</script>
</div>
搜索结果页
博客详情页将原来的adCollege注释掉,其相同位置放置如下div。
博客详情页
http://blog.csdn.net/hu1991die/article/details/45564465
<div id="adCollege" style="width: 42%;float: left;">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.showEdu({
sourceType: "blog",
searchType: "detail",
searchKey: "博文id",
username: "当前登录用户名",
recordcount: "5",
containerId: "adCollege" //容器DIV的id。
});
</script>
</div>
下载详情页将原来的related po_down_detail_big_div注释掉,其相同位置放置如下div。
下载详情页
http://download.csdn.net/detail/dudud20/8662993
<div id="edu_down_reco" class="related po_down_detail_big_div">
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script>
<script type="text/javascript">
csdn.position.showEdu({
sourceType: "down",
searchType: "detail",
searchKey: "下载资源id",
username: "当前登录用户名",
recordcount: "5",
containerId: "edu_down_reco" //容器DIV的id。
});
</script>
</div>
//------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------
*/
$(document).ready(function() {
var i = 1;
});
(function (window) {
var csdn = window.csdn || {};
function Position() {
this.prefix = window.location.protocol;
$("<link>")
.attr({ rel: "stylesheet",
type: "text/css",
href: window.location.protocol + "//csdnimg.cn/jobreco/job_reco.css" //"//c.csdnimg.cn/jobreco/job_reco.css"//
})
.appendTo("head");
/*
http://blog.csdn.net/lmj623565791/article/details/42407923#t7
http://blog.csdn.net/column.html
http://bbs.csdn.net/topics/390963719
http://ask.csdn.net/
http://my.csdn.net/
http://my.csdn.net/my/mycsdn
http://hero.csdn.net/
*/
//博客详情:tplType = blogDetail
this.blogTpl = '<dl class="blog-ass-articl tracking-ad" data-mod="{0}">' +
'<dt><span>准备好了么? <label class="po_blg_detail_tiao">跳</label><label class="po_blg_detail_ba">吧</label><label class="po_blg_detail_th"> !</label></span>' +
'<a href="{1}" target="_blank" class="po_blg_more">更多职位尽在 <label class="po_blg_detail_csdn">CSDN JOB</label></a></dt>' +
'{2}' +
'</dl>';//{0},点击标记popu_36 //{1},http, https ://job.csdn.net //{2},内容
this.blogItem = '<dd class="po_blg_dd">' +
'<div class="po_blg_po">' +
'<a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a>' +
'</div>' +
'<div class="po_blg_company">' +
'<a href="{3}" title="{4}" target="_blank">{5}</a>' +
'</div>' +
'<label class="po_blg_separator">|</label>' +
'<div class="po_blg_salary"><a href="{6}" target="_blank">{7}</a></div>' +
'<a class="po_blg_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</dd>' ;
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
//博客专栏:tplType = blogSpec
this.blogSpecTpl = '<div class="box_1 tracking-ad" data-mod="{0}">' +
'<div style="position: relative;">' +
'<h2>准备好了么? <label class="po_blg_detail_tiao">跳</label><label class="po_blg_detail_ba">吧</label><label> !</label></h2>' +
'</div>' +
'<ul class="list_comm">' +
'{2}' +
'</ul>' +
'<div class="po_blg_spec_more_div"><a href="{1}" target="_blank" class="po_blg_spec_more">更多职位尽在 <label class="po_blg_spec_csdn">CSDN JOB</label></a></div>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.blogSpecItem = '<li>' +
'<div class="po_blg_spec_po">' +
'<a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a>' +
'</div>' +
'<div class="po_blg_spec_company">' +
'<a href="{3}" title="{4}" target="_blank">{5}</a>' +
'</div>' +
'<div class="po_blg_spec_salary"><a href="{6}" target="_blank">{7}</a></div>' +
'<div><a class="po_blg_spec_iwant" href="{9}" target="_blank">我要跳槽</a></div>' +
'</li>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
//论坛详情:tplType = bbsDetail
this.bbsTpl = '<div id="topic-suggest" class="po_bbs_div tracking-ad" data-mod="{0}">' +
'<div class="related-tags po_bbs_tit_div">' +
'<span>准备好了么? <label class="po_blg_detail_tiao">跳</label><label class="po_blg_detail_ba">吧</label><label> !</label></span>' +
'<a class="po_bbs_more" href="{1}" target="_blank">更多职位尽在 <label class="po_bbs_csdn">CSDN JOB</label></a>' +
'</div>' +
'<div class="related-topics po_bbs_item_div">' +
'<ul>' +
'{2}' +
'</ul>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.bbsItem = '<li class="po_bbs_li"><div class="po_bbs_po">' +
'<a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a>' +
'</div>' +
'<div class="po_bbs_company">' +
'<a href="{3}" title="{4}" target="_blank">{5}</a>' +
'</div>' +
'<label class="po_bbs_separator">|</label>' +
'<div class="po_bbs_salary"><a href="{6}" target="_blank">{7}</a></div>' +
'<div><a class="po_bbs_iwant" href="{9}" target="_blank">我要跳槽</a></div>' +
'</li>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
//问答首页:tplType = askDetail
this.askTpl = '<div class="mod_other_ask hot_tags po_ask_div tracking-ad" data-mod="{0}">' +
'<div class="other_ask">' +
'<h3><span>准备好了么? <label class="po_ask_tiao">跳</label><label class="po_ask_ba">吧</label><label class="po_blg_detail_th">!</label></span></h3>' +
'<div class="po_ask_div_list">' +
'{2}' +
'</div>' +
'<div class="po_ask_more_div"><a href="{1}" target="_blank" class="po_ask_more">更多职位尽在 <label class="po_my_home_csdn">CSDN JOB</label></a></div>' +
'</div>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.askItem = '<div class="po_ask_item_div">' +
'<div class="po_ask_po">' +
'<a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a>' +
'</div>' +
'<div class="po_ask_salary">' +
'<a href="{6}" target="_blank">{7}</a>' +
'</div>' +
'<div class="po_ask_company">' +
'<a href="{3}" title="{4}" target="_blank">{5}</a>' +
'</div>' +
'<a class="po_ask_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
//个人空间-首页:tplType = personalSpaceHome
this.perSpaceHomeTpl = '<div class="phr_third clearfix tracking-ad" data-mod="{0}">' +
'<div class="phr_third_tit po_my_home_tit">' +
'<div class="phrt_t po_my_home_t">准备好了么? <label class="po_my_my_tiao">跳</label><label class="po_my_my_ba">吧</label><label class="po_blg_detail_th"> !</label></div>' +
'</div>' +
'<div class="phr_third_con po_my_home_div">' +
'{2}' +
'</div>' +
'<div class="po_my_home_more"><a href="{1}" target="_blank" class="po_my_home_more">更多职位尽在 <label class="po_my_home_csdn">CSDN JOB</label></a></div>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.perSpaceHomeItem = '<div class="po_my_home_item_div clearfix">' +
'<div class="po_my_home_po"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_my_home_salary"><a href="{6}" target="_blank">{7}</a></div>' +
'<div class="po_my_home_company"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<a class="po_my_home_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
//个人空间-我的:tplType = personalSpaceMy
this.perSpaceMyTpl = '<div class="interested_con tracking-ad" data-mod="{0}" style="display: block;">' +
'<h3 class="po_my_my_h3">准备好了么? <label class="po_my_my_tiao">跳</label><label class="po_my_my_ba">吧</label><label class="po_blg_detail_th"> !</label></h3>' +
'{2}' +
'<div class="po_my_my_more_div"><a href="{1}" target="_blank" class="po_my_my_more">更多职位尽在 <label class="po_my_my_csdn">CSDN JOB</label></a></div>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.perSpaceMyItem = '<div class="po_my_my_item_div">' +
'<div class="po_my_my_po">' +
'<a class="po_my_my_po_a" href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a>' +
'</div>' +
'<div class="po_my_my_salary">' +
'<a href="{6}" target="_blank">{7}</a>' +
'</div>' +
'<div class="po_my_my_company">' +
'<a href="{3}" title="{4}" target="_blank">{5}</a>' +
'</div>' +
'<a class="po_my_my_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略 //{9},职位链接
//英雄会--首页
this.heroHomeTpl = '<div class="her_topic_right tracking-ad" data-mod="{0}">' +
'<h3 class="haping_t">准备好了么? <span class="po_yx_home_tiao">跳</span><span class="po_yx_home_ba">吧</span><span> !</span></h3>' +
'{2}' +
'<div class="po_yx_home_more_div"><a href="{1}" target="_blank" class="po_yx_home_more">更多职位尽在 <label class="po_yx_home_csdn">CSDN JOB</label></a></div>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.heroHomeItem = '<div class="her_platform po_yx_home_item_div">' +
'<div class="po_yx_home_po"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_yx_home_salary"><a href="{6}" target="_blank">{7}</a></div>' +
'<div class="po_yx_home_company"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<a class="po_yx_home_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
//英雄会--答题专家组
this.heroExpertTpl = '<div class="her-r-expli po_yx_ex_div tracking-ad" data-mod="{0}">' +
'<h3 class="tit"><span class="po_yx_ex_tit">准备好了么? </span><label class="po_yx_home_tiao px_yx_ex_tiao">跳</label><label class="po_yx_home_ba px_yx_ex_ba">吧</label><span class="po_yx_ex_tit"> !</span></h3>' +
'{2}' +
'<div class="po_yx_ex_more_div"><a href="{1}" target="_blank" class="po_yx_ex_more">更多职位尽在 <label class="po_yx_ex_csdn">CSDN JOB</label></a></div>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.heroExpertItem = '<dl class="her-r-explicon po_yx_ex_po_item_div">' +
'<dt class="po_yx_ex_po"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></dt>' +
'<dd class="po_yx_ex_salary"><a href="{6}" target="_blank">{7}</a></dd>' +
'<dd class="py_yx_ex_company"><a href="{3}" title="{4}" target="_blank">{5}</a></dd>' +
'<a class="po_yx_ex_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</dl>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
//英雄会--挑战题目详情页
this.heroFightDetailTpl = '<div class="her_format_right py_yx_fd_div tracking-ad" data-mod="{0}">' +
'<h3 class="po_yx_fd_tit"><span>准备好了么? </span><label class="po_yx_home_tiao">跳</label><label class="po_yx_home_ba">吧</label><span> !</span></h3>' +
'{2}' +
'<div class="po_yx_fd_more_div"><a href="{1}" target="_blank" class="po_yx_fd_more">更多职位尽在 <label class="po_yx_fd_csdn">CSDN JOB</label></a></div>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.heroFightDetailItem = '<div class="po_yx_fd_item_div">' +
'<div class="po_yx_fd_po"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_yx_fd_company"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<div class="po_yx_fd_salary"><a href="{6}" target="_blank">{7}</a></div>' +
'<div><a class="po_yx_fd_iwant" href="{9}" target="_blank">我要跳槽</a></div>' +
'</div>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
//英雄会--我的英雄会
this.heroMyTpl = '<div class="her-resultli po_yx_my_div tracking-ad" data-mod="{0}">' +
'<h3><span>准备好了么? </span><label class="po_yx_home_tiao">跳</label><label class="po_yx_home_ba">吧</label><span> !</span>' +
'<a href="{1}" target="_blank" class="po_yx_my_more">更多职位尽在 <label class="po_yx_my_csdn">CSDN JOB</label></a></h3>' +
'{2}' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.heroMyItem = '<div class="po_yx_my_item_div">' +
'<div class="po_yx_my_item_dot">▪</div>' +
'<div class="po_yx_my_item_cont">' +
'<div class="po_yx_my_po"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_yx_my_company"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<label class="po_yx_my_separator">|</label>' +
'<div class="po_yx_my_salary"><a href="{6}" target="_blank">{7}</a></div>' +
'</div>' +
'<a class="po_yx_my_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
this.heroFightDetailTpl = this.heroMyTpl;
this.heroFightDetailItem = this.heroMyItem;
//在线培训--课程详情页
this.eduDetailTpl = '<div class="boutique-curr-box tracking-ad" data-mod="{0}">' +
'<div class="boutique-curr"><h3>准备好了么? <label class="po_my_my_tiao">跳</label><label class="po_my_my_ba">吧</label><label class="po_blg_detail_th"> !</label></h3>' +
'<div class="cutt-column">' +
'{2}' +
'<div class="po_edu_detail_more_div"><a href="{1}" target="_blank" class="po_edu_detail_more">更多职位尽在 <label class="po_edu_detail_csdn">CSDN JOB</label></a></div>' +
'</div></div></div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.eduDetailItem = '<div class="po_edu_detail_item_div clearfix">' +
'<div class="po_edu_detail_po"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}<a></div>' +
'<div class="po_edu_detail_salary"><a href="{6}" target="_blank">{7}</a></div>' +
'<div class="po_edu_detail_company"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<a class="po_edu_detail_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
//在线培训--课程分类列表
this.eduListTpl = this.eduDetailTpl;
this.eduListItem = this.eduDetailItem;
//--------------------------------------------------------------------------------------------------------------------------------
//搜索培训推广
this.search_reco_edu = '' +
'<div class="common-box tracking-ad" data-mod="popu_84" style="display: block;">' + //todo 增加统计号码
'<h3 id="job-pos-title" class="po_search_tit">精品课程<a class="class-edu-more" href="http://edu.csdn.net">更多</a></h3>' +
'<div class="po_search_div">' +
'{0}' +
'</div>' +
'</div>';
this.search_reco_edu_item = '<div class="po_search_item_div">' +
'<div class="class-img-box"><a href="{0}" target="_blank" strategy="{7}"><img src="{1}"></a></div>' +
'<div class="class-content-box">' +
'<div class="class-content-tit"><a href="{2}" target="_blank" title="{3}" strategy="{8}">{4}</a></div>' +
'<div class="class-content-hp">好评率:<a href="{9}" class="class-content-hp-hpl">{5}%</a> <span class="class-content-hp-rzx"><i class="class-content-icon"> </i><a href="{10}" class="class-content-icon-rdx">{6}</a>人在学</span></div>' +
'</div>' +
'</div>';
//<div id="adCollege" style="width: 42%;float: left;">
this.blog_reco_edu = '<div class="tracking-ad" data-mod="popu_84">{0}</div>'; //todo 增加统计号码
this.blog_reco_edu_item = '<dd style="background:url(http://static.blog.csdn.net/skin/default/images/blog-dot-red3.gif) no-repeat 0 10px; white-space: nowrap;">' +
'<a href="{0}" title="{1}" strategy="{3}" target="_blank">{2}</a>' +
'</dd>';
//<div class="related po_down_detail_big_div">
this.down_reco_edu = '<div class="section-list panel panel-default tracking-ad" data-mod="popu_84">' + //todo 修改统计号码
'<div class="panel-heading po_down_detail_tit_div">' +
'<h3 class="panel-title po_down_detail_tit">相关课程</h3>' +
'</div>' +
'<div class="panel-body">' +
'<ul class="down_edu_t">' +
'{0}' +
'</ul>' +
'</div>' +
'</div>' +
'';
this.down_reco_edu_item = ' <li style="line-height: 25px;display:block;margin-bottom: 9px;margin-top: 9px;padding-top: 0px;">' +
'<div style="padding:0;margin:0;border:0;text-overflow: ellipsis;overflow: hidden;">' +
'<a href="{0}" title="{1}" alt="" target="_blank" strategy="{3}">{2}</a>' +
'</div>' +
'</li>';
this.edu_detail_url_base = 'http://edu.csdn.net/course/detail/';
//结束。
//----------------------------------------------------------------------------------------------------------------------------------------
//搜索
this.searchTpl = '<div class="common-box tracking-ad" data-mod="{0}" style="display: block;">' +
'<h3 id="job-pos-title" class="po_search_tit">准备好了么? <span class="po_blg_detail_tiao">跳</span><span class="po_blg_detail_ba">吧</span><span> !</span></h3>' +
'<div class="po_search_div">' +
'{2}' +
'<div class="po_search_more_div"><a href="{1}" target="_blank" class="po_search_more">更多职位尽在 <label class="po_search_csdn">CSDN JOB</label></a></div>' +
'</div>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.searchItem = '<div class="po_search_item_div">' +
'<div class="po_search_po_div"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_search_salary_div"><a href="{6}" target="_blank">{7}</a></div>' +
'<div class="po_search_company_div"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<a class="po_search_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>' +
'';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略 //{9},我要跳槽
//下载--我的资源
this.downMyTpl = '<div id="my-tags-side" class="panel panel-default tracking-ad" data-mod="{0}">' +
'<div class="panel-heading po_downmy_div">' +
'<h3 class="panel-title">准备好了么? <span class="po_blg_detail_tiao">跳</span><span class="po_blg_detail_ba">吧</span><span class="po_blg_detail_th"> !</span></h3>' +
'</div>' +
'<div>' +
'{2}' +
'</div>' +
'<div class="po_downmy_more_div"><a href="{1}" target="_blank" class="po_downmy_more">更多职位尽在 <label class="po_downmy_csdn">CSDN JOB</label></a></div>' +
'</div>';//{0},点击标记popu_36 //{1},更多的链接 //{2},内容
this.downMyItem = '<div class="po_downmy_item_div">' +
'<div class="po_downmy_po_div"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_downmy_company_div"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<div class="po_downmy_salary_div"><a href="{6}">{7}</a></div>' +
'<a class="po_downmy_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略 //{9},我要跳槽
//下载--下载页和下载详情页
this.downDetailTpl = '<div class="related po_down_detail_big_div tracking-ad" data-mod="{0}">' +
'<div>' +
'<div class="section-list panel panel-default">' +
'<div class="panel-heading po_down_detail_tit_div">' +
'<h3 class="panel-title po_down_detail_tit">准备好了么? <span class="po_blg_detail_tiao">跳</span><span class="po_blg_detail_ba">吧</span><span class="po_blg_detail_th"> !</span></h3>' +
'<a class="po_downdetail_more" href="{1}" target="_blank">更多职位尽在 <label class="po_dwondetail_csdn">CSDN JOB</label></a>' +
'</div>' +
'{2}' +
'</div>' +
'</div>' +
'</div>';
this.downDetailItem = '<div class="panel-body po_down_detail_item_div">' +
'<ul>' +
'<li>' +
'<div class="po_down_detail_left"><a class="con" href="{0}" title="{1}" target="_blank">【{7}】{2}</a></div>' +
'<div class="po_down_detail_right"><a class="po_downdetail_iwant" href="http://job.csdn.net/Job/Index?jobID=81328" target="_blank">我要跳槽</a></div>' +
'</li>' +
'</ul>' +
'</div>';
//CSTO案例库列表:cstoCaseList
this.cstoCaseListTpl = '<div class="contbox tracking-ad" data-mod="{0}">' +
'<h3 class="po_csto_caselist_tit"><span>准备好了么? </span><span class="po_my_my_tiao">跳</span><span class="po_my_my_ba">吧</span><span class="po_blg_detail_th"> !</span></h3>' +
'<div class="po_caselist_div">' +
'{2}' +
'<div class="po_caselist_more_div"><a href="{1}" target="_blank" class="po_caselist_more">更多职位尽在 <label class="po_caselist_csdn">CSDN JOB</label></a></div>' +
'</div>' +
'</div>';
this.cstoCaseListItem = '<div class="po_caselist_item_div">' +
'<div class="po_caselist_po_div"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_caselist_salary_div"><a href="{6}" target="_blank">{7}</a></div>' +
'<div class="po_caselist_company_div"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<a class="po_caselist_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//CSTO案例详情页:cstoCaseDetail
this.cstoCaseDetailTpl = '<ul class="case_list po_case_detail_div tracking-ad" data-mod="{0}">' +
'<h3 class="po_csto_casedetail_tit"><span>准备好了么? </span><span class="po_my_my_tiao">跳</span><span class="po_my_my_ba">吧</span><span class="po_blg_detail_th"> !</span></h3>' +
'<div class="po_casedetail_div">' +
'{2}' +
'<div class="po_casedetail_more_div"><a href="{1}" target="_blank" class="po_casedetail_more">更多职位尽在 <label class="po_casedetail_csdn">CSDN JOB</label></a></div>' +
'</div>' +
'</ul>';
this.cstoCaseDetailItem = '<div class="po_casedetail_item_div clearfix">' +
'<div class="po_casedetail_po_div"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_casedetail_company_div"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<div class="po_casedetail_salary_div"><a href="{6}" target="_blank">{7}</a></div>' +
'<a class="po_casedetail_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//CSTO我的T台:cstoMy
this.cstoMyTpl = '<ul class="menu tracking-ad" data-mod="{0}">' +
'<li class="icon selected po_csto_my_big_div">' +
'<h3 class="po_csto_my_tit"><span>准备好了么? </span><span class="po_my_my_tiao">跳</span><span class="po_my_my_ba">吧</span><span class="po_blg_detail_th"> !</span></h3>' +
'<div class="po_csto_my_div">' +
'{2}' +
'</div>' +
'<div class="po_csto_my_more_div"><a href="{1}" target="_blank" class="po_csto_my_more">更多职位尽在 <label class="po_csto_my_csdn">CSDN JOB</label></a></div>' +
'</li>' +
'</ul>';
this.cstoMyItem = '<div class="po_csto_my_item_div">' +
'<div class="po_csto_my_po_div"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_csto_my_salary_div"><a href="{6}" target="_blank">{7}</a></div>' +
'<div class="po_csto_my_company_div"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<a class="po_csto_my_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
//CSTO项目列表页:cstoProjectList
this.cstoProjectListTpl = '' +
'' +
'' +
'';
this.cstoProjectListItem = '' +
'' +
'' +
'';
//CSTO项目详情页:cstoProjectDetail
this.cstoProjectDetailTpl = '<div class="bid_scheme tracking-ad" data-mod="{0}">' +
'<h3 class="po_csto_proj_detail_tit"><span>准备好了么? </span><span class="po_my_my_tiao">跳</span><span class="po_my_my_ba">吧</span><span class="po_blg_detail_th"> !</span></h3>' +
'<div class="po_proj_detail_div">' +
'{2}' +
'<div class="po_proj_detail_more_div"><a href="{1}" target="_blank" class="po_proj_detail_more">更多职位尽在 <label class="po_proj_detail_csdn">CSDN JOB</label></a></div>' +
'</div>' +
'</div>';
this.cstoProjectDetailItem = '<div class="po_proj_detail_item_div clearfix">' +
'<div class="po_proj_detail_po_div"><a href="{0}" title="{1}" strategy="{8}" target="_blank">{2}</a></div>' +
'<div class="po_proj_detail_salary_div"><a href="{6}" target="_blank">{7}</a></div>' +
'<div class="po_proj_detail_company_div"><a href="{3}" title="{4}" target="_blank">{5}</a></div>' +
'<a class="po_proj_detail_iwant" href="{9}" target="_blank">我要跳槽</a>' +
'</div>';
this.getCount = 300;
};
Position.prototype = {
show: function(conf) {
var _conf = conf;
var _this = this;
_this.show_inner(_conf);
/*$(window).load(function() {
_this.show_inner(_conf);
});*/
},
showEdu: function(conf) {
var _conf = conf;
var _this = this;
_this.show_edu_mlgb(_conf);
},
show_edu_mlgb: function(conf) {
this.sourceType = conf.sourceType;//blog, bbs, downlowd, ask, space, hero, edu, csto .....
this.searchType = conf.searchType;
this.searchKey = conf.searchKey;
this.username = conf.username ? conf.username : '';
this.recordcount = conf.recordcount;
this.containerId = conf.containerId;
this.$container = $("#" + this.containerId);
this.prefix = window.location.protocol;
this.load_edu_reco();
},
load_edu_reco: function() {
var tpl = '';
var itemTpl = '';
var _url = '';
_data = {};
//var urlBase = 'http://192.168.5.75:9400';
//var urlBase = 'http://p.search.dm.csdn.net';
var kk = this.searchKey.replace(/%/g,"%25").replace(/#/g,"%23").replace(/&/g,"%26").replace(/\+/g, "%2B");
var urlBase = 'http://internalapi.csdn.net/psearch/psearch/query?x-acl-token=kUOm7x6dCaKGFa8RxxLQ5Hm75ioK&index_name=pro_course_v2';
if (this.sourceType == 'so') {
tpl = this.search_reco_edu;
itemTpl = this.search_reco_edu_item;
//url = 'http://p.search.dm.csdn.net/v2/pro_course/csdn/_search?_client_=rcommend_course&fields=id,title,stu_count,good_ratio,rc_flag&searchStr=初级java教程&user_id=blogchong';
_url = urlBase + '&search_str=' + kk; // + '/v2/pro_course_v2/csdn/_search';
_data = {'_client_': 'rcommend_course','fields': 'id,title,pic,stu_count,good_ratio,rc_flag,source_type', 'user_id': this.username, 'size': this.recordcount}; //'search_str': kk,
if (this.username == '')
_data = {'_client_': 'rcommend_course','fields': 'id,title,pic,stu_count,good_ratio,rc_flag,source_type', 'size': this.recordcount}; //'search_str': kk,
} else if (this.sourceType == 'blog') {
tpl = this.blog_reco_edu;
itemTpl = this.blog_reco_edu_item;
//url = 'http://p.search.dm.csdn.net/v2/pro_course/csdn/_search?_client_=rcommend_course&fields=id,title,stu_count,good_ratio,rc_flag&pro_id=45521251&pro_type=blog&user_id=blogchong';
_url = urlBase + '&pro_id=' + kk;// + '/v2/pro_course_v2/csdn/_search';
_data = {'_client_': 'rcommend_course','fields': 'id,title,pic,stu_count,good_ratio,rc_flag,source_type', 'pro_type': 'blog', 'user_id': this.username, 'size': this.recordcount}; //'pro_id': kk,
if (this.username == '')
_data = {'_client_': 'rcommend_course','fields': 'id,title,pic,stu_count,good_ratio,rc_flag,source_type', 'pro_type': 'blog', 'size': this.recordcount}; //'pro_id': kk,
} else if (this.sourceType == 'down') {
tpl = this.down_reco_edu;
itemTpl = this.down_reco_edu_item;
//url = 'http://p.search.dm.csdn.net/v2/pro_course/csdn/_search?_client_=rcommend_course&fields=id,title,stu_count,good_ratio,rc_flag&pro_id=45521251&pro_type=blog&user_id=blogchong';
_url = urlBase + '&pro_id=' + kk;// + '/v2/pro_course_v2/csdn/_search';
_data = {'_client_': 'rcommend_course','fields': 'id,title,pic,stu_count,good_ratio,rc_flag,source_type', 'pro_type': 'download', 'user_id': this.username, 'size': this.recordcount}; //'pro_id': kk,
if (this.username == '')
_data = {'_client_': 'rcommend_course','fields': 'id,title,pic,stu_count,good_ratio,rc_flag,source_type', 'pro_type': 'download', 'size': this.recordcount}; //'pro_id': kk,
}
if (tpl == '') return;
var _this = this;
$.ajax({
type: 'get',
url: _url,
data: _data,
dataType: "jsonp",
jsonp: "callback",
async: false,
success: function(result) {
if (result.hits && result.hits.length > 0) {
var htmlItems = '';
for (var i = 0; i < _this.recordcount; i ++) {
var item = result.hits[i].object;
var htmlItem = '';
if (_this.sourceType == 'so') {
var rzx = item.stu_count ? item.stu_count : 0;
var kcurl = _this.edu_detail_url_base + item.id;
htmlItem = itemTpl.replace(/\{0\}/, kcurl) //课程url
.replace(/\{1\}/, item.pic) //图片url
.replace(/\{2\}/, kcurl) //课程url
.replace(/\{3\}/, item.title) //课程标题
.replace(/\{4\}/, item.title) //课程名称
.replace(/\{5\}/, item.good_ratio == 0 ? 100 : item.good_ratio) //好评率
.replace(/\{6\}/, rzx) //正在学习的人数
.replace(/\{7\}/, item.rc_flag) //策略
.replace(/\{8\}/, item.rc_flag) //策略
.replace(/\{9\}/, kcurl) //课程url
.replace(/\{10\}/, kcurl); //课程url
} else if (_this.sourceType == 'blog' || _this.sourceType == 'down') {
htmlItem = itemTpl.replace(/\{0\}/, _this.edu_detail_url_base + item.id)
.replace(/\{1\}/, item.title)
.replace(/\{2\}/, item.title) //'【精品课程】' + item.title
.replace(/\{3\}/, item.rc_flag);
}
htmlItems += htmlItem;
}
var jHtml = tpl.replace(/\{0\}/, htmlItems);
var tdd = $(jHtml).appendTo(_this.$container);
var tds = [];
tds.push(tdd[0]);
try {
window['trackingAd']($(tds));
} catch(ee){};
}
},
error: function(result) {
var i = 0;
}
}); //问题:记录数;类型只有blog、download、bbs没有搜索;
//todo 暂时处理一下,因为看不懂原来的猜你在找代码。后面找时间把猜你在找调整为只显示5条数据。
$(function() {
var count = 0;
var setFive = setInterval(function() {
count ++;
if (count > _this.getCount) {
clearInterval(setFive);
}
$('#res').hide();
var cc = $('#res').children();
if (cc.length > 5) {
for (var i = 0; i < cc.length; i++) {
clearInterval(setFive);
var item = cc[i];
if (i > 4) {
$(item).remove();
}
}
$('#res').show();
}
}, 200);
});
},
show_inner: function(conf) {
this.sourceType = conf.sourceType;//blog,bbs, download,ask, space, hero, edu, csto .....
this.tplType = conf.tplType;
//模板类型,博客详情:blogDetail,博客专栏:blogSpec,论坛详情:bbsDetail,问答首页:askDetail,个人空间--我的空间:personalSpaceMy,个人空间--首页:personalSpaceHome,
//英雄会--首页:heroHome,英雄会--答题专家组:heroExpert,英雄会--挑战题目详情页:heroFightDetail,英雄会--我的英雄会:heroMy,
//在线培训--课程分类列表页:eduList,在线培训--课程详情页:eduDetail,.....
this.searchType = conf.searchType;//页面类型,用于搜索函数,detail(详情页) / list(列表页)。
this.searchKey = conf.searchKey;//搜索关键字,例如博客详情:博文ID,如果是博客专栏:分类字符串。
this.username = conf.username;
this.containerId = conf.containerId;
this.$container = $("#" + this.containerId);
this.prefix = window.location.protocol;
this.load();
},
goInPage: function(containerTpl, itemTpl, container, _prefix) {
var homeUrl = _prefix + "//job.csdn.net";
var jHtml = containerTpl.replace(/\{0\}/, "popu_72")
.replace(/\{1\}/, homeUrl)
.replace(/\{2\}/, totalHtmlItems);
//container.html(jHtml);
container.html("");
var tdd = $(jHtml).appendTo(container);
var tds = [];
tds.push(tdd[0]);
try {
window['trackingAd']($(tds));
} catch(ee) {};
return true;
},
totalHtmlItems: "",
load: function() {
var that = this;
if (that.searchKey === "NO" && that.username === "") {
return;
}
var _url = that.get_url(that.username, that.searchType, that.searchKey, that.sourceType, that.tplType);
var _strategy = that.get_strategy(that.username, that.searchType);
var containerTpl = that.get_containerTpl(that.tplType);
var itemTpl = that.get_itemTpl(that.tplType);
//that.username = that.getUserName();
$.ajax({
type: "get",
url: _url,
dataType: "jsonp",
jsonp: "callback",
async: false,
success: function (obj) {
totalHtmlItems = "";
var htmlItems = "";
var count = obj.hits.length;
if (obj.hits && obj.hits.length > 0) {
totalHtmlItems = that.getData(that.$container, obj.hits, containerTpl, itemTpl, that.prefix, _strategy, true);
}
if (count < 4 && that.username && that.searchType == "detail") {
//以内容搜索职位,再次发送请求
var _strategy_detail = that.get_strategy("", "detail");
that.loadByDetail(containerTpl, itemTpl, _strategy_detail, count, that.$container, that.prefix);
} else if (count < 4) {
//以最新职位发送请求。
var _strategy_latest = that.get_strategy("", "latest");
htmlItems = that.loadByLatest(containerTpl, itemTpl, _strategy_latest, count, that.$container, that.prefix);
}
if (count >= 4) {
that.goInPage(containerTpl, itemTpl, that.$container, that.prefix);
}
},
error: function(err) {
var i = 0;
//alert('err');
}
});
},
loadByDetail: function(_containerTpl, _itemTpl, _strategy, _count, _containerObj, _prefix) {
var that = this;
var _url = that.get_url("", that.searchType, that.searchKey, that.sourceType, that.tplType , 4 - _count);
$.ajax({
type: "get",
url: _url,
dataType: "jsonp",
jsonp: "callback",
async: false,
success: function (obj) {
var count = obj.hits.length;
var htmlItems = "";
if (obj.hits && obj.hits.length > 0) {
totalHtmlItems += that.getData(_containerObj, obj.hits, _containerTpl, _itemTpl, _prefix, _strategy, false);
}
if (count + _count < 4) {
//以最新职位再次发送请求。
var _strategy_latest = that.get_strategy("", "latest");
that.loadByLatest(_containerTpl, _itemTpl, _strategy, count + _count, _containerObj, _prefix);
}
if (count + _count >= 4) {
that.goInPage(_containerTpl, _itemTpl, _containerObj, _prefix);
}
},
error: function(err) {
var i = 0;
}
});
},
loadByLatest: function(_containerTpl, _itemTpl, _strategy, _count, _containerObj, _prefix) {
var that = this;
var _url = "http://job.csdn.net/api/lastJobList";//http://job.csdn.net/api/lastJobList //http://tmpjob.csdn.net/api/LastJobList
var homeUrl = _prefix + "//job.csdn.net";
var jobUrl = _prefix + "//job.csdn.net/Job/Index?jobID=";
var companyUrl = _prefix + "//pr.csdn.net/enterprise/ent_home?orgid=";
$.ajax({
type: "get",
url: _url,
dataType: "jsonp",
jsonp: "callback",
async: false,
success: function(obj) {
var count = obj;
if (obj.Data && obj.Data.paperList && obj.Data.paperList.length > 0 && obj.Data.paperList.length >= 4 - _count) {
var htmlItems = "";
for (var i = 0; i < 4 - _count; i ++) {
var item = obj.Data.paperList[i];
if (item.JobID && item.JobName && item.OrgID && item.OrgName && item.SalaryMax && item.SalaryMin) {
var salaryText = "";
if (item.SalaryMax == 0 && item.SalaryMin == 0) {
salaryText = "面议";
} else {
var mins = item.SalaryMin / 1000;
var maxs = item.SalaryMax / 1000;
salaryText = mins + "-" + maxs + "K/月";
}
var htmlItem = _itemTpl.replace(/\{0\}/, jobUrl + item.JobID)
.replace(/\{1\}/, item.JobName)
.replace(/\{2\}/, item.JobName)
.replace(/\{3\}/, companyUrl + item.OrgID)
.replace(/\{4\}/, item.OrgName)
.replace(/\{5\}/, item.OrgName)
.replace(/\{6\}/, jobUrl + item.JobID)
.replace(/\{7\}/, salaryText)
.replace(/\{8\}/, _strategy)
.replace(/\{9\}/, jobUrl + item.JobID);
htmlItems += htmlItem;
}
}
totalHtmlItems += htmlItems;
/*if (htmlItems != "") {
var jHtml = _containerTpl.replace(/\{0\}/, "popu_72")
.replace(/\{1\}/, homeUrl)
.replace(/\{2\}/, htmlItems);
//_containerObj.html("");
var tdd = $(jHtml).appendTo(_containerObj);
var tds = [];
tds.push(tdd[0]);
try {
window['trackingAd']($(tds));
} catch (ee) {};
}*/
}
that.goInPage(_containerTpl, _itemTpl, _containerObj, _prefix);
return "";
/*
obj.Data.paperList[0].JobID
obj.Data.paperList[0].JobName
obj.Data.paperList[0].OrgID
obj.Data.paperList[0].OrgName
obj.Data.paperList[0].SalaryMax
obj.Data.paperList[0].SalaryMin
* */
},
error: function(err) {
var i = 0;
}
});
},
getData: function(container, items, containerTpl, itemTpl, prefix, _strategy, isClear) {
var homeUrl = prefix + "//job.csdn.net";
var jobUrl = prefix + "//job.csdn.net/Job/Index?jobID=";//职位页面url,样例:http://job.csdn.net/Job/Index?jobID=80500,http://tmpjob.csdn.net/Job/Index?jobID=80500
var companyUrl = prefix + "//pr.csdn.net/enterprise/ent_home?orgid=";//3,样例:http://pr.csdn.net/enterprise/ent_home?orgid=406854,http://lpr.csdn.net/enterprise/ent_home?orgid=406854
var htmlItems = "";
for (var i = 0; i < items.length; i++) {
var item = items[i];
var obj = item.object;
if (obj.id && obj.title && obj.org_id && obj.org_name) {
var salaryText = "";
if (obj.salary_max == 0 && obj.salary_min == 0) {
salaryText = "面议";
} else {
var mins = obj.salary_min / 1000;
var maxs = obj.salary_max / 1000;
salaryText = mins + "-" + maxs + "K/月";
}
var htmlItem = itemTpl.replace(/\{0\}/, jobUrl + obj.id)
.replace(/\{1\}/, obj.title)
.replace(/\{2\}/, obj.title)
.replace(/\{3\}/, companyUrl + obj.org_id)
.replace(/\{4\}/, obj.org_name)
.replace(/\{5\}/, obj.org_name)
.replace(/\{6\}/, jobUrl + obj.id)
.replace(/\{7\}/, salaryText)
.replace(/\{8\}/, _strategy)
.replace(/\{9\}/, jobUrl + obj.id);
//{0},职位链接 //{1},职位名称 //{2},职位名称 //{3},公司链接 //{4},公司名称 //{5},公司名称 //{6},职位链接 //{7},职位薪水 //{8},上报策略
htmlItems += htmlItem;
}
}
return htmlItems;
/*var jHtml = containerTpl.replace(/\{0\}/, "popu_72")
.replace(/\{1\}/, homeUrl)
.replace(/\{2\}/, htmlItems);
//container.html(jHtml);
if (isClear) {
container.html("");
}
var tdd = $(jHtml).appendTo(container);
var tds = [];
tds.push(tdd[0]);
try {
window['trackingAd']($(tds));
} catch(ee) {};
return true; */
},
get_strategy: function(un, searcht) {
var _st = "";
if (un != "") {
_st = "PersonalRecommend";
} else if (searcht == "detail") {
_st = "DetailRecommend";
} else if (searcht == "list") {
_st = "ListRecommend";
} else if (searcht == "latest") {
_st = "LatestRecommend";
} else {
_st = "unknown";
}
return _st;
},
get_itemTpl: function(tplType) {
var c = "";
switch (tplType) {
case "blogDetail":
c = this.blogItem;
break;
case "blogSpec":
c = this.blogSpecItem;
break;
case "bbsDetail":
c = this.bbsItem;
break;
case "askDetail":
c = this.askItem;
break;
case "personalSpaceMy":
c = this.perSpaceMyItem;
break;
case "personalSpaceHome":
c = this.perSpaceHomeItem;
break;
case "heroHome":
c = this.heroHomeItem;
break;
case "heroExpert":
c = this.heroExpertItem;
break;
case "heroFightDetail":
c = this.heroFightDetailItem;
break;
case "heroMy":
c = this.heroMyItem;
break;
case "eduList":
c = this.eduListItem;
break;
case "eduDetail":
c = this.eduDetailItem;
break;
case "search":
c = this.searchItem;
break;
case "downMy":
c = this.downMyItem;
break;
case "downDetail":
c = this.downDetailItem;
break;
case"cstoCaseList":
c = this.cstoCaseListItem;
break;
case"cstoCaseDetail":
c = this.cstoCaseDetailItem;
break;
case"cstoMy":
c = this.cstoMyItem;
break;
case"cstoProjectList":
c = this.cstoCaseListItem;//同案例列表
break;
case"cstoProjectDetail":
c = this.cstoProjectDetailItem;
break;
default:
break;
}
return c;
},
get_containerTpl: function(tplType) {
var c = "";
switch (tplType) {
case "blogDetail":
c = this.blogTpl;
break;
case "blogSpec":
c = this.blogSpecTpl;
break;
case "bbsDetail":
c = this.bbsTpl;
break;
case "askDetail":
c = this.askTpl;
break;
case "personalSpaceMy":
c = this.perSpaceMyTpl;
break;
case "personalSpaceHome":
c = this.perSpaceHomeTpl;
break;
case "heroHome":
c = this.heroHomeTpl
break;
case "heroExpert":
c = this.heroExpertTpl;
break;
case "heroFightDetail":
c = this.heroFightDetailTpl;
break;
case "heroMy":
c = this.heroMyTpl;
break;
case "eduList":
c = this.eduListTpl;
break;
case "eduDetail":
c = this.eduDetailTpl;
break;
case "search":
c = this.searchTpl;
break;
case "downMy":
c = this.downMyTpl;
break;
case "downDetail":
c = this.downDetailTpl;
break;
case "cstoCaseList":
c = this.cstoCaseListTpl;
break;
case "cstoCaseDetail":
c = this.cstoCaseDetailTpl;
break;
case "cstoMy":
c = this.cstoMyTpl;
break;
case "cstoProjectList":
c = this.cstoCaseListTpl;//同案例列表
break;
case "cstoProjectDetail":
c = this.cstoProjectDetailTpl;
break;
default:
break;
}
return c;
},
get_url: function(un, searcht, key, st, tt, count) {
var _st = st;
var kk = key.replace(/%/g,"%25").replace(/#/g,"%23").replace(/&/g,"%26").replace(/\+/g, "%2B");
var u = "http://internalapi.csdn.net/psearch/psearch/query?x-acl-token=kUOm7x6dCaKGFa8RxxLQ5Hm75ioK&index_name=test_b2d_job_141211&_client_=";
//var u = "http://p.search.dm.csdn.net/v2/test_b2d_job_141211/csdn/_search?_client_=";
if (un != "" && un != undefined && un != null) {
_st = "uc_proxy";
u = u + "search_job_by_user";
u = u + "&from=1&size=4";
u = u + "&id=" + un;
} else if (tt == "search") {
u = u + "job_position_query";
u = u + "&like=title:" + kk;
u = u + "&shouldNum=0&from=1&size=" + (count ? count : 4);
} else if (searcht == "detail") {
u = u + "search_job_by_content";
u = u + "&id=" + kk;
u = u + "&from=1&size=" + (count ? count : 4);
} else if (searcht == "list") {
u = u + "search_job_by_content";
u = u + "&content=" + kk;
u = u + "&from=1&size=" + (count ? count : 4);
}
u = u + "&source_type=" + _st;
u = u + "&fields=id,publish_time,title,org_name,org_id,salary_max,salary_min";
return u;
},
getThisCss: function() {
$("<link>")
.attr({ rel: "stylesheet",
type: "text/css",
href: csdn.position.prefix + "//csdnimg.cn/jobreco/job_reco.css"
})
.appendTo("head");
},
getUserName: function() {
return this.getCookie("UserName");
},
getCookie: function(objName) {
var arrStr = document.cookie.split("; ");
for(var i = 0;i < arrStr.length;i ++){
var temp = arrStr[i].split("=");
if(temp[0] == objName) return decodeURI(temp[1]);
}
},
evil: function() {
}
};
csdn.position = new Position();
window["csdn"] = csdn;
})(window); |
#!/usr/bin/env bash
#import
source "${KOGITO_HOME}"/launch/logging.sh
function prepareEnv() {
# keep it on alphabetical order
unset KOGITO_DATAINDEX_HTTP_URL
}
function configure() {
configure_data_index_url
}
# Exit codes:
# 10 - invalid url
function configure_data_index_url {
url_simple_regex='(https?)://'
local dataIndexURL=${KOGITO_DATAINDEX_HTTP_URL}
if [ "${dataIndexURL}x" != "x" ]; then
if [[ ! "${dataIndexURL}x" =~ $url_simple_regex ]]; then
log_error "URL must start with http or https."
exit 10
fi
else
log_info "Data index url not set, default will be used: http://localhost:8180"
dataIndexURL="http://localhost:8180"
fi
KOGITO_MANAGEMENT_CONSOLE_PROPS="${KOGITO_DATA_INDEX_PROPS} -Dkogito.dataindex.http.url=${dataIndexURL}"
}
|
#!/bin/python
def perform_operation(arr):
# Implementation of the operation: square each element in the list
modified_list = [x**2 for x in arr]
return modified_list
def find_max_value(arr):
# Find the maximum value in the modified list
max_value = max(arr)
return max_value
# Example usage
input_list = [1, 5, 3, 9, 2]
modified_list = perform_operation(input_list)
max_value = find_max_value(modified_list)
print("Maximum value in the modified list:", max_value) |
<filename>assets/eazax-ccc/components/popups/PopupBase.ts
const { ccclass, property } = cc._decorator;
/**
* @author (ifaswind)
* @version 20211011
* @see PopupBase.ts https://gitee.com/ifaswind/eazax-ccc/blob/master/components/popups/PopupBase.ts
* @see PopupManager.ts https://gitee.com/ifaswind/eazax-ccc/blob/master/core/PopupManager.ts
*/
@ccclass
export default class PopupBase<Options = any> extends cc.Component {
@property({ type: cc.Node, tooltip: CC_DEV && 'Background mask' })
public background: cc.Node = null;
@property({ type: cc.Node, tooltip: CC_DEV && 'The main body of the pop-up window' })
public main: cc.Node = null;
public animDuration: number = 0.3;
protected blocker: cc.Node = null;
protected options: Options = null;
public async show(options?: Options, duration?: number) {
this.options = options;
this.init(this.options);
this.updateDisplay(this.options);
if (duration == undefined || duration < 0) {
duration = this.animDuration;
}
await this.playShowAnim(duration);
this.onShow && this.onShow();
}
public async hide(suspended: boolean = false, duration?: number) {
const node = this.node;
if (duration !== 0) {
let blocker = this.blocker;
if (!blocker) {
blocker = this.blocker = new cc.Node('blocker');
blocker.addComponent(cc.BlockInputEvents);
blocker.setParent(node);
blocker.setContentSize(node.getContentSize());
}
blocker.active = true;
}
if (duration == undefined || duration < 0) {
duration = this.animDuration;
}
await this.playHideAnim(duration);
this.blocker && (this.blocker.active = false);
node.active = false;
this.onHide && this.onHide(suspended);
this.finishCallback && this.finishCallback(suspended);
}
protected playShowAnim(duration: number): Promise<void> {
return new Promise<void>(res => {
const background = this.background,
main = this.main;
this.node.active = true;
background.active = true;
background.opacity = 0;
main.active = true;
main.scale = 0.5;
main.opacity = 0;
cc.tween(background)
.to(duration * 0.5, { opacity: 150 })
.start();
cc.tween(main)
.to(duration, { scale: 1, opacity: 255 }, { easing: 'backOut' })
.call(res)
.start();
});
}
protected playHideAnim(duration: number): Promise<void> {
return new Promise<void>(res => {
cc.tween(this.background)
.delay(duration * 0.5)
.to(duration * 0.5, { opacity: 0 })
.start();
cc.tween(this.main)
.to(duration, { scale: 0.5, opacity: 0 }, { easing: 'backIn' })
.call(res)
.start();
});
}
protected init(options: Options) { }
protected updateDisplay(options: Options) { }
protected onShow() { }
protected onHide(suspended: boolean) { }
protected finishCallback: (suspended: boolean) => void = null;
public setFinishCallback(callback: (suspended: boolean) => void) {
this.finishCallback = callback;
}
}
|
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.politaktiv.map.domain;
import javax.portlet.ValidatorException;
import org.politaktiv.map.infrastructure.service.BackgroundLocalServiceUtil;
import org.politaktiv.map.infrastructure.service.BackgroundServiceUtil;
import org.politaktiv.map.infrastructure.service.persistence.BackgroundUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
public class MapViewPreferences {
double lon;
double lat;
int zoom;
long backgroundId;
public MapViewPreferences(double lon, double lat, int zoom, long backgroundId){
this.lon = lon;
this.lat = lat;
this.zoom = zoom;
this.backgroundId = backgroundId;
}
public void valide() throws ValidatorException, SystemException {
this.validateLat();
this.valideLon();
this.validateZoom();
this.validateBackgroundId();
}
private void validateBackgroundId() throws ValidatorException {
try {
BackgroundLocalServiceUtil.fetchBackground(this.backgroundId);
} catch (SystemException e) {
throw new ValidatorException("background-does-not-exist", null);
}
}
private void valideLon() throws ValidatorException {
if(! (this.lon >= -20014392.722699 &&
this.lon <= 19904080.923394)){
throw new ValidatorException("wrongLongitude", null);
}
}
private void validateLat() throws ValidatorException {
if(!(this.lat >= -20027726 &&
this.lat <= 20033103)){
throw new ValidatorException("wrongLatitude", null);
}
}
private void validateZoom() throws ValidatorException{
//if its not 0 <= x <= 15
if(!(this.zoom >= 0 &&
this.zoom <= 18)){
throw new ValidatorException("wrongZoomLevel", null);
}
}
public double getLon() {
return this.lon;
}
public double getLat() {
return this.lat;
}
public int getZoom() {
return this.zoom;
}
public long getBackgroundId(){
return this.backgroundId;
}
}
|
<reponame>mohamedkhairy/dhis2-android-sdk
/*
* Copyright (c) 2004-2021, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.program.internal;
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore;
import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction;
import org.hisp.dhis.android.core.arch.handlers.internal.IdentifiableHandlerImpl;
import org.hisp.dhis.android.core.arch.handlers.internal.LinkHandler;
import org.hisp.dhis.android.core.arch.handlers.internal.OrderedLinkHandler;
import org.hisp.dhis.android.core.dataelement.DataElement;
import org.hisp.dhis.android.core.program.ProgramIndicator;
import org.hisp.dhis.android.core.program.ProgramStageSection;
import org.hisp.dhis.android.core.program.ProgramStageSectionDataElementLink;
import org.hisp.dhis.android.core.program.ProgramStageSectionProgramIndicatorLink;
import javax.inject.Inject;
import dagger.Reusable;
@Reusable
final class ProgramStageSectionHandler extends IdentifiableHandlerImpl<ProgramStageSection> {
private final LinkHandler<ProgramIndicator, ProgramStageSectionProgramIndicatorLink>
programStageSectionProgramIndicatorLinkHandler;
private final OrderedLinkHandler<DataElement, ProgramStageSectionDataElementLink>
programStageSectionDataElementLinkHandler;
@Inject
ProgramStageSectionHandler(IdentifiableObjectStore<ProgramStageSection> programStageSectionStore,
LinkHandler<ProgramIndicator, ProgramStageSectionProgramIndicatorLink>
programStageSectionProgramIndicatorLinkHandler,
OrderedLinkHandler<DataElement, ProgramStageSectionDataElementLink>
programStageSectionDataElementLinkHandler) {
super(programStageSectionStore);
this.programStageSectionProgramIndicatorLinkHandler = programStageSectionProgramIndicatorLinkHandler;
this.programStageSectionDataElementLinkHandler = programStageSectionDataElementLinkHandler;
}
@Override
protected void afterObjectHandled(ProgramStageSection programStageSection, HandleAction action) {
programStageSectionDataElementLinkHandler.handleMany(
programStageSection.uid(),
programStageSection.dataElements(),
(dataElement, sortOrder) -> ProgramStageSectionDataElementLink.builder()
.programStageSection(programStageSection.uid())
.dataElement(dataElement.uid())
.sortOrder(sortOrder)
.build());
programStageSectionProgramIndicatorLinkHandler.handleMany(programStageSection.uid(),
programStageSection.programIndicators(),
programIndicator -> ProgramStageSectionProgramIndicatorLink.builder()
.programStageSection(programStageSection.uid())
.programIndicator(programIndicator.uid())
.build());
}
} |
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
int x, y;
cout << "Please enter your values for x and y: ";
cin >> x >> y;
// Polynomial expression
float expression = 3*pow(x, 2) + 4*x*y + 5*pow(y, 2);
cout << "The expression is: " << expression << endl;
return 0;
} |
public class ClothingItem
{
public virtual float WeightGrammsPerUnit { get; }
public virtual int WaterResistance { get; }
public virtual int ColdResistance { get; }
}
public class Jacket : ClothingItem
{
public override float WeightGrammsPerUnit
{
get { return 1615; }
}
public override int WaterResistance
{
get { return 10; }
}
public override int ColdResistance
{
get { return 5; }
}
} |
"""textutils URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from textutilapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index,name="index"),
path('about/', views.about,name="about"),
path('removepunc/', views.removepunc,name="removepunc"),
path('capfirst/', views.capfirst,name="capfirst"),
path('newlineremove/', views.newlineremove,name="newlineremove"),
path('spaceremover/', views.spaceremover,name="spaceremover"),
path('charcount/', views.charcount,name="charcount"),
path('analyzer/',views.analyzer,name="analyzer")
]
|
#!/bin/sh
DESTDIR=${DESTDIR:-}
PREFIX=${PREFIX:-/usr}
install -d ${DESTDIR}${PREFIX}/bin
install -d ${DESTDIR}${PREFIX}/lib/vagga
install -m 755 vagga ${DESTDIR}${PREFIX}/lib/vagga/vagga
install -m 755 apk ${DESTDIR}${PREFIX}/lib/vagga/apk
install -m 755 busybox ${DESTDIR}${PREFIX}/lib/vagga/busybox
install -m 755 alpine-keys.apk ${DESTDIR}${PREFIX}/lib/vagga/alpine-keys.apk
ln -snf ../lib/vagga/vagga ${DESTDIR}${PREFIX}/bin/vagga
|
<reponame>productiveprogrammer-net/common-dev-env
require_relative 'utilities'
require 'yaml'
THREAD_COUNT = 3
def update_apps(root_loc)
# Load configuration.yml into a Hash
config = YAML.load_file("#{root_loc}/dev-env-config/configuration.yml")
return unless config['applications']
output_mutex = Mutex.new
threads = []
queue = Queue.new
# Launch threads with our app-updating code in them.
THREAD_COUNT.times do
threads << Thread.new do
loop do
# Block on queue.pop until a nil object is received
queue_item = queue.pop
break if queue_item.nil?
appname, appconfig = queue_item
output_lines = [colorize_green("================== #{appname} ==================")]
# Check if dev-env-config exists, and if so pull the dev-env configuration. Otherwise clone it.
output_lines += update_or_clone(appconfig, root_loc, appname)
output_mutex.synchronize do
output_lines.each { |line| puts line }
end
end
end
end
populate_queue(config, queue)
threads.map(&:join)
end
def populate_queue(config, queue)
# Put an item representing each app onto the queue
config['applications'].each do |appname, appconfig|
queue.push [appname, appconfig]
end
# Put enough nil objects onto the queue to ensure all the threads shut down once they have processed all the apps
THREAD_COUNT.times do
queue.push nil
end
end
def required_ref(appconfig)
# Ref is the key we check first, but then branch for backwards compatibility
appconfig.fetch('ref', appconfig['branch'])
end
def update_or_clone(appconfig, root_loc, appname)
output = if Dir.exist?("#{root_loc}/apps/#{appname}")
update_app(appconfig, root_loc, appname)
else
clone_app(appconfig, root_loc, appname)
end
# Attempt to merge our remote branch into our local branch, if it's straightforward
output += merge(root_loc, appname, required_ref(appconfig))
output
end
def current_branch(root_loc, appname)
# What branch are we working on?
current_branch = `git -C #{root_loc}/apps/#{appname} rev-parse --abbrev-ref HEAD`.strip
# Check for a detached head scenario (i.e. a specific commit) - technically there is therefore no branch
current_branch = 'detached' if current_branch.eql? 'HEAD'
current_branch
end
def merge(root_loc, appname, required_branch)
return [] if current_branch(root_loc, appname) == 'detached'
output_lines = [colorize_lightblue("Bringing #{required_branch} up to date")]
if run_command("git -C #{root_loc}/apps/#{appname} merge --ff-only", output_lines) != 0
output_lines << colorize_yellow("The local branch couldn't be fast forwarded (a merge is probably " \
"required), so to be safe I didn't update anything")
end
output_lines
end
def update_app(appconfig, root_loc, appname)
output_lines = []
output_lines << colorize_lightblue(
'The repo directory for this app already exists, so I will try to update it'
)
current_branch = current_branch(root_loc, appname)
# If the configuration specifies a fixed commit leave them be
if current_branch == 'detached'
output_lines << colorize_yellow('Detached head detected, nothing to update')
return output_lines
end
# Or the user is not working in the branch originally checked out...
required_reference = required_ref(appconfig)
unless current_branch.eql? required_reference
output_lines << colorize_yellow("The current branch (#{current_branch}) differs from the devenv " \
"configuration (#{required_reference}) so I'm not going to update anything")
return output_lines
end
# Update all the remote branches (this will not change the local branch, we'll do that further down')
output_lines << colorize_lightblue('Fetching from remote...')
return output_lines unless run_command('git -C ' + "#{root_loc}/apps/#{appname} fetch origin", output_lines) != 0
# If there is a git error we shouldn't continue
output_lines << colorize_red("Error while updating #{appname}")
output_lines << colorize_yellow('Continuing in 3 seconds...')
sleep(3)
output_lines
end
def clone_app(appconfig, root_loc, appname)
output_lines = []
output_lines << colorize_lightblue("#{appname} does not yet exist, so I will clone it")
repo = appconfig['repo']
if run_command("git clone #{repo} #{root_loc}/apps/#{appname}", output_lines) != 0
# If there is a git error we shouldn't continue
output_lines << colorize_red("Error while cloning #{appname}")
output_lines << colorize_yellow('Continuing in 3 seconds...')
sleep(3)
end
# What branch are we working on?
current_branch = current_branch(root_loc, appname)
# If we have to, check out the branch/tag/commit that the config wants us to use
required_reference = required_ref(appconfig)
if !current_branch.eql? required_reference
output_lines << colorize_lightblue("Switching to #{required_reference}")
run_command("git -C #{root_loc}/apps/#{appname} checkout #{required_reference}", output_lines)
else
output_lines << colorize_lightblue("Current branch is already #{current_branch}")
end
output_lines
end
update_apps(File.dirname(__FILE__) + '../../') if $PROGRAM_NAME == __FILE__
|
-- ***************************************************************************
-- File: 12_12.sql
--
-- Developed By TUSC
--
-- Disclaimer: Neither Osborne/McGraw-Hill, TUSC, nor the author warrant
-- that this source code is error-free. If any errors are
-- found in this source code, please report them to TUSC at
-- (630)960-2909 ext 1011 or <EMAIL>.
-- ***************************************************************************
SPOOL 12_12.lis
DECLARE
lv_job_num NUMBER;
BEGIN
DBMS_JOB.SUBMIT(lv_job_num, 'LOG_SOURCE;', SYSDATE,
'SYSDATE + 1/24', NULL);
DBMS_OUTPUT.PUT_LINE('Assigned Job #: ' || lv_job_num);
END;
/
SPOOL OFF
|
<gh_stars>0
import React, { Component, PropTypes } from 'react';
import { observer } from 'mobx-react';
import styles from './index.less';
@observer
export default class DetailModal extends Component {
static propTypes = {
visible: PropTypes.bool.isRequired,
title: PropTypes.string,
isNeedheight: PropTypes.bool,
titleComp: PropTypes.func,
contentComp: PropTypes.func,
sourceComp: PropTypes.func,
closeAction: PropTypes.func,
leftBarComp: PropTypes.func
};
componentDidMount() {
this.bodyStyle();
}
componentDidUpdate() {
this.bodyStyle();
setTimeout(() => {
this.contentStyle();
}, 100);
}
getStyle(ele) {
let style = null;
if (window.getComputedStyle) {
style = window.getComputedStyle(ele, null);
} else {
style = ele.currentStyle;
}
return style;
}
contentStyle() {
const detailModalTag = this.refs['detail-modal'];
const titleTag = this.refs['detail-modal-title'];
const contentTag = this.refs['detail-modal-content'];
const titleTagHeight = parseInt(this.getStyle(titleTag).height, 10);
contentTag.style.height = 630 - titleTagHeight - 60 + 'px';
contentTag.scrollTop = 0;
// 设置modal相对于顶部的高度
const windowHeight = document.documentElement.clientHeight;
detailModalTag.style.marginTop = windowHeight / 2 - 315 + 'px';
}
// 隐藏body的滚动条
bodyStyle() {
const body = document.getElementsByTagName('body')[0];
if (this.props.visible) {
setTimeout(() => {
body.style.overflowY = 'hidden';
}, 100);
} else {
body.removeAttribute('style');
}
}
render() {
const modalBox = this.props.visible
? `${styles.modal} ${styles.modalVisible}`
: `${styles.modal}`;
const contentBox = this.props.visible
? `${styles.contentLayer} ${styles.visible}`
: `${styles.contentLayer}`;
return (
<div className={modalBox}>
<div className={styles.bgClick} onClick={this.props.closeAction}></div>
<div ref="detail-modal" className={contentBox}>
<div ref="detail-modal-title" className="clearfix">
<div className={`clearfix ${styles.title}`}>
<div className={styles.titleName}>{this.props.title}</div>
<div className={styles.close} onClick={this.props.closeAction}>
<i className="fa fa-times"></i>
</div>
</div>
<div className="clearfix">
{this.props.titleComp ? <this.props.titleComp /> : null}
</div>
<div className={styles.line}></div>
</div>
<div ref="detail-modal-leftBar" className={styles.leftBar}>
{
this.props.leftBarComp ? <this.props.leftBarComp /> : null
}
</div>
<div ref="detail-modal-content" className={`clearfix ${styles.content}`}>
{this.props.contentComp ? <this.props.contentComp /> : null}
</div>
<div ref="detail-modal-source" className={`clearfix ${styles.source}`}>
{this.props.sourceComp ? <this.props.sourceComp /> : null}
</div>
</div>
</div>
);
}
}
|
package main
import (
"context"
"log"
"net"
"github.com/Wappsto/wedge-api/go/wedge"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type wedgeServer struct{}
// func (*wedgeServer) SetModel(ctx context.Context, req *wedge.SetModelRequest) *wedge.Replay {
// return &wedge.Replay{
// Ok: true,
// Error: nil,
// }
// }
// func (*wedgeServer) SetDevice(ctx context.Context, req *wedge.SetDeviceRequest) *wedge.Replay {
// return &wedge.Replay{
// Ok: true,
// Error: nil,
// }
// }
// func (*wedgeServer) SetValue(ctx context.Context, req *wedge.SetValueRequest) *wedge.Replay {
// return &wedge.Replay{
// Ok: true,
// Error: nil,
// }
// }
// func (*wedgeServer) SetState(ctx context.Context, req *wedge.SetStateRequest) *wedge.Replay {
// return &wedge.Replay{
// Ok: true,
// Error: nil,
// }
// }
func (*wedgeServer) SetModel(context.Context, *wedge.SetModelRequest) (*wedge.Replay, error) {
return nil, status.Errorf(codes.Unimplemented, "method SetModel not implemented")
}
func (*wedgeServer) SetDevice(context.Context, *wedge.SetDeviceRequest) (*wedge.Replay, error) {
return nil, status.Errorf(codes.Unimplemented, "method SetDevice not implemented")
}
func (*wedgeServer) SetValue(context.Context, *wedge.SetValueRequest) (*wedge.Replay, error) {
return nil, status.Errorf(codes.Unimplemented, "method SetValue not implemented")
}
func (*wedgeServer) SetState(context.Context, *wedge.SetStateRequest) (*wedge.Replay, error) {
return nil, status.Errorf(codes.Unimplemented, "method SetState not implemented")
}
func (*wedgeServer) GetModel(context.Context, *wedge.GetModelRequest) (*wedge.Model, error) {
return nil, nil
}
func (*wedgeServer) GetControl(context.Context, *wedge.GetControlRequest) (*wedge.Control, error) {
return nil, nil
}
func main() {
l, err := net.Listen("tcp", "localhost:50051")
if err != nil {
log.Fatal("Could not create wedge listener on port 50051")
}
grpcServ := grpc.NewServer()
wedge.RegisterWedgeServer(grpcServ, &wedgeServer{})
if err := grpcServ.Serve(l); err != nil {
log.Fatal("Failed to serve from wedge server")
}
log.Println("Wedge server running on port: 50051...")
}
|
package com.idankorenisraeli.spyboard.input;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.inputmethodservice.Keyboard;
import android.util.AttributeSet;
import android.util.Log;
import java.util.List;
/**
* Provides a distinctive keyboard class view to the keyboard of this application
*/
public class SpyKeyboardView extends android.inputmethodservice.KeyboardView {
public SpyKeyboardView(Context context, AttributeSet attrs) {
super(context, attrs);
}
} |
#!/bin/sh
#
# 1. find *.c or *.h file from current directory
# 2. if the file is utf-8 encoded file, then convert it to cp936 encoded.
#
# it will replace the original file.
#
# Author: wangjinle
# Usage: utf8tocp936.sh
#
find ./ -name "*."[ch] | while read fname
do
# echo "$fname";
has_utf8=$(file "$fname" | grep "UTF-8")
if [ -n "$has_utf8" ];then
# echo $has_utf8
iconv -f utf-8 -t cp936 "$fname" -o "$fname"
fi
done
|
package callback
import (
"errors"
"github.com/nspcc-dev/neo-go/pkg/core/interop"
"github.com/nspcc-dev/neo-go/pkg/vm"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
)
// SyscallCallback represents callback for a syscall.
type SyscallCallback struct {
desc *interop.Function
}
var _ Callback = (*SyscallCallback)(nil)
// ArgCount implements Callback interface.
func (p *SyscallCallback) ArgCount() int {
return p.desc.ParamCount
}
// LoadContext implements Callback interface.
func (p *SyscallCallback) LoadContext(v *vm.VM, args []stackitem.Item) {
for i := len(args) - 1; i >= 0; i-- {
v.Estack().PushVal(args[i])
}
}
// CreateFromSyscall creates callback from syscall.
func CreateFromSyscall(ic *interop.Context) error {
id := uint32(ic.VM.Estack().Pop().BigInt().Int64())
f := ic.GetFunction(id)
if f == nil {
return errors.New("syscall not found")
}
if f.DisallowCallback {
return errors.New("syscall is not allowed to be used in a callback")
}
ic.VM.Estack().PushVal(stackitem.NewInterop(&SyscallCallback{f}))
return nil
}
|
export default interface Config {
enablePasswordless: boolean;
enable2FAWithFido2: boolean;
} |
<filename>BasicCucumberFramework/com.automationpractice/src/main/java/com/automationpractice/pages/SignInPage.java
package com.automationpractice.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class SignInPage extends BasePage {
@FindBy(id = "email")
private WebElement emailButton;
@FindBy(id = "passwd")
private WebElement passwordButton;
@FindBy(id = "SubmitLogin")
private WebElement clickLoginButton ;
public SignInPage(WebDriver driver) {
super(driver);
}
public MyAccountPage loginInWithDetails(String email, String password) {
try{
logger.info("loginInWithDetails started execution");
emailButton.sendKeys(email);
logger.info("email was entered successfully");
passwordButton.sendKeys(password);
clickLoginButton.click();
logger.info("loginInWithDetails executed successfully");
}catch(Throwable t){
logger.error("loginInWithDetails encountered error : " + t);
camera.takeShot("loginInWithDetails");
}
return PageFactory.initElements(driver, MyAccountPage.class);
}
public boolean validateThatIamLoggedOutWith(String message) {
boolean result = false;
try{
logger.info("validateThatIamLoggedOutWith started execution");
result = driver.getPageSource().contains(message);
logger.info("validateThatIamLoggedOutWith encountered executed successfully");
}catch(Throwable t){
camera.takeShot("validateThatIamLoggedOutWith");
}
return result;
}
}
|
<gh_stars>10-100
import os
import random
import string
from dotenv import load_dotenv
from twitter import Api
load_dotenv()
api = Api(
consumer_key=os.environ.get("TWITTER_CONSUMER_KEY"),
consumer_secret=os.environ.get("TWITTER_CONSUMER_SECRET"),
access_token_key=os.environ.get("TWITTER_ACCESS_TOKEN_KEY"),
access_token_secret=os.environ.get("TWITTER_ACCESS_TOKEN_SECRET"),
)
intro_phrases = [
"Swatcheriffic!",
"Just added a new swatch!",
"What's that I see? A new swatch‽",
"New swatch ahoy!",
"A new swatch appears!",
"More filament!",
"Another swatch? Another!",
"Let there be color!",
"What's this?",
"More plastic has arrived!",
"Where'd this come from?",
"A new swatch!",
"A new color!",
"Colors ahoy!",
"Swatches abound!",
"A new color!",
"Gadzooks!",
]
outro_phrases = [
"can be found here:",
"can be seen here:",
"joins the library!",
"now available!",
"is now available in the library!",
"now listed!",
"has been added!",
"has been added here:",
"now listed!",
"is now listed!",
"is now in the library!",
"can be found in the library!",
"appears here:",
"is listed here:",
"",
]
def generate_swatch_upload_tweet(swatch) -> str:
plural = "'" if swatch.manufacturer.name.endswith("s") else "'s"
return (
f"{random.choice(intro_phrases)} {swatch.manufacturer.name}{plural}"
f" {swatch.color_name} {swatch.filament_type.name}"
f" {random.choice(outro_phrases)}"
f" https://filamentcolors.xyz/swatch/{swatch.id}?ref=newswatchtweet"
)
def send_tweet(message: str = None, swatch=None) -> None:
if not message:
message = generate_swatch_upload_tweet(swatch)
api.PostUpdate(message)
daily_tweet_intro = [
"There are colors we know and colors we have yet to know!",
"Let's take a stroll through the archives!",
"Spin the wheel of random selection to see what we get!",
"It's always fun to find colors we may not have seen before.",
"`return random.choice(Swatch.objects.all())`",
"A quick scroll through the archives unearthed this!",
"[insert clickbait intro here]",
"Remember, filaments in the mirror may be closer than they appear.",
"This tweet may be automated, but it's more reliable than some printers I've worked on.",
"Maybe you've seen this one before, maybe you haven't.",
"Maybe this one's new to you, maybe it's not!",
"Wanted: 3D-printing-related one-liners to put as intros to these tweets. Apply within.",
"Pick a color, any color... nevermind, I guessed wrong. But!",
"The history books pulled this swatch for your perusal.",
"A website sending its own tweets? That's preposterous. Let's look at swatches instead!",
"Is it just me or is the interrobang criminally underrated‽ But anyway, back to swatches.",
"Today's fashion-forward color is brought to you by Python! Python: not just a snake!",
'"Swatches?! Why does it always have to be swatches???"',
"Fun fact: this system is incompatible with Pantone!",
"🎶 Do you hear the swatches print? Swatches are printing all the time... 🎵",
"Looking for some new colors? The librarian has some recommendations!",
"I asked the Magic 8-Ball for your favorite color and it gave me something!",
"I've always wondered why my copy of Gray's Anatomy is tan... hmm...",
"🎶 Voulez-vous coloriez avec moi, ce soir? 🎵",
"If a print fails and no one is around to hear it, does it still spaghetti? Anyway..."
"Did you see that clip of {famous_person} doing {totally_normal_thing}??? Anyway...",
f"This tweet is brought to you by the number {random.choice(string.digits)}!",
"Heeeere's Swatchy!",
"Fun fact: my bookshelves are (mostly!) organized by color. Ask me about it sometime!",
"One of these days I'll add a bunch of Sims loading messages. Reticulating splines...",
"Is it possible to have too many samples? Yes, but actually no.",
]
def generate_daily_swatch_tweet(swatch):
plural = swatch.manufacturer.get_possessive_apostrophe
intro = random.choice(daily_tweet_intro)
full_update = (
f"{intro}\n\nHave you seen this one yet? {swatch.manufacturer.name}{plural}"
f" {swatch.color_name} {swatch.filament_type.name} can be found here:"
f" https://filamentcolors.xyz/swatch/{swatch.id}?ref=autotweet"
)
return full_update
|
/** The picture file to be uploaded. */
var fileData = null;
$(function(){
initFileUpload();
initEvents();
});
function initFileUpload() {
$('#fileupload').fileupload({
autoUpload: false,
url: userPictureUploadUrl,
acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
maxFileSize: 1000000, //1 MB
}).on('fileuploadadd', function (e, data) {
fileData = data;
var file = fileData.files[0];
if(file.size > userPictureMaxSize) {
$('#note').attr('class', 'alert alert-danger').text('Picture exceeds file size limit.').show();
fileData = null;
return;
}
if(!file.type.match(/(\.|\/)(jpe?g|png)$/i)) {
$('#note').attr('class', 'alert alert-danger').text('Only png or jpg pictures files are allowed.').show();
fileData = null;
return;
}
//Load preview
loadImage(file,
function (img) {
$(img).attr({'id': 'user-picture', 'class':'img-circle'}).
css({'width':60,'margin-right':20}).
removeAttr('width').removeAttr('height');
$('#user-picture').replaceWith(img);
},
{maxWidth: 600} // Options
);
});
}
function initEvents() {
$('#change-pic-btn').click(changePictureClicked);
$('#save-btn').click(saveClicked);
}
function changePictureClicked() {
$('#picture-input').trigger('click');
}
function saveClicked() {
if(fileData == null) {
updateUserInfo();
return;
}
//Upload picture
fileData.submit().error(function(jqXHR, textStatus, errorThrown){
var responseText = jqXHR.responseText;
var start = responseText.indexOf(':');
var message = responseText.substring(start + 1).trim();
$('#note').attr('class', 'alert alert-danger').text(message).show();
}).success(function(result, textStatus, jqXHR){
updateUserInfo();
});
}
function updateUserInfo() {
$.ajax({
type: 'POST',
url: userUpdateUrl,
data: $('#account-basics-form').serialize(),
error: function(jqXHR, textStatus, errorThrown) {
var responseText = jqXHR.responseText;
var start = responseText.indexOf(':');
var message = responseText.substring(start + 1).trim();
$('#note').attr('class', 'alert alert-danger').text(message).show();
},
success: function(data, textStatus, jqXHR) {
$('#note').attr('class', 'alert alert-success').text('Your information has been updated!').show();
}
});
}
|
#!/bin/bash
set -e
set -u
set -o pipefail
sed 's/<<<TAGPOST_GRPC_WEB_PORT>>>/'"$TAGPOST_GRPC_WEB_PORT"'/g;s/<<<TAGPOST_GRPC_WEB_HOST>>>/'"$TAGPOST_GRPC_WEB_HOST"'/g' \
/opt/bootstrap/default.conf.template \
> /etc/nginx/conf.d/default.conf
exec nginx -g "daemon off;"
|
#!/usr/bin/env bash
#SBATCH -p localLimited
#SBATCH -A ecortex
#SBATCH --mem=2G
#SBATCH --gres=gpu:1
#SBATCH --output=results_mlp_lesionp90.out
export HOME=`getent passwd $USER | cut -d':' -f6`
export PYTHONUNBUFFERED=1
echo Running on $HOSTNAME
source /usr/local/anaconda3/etc/profile.d/conda.sh
conda activate /home/mazlfghr/.conda/envs/csls
echo "Process mlp - lesioned with p 90 starts"
python main.py \
--cortical_model 'mlp' \
--nruns_cortical 20 \
--truncated_mlp 'false' \
--is_lesion \
--lesion_p 90 \
--out_file 'results_mlp_lesionp90.P' \
--seed 0 \
--use_images \
--print_every 200 \
--N_episodic 1000 \
--bs_episodic 16 \
--lr_episodic 0.001 \
--cortical_task 'face_task' \
--N_cortical 1000 \
--bs_cortical 32 \
--lr_cortical 0.001 \
--checkpoints 50 \
--order_ctx 'first' \
--N_responses 'one' \
--N_contexts 2 \
--dimred_method 'pca' \
|
package httpserver
import (
"context"
"github.com/fighthorse/redisAdmin/component/httpclient"
"github.com/fighthorse/redisAdmin/component/log"
"github.com/fighthorse/redisAdmin/protos"
)
// 高德地图 api
// https://lbs.amap.com/api/webservice/guide/api/weatherinfo
type AmapClient struct {
*httpclient.Client
name string
}
func (c *AmapClient) GetWeatherInfo(ctx context.Context, reqBody map[string]interface{}) (result protos.WeatherInfoRep, err error) {
err = c.Client.Send(ctx, "GET", "/ip/grade/get", reqBody, &result)
if err != nil {
log.Error(ctx, "GetWeatherInfoErr", log.Fields{"in": reqBody, "out": result, "err": err.Error()})
}
return result, err
}
|
#
set -e
set -x
./scripts/importbvi.py -o PipeClock.bsv -P pclk -I pclk -p pcie_lane \
xilinx/7x/pcie/source/pcie_7x_0_pipe_clock.v
|
// GlobalDailyReport the Global Daily Reports
export interface IGlobalDailyReport {
Code: number;
Message: string;
Document: IReport[];
}
// Report holds the cases data for each month (the reports inside document)
export interface IReport {
id: number;
province_state: string;
country_region: string;
last_update: string;
confirmed: number;
deaths: number;
recovered: number;
active: number;
fips: string;
admin2: string;
case_fatality_ratio: number;
combined_key: string;
incidence_rate: number;
}
// TimeSeriesSummary Time Series Summary
export interface ITimeSeriesSummary {
Code: number;
Message: string;
Reports: ITimeSeriesReport[];
}
// TimeSeriesReport holds the time series data
export interface ITimeSeriesReport {
ID: number;
UID: number;
ISO2: string;
ISO3: string;
Code3: number;
FIPS: number;
Admin2: string;
CombinedKey: string;
ProvinceState: string;
CountryRegion: string;
Latitude: number;
Longitude: number;
Population: number;
Data: { [date: string]: number };
}
export type TimeSeriesType = "deaths" | "recovered" | "confirmed";
export type TimeSeriesCountry = "us" | "global";
|
export { default } from '../src/components/ComponentSandbox/ComponentSandbox.vue' |
#!/bin/sh
fpcore_dir="tests/scripts/fpcores/"
script_dir="tests/scripts/"
tmp_dir="/tmp/"
target="${script_dir}batch.txt"
test="${script_dir}test-toolserver.txt"
expected="${script_dir}test-toolserver.out.txt"
exp_file="${fpcore_dir}export.fpcore"
trans_file="${fpcore_dir}transform.fpcore"
eval_file="${fpcore_dir}eval2.fpcore"
out_name="${tmp_dir}test-toolserver"
# setup
cd "$(dirname "$0")/../.."
if [ "$1" = "generate" ]
then
echo "Generating expected output for test-transform.sh..."
test=$expected
fi
rm -f $test
# testing
cat $target | sed -e "s,EXPORT,$exp_file,g" | sed -e "s,TRANSFORM,$trans_file,g" | sed -e "s,EVALUATE,$eval_file,g" | sed -e "s,OUTNAME,$out_name,g" | racket toolserver.rkt 2>> $test
cat "${out_name}.txt" >> $test
# compare
if [ "$1" != "generate" ]
then
cmp -s $test $expected
ret=$?
if [ "$ret" -ne 0 ]
then
diff $test $expected
fi
rm $test
exit $ret
else
echo "Done"
fi |
<reponame>mason-fish/brim
import {css} from "styled-components"
const headingSection = css`
font-family: system-ui, sans-serif;
font-size: 13px;
font-weight: 500;
letter-spacing: 1px;
`
const headingList = css`
font-family: system-ui, sans-serif;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.8px;
text-transform: uppercase;
`
const headingPage = css`
font-family: system-ui, sans-serif;
font-size: 18px;
line-height: 1.2;
font-weight: 700;
`
const labelSmall = css`
font-family: system-ui, sans-serif;
font-size: 11px;
line-height: 17px;
font-weight: 400;
`
const labelNormal = css`
font-family: system-ui, sans-serif;
font-size: 13px;
line-height: 16px;
font-weight: 400;
`
const labelBold = css`
font-family: system-ui, sans-serif;
letter-spacing: -0.08;
font-size: 13px;
line-height: 16px;
font-weight: 600;
`
const hoverQuiet = css`
&:hover {
background: rgba(0, 0, 0, 0.08);
}
&:active {
background: rgba(0, 0, 0, 0.1);
}
`
const typeStyles = css`
&.addr,
&.set\[addr\] {
color: var(--ip);
}
&.port,
&.set\[port\] {
color: var(--port);
}
&.interval,
&.set\[interval\] {
color: var(--interval);
}
&.count,
&.set\[count\] {
color: var(--count);
text-align: right;
}
&.bool,
&.set\[bool\] {
color: var(--blue);
}
`
const theme = {
typography: {
headingSection,
headingList,
headingPage,
labelSmall,
labelNormal,
labelBold,
typeStyles
},
hoverQuiet
}
export default theme
|
<filename>veriloggen/stream/visitor.py
from __future__ import absolute_import
from __future__ import print_function
from . import stypes
class _Visitor(object):
def __init__(self):
self.visited_node = set()
self.result_cache = {}
def generic_visit(self, node):
raise TypeError("Type '%s' is not supported." % str(type(node)))
def visit(self, node):
if node in self.result_cache:
return self.result_cache[node]
if node in self.visited_node:
raise ValueError("Loop detected.")
self.visited_node.add(node)
rslt = self._visit(node)
self.result_cache[node] = rslt
return rslt
def _visit(self, node):
if isinstance(node, stypes._Accumulator):
return self.visit__Accumulator(node)
if isinstance(node, stypes._BinaryOperator):
return self.visit__BinaryOperator(node)
if isinstance(node, stypes._UnaryOperator):
return self.visit__UnaryOperator(node)
if isinstance(node, stypes._SpecialOperator):
return self.visit__SpecialOperator(node)
if isinstance(node, stypes._ParameterVariable):
return self.visit__ParameterVariable(node)
if isinstance(node, stypes._Variable):
return self.visit__Variable(node)
if isinstance(node, stypes._Constant):
return self.visit__Constant(node)
visitor = getattr(
self, 'visit_' + node.__class__.__name__, self.generic_visit)
return visitor(node)
def visit__BinaryOperator(self, node):
raise NotImplementedError()
def visit__UnaryOperator(self, node):
raise NotImplementedError()
def visit__SpecialOperator(self, node):
raise NotImplementedError()
def visit__Accumulator(self, node):
raise NotImplementedError()
def visit__ParameterVariable(self, node):
raise NotImplementedError()
def visit__Variable(self, node):
raise NotImplementedError()
def visit__Constant(self, node):
raise NotImplementedError()
class InputVisitor(_Visitor):
def visit__BinaryOperator(self, node):
left = self.visit(node.left)
right = self.visit(node.right)
return left | right
def visit__UnaryOperator(self, node):
right = self.visit(node.right)
return right
def visit__SpecialOperator(self, node):
ret = set()
for var in node.args:
var = self.visit(var)
ret.update(var)
return ret
def visit__Accumulator(self, node):
right = self.visit(node.right)
size = self.visit(node.size) if node.size is not None else set()
initval = (self.visit(node.initval)
if node.initval is not None else set())
enable = self.visit(node.enable) if node.enable is not None else set()
reset = self.visit(node.reset) if node.reset is not None else set()
return right | size | initval | enable | reset
def visit__ParameterVariable(self, node):
return set([node])
def visit__Variable(self, node):
if isinstance(node.input_data, stypes._Numeric):
return self.visit(node.input_data)
return set([node])
def visit__Constant(self, node):
return set()
class OutputVisitor(_Visitor):
def visit__BinaryOperator(self, node):
left = self.visit(node.left)
right = self.visit(node.right)
mine = set([node]) if node._has_output() else set()
return left | right | mine
def visit__UnaryOperator(self, node):
right = self.visit(node.right)
mine = set([node]) if node._has_output() else set()
return right | mine
def visit__SpecialOperator(self, node):
ret = set()
for var in node.args:
var = self.visit(var)
ret.update(var)
mine = set([node]) if node._has_output() else set()
return ret | mine
def visit__Accumulator(self, node):
right = self.visit(node.right)
size = self.visit(node.size) if node.size is not None else set()
initval = (self.visit(node.initval)
if node.initval is not None else set())
enable = self.visit(node.enable) if node.enable is not None else set()
#reset = self.visit(node.reset) if node.reset is not None else set()
reset = set()
mine = set([node]) if node._has_output() else set()
return right | size | initval | enable | reset | mine
def visit__ParameterVariable(self, node):
mine = set([node]) if node._has_output() else set()
return mine
def visit__Variable(self, node):
if isinstance(node.input_data, stypes._Numeric):
return self.visit(node.input_data)
mine = set([node]) if node._has_output() else set()
return mine
def visit__Constant(self, node):
mine = set([node]) if node._has_output() else set()
return mine
class OperatorVisitor(_Visitor):
def visit__BinaryOperator(self, node):
left = self.visit(node.left)
right = self.visit(node.right)
mine = set([node])
return left | right | mine
def visit__UnaryOperator(self, node):
right = self.visit(node.right)
mine = set([node])
return right | mine
def visit__SpecialOperator(self, node):
ret = set()
for var in node.args:
var = self.visit(var)
ret.update(var)
mine = set([node])
return ret | mine
def visit__Accumulator(self, node):
right = self.visit(node.right)
size = self.visit(node.size) if node.size is not None else set()
initval = (self.visit(node.initval)
if node.initval is not None else set())
enable = self.visit(node.enable) if node.enable is not None else set()
reset = self.visit(node.reset) if node.reset is not None else set()
mine = set([node])
return right | size | initval | enable | reset | mine
def visit__ParameterVariable(self, node):
return set()
def visit__Variable(self, node):
if isinstance(node.input_data, stypes._Numeric):
return self.visit(node.input_data)
return set()
def visit__Constant(self, node):
return set()
class AllVisitor(OperatorVisitor):
def visit__ParameterVariable(self, node):
return set([node])
def visit__Variable(self, node):
if isinstance(node.input_data, stypes._Numeric):
return self.visit(node.input_data)
return set([node])
def visit__Constant(self, node):
return set([node])
|
#!/usr/bin/env python3
# Copyright 2020 <NAME>
# See LICENSE file for licensing details.
"""Charm for the ML Flow Server.
https://github.com/canonical/mlflow-operator
"""
import json
import logging
from base64 import b64encode
from oci_image import OCIImageResource, OCIImageResourceError
from ops.charm import CharmBase
from ops.main import main
from ops.model import ActiveStatus, BlockedStatus, MaintenanceStatus, WaitingStatus
from serialized_data_interface import (
NoCompatibleVersions,
NoVersionsListed,
get_interfaces,
)
DB_NAME = "mlflow"
BUCKET_NAME = "mlflow"
class Operator(CharmBase):
"""Charm for the ML Flow Server.
https://github.com/canonical/mlflow-operator
"""
def __init__(self, *args):
super().__init__(*args)
self.image = OCIImageResource(self, "oci-image")
self.log = logging.getLogger(__name__)
for event in [
self.on.install,
self.on.leader_elected,
self.on.upgrade_charm,
self.on.config_changed,
self.on.db_relation_changed,
self.on["object-storage"].relation_changed,
self.on["ingress"].relation_changed,
]:
self.framework.observe(event, self.main)
# Register relation events
for event in [
self.on.pod_defaults_relation_joined,
self.on.pod_defaults_relation_changed,
]:
self.framework.observe(event, self._on_pod_defaults_relation_changed)
def _on_pod_defaults_relation_changed(self, event):
try:
interfaces = self._get_interfaces()
except CheckFailedError as check_failed:
self.model.unit.status = check_failed.status
return
obj_storage = interfaces["object-storage"].get_data()
config = self.model.config
endpoint = f"http://{obj_storage['service']}:{obj_storage['port']}"
tracking = f"{self.model.app.name}.{self.model.name}.svc.cluster.local"
tracking = f"http://{tracking}:{config['mlflow-port']}"
event.relation.data[self.app]["pod-defaults"] = json.dumps(
{
"minio": {
"env": {
"AWS_ACCESS_KEY_ID": obj_storage["access-key"],
"AWS_SECRET_ACCESS_KEY": obj_storage["secret-key"],
"MLFLOW_S3_ENDPOINT_URL": endpoint,
"MLFLOW_TRACKING_URI": tracking,
}
}
}
)
requirements = []
try:
for req in open("files/mlflow_requirements.txt", "r"):
requirements.append(req.rstrip("\n"))
except IOError as e:
print("Error loading mlflow requirements file:", e)
event.relation.data[self.unit]["requirements"] = str(requirements)
def main(self, event):
"""Main function of the charm.
Runs at install, update, config change and relation change.
"""
try:
self._check_leader()
interfaces = self._get_interfaces()
image_details = self._check_image_details()
except CheckFailedError as check_failed:
self.model.unit.status = check_failed.status
return
self._configure_mesh(interfaces)
config = self.model.config
charm_name = self.model.app.name
mysql = self.model.relations["db"]
if len(mysql) > 1:
self.model.unit.status = BlockedStatus("Too many mysql relations")
return
try:
mysql = mysql[0]
unit = list(mysql.units)[0]
mysql = mysql.data[unit]
mysql["database"]
except (IndexError, KeyError):
self.model.unit.status = WaitingStatus("Waiting for mysql relation data")
return
if not ((obj_storage := interfaces["object-storage"]) and obj_storage.get_data()):
self.model.unit.status = WaitingStatus("Waiting for object-storage relation data")
return
self.model.unit.status = MaintenanceStatus("Setting pod spec")
obj_storage = list(obj_storage.get_data().values())[0]
secrets = [
{
"name": f"{charm_name}-minio-secret",
"data": {
k: b64encode(v.encode("utf-8")).decode("utf-8")
for k, v in {
"AWS_ENDPOINT_URL": "http://{service}:{port}".format(**obj_storage),
"AWS_ACCESS_KEY_ID": obj_storage["access-key"],
"AWS_SECRET_ACCESS_KEY": obj_storage["secret-key"],
"USE_SSL": str(obj_storage["secure"]).lower(),
}.items()
},
},
{
"name": f"{charm_name}-db-secret",
"data": {
k: b64encode(v.encode("utf-8")).decode("utf-8")
for k, v in {
"DB_ROOT_PASSWORD": mysql["root_password"],
"MLFLOW_TRACKING_URI": "mysql+pymysql://{}:{}@{}:{}/{}".format(
"root",
mysql["root_password"],
mysql["host"],
mysql["port"],
mysql["database"],
),
}.items()
},
},
]
self.model.pod.set_spec(
{
"version": 3,
"containers": [
{
"name": "mlflow",
"imageDetails": image_details,
"ports": [{"name": "http", "containerPort": config["mlflow_port"]}],
"args": [
"--host",
"0.0.0.0",
"--backend-store-uri",
"$(MLFLOW_TRACKING_URI)",
"--default-artifact-root",
"s3://{}/".format(BUCKET_NAME),
],
"envConfig": {
"db-secret": {"secret": {"name": f"{charm_name}-db-secret"}},
"aws-secret": {"secret": {"name": f"{charm_name}-minio-secret"}},
"AWS_DEFAULT_REGION": "us-east-1",
"MLFLOW_S3_ENDPOINT_URL": "http://{service}:{port}".format(
**obj_storage
),
},
}
],
"kubernetesResources": {
"secrets": secrets,
"services": [
{
"name": "mlflow-external",
"spec": {
"type": "NodePort",
"selector": {
"app.kubernetes.io/name": "mlflow",
},
"ports": [
{
"protocol": "TCP",
"port": config["mlflow_port"],
"targetPort": config["mlflow_port"],
"nodePort": config["mlflow_nodeport"],
}
],
},
},
{
"name": "kubeflow-external",
"spec": {
"type": "NodePort",
"selector": {
"app.kubernetes.io/name": "istio-ingressgateway",
},
"ports": [
{
"protocol": "TCP",
"port": config["kubeflow_port"],
"targetPort": config["kubeflow_port"],
"nodePort": config["kubeflow_nodeport"],
}
],
},
},
{
"name": "kubeflow-external-lb",
"spec": {
"type": "LoadBalancer",
"selector": {
"app.kubernetes.io/name": "istio-ingressgateway",
},
"ports": [
{
"protocol": "TCP",
"port": config["kubeflow_port"],
"targetPort": config["kubeflow_port"],
}
],
},
},
],
},
},
)
self.model.unit.status = ActiveStatus()
def _configure_mesh(self, interfaces):
if interfaces["ingress"]:
interfaces["ingress"].send_data(
{
"prefix": "/mlflow/",
"rewrite": "/",
"service": self.model.app.name,
"port": self.model.config["mlflow_port"],
}
)
def _check_leader(self):
if not self.unit.is_leader():
# We can't do anything useful when not the leader, so do nothing.
raise CheckFailedError("Waiting for leadership", WaitingStatus)
def _get_interfaces(self):
try:
interfaces = get_interfaces(self)
except NoVersionsListed as err:
raise CheckFailedError(err, WaitingStatus)
except NoCompatibleVersions as err:
raise CheckFailedError(err, BlockedStatus)
return interfaces
def _check_image_details(self):
try:
image_details = self.image.fetch()
except OCIImageResourceError as e:
raise CheckFailedError(f"{e.status.message}", e.status_type)
return image_details
class CheckFailedError(Exception):
"""Raise this exception if one of the checks in main fails."""
def __init__(self, msg, status_type=None):
super().__init__()
self.msg = str(msg)
self.status_type = status_type
self.status = status_type(msg)
if __name__ == "__main__":
main(Operator)
|
<html>
<head>
<title>Table of Information</title>
<style type="text/css">
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<h1>Table of Information</h1>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>30</td>
</tr>
<tr>
<td>Mary</td>
<td>25</td>
</tr>
<tr>
<td>Bob</td>
<td>32</td>
</tr>
</table>
</body>
</html> |
<reponame>k-dominik/nifty<filename>src/python/lib/graph/opt/minstcut/minstcut.cxx
#include <pybind11/pybind11.h>
#include <iostream>
namespace py = pybind11;
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
namespace nifty{
namespace graph{
namespace opt{
namespace minstcut{
void exportMinstcutObjective(py::module &);
void exportMinstcutFactory(py::module &);
void exportMinstcutVisitorBase(py::module &);
void exportMinstcutBase(py::module &);
} // namespace nifty::graph::opt::minstcut
} // namespace nifty::graph::opt
}
}
PYBIND11_PLUGIN(_minstcut) {
py::options options;
options.disable_function_signatures();
py::module minstcutModule("_minstcut", "minstcut submodule of nifty.graph");
using namespace nifty::graph::opt::minstcut;
exportMinstcutObjective(minstcutModule);
exportMinstcutVisitorBase(minstcutModule);
exportMinstcutBase(minstcutModule);
exportMinstcutFactory(minstcutModule);
return minstcutModule.ptr();
}
|
#!/bin/sh
PATH="/rescue"
kenv init_shell="/bin/sh" >/dev/null 2>/dev/null
if [ ! -d "/memdisk" ] ; then
mount -uw /
mdconfig -du md0
mdconfig -du md1
rm /init-reroot.sh
fi
exit 0
|
# The Book of Ruby - http://www.sapphiresteel.com
class MyClass
attr_accessor :name
attr_accessor :number
def initialize( aName, aNumber )
@name = aName
@number = aNumber
end
def ten
return 10
end
end
ob = MyClass.new( "<NAME>", "007" )
puts( "Double-quoted: My name is #{ob.name} and my number is #{ob.number}" )
puts( "Here's a tab\ta new line\na calculation #{2*3} and a method-call #{ob.ten}" )
puts( 'Single-quoted: My name is #{ob.name} and my number is #{ob.number}' )
puts( 'Here\'s a tab\ta new line\na calculation #{2*3} and a method-call #{ob.ten}' )
|
def find_largest_number(lst):
largest_num = 0
for num in lst:
if num > largest_num:
largest_num = num
return largest_num
result = find_largest_number([12, 34, 56, 78, 99])
print(result) |
#!/bin/bash
host=`hostname`
experiment_dir="../"
output_dir="results"
experiment_file=$experiment_dir/0.txt
output_dir=$output_dir/lse
data_dir="../data/output/"
gpu_id=0
numEntityTypes=1
includeEntityTypes=1
includeEntity=1
numEpoch=20
numFeatureTemplates=3
rnnHidSize=250
relationEmbeddingDim=25
entityTypeEmbeddingDim=50
entityEmbeddingDim=50
relationVocabSize=9
entityVocabSize=2851220
entityTypeVocabSize=6
topK=2 #0 is max; 1 is top K , 2 is LogSumExp
K=5
regularize=0
learningRate=1e-3
learningRateDecay=0.0167 #(1/60)
l2=1e-3
rnnType='lstm' #rnn or lstm as of now
epsilon=1e-8 #epsilon for adam
gradClipNorm=5
gradientStepCounter=100000 #to print loss after gradient updates
saveFrequency=1
batchSize=128
useGradClip=1 # 0 == L2 regularization
# package_path='/home/rajarshi/ChainsofReasoning/model/?.lua'
useAdam=1
paramInit=0.1
evaluationFrequency=5
createExptDir=1 #make it 0 if you dont want to create a directory and only print stuff
useReLU=1
rnnInitialization=1
numLayers=1
useDropout=0
dropout=0.3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.