text
stringlengths
27
775k
# test_logger from opyprint import print # noqa: F401 from opyprint.logger import Logger, LoggerBase, PrintLogger def test_base_logger(): assert Logger.DEBUG == LoggerBase.DEBUG assert Logger.DISABLED == LoggerBase.DISABLED assert Logger.TRACE == LoggerBase.TRACE assert Logger.INFO == LoggerBase.INFO def test_print_logger(): assert LoggerBase.DEBUG == PrintLogger.DEBUG assert LoggerBase.DISABLED == PrintLogger.DISABLED assert LoggerBase.TRACE == PrintLogger.TRACE assert LoggerBase.INFO == PrintLogger.INFO logger = PrintLogger(PrintLogger.INFO) assert isinstance(logger, LoggerBase) assert isinstance(logger, Logger) assert logger.level == PrintLogger.INFO # logger.debug("test-msg")
import { BlendMode, FillRule, ShapeType } from '../helpers'; import { MultiDimensionalKeyframed, Value, OffsetKeyframe } from '../properties'; export type Fill = { /** * Match Name * @desc After Effect's Match Name. Used for expressions */ mn: string; /** * Name * @desc After Effect's Name. Used for expressions */ nm: string; /** * Direction * @desc After Effect's Direction. Direction how the shape is drawn. Used for trim path for example */ d: number; /** * Type * @desc Shape content type */ ty: ShapeType.Fill; /** * Opacity * @desc Fill Opacity */ o: Value<number | OffsetKeyframe[]>; /** * Color * @desc Fill Color */ c: MultiDimensionalKeyframed; /** * Rule * @desc Fill Rule */ r: FillRule; /** * Property Index * @desc Property Index. Used for expressions */ ix?: number; /** * Hide element */ hd?: boolean; /** * 混合模式 - Blend Mode * @default BlendMode.Normal */ bm?: BlendMode; };
import numpy as np import sys from plotter import Plotter, PlotterType x = np.linspace(-np.pi, np.pi, 201) to_plot = [ { "title": "Plot", "type": PlotterType.PLOT, "data": [x, np.sin(x)] }, ] pl = Plotter(to_plot) pl.export_tikz(filename="tikz/tikz_figure.tex")
package com.ichmed.trinketeers.util.render; public interface IGraphic { public void render(); }
using LagoVista.Core.PlatformSupport; using System; using System.Collections.Generic; using System.Text; namespace LagoVista.DroneBaseStation.Core.Interfaces { public interface IChannel : ISerialPort { } }
package com.ociweb.gl.impl.stage; import com.ociweb.gl.api.HTTPResponseReader; public interface CallableHTTPResponse { boolean responseHTTP(HTTPResponseReader reader); }
import React from 'react'; import * as d3 from "d3"; export default class BasicPieChart extends React.Component { constructor(props) { super(props); this.state = { data: [ { apps_by_deployment: "error", apps_by_deployment_doc_count: "5" }, { apps_by_deployment: "success", apps_by_deployment_doc_count: "15" }, { apps_by_deployment: "warning", apps_by_deployment_doc_count: "3" }, { apps_by_deployment: "aborted", apps_by_deployment_doc_count: "2" } ] }; } componentDidMount() { const width = 960, height = 500, outerRadius = height / 2 - 20, innerRadius = outerRadius / 3, cornerRadius = 10; const radius = Math.min(width, height) / 2, labelRadius = radius - 10; const colors = d3.scaleOrdinal(d3.schemeCategory10); const chart = d3.select(this.chartRef) .attr("width", window.innerWidth - 100) .attr("height", height + 100) .append("g") .attr("transform", `translate(${width / 2}, ${height / 2})`); //Center label chart .append('text') .attr("text-anchor", "middle") .attr('dy', '0.35em') .style('font-size', '24px') .text('1912'); const pie = d3.pie() .sort(null) .value((d) => +d.apps_by_deployment_doc_count) .padAngle(.02); const arc = d3.arc() .outerRadius(outerRadius - 20) .innerRadius(innerRadius); const arcsWithData = pie(this.state.data); const gContainer = chart.selectAll("path") .data(arcsWithData) .enter() .append('g'); gContainer .append("path") .attr("fill", (d, i) => colors(i)) .attr("d", arc); //Add outside labels gContainer .append('text') .attr("transform", (d) => { const c = arc.centroid(d); const x = c[0]; const y = c[1]; const h = Math.sqrt(x*x + y*y); return `translate(${x/h * labelRadius},${y/h * labelRadius})`; }) .attr("text-anchor", (d) => { // did we past the center? return (d.endAngle + d.startAngle) / 2 > Math.PI ? "end" : "start"; }) .attr("dy", ".35em") .text((d) => { return `${d.data.apps_by_deployment}: ${d.data.apps_by_deployment_doc_count}`; }); } render() { return ( <svg className="pie-chart--basic" ref={(r) => this.chartRef = r}></svg> ); } }
export PYTHONPATH=`pwd`:$PYTHONPATH # class-agnostic CONFIG='solov2_release_x101_dcn_fpn_2gpu_3x_6lambda_bothfocalloss_Tdiv4_rlemask_crop' # Notice! Need to check # mmdet/datasets/synthetics.py#21-244 # tools/test_ins_vis.py#44 vis_seg() CUDA_VISIBLE_DEVICES=2 python tools/test_ins_vis.py \ configs/solov2/synthetics/solov2_x101_dcn_fpn_8gpu_3x.py \ work_dirs/$CONFIG/latest.pth \ --out results/$CONFIG/test.pkl \ --eval segm \ --save_dir results/$CONFIG/viz/ \ --show # # class-specified # CONFIG='solov2_release_x101_dcn_fpn_2gpu_3x_6lambda_bothfocalloss_Tdiv4_rlemask' # # Notice! Need to check # # mmdet/datasets/synthetics.py#21-244 # # tools/test_ins_vis.py#44 vis_seg() # CUDA_VISIBLE_DEVICES=2 python tools/test_ins_vis.py \ # configs/solov2/synthetics/solov2_x101_dcn_fpn_8gpu_3x.py \ # work_dirs/$CONFIG/latest.pth \ # --out results/$CONFIG/test.pkl \ # --eval segm \ # --save_dir results/$CONFIG/viz/ \ # --show # # python tools/crop_patch.py \
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.fragment.app.strictmode import android.annotation.SuppressLint import android.os.Looper import android.util.Log import android.view.ViewGroup import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.strictmode.FragmentStrictMode.Policy /** * FragmentStrictMode is a tool which detects things you might be doing by accident and brings * them to your attention so you can fix them. Basically, it's a version of * [android.os.StrictMode] specifically for fragment-related issues. * * You can decide what should happen when a violation is detected. For example, using * [Policy.Builder.penaltyLog] you can watch the output of `adb logcat` while you * use your application to see the violations as they happen. */ object FragmentStrictMode { private const val TAG = "FragmentStrictMode" /** * The current policy for what actions should be detected, as well as the penalty if such * actions occur. */ var defaultPolicy = Policy.LAX private fun getNearestPolicy(fragment: Fragment?): Policy { var declaringFragment = fragment while (declaringFragment != null) { if (declaringFragment.isAdded) { val fragmentManager = declaringFragment.parentFragmentManager if (fragmentManager.strictModePolicy != null) { return fragmentManager.strictModePolicy!! } } declaringFragment = declaringFragment.parentFragment } return defaultPolicy } /** * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY) fun onFragmentReuse(fragment: Fragment, previousFragmentId: String) { val violation: Violation = FragmentReuseViolation(fragment, previousFragmentId) logIfDebuggingEnabled(violation) val policy = getNearestPolicy(fragment) if (policy.flags.contains(Flag.DETECT_FRAGMENT_REUSE) && shouldHandlePolicyViolation(policy, fragment.javaClass, violation.javaClass) ) { handlePolicyViolation(policy, violation) } } /** * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY) fun onFragmentTagUsage( fragment: Fragment, container: ViewGroup? ) { val violation: Violation = FragmentTagUsageViolation(fragment, container) logIfDebuggingEnabled(violation) val policy = getNearestPolicy(fragment) if (policy.flags.contains(Flag.DETECT_FRAGMENT_TAG_USAGE) && shouldHandlePolicyViolation(policy, fragment.javaClass, violation.javaClass) ) { handlePolicyViolation(policy, violation) } } /** * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY) fun onSetRetainInstanceUsage(fragment: Fragment) { val violation: Violation = SetRetainInstanceUsageViolation(fragment) logIfDebuggingEnabled(violation) val policy = getNearestPolicy(fragment) if (policy.flags.contains(Flag.DETECT_RETAIN_INSTANCE_USAGE) && shouldHandlePolicyViolation(policy, fragment.javaClass, violation.javaClass) ) { handlePolicyViolation(policy, violation) } } /** * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY) fun onGetRetainInstanceUsage(fragment: Fragment) { val violation: Violation = GetRetainInstanceUsageViolation(fragment) logIfDebuggingEnabled(violation) val policy = getNearestPolicy(fragment) if (policy.flags.contains(Flag.DETECT_RETAIN_INSTANCE_USAGE) && shouldHandlePolicyViolation(policy, fragment.javaClass, violation.javaClass) ) { handlePolicyViolation(policy, violation) } } /** * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY) fun onSetUserVisibleHint(fragment: Fragment, isVisibleToUser: Boolean) { val violation: Violation = SetUserVisibleHintViolation(fragment, isVisibleToUser) logIfDebuggingEnabled(violation) val policy = getNearestPolicy(fragment) if (policy.flags.contains(Flag.DETECT_SET_USER_VISIBLE_HINT) && shouldHandlePolicyViolation(policy, fragment.javaClass, violation.javaClass) ) { handlePolicyViolation(policy, violation) } } /** * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY) fun onSetTargetFragmentUsage( violatingFragment: Fragment, targetFragment: Fragment, requestCode: Int ) { val violation: Violation = SetTargetFragmentUsageViolation( violatingFragment, targetFragment, requestCode ) logIfDebuggingEnabled(violation) val policy = getNearestPolicy(violatingFragment) if (policy.flags.contains(Flag.DETECT_TARGET_FRAGMENT_USAGE) && shouldHandlePolicyViolation(policy, violatingFragment.javaClass, violation.javaClass) ) { handlePolicyViolation(policy, violation) } } /** * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY) fun onGetTargetFragmentUsage(fragment: Fragment) { val violation: Violation = GetTargetFragmentUsageViolation(fragment) logIfDebuggingEnabled(violation) val policy = getNearestPolicy(fragment) if (policy.flags.contains(Flag.DETECT_TARGET_FRAGMENT_USAGE) && shouldHandlePolicyViolation(policy, fragment.javaClass, violation.javaClass) ) { handlePolicyViolation(policy, violation) } } /** * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY) fun onGetTargetFragmentRequestCodeUsage(fragment: Fragment) { val violation: Violation = GetTargetFragmentRequestCodeUsageViolation(fragment) logIfDebuggingEnabled(violation) val policy = getNearestPolicy(fragment) if (policy.flags.contains(Flag.DETECT_TARGET_FRAGMENT_USAGE) && shouldHandlePolicyViolation(policy, fragment.javaClass, violation.javaClass) ) { handlePolicyViolation(policy, violation) } } /** * @hide */ @JvmStatic @RestrictTo(RestrictTo.Scope.LIBRARY) fun onWrongFragmentContainer( fragment: Fragment, container: ViewGroup ) { val violation: Violation = WrongFragmentContainerViolation(fragment, container) logIfDebuggingEnabled(violation) val policy = getNearestPolicy(fragment) if (policy.flags.contains(Flag.DETECT_WRONG_FRAGMENT_CONTAINER) && shouldHandlePolicyViolation(policy, fragment.javaClass, violation.javaClass) ) { handlePolicyViolation(policy, violation) } } @VisibleForTesting fun onPolicyViolation(violation: Violation) { logIfDebuggingEnabled(violation) val fragment: Fragment = violation.fragment val policy = getNearestPolicy(fragment) if (shouldHandlePolicyViolation(policy, fragment.javaClass, violation.javaClass)) { handlePolicyViolation(policy, violation) } } private fun logIfDebuggingEnabled(violation: Violation) { if (FragmentManager.isLoggingEnabled(Log.DEBUG)) { Log.d( FragmentManager.TAG, "StrictMode violation in ${violation.fragment.javaClass.name}", violation ) } } private fun shouldHandlePolicyViolation( policy: Policy, fragmentClass: Class<out Fragment>, violationClass: Class<out Violation> ): Boolean { val violationsToBypass = policy.mAllowedViolations[fragmentClass] ?: return true if (violationClass.superclass != Violation::class.java) { if (violationsToBypass.contains(violationClass.superclass)) { return false } } return !violationsToBypass.contains(violationClass) } private fun handlePolicyViolation( policy: Policy, violation: Violation ) { val fragment: Fragment = violation.fragment val fragmentName = fragment.javaClass.name if (policy.flags.contains(Flag.PENALTY_LOG)) { Log.d(TAG, "Policy violation in $fragmentName", violation) } if (policy.listener != null) { runOnHostThread(fragment) { policy.listener.onViolation(violation) } } if (policy.flags.contains(Flag.PENALTY_DEATH)) { runOnHostThread(fragment) { Log.e(TAG, "Policy violation with PENALTY_DEATH in $fragmentName", violation) throw violation } } } private fun runOnHostThread(fragment: Fragment, runnable: Runnable) { if (fragment.isAdded) { val handler = fragment.parentFragmentManager.host.handler if (handler.looper == Looper.myLooper()) { runnable.run() // Already on correct thread -> run synchronously } else { handler.post(runnable) // Switch to correct thread } } else { runnable.run() // Fragment is not attached to any host -> run synchronously } } internal enum class Flag { PENALTY_LOG, PENALTY_DEATH, DETECT_FRAGMENT_REUSE, DETECT_FRAGMENT_TAG_USAGE, DETECT_RETAIN_INSTANCE_USAGE, DETECT_SET_USER_VISIBLE_HINT, DETECT_TARGET_FRAGMENT_USAGE, DETECT_WRONG_FRAGMENT_CONTAINER } /** * When [Policy.Builder.penaltyListener] is enabled, the listener is called when a * violation occurs. */ fun interface OnViolationListener { /** Called on a policy violation. */ fun onViolation(violation: Violation) } /** * [FragmentStrictMode] policy applied to a certain [FragmentManager] (or globally). * * This policy can either be enabled globally using [defaultPolicy] or for a * specific [FragmentManager] using [FragmentManager.setStrictModePolicy]. * The current policy can be retrieved using [defaultPolicy] and * [FragmentManager.getStrictModePolicy] respectively. * * Note that multiple penalties may be provided and they're run in order from least to most * severe (logging before process death, for example). There's currently no mechanism to choose * different penalties for different detected actions. */ class Policy internal constructor( internal val flags: Set<Flag>, listener: OnViolationListener?, allowedViolations: Map<Class<out Fragment>, MutableSet<Class<out Violation>>> ) { internal val listener: OnViolationListener? internal val mAllowedViolations: Map<Class<out Fragment>, Set<Class<out Violation>>> /** * Creates [Policy] instances. Methods whose names start with `detect` specify * what problems we should look for. Methods whose names start with `penalty` specify * what we should do when we detect a problem. * * You can call as many `detect` and `penalty` methods as you like. Currently * order is insignificant: all penalties apply to all detected problems. */ class Builder { private val flags: MutableSet<Flag> = mutableSetOf() private var listener: OnViolationListener? = null private val mAllowedViolations: MutableMap<Class<out Fragment>, MutableSet<Class<out Violation>>> = mutableMapOf() /** Log detected violations to the system log. */ @SuppressLint("BuilderSetStyle") fun penaltyLog(): Builder { flags.add(Flag.PENALTY_LOG) return this } /** * Throws an exception on violation. This penalty runs at the end of all enabled * penalties so you'll still get to see logging or other violations before the exception * is thrown. */ @SuppressLint("BuilderSetStyle") fun penaltyDeath(): Builder { flags.add(Flag.PENALTY_DEATH) return this } /** * Call [OnViolationListener.onViolation] for every violation. The listener will * be called on the main thread of the fragment host. */ @SuppressLint("BuilderSetStyle") fun penaltyListener(listener: OnViolationListener): Builder { this.listener = listener return this } /** * Detects cases, where a [Fragment] instance is reused, after it was previously * removed from a [FragmentManager]. */ @SuppressLint("BuilderSetStyle") fun detectFragmentReuse(): Builder { flags.add(Flag.DETECT_FRAGMENT_REUSE) return this } /** Detects usage of the <fragment> tag inside XML layouts. */ @SuppressLint("BuilderSetStyle") fun detectFragmentTagUsage(): Builder { flags.add(Flag.DETECT_FRAGMENT_TAG_USAGE) return this } /** * Detects calls to [Fragment.setRetainInstance] and [Fragment.getRetainInstance]. */ @SuppressLint("BuilderSetStyle") fun detectRetainInstanceUsage(): Builder { flags.add(Flag.DETECT_RETAIN_INSTANCE_USAGE) return this } /** Detects calls to [Fragment.setUserVisibleHint]. */ @SuppressLint("BuilderSetStyle") fun detectSetUserVisibleHint(): Builder { flags.add(Flag.DETECT_SET_USER_VISIBLE_HINT) return this } /** * Detects calls to [Fragment.setTargetFragment], [Fragment.getTargetFragment] and * [Fragment.getTargetRequestCode]. */ @SuppressLint("BuilderSetStyle") fun detectTargetFragmentUsage(): Builder { flags.add(Flag.DETECT_TARGET_FRAGMENT_USAGE) return this } /** * Detects cases where a [Fragment] is added to a container other than a * [androidx.fragment.app.FragmentContainerView]. */ @SuppressLint("BuilderSetStyle") fun detectWrongFragmentContainer(): Builder { flags.add(Flag.DETECT_WRONG_FRAGMENT_CONTAINER) return this } /** * Allow the specified [Fragment] class to bypass penalties for the specified * [Violation], if detected. * * By default, all [Fragment] classes will incur penalties for any detected [Violation]. */ @SuppressLint("BuilderSetStyle") fun allowViolation( fragmentClass: Class<out Fragment>, violationClass: Class<out Violation> ): Builder { var violationsToBypass = mAllowedViolations[fragmentClass] if (violationsToBypass == null) { violationsToBypass = mutableSetOf() } violationsToBypass.add(violationClass) mAllowedViolations[fragmentClass] = violationsToBypass return this } /** * Construct the Policy instance. * * Note: if no penalties are enabled before calling `build`, [penaltyLog] is implicitly * set. */ fun build(): Policy { if (listener == null && !flags.contains(Flag.PENALTY_DEATH)) { penaltyLog() } return Policy(flags, listener, mAllowedViolations) } } internal companion object { /** The default, lax policy which doesn't catch anything. */ @JvmField val LAX = Policy(emptySet(), null, emptyMap()) } init { this.listener = listener val newAllowedViolationsMap: MutableMap<Class<out Fragment>, Set<Class<out Violation>>> = mutableMapOf() for ((key, value) in allowedViolations) { newAllowedViolationsMap[key] = value } mAllowedViolations = newAllowedViolationsMap } } }
import kotlin.math.abs class Solution { fun findClosestElements(arr: IntArray, k: Int, x: Int): List<Int> { val ans = arr.sortedBy { abs(it - x) } return ans.take(k).sorted() } }
import family.haschka.wolkenschloss.gradle.ca.ServerCertificate import family.haschka.wolkenschloss.gradle.testbed.Apply import family.haschka.wolkenschloss.gradle.testbed.domain.DomainExtension import family.haschka.wolkenschloss.gradle.testbed.domain.DomainTasks plugins { id("family.haschka.wolkenschloss.testbed") } defaultTasks("start") testbed { domain { name.set("testbed") domainSuffix.set(System.getProperty(DomainExtension.DOMAIN_SUFFIX_PROPERTY)) hosts.addAll("dashboard", "registry", "grafana", "prometheus", "cookbook", "linkerd", "dex") } } tasks { register<ServerCertificate>("localhost") { subjectAlternativeNames.set(listOf( ServerCertificate.dnsName("localhost"), ServerCertificate.ipAddress("127.0.0.1") )) } start { dependsOn(DomainTasks.COPY_KUBE_CONFIG_TASK_NAME) } register<Apply>("staging") { group = "client" description = "apply staging overlay" logging.captureStandardOutput(LogLevel.QUIET) } }
using Aktien.Data.Types; using Aktien.Logic.Core; using Aktien.Logic.Messages.Base; using Base.Logic.Core; using Base.Logic.Messages; using Base.Logic.ViewModels; using GalaSoft.MvvmLight.CommandWpf; using GalaSoft.MvvmLight.Messaging; using Logic.Messages.Base; using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace Aktien.Logic.UI { public class StartingProgrammViewModel : ViewModelBasis { public StartingProgrammViewModel() { Title = "Loading..."; CheckServerIsOnlineCommand = new RelayCommand(() => ExecuteCheckServerIsOnlineCommand()); } private void ExecuteCheckServerIsOnlineCommand() { new BackendHelper().CheckServerIsOnline(); Messenger.Default.Send(new CloseViewMessage(), "StartingProgramm"); if (GlobalVariables.ServerIsOnline) { Messenger.Default.Send(new OpenLoginViewMessage { }); } else { Messenger.Default.Send(new CloseApplicationMessage { }); } } public ICommand CheckServerIsOnlineCommand { get; private set; } } }
// (c) Copyright 2017 Cloudera, 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. package com.cloudera.director.aws.network; import com.google.common.base.MoreObjects; import com.google.common.collect.Iterables; import com.google.common.collect.Range; import com.typesafe.config.Config; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; /** * The data model for a network rule. */ public final class NetworkRule { /** * The config key for protocol. */ private final static String PROTOCOL_KEY = "protocol"; /** * The config key for port. */ private final static String PORT_KEY = "port"; /** * The config key for ip range list. */ private final static String IPRANGE_KEY = "ipRanges"; /** * The network protocol that this rule applies to. */ private final Protocol protocol; /** * The port that this rule applies to. * <p> * The valid port range is [0, 65535]. If it is -1, it means any port. */ private final int port; /** * The IP ranges that this rule applies to. */ private final CidrBlock cidrBlock; /** * The access type of this rule. It indicates if the network traffic defined * by this rule should be allowed or denied. */ private final AccessType access; /** * Error message indicates a rule component is missing when parsing the HOCON config. */ private final static String MISSING_ERROR_MSG = "Failed to create a network rule due to missing %s"; /** * Error message indicates a rule component is invalid when parsing the HOCON config. */ private final static String INVALID_ERROR_MSG = "Failed to create a network rule due to invalid %s"; /** * Constructs an unmodifiable view of {@code Iterable} over the network rules described * by the given HOCON config. * * @param config the HOCON config * @param access the access type * @return an unmodifiable view of {@code Iterable} over the network rules described * by the given HOCON config. */ public static Iterable<NetworkRule> fromConfig(Config config, AccessType access) { if (!config.hasPath(PROTOCOL_KEY)) { throw new IllegalArgumentException(String.format(MISSING_ERROR_MSG, PROTOCOL_KEY)); } if (!config.hasPath(IPRANGE_KEY)) { throw new IllegalArgumentException(String.format(MISSING_ERROR_MSG, IPRANGE_KEY)); } Protocol protocolFromConfig = Protocol.toProtocol(config.getString(PROTOCOL_KEY)); if (protocolFromConfig == Protocol.UNKNOWN) { throw new IllegalArgumentException((String.format(INVALID_ERROR_MSG, PROTOCOL_KEY))); } List<String> ipRangesFromConfig = config.getStringList(IPRANGE_KEY); if (ipRangesFromConfig == null || ipRangesFromConfig.isEmpty()) { throw new IllegalArgumentException((String.format(INVALID_ERROR_MSG, IPRANGE_KEY))); } Set<NetworkRule> rules = new HashSet<>(); // If the protocol is ALL, the port is set to -1 regardless of the value in the config. if (protocolFromConfig == Protocol.ALL) { for (String ipRange : ipRangesFromConfig) { rules.add(new NetworkRule(protocolFromConfig, -1, ipRange, access)); } } else { if (!config.hasPath(PORT_KEY)) { throw new IllegalArgumentException(String.format(MISSING_ERROR_MSG, PORT_KEY)); } int portFromConfig = config.getInt(PORT_KEY); if (!(-1 <= portFromConfig && portFromConfig <= 65535)) { throw new IllegalArgumentException((String.format(INVALID_ERROR_MSG, PORT_KEY))); } for (String ipRange : ipRangesFromConfig) { rules.add(new NetworkRule(protocolFromConfig, portFromConfig, ipRange, access)); } } return Iterables.unmodifiableIterable(rules); } /** * Internal network rule constructor. */ private NetworkRule(Protocol protocol, int port, String ipRange, AccessType access) { this.protocol = protocol; this.port = port; this.access = access; this.cidrBlock = CidrBlock.fromString(ipRange); } /** * Checks if this network rule is enforced by a network permission with the given parameters. * * @param protocolNameOrNumber the network protocol * @param portRange the range of ports * @param ipRangeList the IP range list * @param accessType the access type * @return true if the network rule is enforced by the network permission */ public boolean isEnforced(String protocolNameOrNumber, Range<Integer> portRange, List<String> ipRangeList, AccessType accessType) { if (this.access != accessType) { return false; } // Check the protocol Protocol proto = Protocol.toProtocol(protocolNameOrNumber); if (proto != Protocol.ALL && proto != this.protocol) { return false; } // Check the port if (proto != Protocol.ALL && (portRange == null || (!portRange.contains(-1) && !portRange.contains(this.port)))) { return false; } // Check the ip ranges for (String curIpRange : ipRangeList) { CidrBlock curCidr = CidrBlock.fromString(curIpRange); if (curCidr.contains(this.cidrBlock)) { return true; } } return false; } /** * Checks if this network rule is violated by a network permission with the given parameters. * * @param protocolNameOrNumber the network protocol * @param portRange the range of ports * @param ipRangeList the IP range list * @param accessType the access type * @return true if the network rule is violated by the network permission */ public boolean isViolated(String protocolNameOrNumber, Range<Integer> portRange, List<String> ipRangeList, AccessType accessType) { if (this.access == accessType) { return false; } // Check the protocol Protocol proto = Protocol.toProtocol(protocolNameOrNumber); if (this.protocol != Protocol.ALL && proto != Protocol.ALL && proto != this.protocol) { return false; } // Check the port if (this.protocol != Protocol.ALL && proto != Protocol.ALL && (this.port != -1 && !portRange.contains(-1) && !portRange.contains(this.port))) { return false; } // Check the ip ranges for (String curIpRange : ipRangeList) { CidrBlock curCidr = CidrBlock.fromString(curIpRange); if (curCidr.contains(this.cidrBlock) || this.cidrBlock.contains(curCidr)) { return true; } } return false; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("protocol", this.protocol) .add("port", this.port) .add("cidrBlock", this.cidrBlock) .add("access", this.access) .toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NetworkRule that = (NetworkRule) o; return port == that.port && protocol == that.protocol && Objects.equals(cidrBlock, that.cidrBlock) && access == that.access; } @Override public int hashCode() { return Objects.hash(protocol, port, cidrBlock, access); } }
const firebaseService = require("./db/firebase-service"); const db = firebaseService.db; const bucket = firebaseService.bucket; const WORDS_COLLECTION_NAME = firebaseService.WORDS_COLLECTION_NAME; const wordListsCollection = firebaseService.wordListsCollection; module.exports.insertNewWord = (listId, word) => { return new Promise(resolve => { return wordListsCollection.doc(listId).listCollections() .then(collections => { const collectionId = collections[0].id; wordListsCollection.doc(listId).collection(collectionId) .add({word: word, timestamp: Date.now()}) .then(onSuccess => { return resolve(onSuccess); }); }); }); } module.exports.getWord = (listId, wordId) => { return new Promise((resolve, reject) => { return wordListsCollection.doc(listId).listCollections() .then(collections => { const collectionId = collections[0].id; wordListsCollection.doc(listId).collection(collectionId).doc(wordId).get() .then(result => { const word = result.data().word; const uploadedImage = bucket.file(wordId); uploadedImage.get() .then(image => { return resolve({word: word, hasImage: true, image: image[1].mediaLink}); }) .catch(() => { return reject({word: word, hasImage: false}); }); }); }); }); } module.exports.updateWord = (listId, wordId, word) => { return new Promise(resolve => { return wordListsCollection.doc(listId).listCollections() .then(collections => { const collectionId = collections[0].id; wordListsCollection.doc(listId).collection(collectionId).doc(wordId) .update({word: word, timestamp: Date.now()}) .then(() => { return resolve(true); }) }) }); } module.exports.deleteWord = (listId, wordId) => { return new Promise(resolve => { return wordListsCollection.doc(listId).listCollections() .then(collections => { const collectionId = collections[0].id; wordListsCollection.doc(listId).collection(collectionId).doc(wordId) .delete() .then(() => { return resolve(true); }); }); }); } module.exports.saveImage = (wordId, buffer, mimeType) => { return new Promise(resolve => { const uploadedImage = bucket.file(wordId) uploadedImage.save(buffer, { public: true, contentType: mimeType }).then(() => { return resolve(true); }); }); }
import collections import functools import io import logging import os.path import pathlib import shutil import subprocess import sys import tempfile import textwrap from typing import Dict, Optional, Type, Union import teetime from . import core, package_managers __all__ = [ "VirtualEnvironment", "VirtualEnv", ] class VirtualEnvironment: __slots__ = ( "_path", "_program", "_flags", "_package_manager", "_expand_program", ) def __init__( self, path: Union[str, pathlib.PurePath], package_manager: Type[package_managers.PackageManager], program: Optional[str] = None, flags: Optional[core.Flags] = None, ) -> None: self._path = path self._program = program self._flags = flags self._package_manager = package_manager self._expand_program = functools.lru_cache(8)(core._expand_program) def exists(self) -> bool: return self._exists() def make(self, force: bool = False) -> None: if self.exists(): if not force: return self.remove() self._make() def load(self, force: bool = False) -> core.Environment: self.make(force=force) return core.Environment( self._env(), self._package_manager(), self._expand_program, ) def remove(self) -> None: self._remove() def _exists(self) -> bool: return os.path.exists(self._path) def _make(self) -> None: if not self.exists(): os.mkdir(self._path) def _env(self) -> Dict[str, str]: return os.environ.copy() def _remove(self) -> None: shutil.rmtree(self._path, ignore_errors=True) class VirtualEnv(VirtualEnvironment): def _make(self) -> None: flags = self._flags or core.Flags() if self._program is not None: flags = flags(f"--python={self._program}") core.popen(["python", "-m", "virtualenv", self._path] + flags).log() def _env(self) -> Dict[str, str]: env = super()._env() env["PATH"] = ( os.path.abspath(os.path.join(self._path, "Scripts")) + ";" + env["PATH"] ) return env
# Dark Mode Toggle 🐧 Dark mode toggle using button click! ![](../images/light-mode.PNG) ![](../images/dark-mode.PNG)
/** * Copyright 2016 Damian Glinkowski <damianglinkowski@gmail.com> */ #include "./Color.h" Color::Color() : r(0.0f), g(0.0f), b(0.0f), a(1.0f) { } Color::Color(float r, float g, float b) : r(r), g(g), b(b), a(1.0f) { } Color::Color(float r, float g, float b, float a) : r(r), g(g), b(b), a(a) { } Color::Color(Vector3f vector) : r(vector.x), g(vector.y), b(vector.z), a(1.0f) { } Color::Color(const Color &color) : r(color.r), g(color.g), b(color.b), a(color.a) { } Color &Color::operator=(const Color &color) { r = color.r; g = color.g; b = color.b; a = color.a; return *this; } Color Color::operator+(const Color &color) { r = (r + color.r) > 1.0000f ? (r + color.r) - 1.0000f : (r + color.r); g = (g + color.g) > 1.0000f ? (g + color.g) - 1.0000f : (g + color.g); b = (b + color.b) > 1.0000f ? (b + color.b) - 1.0000f : (b + color.b); a = (a + color.a) > 1.0000f ? (a + color.a) - 1.0000f : (a + color.a); return *this; } Color &Color::operator+=(const Color &color) { r = (r + color.r) > 1.0000f ? (r + color.r) - 1.0000f : (r + color.r); g = (g + color.g) > 1.0000f ? (g + color.g) - 1.0000f : (g + color.g); b = (b + color.b) > 1.0000f ? (b + color.b) - 1.0000f : (b + color.b); a = (a + color.a) > 1.0000f ? (a + color.a) - 1.0000f : (a + color.a); return *this; } bool Color::operator==(const Color &rhs) const { return r == rhs.r && g == rhs.g && b == rhs.b && a == rhs.a; } bool Color::operator!=(const Color &rhs) const { return !(rhs == *this); } bool Color::operator<(const Color &rhs) const { if (r < rhs.r) return true; if (rhs.r < r) return false; if (g < rhs.g) return true; if (rhs.g < g) return false; if (b < rhs.b) return true; if (rhs.b < b) return false; return a < rhs.a; } bool Color::operator>(const Color &rhs) const { return rhs < *this; } bool Color::operator<=(const Color &rhs) const { return !(rhs < *this); } bool Color::operator>=(const Color &rhs) const { return !(*this < rhs); } wxString &operator<<(wxString &s, const Color &color) { s << "r:" << color.r << ", " << "g:" << color.g << ", " << "b:" << color.b << ", " << "a:" << color.a; return s; }
/** * Created by Kelvin on 6/16/2016. */ (function() { 'use strict'; angular.module('tiffanyAndKelvin') .controller('RSVPCodeCtrl', RSVPCodeCtrl); function RSVPCodeCtrl(RSVPFactory, $state) { var vm = this; vm.form = {}; vm.formModel = { code: '' }; vm.submit = submit; vm.isBusy = false; vm.invalidCode = null; vm.codeWatcher = codeWatcher; function codeWatcher(code) { if(vm.invalidCode) { if(code !== vm.invalidCode) { vm.invalidCode = null; } } } function submit(formModel) { vm.isBusy = true; RSVPFactory.getData(formModel.code).then(function() { $state.go('rsvp', {code: formModel.code}); }).catch(function() { // show error message when null vm.invalidCode = formModel.code; }).then(function() { vm.isBusy = false; }); } } })();
class BoggleGame { /* make a new game at this DOM id */ constructor(boardId, secs = 60) { this.secs = secs; // game length this.showTimer(); this.score = 0; this.words = new Set(); this.board = $("#" + boardId); // REMOVE - Added this in because i couldn't get form to stop without it! // $(".add-word").on("submit", function stop_form(e){ // e.preventDefault() // }) // every 1000 msec, "tick" this.timer = setInterval(this.tick.bind(this), 1000); // TOOK $(".add-word", this.board) out REPLACE IF NOT WORKED $(".add-word", this.board).on("submit", this.handleSubmit.bind(this)); } /* show word in list of words */ showWord(word) { $(".words", this.board).append($("<li>", { text: word })); } /* show score in html */ showScore() { $(".score", this.board).text(this.score); } /* show a status message */ showMessage(msg, cls) { $(".msg", this.board) .text(msg) .removeClass() .addClass(`msg ${cls}`); } /* handle submission of word: if unique and valid, score & show */ async handleSubmit(evt) { evt.preventDefault(); const $word = $(".word", this.board); console.log("value is", $word.val()) let word = $word.val(); if (!word) return; if (this.words.has(word)) { this.showMessage(`Already found ${word}`, "err"); return; } // check server for validity const resp = await axios.get("/check-guess", { params: { word: word }}); if (resp.data.result === "not-word") { this.showMessage(`${word} is not a valid English word`, "err"); } else if (resp.data.result === "not-on-board") { this.showMessage(`${word} is not a valid word on this board`, "err"); } else { this.showWord(word); this.score += word.length; this.showScore(); this.words.add(word); this.showMessage(`Added: ${word}`, "ok"); } $word.val("").focus(); } /* Update timer in DOM */ showTimer() { $(".timer", this.board).text(this.secs); } /* Tick: handle a second passing in game */ async tick() { this.secs -= 1; this.showTimer(); if (this.secs === 0) { clearInterval(this.timer); await this.scoreGame(); } } /* end of game: score and update message. */ async scoreGame() { $(".add-word", this.board).hide(); const resp = await axios.post("/post-score", { score: this.score }); if (resp.data.brokeRecord) { this.showMessage(`New record: ${this.score}`, "ok"); } else { this.showMessage(`Final score: ${this.score}`, "ok"); } } }
<?php namespace Omnipay\Yeepay\Requests; use Omnipay\Yeepay\Common\Signer; use Omnipay\Yeepay\Request\YeepayPurchaseRequest; use Omnipay\Yeepay\Responses\YeepayPurchaseResponse; use Omnipay\Common\Exception\InvalidRequestException; /** * Class YeepayWebPurchaseRequest * @package Omnipay\Yeepay\Requests */ class YeepayWebPurchaseRequest extends YeepayPurchaseRequest { public function getData() { $this->validateParams(); $data = $this->parameters->all(); $data['sign_type'] = $this->getSignType(); $data['sign'] = $this->sign($data, $this->getSignType()); return $data; } protected function validateParams() { $this->validate( 'order_serial_number', 'subject', 'total_fee', 'return_url', 'notify_url' ); } public function sendData($data) { return $this->response = new YeepayPurchaseResponse($this, $data); } protected function sign($params, $signType) { $signer = new Signer($params); $signType = strtoupper($signType); if ($signType == 'MD5') { if (! $this->getKey()) { throw new InvalidRequestException('The `key` is required for `MD5` sign_type'); } $sign = $signer->signWithMD5($this->getKey()); } else { throw new InvalidRequestException('The signType is not allowed'); } return $sign; } }
#!/usr/bin/bash #target location of script: /tensorflow/containerstarter.sh echo -e "changeme" | (passwd --stdin tensorflow) printf "changemee\nchangemee\n\n" | vncpasswd vncserver sleep infinity
/* @flow */ import type { MismatchedModules, UpdateDepsPromptResults } from '../../types'; const path = require('path'); const getSingleEntryFromGenerator = require('./getSingleEntryFromGenerator'); const parseConfig = require('gluestick-generators').parseConfig; const { isValidVersion, promptModulesUpdate } = require('./utils'); const version = require('../../../package.json').version; type ProjectPackage = { dependencies: Object, devDependencies: Object, }; const isFileDependency = (name: string) => { return name.startsWith('file'); }; const isMismatched = (project, template) => { return ( !project || (!isValidVersion(project, template) && !isFileDependency(project)) ); }; /** * Open the package.json file in both the project as well as the one used by * this command line interface, then compare the versions for shared modules. * If the CLI uses a different version than the project we are working in then * it will prompt the user to automatically update their project so that it * matches the module versions used by the CLI. * * Now when we update versions in the CLI that the package uses, the projects * will automatically get updated too. * * Also, We include all of the required dependencies when you generate a new * project. Sometimes these dependencies change over time and we need a nice * way of updating apps that were generated with previous versions of the CLI. * To solve this problem, we look at both the dependencies and development * dependencies that would be included in a brand new application. If the * project is missing a required dependency, then we prompt the user to update * that as well. * * A Promise is returned so that we can use async/await when calling this * method. * * @return {Promise} */ const checkForMismatch = ( requiredPackage: ProjectPackage, dev: boolean, ): Promise<UpdateDepsPromptResults> => { // This is done to keep live reference to mock single function in testing const projectPackage: ProjectPackage = { dependencies: {}, devDependencies: {}, ...requiredPackage, }; const pathToPackageGenerator: string = path.join( require.resolve('gluestick-generators').split('gluestick-generators')[0], 'gluestick-generators', 'build/templates/package', ); const packageGeneratorEntry: Object = getSingleEntryFromGenerator( pathToPackageGenerator, 'package.json', { gluestickDependencies: { gluestick: version } }, ); const templatePackage: ProjectPackage = JSON.parse( // $FlowIgnore template at this point will be a string parseConfig( { entry: packageGeneratorEntry, }, {}, ).entry.template, ); const mismatchedModules: MismatchedModules = {}; const markMissing = (dep, type) => { mismatchedModules[dep] = { required: templatePackage[type][dep], project: projectPackage[type][dep] || 'missing', type, }; }; Object.keys(templatePackage.dependencies).forEach((dep: string): void => { const project = projectPackage.dependencies[dep]; const template = templatePackage.dependencies[dep]; if (dev && dep === 'gluestick' && !/\d+\.\d+\.\d+.*/.test(project)) { return; } if (isMismatched(project, template)) { markMissing(dep, 'dependencies'); } }); Object.keys(templatePackage.devDependencies).forEach((dep: string): void => { const project = projectPackage.devDependencies[dep]; const template = templatePackage.devDependencies[dep]; if (isMismatched(project, template)) { markMissing(dep, 'devDependencies'); } }); // prompt for updates if we have any, otherwise we are done if (Object.keys(mismatchedModules).length > 0) { return promptModulesUpdate(mismatchedModules); } return Promise.resolve({ shouldFix: false, mismatchedModules: {} }); }; module.exports = checkForMismatch;
/** * External dependencies */ import { __ } from '@wordpress/i18n'; export const sellingVenueOptions = [ { key: 'no', label: __( 'No', 'woocommerce' ), }, { key: 'other', label: __( 'Yes, on another platform', 'woocommerce' ), }, { key: 'other-woocommerce', label: __( 'Yes, I own a different store powered by WooCommerce', 'woocommerce' ), }, { key: 'brick-mortar', label: __( 'Yes, in person at physical stores and/or events', 'woocommerce' ), }, { key: 'brick-mortar-other', label: __( 'Yes, on another platform and in person at physical stores and/or events', 'woocommerce' ), }, ];
package scala.build.options import scala.build.Positioned import scala.build.errors.{BuildException, MalformedInputError} import scala.build.internal.Licenses final case class PublishOptions( organization: Option[Positioned[String]] = None, name: Option[Positioned[String]] = None, version: Option[Positioned[String]] = None, url: Option[Positioned[String]] = None, license: Option[Positioned[PublishOptions.License]] = None, versionControl: Option[PublishOptions.Vcs] = None, description: Option[String] = None, developers: Seq[PublishOptions.Developer] = Nil, scalaVersionSuffix: Option[String] = None, scalaPlatformSuffix: Option[String] = None, repository: Option[String] = None, sourceJar: Option[Boolean] = None ) object PublishOptions { implicit val monoid: ConfigMonoid[PublishOptions] = ConfigMonoid.derive final case class License(name: String, url: String) final case class Developer(id: String, name: String, url: String, mail: Option[String] = None) final case class Vcs(url: String, connection: String, developerConnection: String) def parseLicense(input: Positioned[String]): Either[BuildException, Positioned[License]] = input.value.split(":", 2) match { case Array(name) => Licenses.map.get(name) match { case None => Left(new MalformedInputError( "license", input.value, "license-id|license-id:url", input.positions )) case Some(license) => Right(input.map(_ => License(name, license.url))) } case Array(name, url) => Right(input.map(_ => License(name, url))) } def parseDeveloper(input: Positioned[String]): Either[BuildException, Developer] = input.value.split("|", 4) match { case Array(id, name, url) => Right(Developer(id, name, url)) case Array(id, name, url, mail) => Right(Developer(id, name, url, Some(mail).map(_.trim).filter(_.nonEmpty))) case _ => Left( new MalformedInputError("developer", input.value, "id|name|URL", input.positions) ) } def parseVcs(input: Positioned[String]): Either[BuildException, Vcs] = if (input.value.startsWith("github:")) input.value.stripPrefix("github:").split("/", 2) match { case Array(org, project) => val vcs = Vcs( s"https://github.com/$org/$project.git", s"scm:git:github.com/$org/$project.git", s"scm:git:git@github.com:$org/$project.git" ) Right(vcs) case _ => Left( new MalformedInputError( "github-vcs", input.value, "github:org/project", input.positions ) ) } else input.value.split("|", 3) match { case Array(url, conn, devConn) => val vcs = Vcs(url, conn, devConn) Right(vcs) case _ => Left( new MalformedInputError( "vcs", input.value, "url|connection|developer-connection", input.positions ) ) } }
package com.stripe.android; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.stripe.android.exception.InvalidRequestException; import com.stripe.android.utils.ObjectUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A class representing a fingerprint request. */ final class FingerprintRequest extends StripeRequest { private static final String MIME_TYPE = "application/json"; private static final String URL = "https://m.stripe.com/4"; @NonNull private final String guid; FingerprintRequest(@NonNull Map<String, Object> params, @NonNull String guid) { super(Method.POST, URL, params, MIME_TYPE); this.guid = guid; } @NonNull @Override Map<String, String> getHeaders() { final Map<String, String> props = new HashMap<>(); props.put("Cookie", "m=" + guid); return props; } @NonNull @Override byte[] getOutputBytes() throws UnsupportedEncodingException, InvalidRequestException { final JSONObject jsonData = mapToJsonObject(params); if (jsonData == null) { throw new InvalidRequestException("Unable to create JSON data from " + "parameters. Please contact support@stripe.com for assistance.", null, null, 0, null, null, null, null); } return jsonData.toString().getBytes(CHARSET); } @Override public int hashCode() { return ObjectUtils.hash(getBaseHashCode(), guid); } @Override public boolean equals(@Nullable Object obj) { return super.equals(obj) || (obj instanceof FingerprintRequest && typedEquals((FingerprintRequest) obj)); } private boolean typedEquals(@NonNull FingerprintRequest obj) { return super.typedEquals(obj) && ObjectUtils.equals(guid, obj.guid); } /** * Converts a string-keyed {@link Map} into a {@link JSONObject}. This will cause a * {@link ClassCastException} if any sub-map has keys that are not {@link String Strings}. * * @param mapObject the {@link Map} that you'd like in JSON form * @return a {@link JSONObject} representing the input map, or {@code null} if the input * object is {@code null} */ @Nullable private static JSONObject mapToJsonObject(@Nullable Map<String, ?> mapObject) { if (mapObject == null) { return null; } JSONObject jsonObject = new JSONObject(); for (String key : mapObject.keySet()) { Object value = mapObject.get(key); if (value == null) { continue; } try { if (value instanceof Map<?, ?>) { try { //noinspection unchecked Map<String, Object> mapValue = (Map<String, Object>) value; jsonObject.put(key, mapToJsonObject(mapValue)); } catch (ClassCastException classCastException) { // don't include the item in the JSONObject if the keys are not Strings } } else if (value instanceof List<?>) { //noinspection unchecked jsonObject.put(key, listToJsonArray((List<Object>) value)); } else if (value instanceof Number || value instanceof Boolean) { jsonObject.put(key, value); } else { jsonObject.put(key, value.toString()); } } catch (JSONException jsonException) { // Simply skip this value } } return jsonObject; } /** * Converts a {@link List} into a {@link JSONArray}. A {@link ClassCastException} will be * thrown if any object in the list (or any sub-list or sub-map) is a {@link Map} whose keys * are not {@link String Strings}. * * @param values a {@link List} of values to be put in a {@link JSONArray} * @return a {@link JSONArray}, or {@code null} if the input was {@code null} */ @Nullable private static JSONArray listToJsonArray(@Nullable List<?> values) { if (values == null) { return null; } final JSONArray jsonArray = new JSONArray(); for (Object object : values) { if (object instanceof Map<?, ?>) { // We are ignoring type erasure here and crashing on bad input. // Now that this method is not public, we have more control on what is // passed to it. //noinspection unchecked final Map<String, Object> mapObject = (Map<String, Object>) object; jsonArray.put(mapToJsonObject(mapObject)); } else if (object instanceof List<?>) { jsonArray.put(listToJsonArray((List) object)); } else if (object instanceof Number || object instanceof Boolean) { jsonArray.put(object); } else { jsonArray.put(object.toString()); } } return jsonArray; } }
package com.task.noteapp.features.notes.data.datasource import com.task.noteapp.db.NotesDao import com.task.noteapp.db.entity.NoteEntity import com.task.noteapp.db.entity.NoteHistoryEntity import javax.inject.Inject /** * Created by Bulent Turkmen on 29.09.2021. */ class NotesLocalDataSource @Inject constructor( private val dao: NotesDao ) { /** * Returns all notes with edit history */ fun getNotes() = dao.getNotes() /** * Creates a new note entity in db */ suspend fun createNote(noteEntity: NoteEntity) = dao.insertNote(noteEntity) /** * Updates the note entity in db */ suspend fun editNote(noteEntity: NoteEntity) = dao.editNote(noteEntity) /** * Creates a edit history entity for a note */ suspend fun insertHistory(history: NoteHistoryEntity) = dao.insertHistory(history) /** * Deletes given note from db */ suspend fun deleteNote(noteEntity: NoteEntity) = dao.removeNote(noteEntity) }
export declare const initUsersDB: () => boolean; export declare const initLicencesDB: () => boolean;
--- title: Micro layouts description: > Build flexible components that can be placed anywhere. authors: - adactio date: 2021-11-03 ---
import { CommonModule } from '@angular/common' import { NgModule } from '@angular/core' import { FormsModule, ReactiveFormsModule } from '@angular/forms' import { MaterialModule } from '@exlibris/exl-cloudapp-angular-lib' import { ColumnOptionComponent } from './column-option.component' import { ColumnOptionsListComponent } from './column-options-list.component' @NgModule({ declarations: [ ColumnOptionComponent, ColumnOptionsListComponent, ], imports: [ CommonModule, MaterialModule, FormsModule, ReactiveFormsModule, ], exports: [ ColumnOptionComponent, ColumnOptionsListComponent, ] }) export class ColumnOptionsModule { }
import { Component, DebugElement, ErrorHandler, NO_ERRORS_SCHEMA } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { RouterTestingModule } from '@angular/router/testing'; import { Observable, Subject } from 'rxjs'; import { createMock } from 'testing/mock'; import { initContext, TestContext } from 'testing/test-context'; import { Broadcaster, Logger } from 'ngx-base'; import { Fabric8WitModule, Space, Spaces, SpaceService } from 'ngx-fabric8-wit'; import { User, UserService } from 'ngx-login-client'; import { RecentSpacesWidget } from './recent-spaces-widget.component'; @Component({ template: '<fabric8-recent-spaces-widget></fabric8-recent-spaces-widget>' }) class HostComponent { } describe('RecentSpacesWidget', () => { type TestingContext = TestContext<RecentSpacesWidget, HostComponent>; initContext(RecentSpacesWidget, HostComponent, { imports: [ Fabric8WitModule, RouterTestingModule ], providers: [ { provide: Broadcaster, useFactory: (): jasmine.SpyObj<Broadcaster> => { const broadcaster: jasmine.SpyObj<Broadcaster> = createMock(Broadcaster); broadcaster.broadcast.and.stub(); return broadcaster; } }, { provide: Logger, useFactory: (): jasmine.SpyObj<Logger> => { const logger: jasmine.SpyObj<Logger> = createMock(Logger); logger.error.and.stub(); return logger; } }, { provide: ErrorHandler, useFactory: (): jasmine.SpyObj<ErrorHandler> => { const errorHandler: jasmine.SpyObj<ErrorHandler> = createMock(ErrorHandler); errorHandler.handleError.and.stub(); return errorHandler; } }, { provide: Spaces, useFactory: (): Spaces => { return { recent: new Subject<Space[]>(), current: Observable.throw('unimplemented') } as Spaces; } }, { provide: UserService, useFactory: (): UserService => { return { currentLoggedInUser: { attributes: { username: 'fooUser' } } as User } as UserService; } }, { provide: SpaceService, useFactory: (): jasmine.SpyObj<SpaceService> => { const service: jasmine.SpyObj<SpaceService> = createMock(SpaceService); service.getSpacesByUser.and.returnValue(new Subject<Space[]>()); return service; } } ], schemas: [NO_ERRORS_SCHEMA] }); it('should be instantiable', function(this: TestingContext): void { expect(this.testedDirective).toBeTruthy(); }); it('should use currentLoggedInUser username', function(this: TestingContext): void { const spaceService: jasmine.SpyObj<SpaceService> = TestBed.get(SpaceService); expect(spaceService.getSpacesByUser).toHaveBeenCalledWith('fooUser'); }); it('should display the loading widget while waiting for the recent spaces', function(this: TestingContext): void { let mockSpacesService: any = TestBed.get(Spaces); mockSpacesService.recent = Observable.never(); let spaceList: DebugElement = this.fixture.debugElement.query(By.css('spaceList')); let emptyList: DebugElement = this.fixture.debugElement.query(By.css('emptyList')); let loading: DebugElement = this.fixture.debugElement.query(By.css('fabric8-loading-widget')); expect(spaceList).toBeNull(); expect(emptyList).toBeNull(); expect(loading).toBeDefined(); expect(this.testedDirective.loading).toEqual(true); }); describe('recentSpaces', () => { it('should relay empty results', function(this: TestingContext, done: DoneFn): void { this.testedDirective.recentSpaces.first().subscribe(function(spaces: Space[]): void { expect(spaces).toEqual([]); done(); }); const spaces: Spaces = TestBed.get(Spaces); (spaces.recent as Subject<Space[]>).next([]); }); it('should relay nonempty results', function(this: TestingContext, done: DoneFn): void { const mockSpaces: Space[] = [ { attributes: { name: 'spaceA' }, relationalData: { creator: { attributes: { username: 'userA' } } } } as Space, { attributes: { name: 'spaceB' }, relationalData: { creator: { attributes: { username: 'userB' } } } } as Space ]; this.testedDirective.recentSpaces.first().subscribe(function(spaces: Space[]): void { expect(spaces).toEqual(mockSpaces); done(); }); const spaces: Spaces = TestBed.get(Spaces); (spaces.recent as Subject<Space[]>).next(mockSpaces); }); }); describe('userHasSpaces', () => { it('should emit "true" if space array is nonempty', function(this: TestingContext, done: DoneFn): void { this.testedDirective.userHasSpaces.first().subscribe((hasSpaces: boolean): void => { expect(hasSpaces).toBeTruthy(); done(); }); const service: jasmine.SpyObj<SpaceService> = TestBed.get(SpaceService); (service.getSpacesByUser() as Subject<Space[]>).next( [ { attributes: { name: 'spaceA' }, relationalData: { creator: { attributes: { username: 'userA' } } } } as Space ] ); }); it('should emit "false" if space array is empty', function(this: TestingContext, done: DoneFn): void { this.testedDirective.userHasSpaces.first().subscribe((hasSpaces: boolean): void => { expect(hasSpaces).toBeFalsy(); done(); }); const service: jasmine.SpyObj<SpaceService> = TestBed.get(SpaceService); (service.getSpacesByUser() as Subject<Space[]>).next([]); }); }); describe('error handling', () => { it('should log errors if SpaceService emits errors', function(this: TestingContext): void { const logger: jasmine.SpyObj<Logger> = TestBed.get(Logger); expect(logger.error).not.toHaveBeenCalled(); const service: jasmine.SpyObj<SpaceService> = TestBed.get(SpaceService); (service.getSpacesByUser() as Subject<Space[]>).error('Some HTTP error'); expect(logger.error).toHaveBeenCalledWith('Some HTTP error'); const errorHandler: jasmine.SpyObj<ErrorHandler> = TestBed.get(ErrorHandler); expect(errorHandler.handleError).toHaveBeenCalledWith('Some HTTP error'); }); }); describe('showAddSpaceOverlay', () => { it('should trigger broadcast event', function(this: TestingContext) { const broadcaster: jasmine.SpyObj<Broadcaster> = TestBed.get(Broadcaster); expect(broadcaster.broadcast).not.toHaveBeenCalled(); this.testedDirective.showAddSpaceOverlay(); expect(broadcaster.broadcast).toHaveBeenCalledWith('showAddSpaceOverlay', true); }); }); });
#include "server.h" #include "tcpserver.h" #include "tcpclient.h" #include <QHostAddress> #include <QMessageBox> #include <QDebug> #include "mainwidget.h" #include "dao.h" #include <QJsonDocument> #include <QJsonObject> #include "enums.h" #include <QJsonArray> #include <QThread> extern MainWidget* mw; Server* Server::singleton = nullptr; Server::Server(QObject *parent) : QObject(parent), tcpserver(new TcpServer), fileServer(new FileServer) { } Server* Server::getInstance() { if (singleton == nullptr) { singleton = new Server(); } return singleton; } Server* Server::getInstance(int) { return singleton; } void Server::start(int messagePort, int filePort) { if (tcpserver->listen(QHostAddress::Any, messagePort) == false) { QMessageBox::warning(nullptr, "error", "hhh", QMessageBox::Yes); } if (fileServer->listen(QHostAddress::Any, filePort) == false) { QMessageBox::warning(nullptr, "error", "hhh", QMessageBox::Yes); } } void Server::stop() { onlineClients.clear(); fileClients.clear(); loginClients.clear(); tcpserver->close(); } QList<TcpClient*> Server::getOnlineClients() { QList<TcpClient*> result; for (auto key : onlineClients.keys()) result.append(onlineClients.value(key)); return result; } QList<TcpFile*> Server::getFileClients() { QList<TcpFile*> result; for (auto key : fileClients.keys()) result.append(fileClients.value(key)); return result; } void Server::addFileClient(TcpFile* fileClient) { fileClients.insert(fileClient->getUser()->getId(), fileClient); } void Server::addOnlineClient(TcpClient *onlineClient) { onlineClients.insert(onlineClient->getUser()->getId(), onlineClient); } QList<TcpClient*> Server::getLoginClients() { return loginClients; } void Server::addLoginClient(TcpClient *login_client) { loginClients.append(login_client); } // 收消息的入口 void Server::receiveMessage(TcpClient* client) { QByteArray message = client->readAll(); qDebug() << "client message"; QJsonDocument document = QJsonDocument::fromJson(message); //QStringList list = message.split(" "); QJsonObject object = document.object(); int type = object.value("type").toInt(); switch (type) { case messageType::LOGIN : login(&object, client); break; case messageType::REGISTER : userRegister(&object, client); break; case messageType::ADDFRIEND : addFriend(&object, client); break; case messageType::SENDMESSAGE : sendMessage(&object, client); break; case messageType::CHATLOG : getChatLog(&object, client); break; case messageType::LOGOUT : logout(&object, client); break; case messageType::ADDFRIENDREPLYINFO : addNewFirendReply(&object, client); break; case messageType::DELETEFRIEND : deleteFriend(&object, client); break; case messageType::GROUPMESSAGE : sendGroupMessage(&object, client); break; default: break; } } // 用户登陆 void Server::login(QJsonObject* object, TcpClient* client) { qDebug() << "login"; QString account = object->value("account").toString(); QString password = object->value("password").toString(); Dao* database = Dao::getInstance(); User* user = database->getUserByAccountAndPassword(account, password); QJsonObject messageObject; messageObject.insert("type",messageType::LOGIN); if (user == nullptr) { qDebug() << "ERROR"; messageObject.insert("resultStatus", resultStatus::ERROR); } else { client->setUser(user); addOnlineClient(client); qDebug() << "SUCCESS"; messageObject.insert("resultStatus", resultStatus::SUCCESS); messageObject.insert("name",user->getName()); messageObject.insert("id",user->getId()); messageObject.insert("password",user->getPassword()); messageObject.insert("account", user->getAccount()); messageObject.insert("email", user->getEmail()); messageObject.insert("gender", user->getGender()); QList<User*> otherUsers = database->getAllUsers(); QList<User*> friends = database->getFriendUserById(user->getId()); QList<int> groupIds = database->getGroupIdByUserId(user->getId()); foreach(User* x, otherUsers) { foreach(User* y, friends) { if (x->getId() == y->getId() || x->getId() == user->getId()) { otherUsers.removeOne(x); break; } } } QJsonArray groupList; for(int i = 0 ;i < groupIds.size() ; i++){ QJsonObject group; group.insert("groupId",groupIds[i]); QList<int> userList = database->getGroupUserIdsByGroupId(groupIds[i]); QJsonArray groupUserList ; qDebug() << "????"; for(int j = 0 ; j < userList.size() ; j++){ qDebug() << "||||" << userList[j]; QJsonObject userId; userId.insert("id",userList[j]); groupUserList.insert(j,userId); } group.insert("groupUserList",groupUserList); group.insert("groupName",database->getGroupNameByGroupId(groupIds[i])); groupList.insert(i, group); } messageObject.insert("groupList", groupList); QJsonArray friendsList; qDebug() << "*********************" << friends.size(); for(int i = 0 ;i < friends.size() ; i++){ qDebug() << i << friends[i]->getId() << friends[i]->getName(); QJsonObject user; user.insert("name",friends[i]->getName()); user.insert("id",friends[i]->getId()); //user.insert("account", friends[i]->getAccount()); //user.insert("email", friends[i]->getEmail()); //user.insert("gender", friends[i]->getGender()); friendsList.insert(i, user); } messageObject.insert("friendsList", friendsList); QJsonArray otherUsersList; qDebug() << "*********************" << otherUsers.size(); for (int i = 0; i < otherUsers.size(); i++) { qDebug() << i << otherUsers[i]->getId() << otherUsers[i]->getName(); QJsonObject user; user.insert("name",otherUsers[i]->getName()); user.insert("id",otherUsers[i]->getId()); //user.insert("account", otherUsers[i]->getAccount()); //user.insert("email", otherUsers[i]->getEmail()); //user.insert("gender", otherUsers[i]->getGender()); otherUsersList.insert(i, user); } messageObject.insert("otherUsersList", otherUsersList); } QJsonDocument document = QJsonDocument(messageObject); QByteArray userInfo = document.toJson();// 转换成QByteArray client->sendMessage(userInfo); } // 用户注册 void Server::userRegister(QJsonObject *object, TcpClient* client) { qDebug() << "register"; QString account = object->value("account").toString(); QString name = object->value("name").toString(); QString password = object->value("password").toString(); QString email = object->value("email").toString(); QString gender = object->value("gender").toString(); //qDebug() << account << name << password << email << gender; QJsonObject messageObject; messageObject.insert("type", messageType::REGISTER); Dao* database = Dao::getInstance(); bool resultStatus = database->addNewUser(account, name, password, email, gender); if (resultStatus == true) { messageObject.insert("resultStatus", resultStatus::SUCCESS); } else { // 找到注册失败的原因 messageObject.insert("resultStatus", resultStatus::ERROR); QList<User*> users = database->getAllUsers(); foreach(User* user, users) { if (user->getAccount() == account) { messageObject.insert("registerErrorCode", registerErrorCode::ACCOUNT_DUPLICATE); break; } else if (user->getEmail() == email) { messageObject.insert("registerErrorCode", registerErrorCode::EMAIL_DUPLICATE); break; } } } QJsonDocument document = QJsonDocument(messageObject); QByteArray userInfo = document.toJson();// 转换成QByteArray client->sendMessage(userInfo); } // 添加好友 void Server::addFriend(QJsonObject *object, TcpClient *client) { qDebug() << "addFriend"; int receiverId = object->value("receiverId").toInt(); TcpClient* receiverClient = onlineClients.value(receiverId); if (receiverClient == nullptr) { // 要添加好友的用户不在线 QJsonObject replyMessageObject; replyMessageObject.insert("type", messageType::ADDFRIENDREPLY); replyMessageObject.insert("addFriendStatus", addFriendStatus::NO); replyMessageObject.insert("addFriendErrorCode", addFriendErrorCode::OFFLINE); QJsonDocument document = QJsonDocument(replyMessageObject); QByteArray messageInfo = document.toJson();// 转换成QByteArray client->sendMessage(messageInfo); } else { //QJsonObject QJsonObject replyMessageObject; replyMessageObject.insert("type", messageType::ADDFRIENDREPLY); replyMessageObject.insert("addFriendStatus", addFriendStatus::OK); QJsonDocument document1 = QJsonDocument(replyMessageObject); QByteArray messageInfo1 = document1.toJson();// 转换成QByteArray client->sendMessage(messageInfo1); QJsonObject addFriendMessageObject; addFriendMessageObject.insert("type", messageType::ADDFRIEND); addFriendMessageObject.insert("senderId", object->value("senderId").toInt()); addFriendMessageObject.insert("account", object->value("account").toString()); addFriendMessageObject.insert("name", object->value("name").toString()); addFriendMessageObject.insert("receiverId", object->value("receiverId").toInt()); addFriendMessageObject.insert("verifyInfo", object->value("verifyInfo").toString()); QJsonDocument document2 = QJsonDocument(addFriendMessageObject); QByteArray messageInfo2 = document2.toJson();// 转换成QByteArray receiverClient->sendMessage(messageInfo2); } } void Server::addNewFirendReply(QJsonObject *object, TcpClient *client) { qDebug() << "******************"; int addFriendReplyInfoStatus = object->value("addFriendReplyInfoStatus").toInt(); int receiverId = object->value("receiverId").toInt(); int senderId = object->value("senderId").toInt(); qDebug() << receiverId << senderId; TcpClient* receiverClient = onlineClients.value(senderId); if (receiverClient == nullptr) { qDebug() << "offline"; return ; } QJsonObject replyMessageObject; replyMessageObject.insert("type", messageType::ADDFRIENDREPLYINFO); replyMessageObject.insert("userId", receiverId); replyMessageObject.insert("account", object->value("account").toString()); replyMessageObject.insert("name", object->value("name").toString()); qDebug() << object->value("account").toString() << object->value("name").toString(); if (addFriendReplyInfoStatus == addFriendReplyInfoStatus::AGREE) { // 添加好友成功 Dao* database = Dao::getInstance(); if (database->addNewFriendShip(senderId, receiverId)) { replyMessageObject.insert("addFriendReplyInfoStatus", addFriendReplyInfoStatus::AGREE); qDebug() << "friendship ok"; } else { replyMessageObject.insert("addFriendReplyInfoStatus", addFriendReplyInfoStatus::UNKNOWN); //replyMessageObject.insert("addFriendErrorCode", addFriendErrorCode::UNKNOWN); qDebug() << "friendship no1"; } } else { // 添加好友失败 replyMessageObject.insert("addFriendReplyInfoStatus", addFriendReplyInfoStatus::REJECT); qDebug() << "friendship no2"; //replyMessageObject.insert("addFriendErrorCode", addFriendErrorCode::REJECTED); } QJsonDocument document = QJsonDocument(replyMessageObject); QByteArray messageInfo = document.toJson();// 转换成QByteArray receiverClient->sendMessage(messageInfo); } // 发送消息 void Server::sendMessage(QJsonObject *object, TcpClient* client) { qDebug() << "sendMessage"; int receiverId = object->value("receiverId").toInt(); int senderId = client->getUser()->getId(); TcpClient* receiverClient = onlineClients.value(receiverId); // 回复的消息 QJsonObject replyMessageObject; qDebug() << receiverId << senderId << object->value("content").toString(); //replyMessageObject.insert("returnType", messageType::SENDMESSAGE); replyMessageObject.insert("type", messageType::SENDMESSAGE); if (receiverClient ==nullptr) { // 该好友当前不在线 replyMessageObject.insert("resultStatus", resultStatus::ERROR); } else { // 该好友当前在线 replyMessageObject.insert("resultStatus", resultStatus::SUCCESS); // 发送的消息 QJsonObject messageObject; messageObject.insert("type", messageType::RECEIVEMESSAGE); messageObject.insert("senderId", senderId); QString content = object->value("content").toString(); QString sendTime = object->value("sendTime").toString(); messageObject.insert("content", content); messageObject.insert("sendTime", sendTime); Dao* database = Dao::getInstance(); bool result = database->saveChatLog(senderId, receiverId, content, sendTime); if (result) qDebug() << "save success"; else { qDebug() << "save failure"; } QJsonDocument document = QJsonDocument(messageObject); QByteArray messageInfo = document.toJson();// 转换成QByteArray receiverClient->sendMessage(messageInfo); } QJsonDocument document = QJsonDocument(replyMessageObject); QByteArray replyInfo = document.toJson();// 转换成QByteArray client->sendMessage(replyInfo); } // 查询聊天记录 void Server::getChatLog(QJsonObject *object, TcpClient *client) { qDebug() << "getChating"; int senderId = object->value("senderId").toInt(); int recevierId = object->value("recevierId").toInt(); Dao* database = Dao::getInstance(); qDebug() << senderId << recevierId; QJsonObject messageObject; messageObject.insert("type",messageType::CHATLOG); QList<ChatLog*> chatLogList = database->getChatLogByIds(senderId, recevierId); User* user = database->getUserById(recevierId); // receiverId //QList<ChatLog*> chatLogList; messageObject.insert("resultStatus", resultStatus::SUCCESS); QJsonArray chatLog ; for(int i = 0 ;i < chatLogList.size() ; i++) { QJsonObject mychatLog; mychatLog.insert("id",chatLogList[i]->getId()); mychatLog.insert("senderId",chatLogList[i]->getSenderId()); mychatLog.insert("recevierId",chatLogList[i]->getRecevierId()); mychatLog.insert("content",chatLogList[i]->getContent()); mychatLog.insert("sendTime",chatLogList[i]->getSendTime()); mychatLog.insert("otherName", user->getName()); chatLog.insert(i,mychatLog); } messageObject.insert("chatLog",chatLog); QJsonDocument document=QJsonDocument(messageObject); QByteArray userInfo = document.toJson();// 转换成QByteArray //qDebug()<<userInfo; client->sendMessage(userInfo); } void Server::logout(QJsonObject *object, TcpClient* client) { int id = object->value("logoutId").toInt(); TcpClient* tempClient = onlineClients.value(id); if (tempClient != nullptr) { qDebug() << "logout success"; onlineClients.remove(id); } else { qDebug() << "logout failure"; } } void Server::deleteFriend(QJsonObject *object, TcpClient *client) { int uid = object->value("uid").toInt(); int fid = object->value("fid").toInt(); Dao* database = Dao::getInstance(); database->deleteFriendship(uid, fid); TcpClient* userClient = onlineClients.value(fid); if (userClient == nullptr) return ; User* user = client->getUser(); QJsonObject messageObject; messageObject.insert("type", messageType::DELETEFRIENDMESSAGE); messageObject.insert("id", uid); messageObject.insert("account", user->getAccount()); messageObject.insert("name", user->getName()); QJsonDocument document=QJsonDocument(messageObject); QByteArray userInfo = document.toJson();// 转换成QByteArray qDebug() << userInfo; userClient->sendMessage(userInfo); } void Server::transmitFile(TcpFile* fileClient) { QByteArray buf = fileClient->readAll(); qDebug() << buf; if (fileClient->isStart) { fileClient->isStart = false; //解析头部 "head#1024" fileClient->senderId = QString(buf).section("#", 0, 0).toInt(); fileClient->receiverId = QString(buf).section("#", 1, 1).toInt(); fileClient->fileName = QString(buf).section("#", 2, 2); fileClient->fileSize = QString(buf).section("#", 3, 3).toInt(); fileClient->receiveSize = 0; fileClient->targetFileClient = fileClients.value(fileClient->receiverId); qDebug() << fileClient->senderId << fileClient->receiverId << fileClient->fileName << fileClient->fileSize; if (fileClient->targetFileClient == nullptr) { qDebug() << "file client not exist error"; fileClient->isStart = true; return ; } qDebug() << buf; fileClient->targetFileClient->write(buf); fileClient->targetFileClient->flush(); QThread::sleep(5); } else { fileClient->targetFileClient->write(buf); fileClient->targetFileClient->flush(); fileClient->receiveSize += buf.size(); if(fileClient->receiveSize == fileClient->fileSize) { qDebug() << "转发文件完成"; //qDebug() << file. fileClient->isStart = true; fileClient->fileSize = 0; fileClient->receiveSize = 0; fileClient->targetFileClient = nullptr; } } } //TODO void Server::sendGroupMessage(QJsonObject *object, TcpClient *client) { QJsonObject replyMessageObject; // senderId groupId 内容 int senderId = object->value("senderId").toInt(); int groupId = object->value("groupId").toInt(); QString content = object->value("content").toString(); Dao* database = Dao::getInstance(); User* user = database->getUserById(senderId); replyMessageObject.insert("type", messageType::GROUPMESSAGE); replyMessageObject.insert("senderId", senderId); replyMessageObject.insert("account", user->getAccount()); replyMessageObject.insert("name", user->getName()); replyMessageObject.insert("groupId", groupId); replyMessageObject.insert("content", content); QJsonDocument document = QJsonDocument(replyMessageObject); QByteArray message = document.toJson(); QList<int> userList = database->getGroupUserIdsByGroupId(groupId); qDebug() << "group message" << message; foreach(int id, userList) { if (id == senderId) continue; else { foreach(TcpClient* client, onlineClients) { if (client->getUser()->getId() == id) { client->sendMessage(message); break; } } } qDebug() << "$$$" << id; } }
#!/usr/bin/env bash set -e set -m SCENARIO="oidc-login-strapi" STRAPI_FOLDER=${PWD}/ci/tests/puppeteer/scenarios/${SCENARIO}/strapi pid=$(cat $STRAPI_FOLDER/strapi.pid) echo "Killing any processes strapi script started" # msys2 ps doesn't support ps format (e.g. -o) kill $(ps | grep $pid | awk '{print $1}')
'use strict'; var assert = require('assert'); var defer = require('./defer'); var p = require('../'); describe('p.all', function () { describe('resolution', function () { var first, second; beforeEach(function () { first = defer(); second = defer(); // Out-of-order so we can test the order too. second.resolve(2); first.resolve(1); }); it('should accept an array of values and return an array of results', function (done) { p.all([ first.promise, second.promise, 3 // Test non-promises too. ]).then(function (results) { assert.deepStrictEqual(results, [1, 2, 3]); done(); }).catch(done); }); it('should accept a map of values and return a map of results', function (done) { p.all({ first: first.promise, second: second.promise, third: 3 }).then(function (results) { assert.deepStrictEqual(results, {first: 1, second: 2, third: 3}); done(); }).catch(done); }); }); describe('emptiness', function () { it('should resolve an empty array', function (done) { p.all([]).then(function (results) { assert.deepStrictEqual(results, []); done(); }).catch(done); }); it('should resolve an empty object', function (done) { p.all({}).then(function (results) { assert.deepStrictEqual(results, {}); done(); }).catch(done); }); }); it('should reject if any promise is rejected', function (done) { var first = defer(); var second = defer(); var expectedReason = {}; first.reject(expectedReason); p.all([ first.promise, second.promise ]).then(function () { assert(false); }, function (reason) { assert(reason === expectedReason); done(); }).catch(done); }); });
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Profile extends Model { protected $guarded = []; public function user() { return $this->belongsTo('App\User'); } public function santa() { return $this->hasMany('App\User', 'id', 'santa_id'); } public function wishlists() { return $this->hasMany('App\Wishlist'); } public function group() { return $this->belongsTo('App\Group'); } }
''' DIVISIBILITY OF STRINGS: FIND IF STRING s IS DIVISIBLE BY t IF YES, THEN FIND u, ON REPEATING WHICH WE GET BOTH s AND t RETURN LENGTH OF u ELSE RETURN -1 EXAMPLE: i/p: s="abcabcabcabc" t="abcabc" o/p: 3 (AS |u|=|"abc"|=3) ''' def FSD2(s, t): temp = "" for i in range(0, int(len(s)/len(t))): temp += t if(temp == s): return True return False def FSD(s, t): temp1 = "" temp2 = "" for i in range(0, int(len(s)/len(t))): temp1 += t if(temp1 == s): for j in range(0, len(t)): u = t[0:j+1] if(FSD2(t, u)): return len(u) return len(t) return -1 ''' print(FSD("rbrb","rbrb")) print(FSD("ababab","abab")) print(FSD("abcabcabcabc","abcabc")) >> 2 >> -1 >> 3 '''
using System.Threading.Tasks; using DemoWeb.Models; namespace DemoWeb.Services { public interface ITranscriptRepository { Task AddToTranscript(int studentId, CreateTranscript transcript); Task<Transcript> GetTranscript(int studentId, int courseId); } }
#!/usr/bin/env node 'use strict'; require('colorful').colorful(); const program = require('commander'); const pkg = require('../../package.json'); // fire-tools -v // fire-tools -h program.version(pkg.version, '-v, --version').usage('<command> [options]'); program.command('run [name]', 'run specified task'); // 如果存在,且没有显示调用action(fn),就会启动子命令程序 fire-tools-run,否则会报错, program.parse(process.argv); // https://github.com/tj/commander.js/pull/260 const proc = program.runningCommand; if (proc) { proc.on('close', process.exit.bind(process)); proc.on('error', () => { process.exit(1); }); } const subCmd = program.args[0]; if (!subCmd || subCmd !== 'run') { program.help(); }
/* * Copyright 2015 Alexey Andreev. * * 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.teavm.flavour.expr; import static org.teavm.flavour.expr.CompilerCommons.methodToDesc; import static org.teavm.flavour.expr.CompilerCommons.typeToString; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.teavm.flavour.expr.ast.AssignmentExpr; import org.teavm.flavour.expr.ast.BinaryExpr; import org.teavm.flavour.expr.ast.BinaryOperation; import org.teavm.flavour.expr.ast.BoundVariable; import org.teavm.flavour.expr.ast.CastExpr; import org.teavm.flavour.expr.ast.ConstantExpr; import org.teavm.flavour.expr.ast.Expr; import org.teavm.flavour.expr.ast.ExprVisitor; import org.teavm.flavour.expr.ast.InstanceOfExpr; import org.teavm.flavour.expr.ast.InvocationExpr; import org.teavm.flavour.expr.ast.LambdaExpr; import org.teavm.flavour.expr.ast.PropertyExpr; import org.teavm.flavour.expr.ast.StaticInvocationExpr; import org.teavm.flavour.expr.ast.StaticPropertyExpr; import org.teavm.flavour.expr.ast.TernaryConditionExpr; import org.teavm.flavour.expr.ast.ThisExpr; import org.teavm.flavour.expr.ast.UnaryExpr; import org.teavm.flavour.expr.ast.VariableExpr; import org.teavm.flavour.expr.plan.ArithmeticCastPlan; import org.teavm.flavour.expr.plan.ArithmeticType; import org.teavm.flavour.expr.plan.ArrayConstructionPlan; import org.teavm.flavour.expr.plan.ArrayLengthPlan; import org.teavm.flavour.expr.plan.BinaryPlan; import org.teavm.flavour.expr.plan.BinaryPlanType; import org.teavm.flavour.expr.plan.CastFromIntegerPlan; import org.teavm.flavour.expr.plan.CastPlan; import org.teavm.flavour.expr.plan.CastToIntegerPlan; import org.teavm.flavour.expr.plan.ConditionalPlan; import org.teavm.flavour.expr.plan.ConstantPlan; import org.teavm.flavour.expr.plan.ConstructionPlan; import org.teavm.flavour.expr.plan.FieldAssignmentPlan; import org.teavm.flavour.expr.plan.FieldPlan; import org.teavm.flavour.expr.plan.GetArrayElementPlan; import org.teavm.flavour.expr.plan.InstanceOfPlan; import org.teavm.flavour.expr.plan.IntegerSubtype; import org.teavm.flavour.expr.plan.InvocationPlan; import org.teavm.flavour.expr.plan.LambdaPlan; import org.teavm.flavour.expr.plan.LogicalBinaryPlan; import org.teavm.flavour.expr.plan.LogicalBinaryPlanType; import org.teavm.flavour.expr.plan.NegatePlan; import org.teavm.flavour.expr.plan.NotPlan; import org.teavm.flavour.expr.plan.Plan; import org.teavm.flavour.expr.plan.ReferenceEqualityPlan; import org.teavm.flavour.expr.plan.ReferenceEqualityPlanType; import org.teavm.flavour.expr.plan.ThisPlan; import org.teavm.flavour.expr.plan.VariablePlan; import org.teavm.flavour.expr.type.GenericArray; import org.teavm.flavour.expr.type.GenericClass; import org.teavm.flavour.expr.type.GenericField; import org.teavm.flavour.expr.type.GenericMethod; import org.teavm.flavour.expr.type.GenericReference; import org.teavm.flavour.expr.type.GenericType; import org.teavm.flavour.expr.type.GenericTypeNavigator; import org.teavm.flavour.expr.type.NullType; import org.teavm.flavour.expr.type.Primitive; import org.teavm.flavour.expr.type.PrimitiveArray; import org.teavm.flavour.expr.type.PrimitiveKind; import org.teavm.flavour.expr.type.TypeArgument; import org.teavm.flavour.expr.type.TypeInference; import org.teavm.flavour.expr.type.TypeInferenceStatePoint; import org.teavm.flavour.expr.type.TypeUtils; import org.teavm.flavour.expr.type.TypeVar; import org.teavm.flavour.expr.type.ValueType; import org.teavm.flavour.expr.type.ValueTypeFormatter; import org.teavm.flavour.expr.type.Variance; import org.teavm.flavour.expr.type.meta.ClassDescriber; class CompilerVisitor implements ExprVisitor<TypedPlan> { private GenericTypeNavigator navigator; private Scope scope; private Map<String, ValueType> boundVars = new HashMap<>(); private Map<String, String> boundVarRenamings = new HashMap<>(); private List<Diagnostic> diagnostics = new ArrayList<>(); private ClassResolver classResolver; private ValueType lambdaReturnType; ValueType expectedType; CompilerVisitor(GenericTypeNavigator navigator, ClassResolver classes, Scope scope) { this.navigator = navigator; this.classResolver = classes; this.scope = scope; } public List<Diagnostic> getDiagnostics() { return diagnostics; } @Override public TypedPlan visit(BinaryExpr expr) { Expr firstOperand = expr.getFirstOperand(); Expr secondOperand = expr.getSecondOperand(); expectedType = null; TypedPlan firstPlan = firstOperand.acceptVisitor(this); expectedType = null; secondOperand.acceptVisitor(this); TypedPlan secondPlan = secondOperand.acceptVisitor(this); switch (expr.getOperation()) { case SUBTRACT: case MULTIPLY: case DIVIDE: case REMAINDER: { ArithmeticTypeAndPlans result = getArithmeticTypeForPair(firstOperand, firstPlan, secondOperand, secondPlan); BinaryPlan plan = new BinaryPlan(result.first.getPlan(), result.second.getPlan(), getPlanType(expr.getOperation()), result.arithmeticType); return planWithLocation(plan, CompilerCommons.getType(result.arithmeticType), expr); } case AND: case OR: { firstPlan = ensureBooleanType(firstOperand, firstPlan); secondPlan = ensureBooleanType(secondOperand, secondPlan); LogicalBinaryPlan plan = new LogicalBinaryPlan(firstPlan.getPlan(), secondPlan.getPlan(), getLogicalPlanType(expr.getOperation())); return planWithLocation(plan, Primitive.BOOLEAN, expr); } case EQUAL: case NOT_EQUAL: { if (CompilerCommons.classesSuitableForComparison.contains(firstPlan.getType()) && CompilerCommons.classesSuitableForComparison.contains(secondPlan.getType())) { ArithmeticTypeAndPlans result = getArithmeticTypeForPair(firstOperand, firstPlan, secondOperand, secondPlan); BinaryPlan plan = new BinaryPlan(result.first.getPlan(), result.second.getPlan(), getPlanType(expr.getOperation()), result.arithmeticType); return planWithLocation(plan, Primitive.BOOLEAN, expr); } else { ReferenceEqualityPlan plan = new ReferenceEqualityPlan(firstPlan.getPlan(), secondPlan.getPlan(), expr.getOperation() == BinaryOperation.EQUAL ? ReferenceEqualityPlanType.EQUAL : ReferenceEqualityPlanType.NOT_EQUAL); return planWithLocation(plan, Primitive.BOOLEAN, expr); } } case LESS: case LESS_OR_EQUAL: case GREATER: case GREATER_OR_EQUAL: { ArithmeticTypeAndPlans result = getArithmeticTypeForPair(firstOperand, firstPlan, secondOperand, secondPlan); BinaryPlan plan = new BinaryPlan(result.first.getPlan(), result.second.getPlan(), getPlanType(expr.getOperation()), result.arithmeticType); return planWithLocation(plan, Primitive.BOOLEAN, expr); } case GET_ELEMENT: return compileGetElement(expr); case ADD: return compileAdd(expr); default: throw new AssertionError(); } } private TypedPlan compileAdd(BinaryExpr expr) { Expr firstOperand = expr.getFirstOperand(); TypedPlan firstPlan = firstOperand.acceptVisitor(this); ValueType firstType = firstPlan.getType(); Expr secondOperand = expr.getSecondOperand(); TypedPlan secondPlan = secondOperand.acceptVisitor(this); ValueType secondType = secondPlan.getType(); if (firstType.equals(TypeUtils.STRING_CLASS) || secondType.equals(TypeUtils.STRING_CLASS)) { if (firstPlan.getPlan() instanceof InvocationPlan) { InvocationPlan invocation = (InvocationPlan) firstPlan.getPlan(); if (invocation.getClassName().equals("java.lang.StringBuilder") && invocation.getMethodName().equals("toString")) { secondPlan = convertToString(expr.getSecondOperand(), secondPlan); Plan instance = invocation.getInstance(); InvocationPlan append = new InvocationPlan("java.lang.StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", instance, secondPlan.getPlan()); invocation.setInstance(append); return planWithLocation(invocation, TypeUtils.STRING_CLASS, expr); } } firstPlan = convertToString(expr.getFirstOperand(), firstPlan); secondPlan = convertToString(expr.getSecondOperand(), secondPlan); ConstructionPlan construction = new ConstructionPlan("java.lang.StringBuilder", "()V"); InvocationPlan invocation = new InvocationPlan("java.lang.StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", construction, firstPlan.getPlan()); invocation = new InvocationPlan("java.lang.StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", invocation, secondPlan.getPlan()); invocation = new InvocationPlan("java.lang.StringBuilder", "toString", "()Ljava/lang/String;", invocation); return planWithLocation(invocation, TypeUtils.STRING_CLASS, expr); } else { ArithmeticTypeAndPlans result = getArithmeticTypeForPair(firstOperand, firstPlan, secondOperand, secondPlan); BinaryPlan plan = new BinaryPlan(result.first.getPlan(), result.second.getPlan(), BinaryPlanType.ADD, result.arithmeticType); return planWithLocation(plan, CompilerCommons.getType(result.arithmeticType), expr); } } private TypedPlan compileGetElement(BinaryExpr expr) { Expr firstOperand = expr.getFirstOperand(); TypedPlan firstPlan = firstOperand.acceptVisitor(this); ValueType firstType = firstPlan.getType(); Expr secondOperand = expr.getSecondOperand(); TypedPlan secondPlan = secondOperand.acceptVisitor(this); ValueType secondType = secondPlan.getType(); if (firstType instanceof GenericArray) { GenericArray arrayType = (GenericArray) firstType; secondPlan = ensureIntType(secondOperand, secondPlan); GetArrayElementPlan plan = new GetArrayElementPlan(firstPlan.getPlan(), secondPlan.getPlan()); return planWithLocation(plan, arrayType.getElementType(), expr); } else if (firstType instanceof PrimitiveArray) { PrimitiveArray arrayType = (PrimitiveArray) firstType; secondPlan = ensureIntType(secondOperand, secondPlan); GetArrayElementPlan plan = new GetArrayElementPlan(firstPlan.getPlan(), secondPlan.getPlan()); return planWithLocation(plan, arrayType.getElementType(), expr); } else if (firstType instanceof GenericClass) { Collection<GenericClass> classes = CompilerCommons.extractClasses(firstType); return compileInvocation(expr, firstPlan, classes, "get", Arrays.asList(secondOperand), expectedType); } return errorAndFakeResult(expr, "Can't apply subscript operator to " + firstType + " with argument of " + secondType); } private TypedPlan errorAndFakeResult(Expr expr, String message) { error(expr, message); return planWithLocation(new ConstantPlan(null), NullType.INSTANCE, expr); } @Override public TypedPlan visit(CastExpr expr) { expectedType = null; TypedPlan result = expr.getValue().acceptVisitor(this); return cast(expr, result, resolveType(expr.getTargetType(), expr)); } private TypedPlan cast(Expr expr, TypedPlan plan, ValueType type) { ValueType sourceType = plan.getType(); plan = tryCast(expr, plan, type); return plan != null ? plan : errorAndFakeResult(expr, "Can't cast " + sourceType + " to " + type); } private TypedPlan tryCast(Expr expr, TypedPlan plan, ValueType targetType) { if (plan.getType().equals(targetType)) { return plan; } if (targetType instanceof Primitive) { if (!(plan.type instanceof Primitive)) { plan = unbox(plan); if (plan == null) { return null; } } plan = tryCastPrimitive(plan, (Primitive) targetType); if (plan == null) { return null; } return plan; } if (plan.type instanceof Primitive) { plan = box(expr, plan); } if (!CompilerCommons.isSuperType(targetType, plan.type, navigator)) { GenericType erasure = ((GenericType) targetType).erasure(); plan = new TypedPlan(new CastPlan(plan.plan, typeToString(erasure)), targetType); } return planWithLocation(plan.getPlan(), targetType, expr); } @Override public TypedPlan visit(InstanceOfExpr expr) { expectedType = null; expr.setCheckedType((GenericType) resolveType(expr.getCheckedType(), expr)); Expr value = expr.getValue(); TypedPlan valuePlan = value.acceptVisitor(this); GenericType checkedType = expr.getCheckedType(); ValueType sourceType = valuePlan.getType(); if (!(sourceType instanceof GenericClass)) { error(expr, "Can't check against " + checkedType); return planWithLocation(new ConstantPlan(false), Primitive.BOOLEAN, expr); } GenericType erasure = checkedType.erasure(); InstanceOfPlan plan = new InstanceOfPlan(valuePlan.getPlan(), typeToString(erasure)); return planWithLocation(plan, Primitive.BOOLEAN, expr); } @Override public TypedPlan visit(InvocationExpr expr) { ValueType expectedType = this.expectedType; TypedPlan instance; if (expr.getInstance() != null) { this.expectedType = null; instance = expr.getInstance().acceptVisitor(this); } else { instance = new TypedPlan(new ThisPlan(), scope.variableType("this")); } if (instance.type instanceof Primitive) { instance = box(expr.getInstance(), instance); } Collection<GenericClass> classes = CompilerCommons.extractClasses(instance.type); return compileInvocation(expr, instance, classes, expr.getMethodName(), expr.getArguments(), expectedType); } @Override public TypedPlan visit(StaticInvocationExpr expr) { ValueType expectedType = this.expectedType; return compileInvocation(expr, null, Collections.singleton(navigator.getGenericClass(expr.getClassName())), expr.getMethodName(), expr.getArguments(), expectedType); } private TypedPlan compileInvocation(Expr expr, TypedPlan instance, Collection<GenericClass> classes, String methodName, List<Expr> argumentExprList, ValueType expectedType) { TypeInference inference = new TypeInference(navigator); MethodLookup lookup = new MethodLookup(inference, classResolver, navigator, scope); GenericMethod method; if (instance != null) { method = lookup.lookupVirtual(classes, methodName, argumentExprList); } else { method = lookup.lookupStatic(classes, methodName, argumentExprList); } if (method == null) { return reportMissingMethod(expr, methodName, argumentExprList, lookup, classes, instance == null); } ValueType returnType = method.getActualReturnType(); ValueType[] capturedReturnType = new ValueType[1]; if (!addReturnTypeConstraint(method.getActualReturnType(), expectedType, inference, capturedReturnType)) { return errorAndFakeResult(expr, "Expected type " + expectedType + " does not match actual return type " + method.getActualReturnType()); } if (capturedReturnType[0] != null) { returnType = capturedReturnType[0]; } ValueType[] argTypes = method.getActualParameterTypes(); ValueType[] matchParamTypes = new ValueType[argumentExprList.size()]; TypeInferenceStatePoint statePointAfterLookup = inference.createStatePoint(); inference.resolve(); TypedPlan[] rawArguments = new TypedPlan[argumentExprList.size()]; for (int i = 0; i < argumentExprList.size(); ++i) { Expr arg = argumentExprList.get(i); ValueType paramType; if (lookup.isVarArgs() && i >= argTypes.length - 1) { ValueType lastArg = argTypes[argTypes.length - 1]; if (lastArg instanceof PrimitiveArray) { paramType = ((PrimitiveArray) lastArg).getElementType(); } else { paramType = ((GenericArray) lastArg).getElementType(); } } else { paramType = argTypes[i]; } matchParamTypes[i] = paramType; if (!(arg instanceof LambdaExpr)) { if (paramType instanceof GenericType) { paramType = ((GenericType) paramType).substitute(inference.getSubstitutions()); } this.expectedType = paramType; TypedPlan argPlan = arg.acceptVisitor(this); rawArguments[i] = argPlan; } } statePointAfterLookup.restoreTo(); for (int i = 0; i < argumentExprList.size(); ++i) { if (rawArguments[i] != null) { if (!inference.subtypeConstraint(rawArguments[i].getType(), matchParamTypes[i])) { return errorAndFakeResult(expr, "Argument " + (i + 1) + " type " + rawArguments[i].getType() + " does not match parameter type " + matchParamTypes[i]); } } } TypeInferenceStatePoint statePointBeforeLambdas = inference.createStatePoint(); if (!inference.resolve()) { return errorAndFakeResult(expr, "Could not infer type"); } ValueType[] lambdaReturnTypes = new ValueType[rawArguments.length]; for (int i = 0; i < argumentExprList.size(); ++i) { Expr arg = argumentExprList.get(i); if (arg instanceof LambdaExpr) { ValueType paramType = matchParamTypes[i]; if (paramType instanceof GenericType) { paramType = ((GenericType) paramType).substitute(inference.getSubstitutions()); } this.expectedType = paramType; TypedPlan lambdaPlan = arg.acceptVisitor(this); rawArguments[i] = lambdaPlan; lambdaReturnTypes[i] = lambdaReturnType; } } statePointBeforeLambdas.restoreTo(); for (int i = 0; i < argumentExprList.size(); ++i) { Expr arg = argumentExprList.get(i); if (!(arg instanceof LambdaExpr)) { continue; } LambdaExpr lambda = (LambdaExpr) arg; ValueType paramType = matchParamTypes[i]; if (!(paramType instanceof GenericClass)) { continue; } GenericMethod paramSam = navigator.findSingleAbstractMethod((GenericClass) paramType); if (paramSam == null) { continue; } ValueType[] paramParamTypes = paramSam.getActualParameterTypes(); for (int j = 0; j < paramParamTypes.length; ++j) { ValueType lambdaArgType = lambda.getBoundVariables().get(j).getType(); if (lambdaArgType != null && !inference.subtypeConstraint(paramParamTypes[j], lambdaArgType)) { return errorAndFakeResult(expr, "Could not infer type"); } } ValueType lambdaReturnType = lambdaReturnTypes[i]; if (paramSam.getActualReturnType() != null && lambdaReturnType != null) { if (!inference.subtypeConstraint(lambdaReturnType, paramSam.getActualReturnType())) { return errorAndFakeResult(expr, "Could not infer type"); } } } if (!inference.resolve()) { return errorAndFakeResult(expr, "Could not infer type"); } for (int i = 0; i < matchParamTypes.length; ++i) { if (matchParamTypes[i] instanceof GenericType) { matchParamTypes[i] = ((GenericType) matchParamTypes[i]).substitute(inference.getSubstitutions()); } } for (int i = 0; i < argTypes.length; ++i) { if (argTypes[i] instanceof GenericType) { argTypes[i] = ((GenericType) argTypes[i]).substitute(inference.getSubstitutions()); } } Plan[] convertedArguments = new Plan[rawArguments.length]; for (int i = 0; i < convertedArguments.length; ++i) { if (rawArguments[i] != null) { convertedArguments[i] = convert(argumentExprList.get(i), rawArguments[i], matchParamTypes[i]).getPlan(); } } method = method.substitute(inference.getSubstitutions()); if (returnType instanceof GenericType) { returnType = ((GenericType) returnType).substitute(inference.getSubstitutions()); } String className = method.getDescriber().getOwner().getName(); String desc = methodToDesc(method.getDescriber()); if (lookup.isVarArgs()) { convertedArguments = convertVarArgs(convertedArguments, argTypes); } Plan plan = new InvocationPlan(className, methodName, desc, instance != null ? instance.plan : null, convertedArguments); return planWithLocation(plan, returnType, expr); } private boolean addReturnTypeConstraint(ValueType actualType, ValueType expectedType, TypeInference inference, ValueType[] newReturnTypeHolder) { if (actualType == null || expectedType == null) { return true; } if (actualType instanceof GenericClass) { GenericClass actualClass = (GenericClass) actualType; if (actualClass.getArguments().stream().anyMatch(arg -> arg.getVariance() != Variance.INVARIANT)) { ClassDescriber describer = navigator.getClassRepository().describe(actualClass.getName()); List<? extends TypeVar> typeParameters = Arrays.asList(describer.getTypeVariables()); List<? extends TypeArgument> capturedTypeArgs = inference.captureConversionConstraint(typeParameters, actualClass.getArguments()); if (capturedTypeArgs == null) { return false; } newReturnTypeHolder[0] = new GenericClass(actualClass.getName(), capturedTypeArgs); return true; } } return inference.subtypeConstraint(actualType, expectedType); } private Plan[] convertVarArgs(Plan[] args, ValueType[] argTypes) { Plan[] varargs = new Plan[argTypes.length]; for (int i = 0; i < varargs.length - 1; ++i) { varargs[i] = args[i]; } Plan[] array = new Plan[args.length - varargs.length + 1]; for (int i = 0; i < array.length; ++i) { array[i] = args[varargs.length - 1 + i]; } ValueType lastArgType = argTypes[argTypes.length - 1]; ValueType elementType; if (lastArgType instanceof PrimitiveArray) { elementType = ((PrimitiveArray) lastArgType).getElementType(); } else { elementType = ((GenericArray) lastArgType).getElementType(); } ArrayConstructionPlan arrayPlan = new ArrayConstructionPlan(typeToString(elementType)); arrayPlan.getElements().addAll(Arrays.asList(array)); varargs[varargs.length - 1] = arrayPlan; return varargs; } private TypedPlan reportMissingMethod(Expr expr, String methodName, List<Expr> args, MethodLookup lookup, Collection<GenericClass> classes, boolean isStatic) { TypedPlan result = planWithLocation(new ConstantPlan(null), NullType.INSTANCE, expr); TypeInference inference = new TypeInference(navigator); MethodLookup altLookup = new MethodLookup(inference, classResolver, navigator, scope); GenericMethod altMethod = isStatic ? altLookup.lookupVirtual(classes, methodName, args) : altLookup.lookupStatic(classes, methodName, args); if (altMethod != null && inference.resolve()) { if (isStatic) { error(expr, "Method should be called as an instance method: " + altMethod); } else { error(expr, "Method should be called as a static method: " + altMethod); } return result; } if (lookup.getCandidates().isEmpty()) { error(expr, "Method not found: " + methodName); } else if (lookup.getCandidates().size() == 1) { error(expr, "Method " + lookup.getCandidates().get(0) + " is not applicable to given arguments"); } else { error(expr, "Ambiguous method invocation " + methodName); } return result; } @Override public TypedPlan visit(PropertyExpr expr) { expectedType = null; TypedPlan instance = expr.getInstance().acceptVisitor(this); if ((instance.type instanceof GenericArray || instance.type instanceof PrimitiveArray) && expr.getPropertyName().equals("length")) { return planWithLocation(new ArrayLengthPlan(instance.plan), Primitive.INT, expr); } if (instance.type instanceof Primitive) { instance = box(expr, instance); } Collection<GenericClass> classes = CompilerCommons.extractClasses(instance.type); return compilePropertyAccess(expr, instance, classes, expr.getPropertyName()); } @Override public TypedPlan visit(StaticPropertyExpr expr) { Collection<GenericClass> classes = Collections.singleton(navigator.getGenericClass(expr.getClassName())); return compilePropertyAccess(expr, null, classes, expr.getPropertyName()); } private TypedPlan compilePropertyAccess(Expr expr, TypedPlan instance, Collection<GenericClass> classes, String propertyName) { GenericField field = findField(classes, propertyName); boolean isStatic = instance == null; if (field != null) { if (isStatic == field.getDescriber().isStatic()) { FieldPlan plan = new FieldPlan(instance != null ? instance.plan : null, field.getDescriber().getOwner().getName(), field.getDescriber().getName(), typeToString(field.getDescriber().getRawType())); return planWithLocation(plan, field.getActualType(), expr); } else { return errorAndFakeResult(expr, "Field " + propertyName + " should " + (!isStatic ? "not " : "") + "be static"); } } else { GenericMethod getter = findGetter(classes, propertyName); if (getter != null) { if (isStatic == getter.getDescriber().isStatic()) { String desc = "()" + typeToString(getter.getDescriber().getRawReturnType()); InvocationPlan plan = new InvocationPlan(getter.getDescriber().getOwner().getName(), getter.getDescriber().getName(), desc, instance != null ? instance.plan : null); return planWithLocation(plan, getter.getActualReturnType(), expr); } else { return errorAndFakeResult(expr, "Method " + getter.getDescriber().getName() + " should " + (!isStatic ? "not " : "") + "be static"); } } else { if (instance.plan instanceof ThisPlan) { return errorAndFakeResult(expr, "Variable " + propertyName + " was not found"); } else { return errorAndFakeResult(expr, "Property " + propertyName + " was not found"); } } } } @Override public TypedPlan visit(UnaryExpr expr) { expectedType = null; TypedPlan operand = expr.getOperand().acceptVisitor(this); switch (expr.getOperation()) { case NEGATE: { ArithmeticTypeAndPlan result = getArithmeticType(expr, operand); NegatePlan plan = new NegatePlan(result.plan.getPlan(), result.type); return planWithLocation(plan, CompilerCommons.getType(result.type), expr); } case NOT: { operand = ensureBooleanType(expr, operand); NotPlan plan = new NotPlan(operand.getPlan()); return planWithLocation(plan, Primitive.BOOLEAN, expr); } default: throw new AssertionError("Should not get here"); } } @Override public TypedPlan visit(VariableExpr expr) { ValueType type = boundVars.get(expr.getName()); if (type != null) { String boundName = boundVarRenamings.get(expr.getName()); return planWithLocation(new VariablePlan(boundName), type, expr); } type = scope.variableType(expr.getName()); if (type == null) { type = scope.variableType("this"); return compilePropertyAccess(expr, new TypedPlan(new ThisPlan(), type), CompilerCommons.extractClasses(type), expr.getName()); } return planWithLocation(new VariablePlan(expr.getName()), type, expr); } @Override public TypedPlan visit(ThisExpr expr) { ValueType type = scope.variableType("this"); return planWithLocation(new ThisPlan(), type, expr); } @Override public TypedPlan visit(LambdaExpr expr) { GenericMethod lambdaSam = null; if (expectedType instanceof GenericClass) { lambdaSam = navigator.findSingleAbstractMethod((GenericClass) expectedType); } if (lambdaSam == null) { return errorAndFakeResult(expr, "Can't infer type of the lambda expression"); } ValueType[] actualArgTypes = lambdaSam.getActualParameterTypes(); ValueType[] oldVarTypes = new ValueType[expr.getBoundVariables().size()]; String[] oldRenamings = new String[oldVarTypes.length]; Set<String> usedNames = new HashSet<>(); List<String> boundVarNames = new ArrayList<>(); for (int i = 0; i < oldVarTypes.length; ++i) { BoundVariable boundVar = expr.getBoundVariables().get(i); if (!boundVar.getName().isEmpty()) { oldVarTypes[i] = boundVars.get(boundVar.getName()); oldRenamings[i] = boundVarRenamings.get(boundVar.getName()); if (!usedNames.add(boundVar.getName())) { error(expr, "Duplicate bound variable name: " + boundVar.getName()); } else { ValueType boundVarType = boundVar.getType(); if (boundVarType == null) { boundVarType = actualArgTypes[i]; } else if (!CompilerCommons.isSuperType(boundVarType, actualArgTypes[i], navigator)) { error(expr, "Expected parameter type " + actualArgTypes[i] + " is not a subtype of actually declared parameterType" + boundVarType); } boundVars.put(boundVar.getName(), boundVarType); String renaming = "$" + boundVarRenamings.size(); boundVarRenamings.put(boundVar.getName(), renaming); boundVarNames.add(renaming); } } else { boundVarNames.add(""); } } expectedType = lambdaSam.getActualReturnType(); TypedPlan body = expr.getBody().acceptVisitor(this); lambdaReturnType = body.getType(); if (lambdaSam.getActualReturnType() != null) { body = convert(expr.getBody(), body, lambdaSam.getActualReturnType()); } String className = lambdaSam.getDescriber().getOwner().getName(); String methodName = lambdaSam.getDescriber().getName(); String methodDesc = methodToDesc(lambdaSam.getDescriber()); LambdaPlan lambda = new LambdaPlan(body.plan, className, methodName, methodDesc, boundVarNames); for (int i = 0; i < oldVarTypes.length; ++i) { BoundVariable boundVar = expr.getBoundVariables().get(i); if (!boundVar.getName().isEmpty()) { boundVars.put(boundVar.getName(), oldVarTypes[i]); boundVarRenamings.put(boundVar.getName(), oldRenamings[i]); } } return planWithLocation(lambda, lambdaSam.getActualOwner(), expr); } @Override public TypedPlan visit(ConstantExpr expr) { ValueType type; if (expr.getValue() == null) { type = NullType.INSTANCE; } else if (expr.getValue() instanceof Boolean) { type = Primitive.BOOLEAN; } else if (expr.getValue() instanceof Character) { type = Primitive.CHAR; } else if (expr.getValue() instanceof Byte) { type = Primitive.BYTE; } else if (expr.getValue() instanceof Short) { type = Primitive.SHORT; } else if (expr.getValue() instanceof Integer) { type = Primitive.INT; } else if (expr.getValue() instanceof Long) { type = Primitive.LONG; } else if (expr.getValue() instanceof Float) { type = Primitive.FLOAT; } else if (expr.getValue() instanceof Double) { type = Primitive.DOUBLE; } else if (expr.getValue() instanceof String) { type = TypeUtils.STRING_CLASS; } else { throw new IllegalArgumentException("Don't know how to compile constant: " + expr.getValue()); } return planWithLocation(new ConstantPlan(expr.getValue()), type, expr); } @Override public TypedPlan visit(TernaryConditionExpr expr) { ValueType expectedType = null; this.expectedType = Primitive.BOOLEAN; TypedPlan condition = expr.getCondition().acceptVisitor(this); condition = convert(expr.getCondition(), condition, Primitive.BOOLEAN); this.expectedType = expectedType; TypedPlan consequent = expr.getConsequent().acceptVisitor(this); this.expectedType = expectedType; TypedPlan alternative = expr.getAlternative().acceptVisitor(this); ValueType a = consequent.getType(); ValueType b = alternative.getType(); ValueType type = CompilerCommons.commonSupertype(a, b, navigator); if (type == null) { ValueTypeFormatter formatter = new ValueTypeFormatter(); return errorAndFakeResult(expr, "Clauses of ternary conditional operator are not compatible: " + formatter.format(a) + " vs. " + formatter.format(b)); } consequent = convert(expr.getConsequent(), consequent, type); alternative = convert(expr.getAlternative(), alternative, type); return planWithLocation(new ConditionalPlan(condition.getPlan(), consequent.getPlan(), alternative.getPlan()), type, expr); } @Override public TypedPlan visit(AssignmentExpr expr) { if (expr.getTarget() instanceof VariableExpr) { ValueType instanceType = scope.variableType("this"); String identifier = ((VariableExpr) expr.getTarget()).getName(); TypedPlan instance = new TypedPlan(new ThisPlan(), instanceType); return compileAssignment(instance, CompilerCommons.extractClasses(instanceType), identifier, expr.getValue(), expr); } else if (expr.getTarget() instanceof PropertyExpr) { PropertyExpr property = (PropertyExpr) expr.getTarget(); TypedPlan instance = property.getInstance().acceptVisitor(this); ValueType instanceType = instance.getType(); String identifier = property.getPropertyName(); return compileAssignment(instance, CompilerCommons.extractClasses(instanceType), identifier, expr.getValue(), expr); } else if (expr.getTarget() instanceof StaticPropertyExpr) { StaticPropertyExpr property = (StaticPropertyExpr) expr.getTarget(); ValueType instanceType = navigator.getGenericClass(property.getClassName()); String identifier = property.getPropertyName(); return compileAssignment(null, CompilerCommons.extractClasses(instanceType), identifier, expr.getValue(), expr); } else { error(expr.getTarget(), "Invalid left side of assignment"); return planWithLocation(new ThisPlan(), voidType(), expr); } } private GenericType voidType() { return new GenericClass("java.lang.Void"); } private TypedPlan compileAssignment(TypedPlan instance, Collection<GenericClass> classes, String name, Expr value, Expr expr) { TypedPlan valuePlan = value.acceptVisitor(this); if (valuePlan.getType() == null) { error(value, "Right side of assignment must return a value"); return planWithLocation(new ThisPlan(), voidType(), expr); } GenericField field = findField(classes, name); if (field != null) { String owner = field.getDescriber().getOwner().getName(); String fieldName = field.getDescriber().getName(); String desc = typeToString(field.getDescriber().getRawType()); return planWithLocation(new FieldAssignmentPlan(instance != null ? instance.getPlan() : null, owner, fieldName, desc, valuePlan.getPlan()), voidType(), expr); } GenericMethod setter = findSetter(classes, name, valuePlan.getType()); if (setter != null) { String owner = setter.getDescriber().getOwner().getName(); String methodName = setter.getDescriber().getName(); String methodDesc = methodToDesc(setter.getDescriber()); return planWithLocation(new InvocationPlan(owner, methodName, methodDesc, instance != null ? instance.getPlan() : null, valuePlan.getPlan()), voidType(), expr); } error(expr, "Property not found: " + name); return planWithLocation(new ThisPlan(), voidType(), expr); } private GenericField findField(Collection<GenericClass> classes, String name) { for (GenericClass cls : classes) { GenericField field = navigator.getField(cls, name); if (field != null) { return field; } } return null; } private GenericMethod findGetter(Collection<GenericClass> classes, String name) { String getterName = getGetterName(name); String booleanGetterName = getBooleanGetterName(name); for (GenericClass cls : classes) { GenericMethod method = navigator.getMethod(cls, getterName); if (method == null) { method = navigator.getMethod(cls, booleanGetterName); if (method != null && method.getActualReturnType() != Primitive.BOOLEAN) { method = null; } } if (method != null) { return method; } } return null; } private GenericMethod findSetter(Collection<GenericClass> classes, String propertyName, ValueType type) { String setterName = getSetterName(propertyName); for (GenericClass cls : classes) { for (GenericMethod method : navigator.findMethods(cls, setterName, 1)) { if (CompilerCommons.isLooselyCompatibleType(method.getActualParameterTypes()[0], type, navigator)) { return method; } } } return null; } private String getGetterName(String propertyName) { if (propertyName.isEmpty()) { return "get"; } return "get" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); } private String getSetterName(String propertyName) { if (propertyName.isEmpty()) { return "set"; } return "set" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); } private String getBooleanGetterName(String propertyName) { if (propertyName.isEmpty()) { return "is"; } return "is" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); } private TypedPlan ensureBooleanType(Expr expr, TypedPlan plan) { return convert(expr, plan, Primitive.BOOLEAN); } private TypedPlan ensureIntType(Expr expr, TypedPlan plan) { return convert(expr, plan, Primitive.INT); } private TypedPlan convertToString(Expr expr, TypedPlan value) { if (value.getType().equals(TypeUtils.STRING_CLASS)) { return value; } ValueType type = value.getType(); Plan plan = value.getPlan(); if (type instanceof Primitive) { GenericClass wrapperClass = (GenericClass) TypeUtils.tryBox(type); plan = new InvocationPlan(wrapperClass.getName(), "toString", "(" + typeToString(type) + ")Ljava/lang/String;", null, plan); } else { plan = new InvocationPlan("java.lang.String", "valueOf", "(Ljava/lang/Object;)Ljava/lang/String;", null, plan); } return planWithLocation(plan, TypeUtils.STRING_CLASS, expr); } private ArithmeticTypeAndPlan getArithmeticType(Expr expr, TypedPlan plan) { ValueType initialType = plan.getType(); if (!(plan.getType() instanceof Primitive)) { plan = unbox(plan); } if (plan != null) { PrimitiveKind kind = ((Primitive) plan.type).getKind(); IntegerSubtype subtype = CompilerCommons.getIntegerSubtype(kind); if (subtype != null) { plan = planWithLocation(new CastToIntegerPlan(subtype, plan.plan), Primitive.INT, expr); kind = ((Primitive) plan.type).getKind(); } ArithmeticType type = CompilerCommons.getArithmeticType(kind); if (type != null) { return new ArithmeticTypeAndPlan(type, plan); } } error(expr, "Invalid operand type: " + initialType); return new ArithmeticTypeAndPlan(ArithmeticType.INT, planWithLocation( new ConstantPlan(0), Primitive.INT, expr)); } static class ArithmeticTypeAndPlan { ArithmeticType type; TypedPlan plan; ArithmeticTypeAndPlan(ArithmeticType type, TypedPlan plan) { this.type = type; this.plan = plan; } } private ArithmeticTypeAndPlans getArithmeticTypeForPair(Expr firstExpr, TypedPlan firstPlan, Expr secondExpr, TypedPlan secondPlan) { ArithmeticTypeAndPlan firstResult = getArithmeticType(firstExpr, firstPlan); ArithmeticTypeAndPlan secondResult = getArithmeticType(secondExpr, secondPlan); ArithmeticType firstType = firstResult.type; ArithmeticType secondType = secondResult.type; firstPlan = firstResult.plan; secondPlan = secondResult.plan; ArithmeticType common = ArithmeticType.values()[Math.max(firstType.ordinal(), secondType.ordinal())]; if (firstType != common) { firstPlan = planWithLocation(new ArithmeticCastPlan(firstType, common, firstPlan.getPlan()), CompilerCommons.getType(common), firstExpr); } if (secondType != common) { secondPlan = planWithLocation(new ArithmeticCastPlan(secondType, common, secondPlan.getPlan()), CompilerCommons.getType(common), secondExpr); } return new ArithmeticTypeAndPlans(common, firstPlan, secondPlan); } static class ArithmeticTypeAndPlans { ArithmeticType arithmeticType; TypedPlan first; TypedPlan second; ArithmeticTypeAndPlans(ArithmeticType arithmeticType, TypedPlan first, TypedPlan second) { this.arithmeticType = arithmeticType; this.first = first; this.second = second; } } private BinaryPlanType getPlanType(BinaryOperation op) { switch (op) { case ADD: return BinaryPlanType.ADD; case SUBTRACT: return BinaryPlanType.SUBTRACT; case MULTIPLY: return BinaryPlanType.MULTIPLY; case DIVIDE: return BinaryPlanType.DIVIDE; case REMAINDER: return BinaryPlanType.REMAINDER; case EQUAL: return BinaryPlanType.EQUAL; case NOT_EQUAL: return BinaryPlanType.NOT_EQUAL; case LESS: return BinaryPlanType.LESS; case LESS_OR_EQUAL: return BinaryPlanType.LESS_OR_EQUAL; case GREATER: return BinaryPlanType.GREATER; case GREATER_OR_EQUAL: return BinaryPlanType.GREATER_OR_EQUAL; default: break; } throw new AssertionError("Don't know how to map binary operation " + op + " to plan"); } private LogicalBinaryPlanType getLogicalPlanType(BinaryOperation op) { switch (op) { case AND: return LogicalBinaryPlanType.AND; case OR: return LogicalBinaryPlanType.OR; default: break; } throw new AssertionError("Don't know how to map binary operation " + op + " to plan"); } TypedPlan convert(Expr expr, TypedPlan plan, ValueType targetType) { TypedPlan convertedPlan = tryConvert(expr, plan, targetType); return convertedPlan != null ? convertedPlan : errorAndFakeResult(expr, "Can't convert " + plan.getType() + " to " + targetType); } private TypedPlan tryConvert(Expr expr, TypedPlan plan, ValueType targetType) { if (plan.getType() == null) { return null; } if (plan.getType().equals(targetType)) { return plan; } if (plan.getType().equals(NullType.INSTANCE)) { return new TypedPlan(plan.plan, targetType); } if (targetType instanceof Primitive) { if (!(plan.type instanceof Primitive)) { plan = unbox(plan); if (plan == null) { return null; } } if (!CompilerCommons.hasImplicitConversion(((Primitive) plan.type).getKind(), ((Primitive) targetType).getKind())) { return null; } plan = tryCastPrimitive(plan, (Primitive) targetType); if (plan == null) { return null; } return plan; } if (plan.type instanceof Primitive) { plan = box(expr, plan); if (plan == null) { return null; } } if (!CompilerCommons.isErasedSuperType(targetType, plan.type, navigator)) { return null; } return new TypedPlan(plan.plan, targetType); } private TypedPlan tryCastPrimitive(TypedPlan plan, Primitive targetType) { Primitive sourceType = (Primitive) plan.type; if (sourceType == targetType) { return plan; } if (sourceType.getKind() == PrimitiveKind.BOOLEAN) { if (targetType != Primitive.BOOLEAN) { return null; } } else { IntegerSubtype subtype = CompilerCommons.getIntegerSubtype(sourceType.getKind()); if (subtype != null) { plan = new TypedPlan(new CastToIntegerPlan(subtype, plan.plan), Primitive.INT); sourceType = (Primitive) plan.type; } ArithmeticType sourceArithmetic = CompilerCommons.getArithmeticType(sourceType.getKind()); if (sourceArithmetic == null) { return null; } subtype = CompilerCommons.getIntegerSubtype(targetType.getKind()); ArithmeticType targetArithmetic = CompilerCommons.getArithmeticType(targetType.getKind()); if (targetArithmetic == null) { if (subtype == null) { return null; } targetArithmetic = ArithmeticType.INT; } plan = new TypedPlan(new ArithmeticCastPlan(sourceArithmetic, targetArithmetic, plan.plan), CompilerCommons.getType(targetArithmetic)); if (subtype != null) { plan = new TypedPlan(new CastFromIntegerPlan(subtype, plan.plan), targetType); } } return plan; } private TypedPlan unbox(TypedPlan plan) { GenericClass cls; if (plan.type instanceof GenericReference) { TypeVar v = ((GenericReference) plan.type).getVar(); cls = (GenericClass) v.getLowerBound().stream() .filter(bound -> TypeUtils.tryUnbox(bound) != bound) .findFirst() .orElse(null); if (cls == null) { return null; } } else if (plan.type instanceof GenericClass) { cls = (GenericClass) plan.type; } else { return null; } Primitive primitive = TypeUtils.unbox(cls); if (primitive == null) { return null; } String methodName = primitive.getKind().name().toLowerCase() + "Value"; return new TypedPlan(new InvocationPlan(cls.getName(), methodName, "()" + typeToString(primitive), plan.plan), primitive); } private TypedPlan box(Expr expr, TypedPlan plan) { if (!(plan.type instanceof Primitive)) { return null; } GenericClass wrapper = TypeUtils.box(plan.type); if (wrapper == null) { return null; } return planWithLocation(new InvocationPlan(wrapper.getName(), "valueOf", "(" + typeToString(plan.type) + ")" + typeToString(wrapper), null, plan.plan), wrapper, expr); } private ValueType resolveType(ValueType type, Expr expr) { if (type instanceof GenericClass) { GenericClass cls = (GenericClass) type; String resolvedName = classResolver.findClass(cls.getName()); if (resolvedName == null) { error(expr, "Class not found: " + cls.getName()); return type; } boolean changed = !resolvedName.equals(cls.getName()); List<TypeArgument> arguments = new ArrayList<>(); for (TypeArgument arg : cls.getArguments()) { TypeArgument resolvedArg = arg.mapBound(bound -> (GenericType) resolveType(bound, expr)); arguments.add(resolvedArg); changed |= resolvedArg != arg; } return !changed ? type : new GenericClass(resolvedName, arguments); } else if (type instanceof GenericArray) { GenericArray array = (GenericArray) type; GenericType elementType = (GenericType) resolveType(array.getElementType(), expr); return elementType == array.getElementType() ? type : new GenericArray(elementType); } else { return type; } } private void error(Expr expr, String message) { diagnostics.add(new Diagnostic(expr.getStart(), expr.getEnd(), message)); } private TypedPlan planWithLocation(Plan plan, ValueType type, Expr expr) { plan.setLocation(new Location(expr.getStart(), expr.getEnd())); return new TypedPlan(plan, type); } }
-- PGOPTIONS=--search_path=stdb psql -d simpletrack -U stdb_user -f schema.sql create or replace function nonempty(text) returns boolean as $$ select length(trim($1)) > 0 $$ language sql strict immutable; -- remove tables in reverse order drop table if exists asset_meta; drop table if exists asset_meta_type; drop table if exists asset; drop table if exists asset_status; drop table if exists asset_type; drop table if exists location; drop table if exists site; drop table if exists st_user; -- For authentication create table st_user ( user_id text primary key, username text not null, email text, password text not null, check (nonempty(username)), check (nonempty(email)), /* metadata */ created_by text, modified_by text, created_datetime timestamp default now(), modified_datetime timestamp default now() ); -- A site is a geographic location. Like Thirsty Nomad Brewing, or Brewery create table site ( site_id text primary key, label text not null unique, description text, address text, check (nonempty(label)), /* metadata */ created_by text, modified_by text, created_datetime timestamp default now(), modified_datetime timestamp default now() ); create index site_label_idx on site (label); -- Location is a more specific part of a site. Like Inventory Walkin create table location ( location_id text primary key, label text not null, site_id text not null, description text, foreign key (site_id) references site (site_id), unique (site_id, label), check (nonempty(label)), /* metadata */ created_by text, modified_by text, created_datetime timestamp default now(), modified_datetime timestamp default now() ); create index location_label_idx on location (label); -- Used for categorizing assets. E.g. 1/6bbl keg, 1/2bbl keg, laptop create table asset_type ( asset_type_id text primary key, label text not null unique, check (nonempty(label)), /* metadata */ created_by text, modified_by text, created_datetime timestamp default now(), modified_datetime timestamp default now() ); create index asset_type_label_idx on asset_type (label); -- for managing asset state. E.g. 'in service', 'broken', 'maintenance/repair', ... create table asset_status ( asset_status_id text primary key, label text not null unique, check (nonempty(label)), /* metadata */ created_by text, modified_by text, created_datetime timestamp default now(), modified_datetime timestamp default now() ); -- create index asset_statusLabel_idx on asset_status (label); -- probably don't need this -- Represents a specific asset create table asset ( asset_id text primary key, label text, -- amounts to a UI overr_ide for asset_type.label in lists code text not null unique, asset_type_id text not null, asset_status_id text not null, location_id text, site_id text not null, -- I could get location from site, but location isn't required (as in customers) check (nonempty(code)), foreign key (asset_type_id) references asset_type (asset_type_id), foreign key (asset_status_id) references asset_status (asset_status_id), foreign key (location_id) references location (location_id), foreign key (site_id) references site (site_id), /* metadata */ created_by text, modified_by text, created_datetime timestamp default now(), modified_datetime timestamp default now() ); create index asset_code_idx on asset (code); -- A class of asset meta data. E.g. "Beer" create table asset_meta_type ( asset_meta_type_id text primary key, label text not null, check(nonempty(label)), /* metadata */ created_by text, modified_by text, created_datetime timestamp default now(), modified_datetime timestamp default now() ); create index asset_meta_type_label_idx on asset_meta_type (label); -- Extra data about an asset instance. E.g. "Sweeney" create table asset_meta ( asset_meta_id text primary key, asset_id text not null, -- fk asset_meta_type_id text not null, -- fk label text not null, check(nonempty(label)), /* metadata */ created_by text, modified_by text, created_datetime timestamp default now(), modified_datetime timestamp default now() ); create index asset_meta_asset_idx on asset_meta (asset_id); create index asset_meta_type_idx on asset_meta (asset_meta_type_id); create index asset_meta_label_idx on asset_meta (label);
package com.example.androidmapspolylines.UI.Interfaces import com.example.androidmapspolylines.Models.Ride interface BottomSheetInterface { fun callbackMethod(rideMode: String?) fun callbackSpqcialReq(rideReq: Ride) }
using Plots,FFTW using JLD2 for (ind, arg) in enumerate(ARGS) t = typeof(arg) msg = "$(ind) -> $arg :$t" println(msg) end function sqaure_windowing_signal(signal::Array{Float64}) windowed_signal = signal window_correction_factor = 1 return (windowed_signal,window_correction_factor) end function hanning_windowing_signal(signal::Array{Float64}) windowed_signal::Array{Float64} = [] window::Array{Float64} = [] total_window_power = 0 j = 1 for w = signal window_val = 0.5*(1 - cos(2*pi*j/length(signal))) push!(window,window_val) windowed = window_val*w push!(windowed_signal, windowed) total_window_power += window_val j += 1 end window_correction_factor = length(signal)/total_window_power return (windowed_signal,window_correction_factor) end function main() sampling_rate = 0.0 window_size = 64*1024*1024; w_m_vals::Array{Float64} = [] jldopen(ARGS[1], "r") do f sampling_rate = f["samplingrate"] w_m_vals = f["w_m"] end println(sampling_rate) println(length(w_m_vals)) #(windowed_signal, window_correction_factor) = sqaure_windowing_signal(w_m_vals[1:window_size]) (windowed_signal, window_correction_factor) = hanning_windowing_signal(w_m_vals[1:window_size]) println(window_correction_factor) powers = map(x->20*log10(abs(x)*window_correction_factor),fft(windowed_signal)|>fftshift) freqs = fftfreq( window_size, sampling_rate )|>fftshift plot_graph=plot(freqs, powers, xlims=(0,2000*1000), fmt =:png) savefig(plot_graph, "fft1.png") plot_graph=plot(freqs, powers, xlims=(944*1000,964*1000), fmt =:png) savefig(plot_graph, "fft2.png") end main()
use simpletcp::simpletcp::{Message, TcpServer, TcpStream}; use std::thread::{sleep, spawn}; use std::time::Duration; fn main() { let server = TcpServer::new("127.0.0.1:4234").unwrap(); spawn(|| { //Give server some time to start sleep(Duration::from_millis(50)); client_thread(); }); server_thread(server); } fn server_thread(server: TcpServer) { let mut client = server.accept_blocking().unwrap(); println!("[Server] Accepted new client"); client.wait_until_ready().unwrap(); let mut i = 1; while i <= 3 { println!("[Server] Sending message [{}/3]", i); let mut msg = Message::new(); msg.write_f64(1.23455); msg.write_buffer(&[3, 1, 4, 56]); client.write(&msg).unwrap(); sleep(Duration::from_secs(1)); i += 1; } } fn client_thread() { let mut client = TcpStream::connect("127.0.0.1:4234").unwrap(); client.wait_until_ready().unwrap(); loop { match client.read() { Ok(opt) => match opt { None => {} Some(mut msg) => { println!( "[Client] Received f64: {} and buffer: {:?}", msg.read_f64().unwrap(), msg.read_buffer().unwrap() ); } }, Err(err) => { println!("[Client] {:?}", err); break; } } } }
module Rescore where import qualified Data.Char as C import Database.Persist import Common import Score rescore :: Entity Contest -> [String] -> DatabaseM () rescore c args' = case args' of [] -> usage cmd':args -> case lookup (fmap C.toLower cmd') dispatch of Nothing -> usage Just cmd -> cmd c args dispatch :: [(String, Entity Contest -> [String] -> DatabaseM ())] dispatch = [ ( "round1", round1), ( "round2", round2),( "round3", round3)] usage :: MonadIO m => m () usage = boolFail $ usageDispatch "RESCORE" dispatch round1 :: Entity Contest -> [String] -> DatabaseM () round1 (Entity contestId _) args' = case args' of [] -> do rescoreBuildRound contestId _ -> boolFail "error: incorrect number of argumnets" round2 :: Entity Contest -> [String] -> DatabaseM () round2 (Entity contestId _) args' = case args' of [] -> do rescoreBreakRound contestId _ -> boolFail "error: incorrect number of argumnets" round3 :: Entity Contest -> [String] -> DatabaseM () round3 (Entity contestId _) args' = case args' of [] -> do rescoreFixRound contestId _ -> boolFail "error: incorrect number of argumnets"
<?php namespace inklabs\kommerce\ActionHandler\User; use inklabs\kommerce\Action\User\ResetPasswordCommand; use inklabs\kommerce\Entity\Cart; use inklabs\kommerce\Entity\TaxRate; use inklabs\kommerce\Entity\User; use inklabs\kommerce\Entity\UserRole; use inklabs\kommerce\Entity\UserToken; use inklabs\kommerce\Event\ResetPasswordEvent; use inklabs\kommerce\tests\Helper\TestCase\ActionTestCase; class ResetPasswordHandlerTest extends ActionTestCase { protected $metaDataClassNames = [ User::class, UserRole::class, UserToken::class, Cart::class, TaxRate::class, ]; public function testHandle() { $user = $this->dummyData->getUser(); $this->persistEntityAndFlushClear($user); $command = new ResetPasswordCommand( $user->getEmail(), self::IP4, self::USER_AGENT ); $this->dispatchCommand($command); /** @var ResetPasswordEvent $event */ $event = $this->getDispatchedEvents()[0]; $this->assertTrue($event instanceof ResetPasswordEvent); $this->assertSame($user->getId()->getHex(), $event->getUserId()->getHex()); $this->assertSame($user->getEmail(), $event->getEmail()); $this->assertSame($user->getFullName(), $event->getFullName()); $this->assertSame(40, strlen($event->getToken())); } }
class StoryIndexForComments < ActiveRecord::Migration[6.0] def change remove_index :stories, name: "index_stories_on_is_expired" remove_index :stories, name: "index_stories_on_is_moderated" remove_index :stories, name: "is_idxes" add_index :stories, [:id, :is_expired] end end
--- title: Cyrus Biotechnology site: https://cyrusbio.com logo: cyrus.svg ---
class OrganismsController < ApplicationController def kingdom render json: Organism.kingdom end def phylum render json: Organism.phylum end def klass render json: Organism.klass end def order render json: Organism.order end def family render json: Organism.family end def genus render json: Organism.genus end def species render json: Organism.species end def cname render json: Organism.cname end end
package observer.screens; import java.util.Observable; public class CurrentConditionsScreen extends AbstractScreenObserver { public CurrentConditionsScreen(Observable weatherData) { super(weatherData); } @Override public void processData() { //do nothing } public void display() { System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity."); } }
/** * Copyright (c) 2017 Bevan Hunt. All rights reserved. * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package cmd import ( "fmt" "log" "net/url" "strconv" "strings" "time" "github.com/bevanhunt/gowrex" "github.com/dixonwille/wmenu" "github.com/gosuri/uitable" "github.com/skratchdot/open-golang/open" "github.com/spf13/cobra" "github.com/ttacon/chalk" ) // flag value for limit var limit int // searchCmd represents the search command var searchCmd = &cobra.Command{ Use: "search", Short: "Keyword search apis.io", Long: `Keyword search apis.io. Example: search trade`, Run: func(cmd *cobra.Command, args []string) { type JSONReceive struct { Status string `json:"status"` Data []struct { CreatedAt *time.Time `json:"createdAt"` Name string `json:"name"` Description string `json:"description"` Image string `json:"image"` BaseURL string `json:"baseURL"` HumanURL string `json:"humanURL"` Properties []struct { Type string `json:"type"` URL string `json:"url"` } `json:"properties"` Contact []struct { FN string `json:"FN"` Email string `json:"email"` OrganizationName string `json:"organizationName"` XTwitter string `json:"X-twitter"` } `json:"contact"` Authoritative bool `json:"authoritative"` APIFileURL string `json:"apiFileUrl"` Slug string `json:"slug"` UpdatedAt *time.Time `json:"updatedAt"` Tags []string `json:"tags,omitempty"` } `json:"data"` Limit int `json:" limit"` Skip int `json:" skip"` Paging struct { Next string `json:"next"` Previous string `json:"previous"` } `json:" paging"` } // join all args into one keyword separated by spaces and url encoded keywords := strings.Join(args, " ") keywordsEscaped := url.QueryEscape(keywords) // make API request to apis.io req, err := gowrex.Request{ URI: "http://apis.io/api/search?q=" + keywordsEscaped + "&limit=" + strconv.Itoa(limit), }.GetJSON() if err != nil { log.Println(err) } res, err := req.Do() if err != nil { log.Println(err) } resp := &JSONReceive{} _, err = res.JSON(resp) if err != nil { log.Println(err) } // create results top bar fmt.Println(chalk.Red.Color("Search: " + keywords)) fmt.Println(chalk.Yellow.Color("Results: ")) fmt.Println("") // handle no results if len(resp.Data) == 1 && resp.Data[0].Name == "" { fmt.Println(chalk.Red.Color("No Results")) return } // create results table table := uitable.New() table.MaxColWidth = 50 table.Wrap = true table.AddRow( "#", "Name", "Description", "Swagger", ) for i, el := range resp.Data { swagger := false for _, elem := range el.Properties { if elem.Type == "Swagger" { swagger = true } } table.AddRow("") table.AddRow( i, el.Name, el.Description, swagger, ) } fmt.Println(table) // site viewing menu actFunc := func(opt wmenu.Opt) error { selection, ok := opt.Value.(int) if ok { open.Run(resp.Data[selection].HumanURL) } return nil } menu := wmenu.NewMenu("Select to show site:") menu.Action(actFunc) for x, elem := range resp.Data { menu.Option(elem.Name, x, false, nil) } menuErr := menu.Run() if menuErr != nil { log.Fatal(menuErr) } // count swagger items swaggerCount := 0 for _, el := range resp.Data { swagger := false for _, elem := range el.Properties { if elem.Type == "Swagger" { swagger = true } } if swagger == true { swaggerCount++ } } // if more than one swagger item then show menu if swaggerCount > 0 { // swagger viewing menu swFunc := func(opt wmenu.Opt) error { url, ok := opt.Value.(string) if ok { open.Run("http://petstore.swagger.io?url=" + url) } return nil } swMenu := wmenu.NewMenu("Select to display Swagger:") swMenu.Action(swFunc) for _, elem := range resp.Data { var url string swaggered := false for _, el := range elem.Properties { if el.Type == "Swagger" { url = el.URL swaggered = true } } if swaggered == true { swMenu.Option(elem.Name, url, false, nil) } } swMenuErr := swMenu.Run() if swMenuErr != nil { log.Fatal(swMenuErr) } } }, } func init() { RootCmd.AddCommand(searchCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // searchCmd.PersistentFlags().String("limit", "l", "# of max results (limit)") // Cobra supports local flags which will only run when this command // is called directly, e.g.: searchCmd.Flags().IntVarP(&limit, "limit", "l", 10, "limit number of results - default 10") }
from django.contrib import admin from src.apps.books.models import Book, BookAuthorship class BookAuthorshipAdminInline(admin.TabularInline): model = BookAuthorship extra = 0 @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'publisher') filter_horizontal = ('authors',) inlines = (BookAuthorshipAdminInline,)
<?php declare(strict_types=1); namespace Tests\Brille24\SyliusCustomerOptionsPlugin\Behat\Context; use Behat\Behat\Context\Context; use Brille24\SyliusCustomerOptionsPlugin\Entity\CustomerOptions\CustomerOptionGroupInterface; use Brille24\SyliusCustomerOptionsPlugin\Entity\CustomerOptions\CustomerOptionInterface; use Brille24\SyliusCustomerOptionsPlugin\Repository\CustomerOptionGroupRepositoryInterface; use Brille24\SyliusCustomerOptionsPlugin\Repository\CustomerOptionRepositoryInterface; use Doctrine\ORM\EntityManagerInterface; use Sylius\Component\Core\Repository\ProductRepositoryInterface; use Webmozart\Assert\Assert; class TransformContext implements Context { /** @var CustomerOptionRepositoryInterface */ private $customerOptionRepository; /** @var CustomerOptionGroupRepositoryInterface */ private $customerOptionGroupRepository; /** @var ProductRepositoryInterface */ private $productRepository; /** @var EntityManagerInterface */ private $em; public function __construct( CustomerOptionRepositoryInterface $customerOptionRepository, CustomerOptionGroupRepositoryInterface $customerOptionGroupRepository, ProductRepositoryInterface $productRepository, EntityManagerInterface $em ) { $this->customerOptionRepository = $customerOptionRepository; $this->customerOptionGroupRepository = $customerOptionGroupRepository; $this->productRepository = $productRepository; $this->em = $em; } /** * @Transform :customerOption * @Transform :customerOption in locale :locale */ public function getCustomerOptionByName(string $name, string $locale = 'en_US'): CustomerOptionInterface { $customerOption = $this->customerOptionRepository->findByName($name, $locale); Assert::true(count($customerOption) > 0); return $customerOption[0]; } /** * @Transform :customerOptionGroup * @Transform :customerOptionGroup in locale :locale */ public function getCustomerOptionGroupByName(string $name, string $locale = 'en_US'): CustomerOptionGroupInterface { $customerOptionGroups = $this->customerOptionGroupRepository->findByName($name, $locale); Assert::true(count($customerOptionGroups) > 0); $this->em->refresh($customerOptionGroups[0]); return $customerOptionGroups[0]; } /** * @Transform /^product(?:|s) "([^"]+)"$/ * @Transform /^"([^"]+)" product(?:|s)$/ * @Transform /^(?:a|an) "([^"]+)"$/ * @Transform :product */ public function getProductByName($productName) { $products = $this->productRepository->findByName($productName, 'en_US'); Assert::eq( count($products), 1, sprintf('%d products has been found with name "%s".', count($products), $productName) ); $this->em->refresh($products[0]); return $products[0]; } /** * @Transform /^products "([^"]+)" and "([^"]+)"$/ * @Transform /^products "([^"]+)", "([^"]+)" and "([^"]+)"$/ */ public function getProductsByNames(...$productsNames) { return array_map(function ($productName) { return $this->getProductByName($productName); }, $productsNames); } }
Using `strings.Builder` is overkill for this simple use case. Use `fmt.Sprintf` or simple concatenation using the `+` operator, instead.
package me.star.security.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import me.star.security.service.OnlineUserService; import me.star.utils.EncryptUtils; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Set; /** * @author Star Chou * @description / * @create 2022/1/8 20:39 */ @RestController @RequiredArgsConstructor @RequestMapping("/auth/online") @Api(tags = "系统:在线用户管理") public class OnlineController { private final OnlineUserService onlineUserService; @ApiOperation("查询在线用户") @GetMapping public ResponseEntity<Object> query(String filter, Pageable pageable){ return new ResponseEntity<>(onlineUserService.getAll(filter, pageable), HttpStatus.OK); } @ApiOperation("导出数据") @GetMapping(value = "/download") public void download(HttpServletResponse response, String filter) throws IOException { onlineUserService.download(onlineUserService.getAll(filter), response); } @ApiOperation("踢出用户") @DeleteMapping public ResponseEntity<Object> delete(@RequestBody Set<String> keys) throws Exception { for (String key : keys) { // 解密Key key = EncryptUtils.desDecrypt(key); onlineUserService.kickOut(key); } return new ResponseEntity<>(HttpStatus.OK); } }
using hw.UnitTest; using Reni.FeatureTest.Helper; namespace Reni.FeatureTest.Function { [UnitTest] [Target(@"f: @100;f() dump_print;")] [Output("100")] [Function] public sealed class ConstantFunction : CompilerTest {} }
package funcify.feature.naming.impl import funcify.feature.naming.NameSegment /** * * @author smccarron * @created 3/16/22 */ data class DefaultNameSegment(override val value: String) : NameSegment { override fun toString(): String { return value } }
module SampleFeeds FEEDS = { sample_atom_feed: "AmazonWebServicesBlog.xml", sample_atom_middleman_feed: "FeedjiraBlog.xml", sample_atom_xhtml_feed: "pet_atom.xml", sample_atom_feed_line_breaks: "AtomFeedWithSpacesAroundEquals.xml", sample_atom_entry_content: "AmazonWebServicesBlogFirstEntryContent.xml", sample_itunes_feed: "itunes.xml", sample_itunes_feed_with_single_quotes: "ITunesWithSingleQuotedAttributes.xml", sample_itunes_feed_with_spaces: "ITunesWithSpacesInAttributes.xml", sample_podlove_feed: "CRE.xml", sample_rdf_feed: "HREFConsideredHarmful.xml", sample_rdf_entry_content: "HREFConsideredHarmfulFirstEntry.xml", sample_rss_feed_burner_feed: "TechCrunch.xml", sample_rss_feed_burner_entry_content: "TechCrunchFirstEntry.xml", sample_rss_feed_burner_entry_description: "TechCrunchFirstEntryDescription.xml", sample_rss_feed: "TenderLovemaking.xml", sample_rss_entry_content: "TenderLovemakingFirstEntry.xml", sample_feedburner_atom_feed: "PaulDixExplainsNothing.xml", sample_feedburner_atom_feed_alternate: "GiantRobotsSmashingIntoOtherGiantRobots.xml", sample_feedburner_atom_entry_content: "PaulDixExplainsNothingFirstEntryContent.xml", sample_wfw_feed: "PaulDixExplainsNothingWFW.xml", sample_google_docs_list_feed: "GoogleDocsList.xml", sample_feed_burner_atom_xhtml_feed: "FeedBurnerXHTML.xml", sample_duplicate_content_atom_feed: "DuplicateContentAtomFeed.xml", sample_youtube_atom_feed: "youtube_atom.xml", sample_atom_xhtml_with_escpaed_html_in_pre_tag_feed: "AtomEscapedHTMLInPreTag.xml", sample_json_feed: "json_feed.json", sample_rss_feed_huffpost_ca: "HuffPostCanada.xml", sample_invalid_date_format_feed: "InvalidDateFormat.xml" }.freeze FEEDS.each do |method, filename| define_method(method) { load_sample filename } end def load_sample(filename) File.read("#{File.dirname(__FILE__)}/sample_feeds/#{filename}") end end
require 'thread' module Imggrabber module Adapters class ThreadsAdapter def self.run(number, path, images) queue = Queue.new images.each { |image| queue << image } threads = number.times.map do Thread.new do while !queue.empty? && image = queue.pop response = Net::HTTP.get(image) Utils.write_file(path, image, response) end end end threads.each(&:join) end end end end
1 2 5 6 8 9 10 2 5 6 11 3 1 2 6 7 9 10 4 1 2 3 5 6 7 10 11 5 3 7 10 6 5 9 10 11 7 1 2 6 11 8 2 3 4 5 6 7 10 11 9 2 4 5 7 8 10 10 2 7 11 1 3 5 9 10
package examples object RecordDefinitionExample { import shapeless._ import record._ import ops.hlist.{ToList,Align} import ops.record.{ Keys, Values } import shapeless.labelled._ import syntax.singleton._ case class Person(firstName:String, lastName:String, age:Int) val personGen = LabelledGeneric[Person] val defaultLastName = Field("lastName" ->> "") val defaultFirstName = Field("firstName" ->> "") type lastNameRepr = defaultLastName.F type firstNameRepr = defaultFirstName.F type PersonRepr = firstNameRepr:: lastNameRepr:: HNil def main(args:Array[String]):Unit = { } trait Field { type K type V type F = FieldType[K, V] } object Field { def apply[K0, V0](sample: FieldType[K0, V0]) = new Field { type K = K0; type V = V0 } } }
package io.github.zeyomir.cv.overview.certificates import io.github.zeyomir.cv.domain.entity.CvCertificate import io.github.zeyomir.cv.domain.repository.CvRepository import io.reactivex.Observable class StreamCvCertificatesUseCase( private val repository: CvRepository ) { fun execute(): Observable<List<CvCertificate>> = repository.getCv().map { it.certificates } }
# Skydot Skydot Architecture Diagram: ![alt text][diagram] [diagram]: https://github.com/lexibrown/Skydot/blob/master/images/lowleveldiagram.PNG "Low Level Diagram"
package root import ( "github.com/BurntSushi/wingo/prompt" "github.com/BurntSushi/xgbutil" "github.com/BurntSushi/xgbutil/ewmh" "github.com/BurntSushi/xgbutil/keybind" "github.com/BurntSushi/xgbutil/xevent" "github.com/BurntSushi/xgbutil/xgraphics" "github.com/BurntSushi/xgbutil/xwindow" "github.com/levavakian/rowm/frame" ) type CycleWrap struct { Cycle *prompt.Cycle Choices []*prompt.CycleItem } type Choice struct { Win *xwindow.Window Context *frame.Context Wrapper *CycleWrap } func (c *CycleWrap) Destroy() { c.Cycle.Destroy() c.Cycle = nil c.Choices = make([]*prompt.CycleItem, 0) } func (c *Choice) CycleIsActive() bool { return true } func (c *Choice) CycleImage() *xgraphics.Image { ximg, err := xgraphics.FindIcon(c.Context.X, c.Win.Id, prompt.DefaultCycleTheme.IconSize, prompt.DefaultCycleTheme.IconSize) if err != nil { return c.Context.DummyIcon } return ximg } func (c *Choice) CycleText() string { name, err := ewmh.WmNameGet(c.Context.X, c.Win.Id) if err != nil { return "N/A" } return name } func (c *Choice) CycleHighlighted() { // Chill } func (c *Choice) CycleSelected() { if f := c.Context.Get(c.Win.Id); f != nil { if f.Container.Hidden { f.Container.ChangeMinimizationState(c.Context) } else { f.Container.RaiseFindFocus(c.Context) } } c.Wrapper.Destroy() } func RegisterChooseHooks(ctx *frame.Context) { wrapper := &CycleWrap{} cycle := func(cycleDir string) { if ctx.Locked { return } if wrapper.Cycle != nil { if cycleDir == ctx.Config.TabBackward.Data { wrapper.Cycle.Prev() } else { wrapper.Cycle.Next() } return } } register := func(cycleDir string) { if ctx.Locked { return } if wrapper.Cycle != nil { shown := wrapper.Cycle.Show(ctx.Screens[0].ToXRect(), cycleDir, wrapper.Choices) if !shown { wrapper.Destroy() } else { return } } wrapper.Cycle = prompt.NewCycle(ctx.X, prompt.DefaultCycleTheme, prompt.DefaultCycleConfig) wrapper.Choices = make([]*prompt.CycleItem, 0) if ctx.Config.TabByFrame { for _, f := range ctx.Tracked { if !f.IsLeaf() || f.Container == nil { continue } item := wrapper.Cycle.AddChoice(&Choice{f.Window, ctx, wrapper}) wrapper.Choices = append(wrapper.Choices, item) } } else { for c, _ := range ctx.Containers { if c.Root == nil { continue } if f := c.Root.Find(func(fr *frame.Frame) bool { return fr.IsLeaf() }); f != nil { item := wrapper.Cycle.AddChoice(&Choice{f.Window, ctx, wrapper}) wrapper.Choices = append(wrapper.Choices, item) } } } wrapper.Cycle.Show(ctx.Screens[0].ToXRect(), cycleDir, wrapper.Choices) cycle(cycleDir) } keybind.KeyPressFun(func(X *xgbutil.XUtil, ev xevent.KeyPressEvent) { register(ctx.Config.TabForward.Data) }).Connect(ctx.X, ctx.X.RootWin(), ctx.Config.TabForward.Data, true) keybind.KeyPressFun(func(X *xgbutil.XUtil, ev xevent.KeyPressEvent) { cycle(ctx.Config.TabForward.Data) }).Connect(ctx.X, ctx.X.Dummy(), ctx.Config.TabForward.Data, true) keybind.KeyPressFun(func(X *xgbutil.XUtil, ev xevent.KeyPressEvent) { register(ctx.Config.TabBackward.Data) }).Connect(ctx.X, ctx.X.RootWin(), ctx.Config.TabBackward.Data, true) keybind.KeyPressFun(func(X *xgbutil.XUtil, ev xevent.KeyPressEvent) { cycle(ctx.Config.TabBackward.Data) }).Connect(ctx.X, ctx.X.Dummy(), ctx.Config.TabBackward.Data, true) }
package controller; import authoring.frontend.exceptions.MissingPropertiesException; import frontend.StageManager; /** * Interface that both controllers in the Authoring/GamePlay MVC setups must * implement. Used to maximized shared responsibility of View class. * @author Sarahbland * */ public interface MVController { /** * Method that creates a new playController and demos a game * based on that playController * @param manager is StageManager holding current stage * @param instructions is String of instructions to be given at the beginning * of the game * @throws MissingPropertiesException */ public void playControllerDemo(StageManager manager, String instructions) throws MissingPropertiesException; }
--- title: Expand the tab heigh to 100% page_title: Expand the tab heigh to 100% description: Expand the tab heigh to 100% --- # Expand the tab heigh to 100% The following runnable sample demonstrates how to expand the tab heigh to 100% of the parent container. #### Example: ```html <div id="tabstrip"> <ul> <li class="k-state-active">Item 1</li> <li>Item 2</li> </ul> <div> Content 1 <p><button type="button" class="k-button" id="appendButton">Append Item</button></p> </div> <div> Content 2 </div> </div> <script> var resizeAll = function() { expandContentDivs(tabStripElement.children(".k-content")); } var tabStripElement = $("#tabstrip").kendoTabStrip({ animation: { open: { effects: "fade" } } }); var tabStrip = tabStripElement.data("kendoTabStrip"); var expandContentDivs = function(divs) { divs.height(tabStripElement.innerHeight() - tabStripElement.children(".k-tabstrip-items").outerHeight() - 16); } // 16px are substracted to compensate for content div vertical paddings and borders tabStripElement.parent().attr("id", "tabstrip-parent"); resizeAll(); $(window).resize(function(){ resizeAll(); }); $("#appendButton").click(function(){ tabStrip.append({ text: "Item N", content: "Appended Item Content" }); expandContentDivs(tabStripElement.children(".k-content").last()); }); </script> ```
using System; using Couchbase.Core.Version; namespace Couchbase.Linq.Versioning { /// <summary> /// Constants for the Couchbase versions where new features are implemented. /// </summary> internal static class FeatureVersions { /// <summary> /// Default version we assume if we can't get the cluster version. /// </summary> public static readonly ClusterVersion DefaultVersion = new ClusterVersion(new Version(5, 5, 0)); } }
import csv def WriteListToCSV(outname, list, delim): ''' Function to write a list of lists into a csv-file. Each entry in the list is thereby a new line --> the function is designed towards the standard output of may of my analyses. PARAMETERS ---------- outname : string (required) Path to the output-file. make sure it ends with ".csv" list : list object (required) List with the data to write. Each sublist is an own line in the csv file. [[line 1], [line 2],...,[line n]] delim : string (required) Deliminter for the csv-File RETURNS ------- theFile : output-file. Directly written to disc ''' with open(outname, "w") as theFile: csv.register_dialect("custom", delimiter = delim, skipinitialspace = True, lineterminator = '\n') writer = csv.writer(theFile, dialect = "custom") for element in list: writer.writerow(element)
--- layout: watch title: TLP4 - 30/05/2019 - M20190530_224233_TLP_4T.jpg date: 2019-05-30 22:42:33 permalink: /2019/05/30/watch/M20190530_224233_TLP_4 capture: TLP4/2019/201905/20190530/M20190530_224233_TLP_4T.jpg ---
import { Location } from "../types"; import { DistanceMatrix } from "../types/distance-matrix.type"; export interface GoogleMatrixClient { getDistance: (originArr: Location[], destinationArr: Location[]) => Promise<DistanceMatrix> }
using System; using System.Data.SQLite; using System.IO; using ClickHouse.Ado; namespace Test.ClickHouse.DbLoad { class Program { static void Main(string[] args) { var dbfilename = Path.GetFullPath("Northwind.db3"); ClickHouseConnectionSettings set = new ClickHouseConnectionSettings(); // set.Database = "Northwind"; set.User = "default"; set.Password = ""; set.Host = "10.200.101.163"; set.Port = 9000; ClickHouseConnection clickHouseConnection = new ClickHouseConnection(set); clickHouseConnection.Open(); using (var connection = new SQLiteConnection($"Data Source={dbfilename};Pooling=True")) { connection.Open(); var northdb = new Northwind(connection); northdb.DoReload(clickHouseConnection); foreach (var emp in northdb.EmployeesList) { Console.WriteLine($"{emp.EmployeeID} {emp.Country} {emp.Title}"); } connection.Close(); } } } }
var group__group__cryptolite__sha__data__structures = [ [ "cy_stc_cryptolite_sha_desc_t", "structcy__stc__cryptolite__sha__desc__t.html", null ], [ "cy_stc_cryptolite_sha_context_t", "structcy__stc__cryptolite__sha__context__t.html", null ] ];
// Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package apm_test import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.elastic.co/apm" "go.elastic.co/apm/model" "go.elastic.co/apm/transport/transporttest" ) func TestStartTransactionTraceContextOptions(t *testing.T) { testStartTransactionTraceContextOptions(t, false) testStartTransactionTraceContextOptions(t, true) } func testStartTransactionTraceContextOptions(t *testing.T, recorded bool) { tracer, _ := transporttest.NewRecorderTracer() defer tracer.Close() tracer.SetSampler(samplerFunc(func(apm.TraceContext) bool { panic("nope") })) opts := apm.TransactionOptions{ TraceContext: apm.TraceContext{ Trace: apm.TraceID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, Span: apm.SpanID{0, 1, 2, 3, 4, 5, 6, 7}, }, } opts.TraceContext.Options = opts.TraceContext.Options.WithRecorded(recorded) tx := tracer.StartTransactionOptions("name", "type", opts) result := tx.TraceContext() assert.Equal(t, recorded, result.Options.Recorded()) tx.Discard() } func TestStartTransactionInvalidTraceContext(t *testing.T) { startTransactionInvalidTraceContext(t, apm.TraceContext{ // Trace is all zeroes, which is invalid. Span: apm.SpanID{0, 1, 2, 3, 4, 5, 6, 7}, }) } func startTransactionInvalidTraceContext(t *testing.T, traceContext apm.TraceContext) { tracer, _ := transporttest.NewRecorderTracer() defer tracer.Close() var samplerCalled bool tracer.SetSampler(samplerFunc(func(apm.TraceContext) bool { samplerCalled = true return true })) opts := apm.TransactionOptions{TraceContext: traceContext} tx := tracer.StartTransactionOptions("name", "type", opts) assert.True(t, samplerCalled) tx.Discard() } func TestStartTransactionTraceParentSpanIDSpecified(t *testing.T) { startTransactionIDSpecified(t, apm.TraceContext{ Trace: apm.TraceID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, Span: apm.SpanID{0, 1, 2, 3, 4, 5, 6, 7}, }) } func TestStartTransactionTraceIDSpecified(t *testing.T) { startTransactionIDSpecified(t, apm.TraceContext{ Trace: apm.TraceID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, }) } func TestStartTransactionIDSpecified(t *testing.T) { startTransactionIDSpecified(t, apm.TraceContext{}) } func startTransactionIDSpecified(t *testing.T, traceContext apm.TraceContext) { tracer, _ := transporttest.NewRecorderTracer() defer tracer.Close() opts := apm.TransactionOptions{ TraceContext: traceContext, TransactionID: apm.SpanID{0, 1, 2, 3, 4, 5, 6, 7}, } tx := tracer.StartTransactionOptions("name", "type", opts) assert.Equal(t, opts.TransactionID, tx.TraceContext().Span) tx.Discard() } func TestTransactionEnsureParent(t *testing.T) { tracer, transport := transporttest.NewRecorderTracer() defer tracer.Close() tx := tracer.StartTransaction("name", "type") traceContext := tx.TraceContext() parentSpan := tx.EnsureParent() assert.NotZero(t, parentSpan) assert.NotEqual(t, traceContext.Span, parentSpan) // EnsureParent is idempotent. parentSpan2 := tx.EnsureParent() assert.Equal(t, parentSpan, parentSpan2) tx.End() // For an ended transaction, EnsureParent will return a zero value // even if the transaction had a parent at the time it was ended. parentSpan3 := tx.EnsureParent() assert.Zero(t, parentSpan3) tracer.Flush(nil) payloads := transport.Payloads() require.Len(t, payloads.Transactions, 1) assert.Equal(t, model.SpanID(parentSpan), payloads.Transactions[0].ParentID) } type samplerFunc func(apm.TraceContext) bool func (f samplerFunc) Sample(t apm.TraceContext) bool { return f(t) }
import pandas import random from tkinter import * BACKGROUND_COLOR = "#B1DDC6" def get_word(): """ Gets a random word from the word list and updates the card to show the details""" global timer, word_data window.after_cancel(timer) word_data = random.choice(word_list) canvas.itemconfig(card_bg, image=fcard_img) canvas.itemconfig(title_text, text="Spanish", fill="black") canvas.itemconfig(word_text, text=word_data["Spanish"], fill="black") timer = window.after(3000, show_translation, word_data["English"]) def show_translation(word): """ Flip the flashcard over and show the word in English """ canvas.itemconfig(card_bg, image=bcard_img) canvas.itemconfig(title_text, text="English", fill="white") canvas.itemconfig(word_text, text=word, fill="white") def knows_word(): """ Remove the word from the word list """ word_list.remove(word_data) data_frame = pandas.DataFrame(word_list) data_frame.to_csv("./data/words_to_learn.csv", index=False) get_word() # Import language data try: practice_data = pandas.read_csv("./data/words_to_learn.csv") except FileNotFoundError: csv_data = pandas.read_csv("./data/spanish_words.csv") word_list = csv_data.to_dict(orient="records") else: word_list = practice_data.to_dict(orient="records") word_data = {} # UI Setup window = Tk() window.title("Spanish Flashcards") fcard_img = PhotoImage(file="./images/card_front.png") bcard_img = PhotoImage(file="./images/card_back.png") green_button = PhotoImage(file="./images/right.png") red_button = PhotoImage(file="./images/wrong.png") window.config(padx=50, pady=50, bg=BACKGROUND_COLOR) window.resizable(False, False) # Flashcard canvas = Canvas(width=800, height=526, bg=BACKGROUND_COLOR, highlightthickness=0) card_bg = canvas.create_image(400, 263, image=fcard_img) title_text = canvas.create_text(400, 150, text="", font=("Arial", 40, "italic")) word_text = canvas.create_text(400, 263, text="", font=("Arial", 60, "bold")) canvas.grid(row=0, column=0, columnspan=2) # Buttons wrong_button = Button(image=red_button, relief="flat", highlightthickness=0, bd=0, command=get_word) wrong_button.grid(row=1, column=0) right_button = Button(image=green_button, relief="flat", highlightthickness=0, bd=0, command=knows_word) right_button.grid(row=1, column=1) # Start the game timer = window.after(100, get_word) window.mainloop()
# Pathos API Documentation for `SystemError` ```swift public enum SystemError ``` An error returned by the OS. ### Conforms to * Equatable * Error ### Nested type aliases ```swift public typealias Code ``` On macOS and Linux, it is aliased to `Int32`. On Windows, it is `UInt32`. ### Initializers ```swift public init(code: Code) ``` ### Enumeration cases ```swift case unspecified(errorCode: Code) ``` Unspecified error returned by the OS.
import React, {useState} from 'react' import Long from 'long' import IconButton from '@material-ui/core/IconButton' import { Button } from '@material-ui/core' import { IndexingService } from 'moneystream-wallet' import { PopupProps } from '../types' import { WalletBalance } from './WalletBalance' export const SendWallet = (props: PopupProps) => { const [walletBalance, setWalletBalance] = useState(props.context.wallet?.balance) const [amount, setAmount] = useState(0) const [address, setAddress] = useState('') const { context: { moneystreamDomain, runtime: { tabOpener }, wallet } } = props async function walletRefresh() { await wallet?.loadUnspent() await setWalletBalance(wallet?.balance) //TODO: update background wallet } async function walletSend(addr:string, amt:number) { if (!amt || amt ===0 || !addr) return // reduce amt by mining fee const buildResult = await wallet?.makeSimpleSpend( Long.fromNumber(amt-300), wallet?.selectedUtxos, addr ) const api = new IndexingService() const broadcastResult = await api.broadcastRaw(buildResult.hex) alert(JSON.stringify(broadcastResult)) await walletRefresh() // if sucess then clear the form if (broadcastResult && broadcastResult.toString().length === 64) { setAddress('') setAmount(0) } } const changeAddress = (event:any) => { console.log(event) setAddress(event.target.value) } const changeAmount = (event:any) => { console.log(event) setAmount(event.target.value) } const changeSendAll = (event:any) => { console.log(event) if (event.target.value) { setAmount(wallet?.balance||0) } } return ( <div> <div> <WalletBalance context={props.context} /> </div> <div> <input type="checkbox" onChange={changeSendAll}></input> <label>Send All?</label> </div> <div> <div> <label>Enter BSV address</label> </div> <input type="text" value={address} onChange={changeAddress}></input> </div> <div> <div> <label>Enter Amount</label> </div> <input type="number" value={amount} onChange={changeAmount}></input> </div> <div> <Button onClick={() => walletSend(address,amount)} size="medium" color="primary" aria-label="Send"> Send </Button> </div> </div> ) }
using System; using Amazon.DynamoDb.Models; namespace Amazon.DynamoDb; public sealed class UpdateTimeToLiveRequest { public UpdateTimeToLiveRequest(string tableName, string attributeName, bool enabled) { ArgumentNullException.ThrowIfNull(tableName); TableName = tableName; TimeToLiveSpecification = new TimeToLiveSpecification(attributeName, enabled); } public string TableName { get; } public TimeToLiveSpecification TimeToLiveSpecification { get; } }
// Copyright (C) 2021 Reece H. Dunn. SPDX-License-Identifier: Apache-2.0 package opennlp.ext.tests.token import opennlp.ext.token.Token import opennlp.ext.token.tokenize import opennlp.tools.util.Span import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test @DisplayName("Tokens") class TokenTest { @Test @DisplayName("empty") fun empty() { val text = "" val spans = arrayOf<Span>() val tokens = text.tokenize(spans) assertThat(tokens.size, `is`(0)) } @Test @DisplayName("one") fun one() { val text = "abc" val spans = arrayOf(Span(0, 3)) val tokens = text.tokenize(spans) assertThat(tokens[0], `is`(Token(0, null, text, Span(0, 3)))) assertThat(tokens.size, `is`(1)) assertThat(tokens[0].text, `is`("abc")) } @Test @DisplayName("two") fun two() { val text = "abcdefg" val spans = arrayOf(Span(0, 3), Span(4, 7)) val tokens = text.tokenize(spans) assertThat(tokens[0], `is`(Token(0, null, text, Span(0, 3)))) assertThat(tokens[1], `is`(Token(1, "d", text, Span(4, 7)))) assertThat(tokens.size, `is`(2)) assertThat(tokens[0].text, `is`("abc")) assertThat(tokens[1].text, `is`("efg")) } @Test @DisplayName("multiple") fun multiple() { val text = "abcdefghijk" val spans = arrayOf(Span(0, 3), Span(4, 7), Span(8, 11)) val tokens = text.tokenize(spans) assertThat(tokens[0], `is`(Token(0, null, text, Span(0, 3)))) assertThat(tokens[1], `is`(Token(1, "d", text, Span(4, 7)))) assertThat(tokens[2], `is`(Token(2, "h", text, Span(8, 11)))) assertThat(tokens.size, `is`(3)) assertThat(tokens[0].text, `is`("abc")) assertThat(tokens[1].text, `is`("efg")) assertThat(tokens[2].text, `is`("ijk")) } }
=head1 NAME PPIx::Regexp::Node::Range - Represent a character range in a character class =head1 SYNOPSIS use PPIx::Regexp::Dumper; PPIx::Regexp::Dumper->new( 'qr{[a-z]}smx' ) ->print(); =head1 INHERITANCE C<PPIx::Regexp::Node::Range> is a L<PPIx::Regexp::Node|PPIx::Regexp::Node>. C<PPIx::Regexp::Node::Range> has no descendants. =head1 DESCRIPTION This class represents a character range in a character class. It is a node rather than a structure because there are no delimiters. The content is simply the two literals with the '-' operator between them. =head1 METHODS This class provides no public methods beyond those provided by its superclass. =cut package PPIx::Regexp::Node::Range; use strict; use warnings; use base qw{ PPIx::Regexp::Node }; use PPIx::Regexp::Constant qw{ MSG_PROHIBITED_BY_STRICT }; our $VERSION = '0.053'; sub explain { my ( $self ) = @_; my $first = $self->schild( 0 ) or return $self->__no_explanation(); my $last = $self->schild( -1 ) or return $self->__no_explanation(); return sprintf q<Characters between '%s' and '%s' inclusive>, $first->content(), $last->content(); } sub __PPIX_LEXER__finalize { my ( $self, $lexer ) = @_; my $rslt = $self->SUPER::__PPIX_LEXER__finalize( $lexer ); if ( $lexer->strict() ) { # If strict is in effect, we're an error unless both ends of the # range are portable. my @kids = $self->schildren(); delete $self->{_range_start}; # Context for compatibility. foreach my $inx ( 0, -1 ) { my $kid = $kids[$inx]; # If we're not a literal, we can not make the test, so we # blindly accept it. $kid->isa( 'PPIx::Regexp::Token::Literal' ) or next; my $content = $kid->content(); $content =~ m/ \A (?: [[:alnum:]] | \\N\{ .* \} ) \z /smx and $self->_range_ends_compatible( $content ) or return $self->_prohibited_by_strict( $rslt ); } } return $rslt; } sub _prohibited_by_strict { my ( $self, $rslt ) = @_; delete $self->{_range_start}; $rslt += $self->__error( join( ' ', 'Non-portable range ends', MSG_PROHIBITED_BY_STRICT ), perl_version_introduced => '5.023008', ); return $rslt; } sub _range_ends_compatible { my ( $self, $content ) = @_; if ( defined( my $start = $self->{_range_start} ) ) { foreach my $re ( qr{ \A [[:upper:]] \z }smx, qr{ \A [[:lower:]] \z }smx, qr{ \A [0-9] \z }smx, qr{ \A \\N \{ .* \} }smx, ) { $start =~ $re or next; return $content =~ $re; } return; } else { $self->{_range_start} = $content; return 1; } } 1; __END__ =head1 SUPPORT Support is by the author. Please file bug reports at L<http://rt.cpan.org>, or in electronic mail to the author. =head1 AUTHOR Thomas R. Wyant, III F<wyant at cpan dot org> =head1 COPYRIGHT AND LICENSE Copyright (C) 2009-2017 by Thomas R. Wyant, III This program is free software; you can redistribute it and/or modify it under the same terms as Perl 5.10.0. For more details, see the full text of the licenses in the directory LICENSES. This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. =cut # ex: set textwidth=72 :
--- title: Building instant features with advanced Plone themes date: "2017-10-23T06:00:00Z" tags: ["chameleon", "plone", "requirejs", "templating", "theming"] --- Plone, "[The Ultimate Enterprise CMS](https://plone.com/)", ships with built-in batteries for building sophisticated content management solutions without writing a single line of new Python code. For example, a fresh installation of Plone allows to build custom structured content types with custom HTML views, define custom state based workflows, customize various user interface elements, and finish the user experience by configuring custom event triggered content rules to react on users\' actions. Not to mention the Diazo based theming tool, which allows unlimited tweaking of the resulting HTML. **All this by just clicking and typing things through-the-web (TTW) with your browser.** Yet, still some say that Plone is a difficult to customize and extend. The flip side of customizing Plone TTW is that it\'s way too easy to lost track of your customizations. That adds to technical debt and therefore cost of maintaining those customizations over years and upgrades to future Plone releases. The suggested solution to avoid those problems has long been to avoid TTW customizations altogether, in favor of customizing everything using "buildout-installed file-system Python packages". But that makes customizing Plone feel unnecessary difficult and technical. At [Plone Conference 2017](https://2017.ploneconf.org/) [I gave a talk](https://github.com/datakurre/ploneconf2017), where I showed an alternative way for this: if it was possible to bundle all those customizations together, for example in TTW managed theme, maintaining those customizations would no longer be the blocker. Customizing Plone could be made easy again. Requirements ------------ Technically, Plone has supported exporting and importing most of the possible TTW customizations for more than ten years, but the user interface for that has been cumbersomely technical. Finally, Plone 4.1 introduced a new [Diazo](http://docs.diazo.org/) based theming feature with easy to use theming control panel and theme editor. And now, with only a couple of extra packages in your Plone setup, Plone theming features get super powers to apply site customizations with any theme. To complete the following example, you need a Plone site with these two extra Python packages installed: [collective.themesitesetup](https://pypi.python.org/pypi/collective.themesitesetup) and [collective.themefragments](https://pypi.python.org/pypi/collective.themefragments). As usual, those can be installed by customizing and running buildout ```properties [instance] eggs = ... collective.themesitesetup collective.themefragments ``` or you can try out with the official Plone docker image: ```bash $ docker run -p 8080:8080 -e PLONE_ADDONS="collective.themesitesetup collective.themefragments" plone fg ``` Case of the day: Wall of images ------------------------------- As an example feature, we build a simple folder view that displays a list of varying size images in an optimal grid layout using popular [Masonry.js](https://masonry.desandro.com/) layout library, with help an another library called [imagesLoaded](https://imagesloaded.desandro.com/). To summarize, building that view requires: - Providing JS bundles for both Masonry and imagesLoaded - Registering those bundles into Plone resource registry - A folder view template that renders images in that folder - Way to configure that view on a folder - JS code to initialize Masonry layout on that view ![image](three-columns.png) Getting started with theming ---------------------------- To get a fast start, we create a dummy theme base named `demotheme` that simply re-uses styles and rules from Barceloneta, the default theme of Plone 5. Your theme base should contain the following files: - `./index.html` - `./rules.xml` - `./scripts.js` - `./styles.css` - `./manifest.cfg` At first, `./index.html` is just a copy of the same theme file from Barceloneta: ```html <!doctype html> <html> <head> <title>Plone Theme</title> <link rel="shortcut icon" type="image/x-icon" href="++theme++barceloneta/barceloneta-favicon.ico" /> <link rel="apple-touch-icon" href="++theme++barceloneta/barceloneta-apple-touch-icon.png" /> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="++theme++barceloneta/barceloneta-apple-touch-icon-144x144-precomposed.png" /> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="++theme++barceloneta/barceloneta-apple-touch-icon-114x114-precomposed.png" /> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="++theme++barceloneta/barceloneta-apple-touch-icon-72x72-precomposed.png" /> <link rel="apple-touch-icon-precomposed" sizes="57x57" href="++theme++barceloneta/barceloneta-apple-touch-icon-57x57-precomposed.png" /> <link rel="apple-touch-icon-precomposed" href="++theme++barceloneta/barceloneta-apple-touch-icon-precomposed.png" /> </head> <body> <section id="portal-toolbar"> </section> <div class="outer-wrapper"> <header id="content-header"> <div class="container"> <header id="portal-top"> </header> <div id="anonymous-actions"> </div> </div> </header> <div id="mainnavigation-wrapper"> <div id="mainnavigation"> </div> </div> <div id="hero" class="principal"> <div class="container"> <div class="gigantic"> </div> </div> </div> <div id="above-content-wrapper"> <div id="above-content"> </div> </div> <div class="container"> <div class="row"> <aside id="global_statusmessage"></aside> </div> <main id="main-container" class="row row-offcanvas row-offcanvas-right"> <div id="column1-container"> </div> <div id="content-container"> </div> <div id="column2-container"> </div> </main><!--/row--> </div><!--/container--> </div> <!--/outer-wrapper --> <footer id="portal-footer-wrapper"> <div class="container" id="portal-footer"></div> </footer> </body> </html> ``` Then, `./rules.xml` does nothing more than includes the existing rules directly from the always available Barceloneta theme: ```xml <?xml version="1.0" encoding="UTF-8"?> <rules xmlns="http://namespaces.plone.org/diazo" xmlns:css="http://namespaces.plone.org/diazo/css" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xi="http://www.w3.org/2001/XInclude"> <!-- Import Barceloneta rules --> <xi:include href="++theme++barceloneta/rules.xml" /> </rules> ``` File `./scripts.js` starts empty and file `./styles.css` with the following content to reuse styles from Barceloneta theme: ```css @import "../++theme++barceloneta/less/barceloneta-compiled.css"; .plone-breadcrumb ol { padding: 18px 0; font-size: 14px; } ``` They both should be registered as the implicit "theme bundle" (or "Diazo-bundle") in `./manifest.cfg` by setting `production-css` and `production-js` attributes as follows: ```properties [theme] title = Demo Theme description = production-css = /++theme++demotheme/styles.css production-js = /++theme++demotheme/scripts.js ``` Saving these files and enabling the theme should already give the basic Barceloneta experience. But let\'s continue to extend it with our special feature\... Registering Masonry.js bundles ------------------------------ Plone 5 resource registry supports many ways to configure new front end resources. We go with the easy way by simply downloading the 3rd party JS distributions and registering them mostly as such for Plone with the following steps: 1. Create folder `./bundles` into theme to keep the required front-end bundles separate from the other theme files 2. Download [the official minified Masonry.js distribution](https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js) and save it as `./bundles/masonry.pkgd.min.js` 3. Download [the official minified imagesLoaded distribution](https://unpkg.com/imagesloaded@4/imagesloaded.pkgd.min.js) and save it as `./bundles/imagesloaded.pkgd.min.js` 4. Edit both of the previous files by adding line ```js (function() { var require, define; ``` into the beginning of the file, and line ```js })(); ``` into the end of the file. These are required for any "AMD packaged" JS distribution to work in Plone\'s Require.js based JS environment. 5. Add two empty files `./bundles/masonry.pkgd.min.css` and `./bundles/imagesloaded.pkgd.min.css` for pleasing the Plone resource registry in the next step. 6. Create folder `./install` with file `./install/registry.xml` with the following contents to register the above bundles into Plone resource registry: ```xml <?xml version="1.0"?> <registry> <records prefix="plone.bundles/imagesloaded-js" interface="Products.CMFPlone.interfaces.IBundleRegistry"> <value key="depends">plone</value> <value key="jscompilation">++theme++demotheme/bundles/imagesloaded.pkgd.min.js</value> <value key="csscompilation">++theme++demotheme/bundles/imagesloaded.pkgd.min.css</value> <value key="last_compilation">2017-10-06 00:00:00</value> <value key="compile">False</value> <value key="enabled">True</value> </records> <records prefix="plone.bundles/masonry-js" interface="Products.CMFPlone.interfaces.IBundleRegistry"> <value key="depends">imagesloaded-js</value> <value key="jscompilation">++theme++demotheme/bundles/masonry.pkgd.min.js</value> <value key="csscompilation">++theme++demotheme/bundles/masonry.pkgd.min.css</value> <value key="last_compilation">2017-10-06 00:00:00</value> <value key="compile">False</value> <value key="enabled">True</value> </records> </registry> ``` Now, once edited theme files are saved and the theme re-activated or updated, thanks to **collective.themesitesetup**, every response from our site should include our these new resources. Creating a folder view with list of images ------------------------------------------ Creating a view with **collective.themefragments** is similar for writing any view template for Plone. Simply add a folder `./fragments` into your theme with our example view `./fragments/wall_of_images.pt` with the following contents: ```html <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:tal="http://xml.zope.org/namespaces/tal" xmlns:metal="http://xml.zope.org/namespaces/metal" xmlns:i18n="http://xml.zope.org/namespaces/i18n" lang="en" metal:use-macro="context/main_template/macros/master" i18n:domain="plone"> <body> <metal:main fill-slot="main"> <metal:content-core define-macro="content-core"> <div class="wall-of-images container-fluid" tal:define="items context/@@contentlisting"> <tal:image tal:repeat="item items"> <img tal:define="obj item/getObject; scale_func obj/@@images; scaled_image python:scale_func.scale('image', scale='preview')" tal:replace="structure python:scaled_image.tag()" tal:on-error="string:error" /> </tal:image> </div> </metal:content-core> </metal:main> </body> </html> ``` Please, note, how the view template uses [plone.app.contentlisting](https://pypi.python.org/pypi/plone.app.contentlisting) API for iterating through every item in the folder and then [plone.app.imaging](https://pypi.python.org/pypi/plone.app.imaging) API for rendering image tags for scaled images. Also, note the use of `tal:on-error` to suppress all possible error messages (you may not always want that, though). Enabling the view on a site --------------------------- Unfortunately, **collective.themefragments**\' views do not magically appear into Plone toolbar display menu yet. Fortunately, those views can be either be set as the default view of a content type or manually assigned to a content item by setting its `layout`-property: 1. At first, let\'s assume that we have a folder `http://localhost:8080/Plone/wall-of-images` 2. Then, let\'s open the good old properties edit form for it `http://localhost:8080/Plone/wall-of-images/manage_propertiesForm` 3. Finally, let\'s add a new property of type `string` with name `layout` and value `++themefragment++wall_of_images` Now the content should be rendered using our brand new template, displaying all the images one after one. It still does not look as intended, though, because nothing enables Masonry.js for it. Invoking Masonry.js on the view ------------------------------- To enable Masonry.js on our brand new view, we could add the following code into a theme file `./scripts.js`: ```js jQuery(function($) { $('.wall-of-images').imagesLoaded(function() { $('.wall-of-images').masonry({ itemSelector: 'img', percentPosition: true }); }); }); ``` That code simply uses jQuery to find our view templates main element and configures Masonry.js for it after every image below it has been loaded. An alternative for that jQuery script would be to rely on Plone\'s Require.js setup and define the code as a pattern: ```js require([ 'pat-base' ], function(Base) { 'use strict'; var Masonry = Base.extend({ name: 'masonry', trigger: '.wall-of-images', init: function() { var self = this; self.$el.imagesLoaded(function() { self.$el.masonry({ itemSelector: 'img', percentPosition: true }); }); } }); return Masonry; }); ``` But something is still missing. Masonry.js is distributed without any default styles. To make our wall of images look as it should, we need to define responsive styles with our desired breakpoints in `./styles.css`: ```css @media only screen { .wall-of-images { padding-left: 0; padding-right: 0; margin-top: -20px; } .wall-of-images img { float: left; width: 100%; height: auto; border: 5px solid transparent; } } @media only screen and (min-width: 768px) { .wall-of-images img { float: left; width: 50%; height: auto; } } @media screen and (min-width: 900px) { .wall-of-images img { float: left; width: 33.3333333%; height: auto; } } @media screen and (min-width: 1200px) { .wall-of-images img { float: left; width: 25%; height: auto; } } ``` Finally, we\'d like to make our wall of images be displayed on full browser window width. That\'s a bit tricky, because we need to escape Barceloneta theme\'s default content container, but still fully possible by adding the following Diazo rules into `./rules.xml`: ```xml <!-- Wall of Images --> <rules css:if-content=".wall-of-images"> <!-- Make fullwidth --> <replace css:theme=".outer-wrapper > .container" css:content=".wall-of-images" /> <!-- Include status message --> <before css:theme=".outer-wrapper > .container" css:content="#global_statusmessage" css:if-content=".wall-of-images" /> <replace css:content="#global_statusmessage"> <div id="global_statusmessage" class="container-fluid"> <xsl:apply-templates /> </div> </replace> </rules> ``` Now our wall of images shines in every resolution: ![image](four-columns.png) ![image](three-columns.png) ![image](two-columns.png) ![image](one-column.png) PS. If want to learn more, my [talk materials](https://github.com/datakurre/ploneconf2017) include a more complex example with custom content types, workflows, permissions, portlet assignments and content rules.
/* Copyright(c) 2013 Andrew Fray Licensed under the MIT license. See the license.txt file for full details. */ using System; using System.Collections.Generic; using System.Linq; namespace UnTest { public static class Assert { public static void IsTrue(bool condition) { if (condition == false) { throw new Exception("Assert failed"); } } public static void IsFalse(bool condition) { if (condition) { throw new Exception("Assert.IsFalse failed"); } } public static void IsEqual(object lhs, object rhs) { if (lhs == null) { if (rhs != null) { throw new Exception("Fail: NULL != " + rhs); } } else if (lhs.Equals(rhs) == false) { throw new Exception("Fail: " + lhs + " != " + rhs); } } public static void ThatThrowsException(Action lambda, Type exceptionType) { bool isThrown = false; try { lambda(); } catch(Exception e) { isThrown = e.GetType() == exceptionType; } finally { if (isThrown == false) { throw new Exception("Did not get exception of type " + exceptionType.ToString()); } } } public static void IsEqualSequence<T>(IEnumerable<T> lhs, IEnumerable<T> rhs) { if (lhs == null) { if (rhs == null) { return; } } else if (lhs.SequenceEqual(rhs)) { return; } var lhsEnumerator = lhs == null ? null : lhs.GetEnumerator(); var rhsEnumerator = rhs == null ? null : rhs.GetEnumerator(); var comp = new System.Text.StringBuilder(); comp.Append("Sequences not equal\n"); comp.AppendFormat("{0} elements in left-hand side, {1} elements in right\n", (lhs == null ? -1 : lhs.Count()), (rhs == null ? -1 : rhs.Count())); comp.Append("LHS | RHS\n"); do { if (lhsEnumerator != null && lhsEnumerator.MoveNext() == false) { lhsEnumerator = null; } if (rhsEnumerator != null && rhsEnumerator.MoveNext() == false) { rhsEnumerator = null; } var lhsValue = lhsEnumerator == null ? " " : lhsEnumerator.Current.ToString(); var rhsValue = rhsEnumerator == null ? " " : rhsEnumerator.Current.ToString(); comp.AppendFormat("{0} | {1}\n", lhsValue, rhsValue); } while(lhsEnumerator != null || rhsEnumerator != null); throw new Exception(comp.ToString()); } public static void IsEmptySequence<T>(IEnumerable<T> seq) { if (seq != null && seq.Any() == false) { return; } var comp = new System.Text.StringBuilder(); comp.AppendFormat("Assert.IsEmptySequence<{0}>() failed\n", typeof(T)); if (seq == null) { comp.Append("(null sequence)\n"); } else { int index = 0; foreach(var val in seq) { comp.AppendFormat("{0}: {1}", index, val); ++index; } } throw new Exception("sequence was not empty:\n"); } } }
// Automatically generated - do not modify! package typescript external interface GetCompletionsAtPositionOptions : UserPreferences { /** * If the editor is asking for completions because a certain character was typed * (as opposed to when the user explicitly requested them) this should be set. */ var triggerCharacter: CompletionsTriggerCharacter? var triggerKind: CompletionTriggerKind? /** @deprecated Use includeCompletionsForModuleExports */ var includeExternalModuleExports: Boolean? /** @deprecated Use includeCompletionsWithInsertText */ var includeInsertTextCompletions: Boolean? }
import Discord from 'discord.js'; import { exit } from 'process'; import commands from './commands' const prefix = process.env.DISCORD_PREFIX || '!'; const client = new Discord.Client(); client.once('ready', () => { console.log('ready!'); }); client.on('message', message => { if (!message.content.startsWith(prefix) || message.author.bot) return; try { const args = message.content.slice(prefix.length).trim().split(/ +/); const commandName = args.shift()?.toLowerCase(); if (!commandName) return; const command = commands.get(commandName); if(!command) return; console.log(command); command.execute(message); } catch (e) { message.channel.send(`Error: ${e}`); } }); const discordToken = process.env.DISCORD_TOKEN; if(!discordToken) { console.error('Discord token missing'); exit(1); } client.login(discordToken);
package org.cloudfoundry.credhub.controllers.v1.management import org.assertj.core.api.Assertions.assertThat import org.cloudfoundry.credhub.helpers.CredHubRestDocs import org.cloudfoundry.credhub.helpers.MockMvcFactory import org.cloudfoundry.credhub.helpers.credHubAuthHeader import org.cloudfoundry.credhub.management.ManagementController import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.skyscreamer.jsonassert.JSONAssert import org.springframework.http.MediaType import org.springframework.restdocs.JUnitRestDocumentation import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post import org.springframework.restdocs.payload.JsonFieldType import org.springframework.restdocs.payload.PayloadDocumentation import org.springframework.restdocs.payload.PayloadDocumentation.requestFields import org.springframework.test.context.junit4.SpringRunner import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.result.MockMvcResultMatchers @RunWith(SpringRunner::class) class ManagementControllerTest { @Rule @JvmField val restDocumentation = JUnitRestDocumentation() lateinit var mockMvc: MockMvc lateinit var spyManagementService: SpyManagementService @Before fun setUp() { spyManagementService = SpyManagementService() val managementController = ManagementController(spyManagementService) mockMvc = MockMvcFactory.newSpringRestDocMockMvc(managementController, restDocumentation) } @Test fun GET__management_mode__returns_result() { spyManagementService.isReadOnlyMode__returns_boolean = false val mvcResult = mockMvc.perform( get(ManagementController.ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .credHubAuthHeader() ) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andDo( MockMvcRestDocumentation.document( CredHubRestDocs.DOCUMENT_IDENTIFIER ) ).andReturn() val expectedResponseBody = """ { "read_only_mode": false } """.trimIndent() val actualResponseBody = mvcResult.response.contentAsString JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, true) } @Test fun POST__management_mode__returns_result() { val mvcResult = mockMvc.perform( post(ManagementController.ENDPOINT) .contentType(MediaType.APPLICATION_JSON) .credHubAuthHeader() .content( """ { "read_only_mode": true } """.trimIndent() ) ) .andExpect(MockMvcResultMatchers.status().isOk) .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andDo( MockMvcRestDocumentation.document( CredHubRestDocs.DOCUMENT_IDENTIFIER, requestFields( PayloadDocumentation.fieldWithPath("read_only_mode") .description("Enables / disables read only mode for the entire API.") .type(JsonFieldType.BOOLEAN) ) ) ).andReturn() assertThat(spyManagementService.toggleReadOnlyMode__calledWith_shouldUseReadOnlyMode).isEqualTo(true) val expectedResponseBody = """ { "read_only_mode": true } """.trimIndent() val actualResponseBody = mvcResult.response.contentAsString JSONAssert.assertEquals(expectedResponseBody, actualResponseBody, true) } }
using Kirinji.LightWands; using Kirinji.LinqToObservableCollection.Support; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kirinji.LinqToObservableCollection.Impl { sealed class Moved<T> : IMoved<T> { public Moved(IReadOnlyList<T> items, int oldStartingIndex, int newStartingIndex) { Contract.Requires<ArgumentNullException>(items != null); Contract.Requires<ArgumentOutOfRangeException>(newStartingIndex >= 0); this.Items = items; this.oldStartingIndex = oldStartingIndex; this.newStartingIndex = newStartingIndex; } public IReadOnlyList<T> Items { get; private set; } // 不明な場合は -1 を返す readonly int oldStartingIndex; public int OldStartingIndex { get { return oldStartingIndex; } } readonly int newStartingIndex; public int NewStartingIndex { get { return newStartingIndex; } } public override string ToString() { return NotifyCollectionChangedEventAction.Move.ToString() + " (index: " + OldStartingIndex + " -> " + NewStartingIndex + ", items: " + Converters.ListToString(Items, 3) + ")"; } } }
#!/bin/bash source activate dema src_lang="en" tgt_lang="de" load_path="../saved_exps/${tgt_lang}" data_path="../data" CUDA_VISIBLE_DEVICES=2 OMP_NUM_THREADS=4 python -u ../evaluation/export_embs.py \ --src_lang ${src_lang} \ --tgt_lang ${tgt_lang} \ --s2t_map_path ${load_path}/best_s2t_params.bin \ --t2s_map_path ${load_path}/best_t2s_params.bin \ --src_emb_path $data_path/fasttext/wiki.${src_lang}.bin \ --tgt_emb_path $data_path/fasttext/wiki.${tgt_lang}.bin \ --vocab_size 50000
require "httparty" require "open-uri" require "redis" require "sequel" require_relative "../lib/fiber_scheduler" DB = Sequel.postgres Sequel.extension(:fiber_concurrency) FiberScheduler do Fiber.schedule do URI.open("https://httpbin.org/delay/2") end Fiber.schedule do HTTParty.get("https://httpbin.org/delay/2") end Fiber.schedule do Redis.new.blpop("abc123", 2) end Fiber.schedule do DB.run("SELECT pg_sleep(2)") end Fiber.schedule do sleep 2 end Fiber.schedule do `sleep 2` end end
package typingsSlinky.googleVisualization.google.visualization import typingsSlinky.googleVisualization.anon.CellColor import typingsSlinky.googleVisualization.anon.Colors import typingsSlinky.googleVisualization.anon.IsHtml import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait CalendarOptions extends StObject { var calendar: CellColor = js.native var colorAxis: js.UndefOr[Colors] = js.native var forceIFrame: js.UndefOr[Boolean] = js.native var height: js.UndefOr[Double] = js.native var noDataPattern: js.UndefOr[js.Object] = js.native var tooltip: IsHtml = js.native var width: js.UndefOr[Double] = js.native } object CalendarOptions { @scala.inline def apply(calendar: CellColor, tooltip: IsHtml): CalendarOptions = { val __obj = js.Dynamic.literal(calendar = calendar.asInstanceOf[js.Any], tooltip = tooltip.asInstanceOf[js.Any]) __obj.asInstanceOf[CalendarOptions] } @scala.inline implicit class CalendarOptionsMutableBuilder[Self <: CalendarOptions] (val x: Self) extends AnyVal { @scala.inline def setCalendar(value: CellColor): Self = StObject.set(x, "calendar", value.asInstanceOf[js.Any]) @scala.inline def setColorAxis(value: Colors): Self = StObject.set(x, "colorAxis", value.asInstanceOf[js.Any]) @scala.inline def setColorAxisUndefined: Self = StObject.set(x, "colorAxis", js.undefined) @scala.inline def setForceIFrame(value: Boolean): Self = StObject.set(x, "forceIFrame", value.asInstanceOf[js.Any]) @scala.inline def setForceIFrameUndefined: Self = StObject.set(x, "forceIFrame", js.undefined) @scala.inline def setHeight(value: Double): Self = StObject.set(x, "height", value.asInstanceOf[js.Any]) @scala.inline def setHeightUndefined: Self = StObject.set(x, "height", js.undefined) @scala.inline def setNoDataPattern(value: js.Object): Self = StObject.set(x, "noDataPattern", value.asInstanceOf[js.Any]) @scala.inline def setNoDataPatternUndefined: Self = StObject.set(x, "noDataPattern", js.undefined) @scala.inline def setTooltip(value: IsHtml): Self = StObject.set(x, "tooltip", value.asInstanceOf[js.Any]) @scala.inline def setWidth(value: Double): Self = StObject.set(x, "width", value.asInstanceOf[js.Any]) @scala.inline def setWidthUndefined: Self = StObject.set(x, "width", js.undefined) } }
require 'spec_helper' describe Lab42::Stream do context 'lazy_take_while (until)' do context "empty" do it 'is empty for empty' do expect( empty_stream.lazy_take_while :true ).to be_empty end end # context "empty" context "finite" do let(:three){1..3} subject do finite_stream three end it "can take one" do one = subject.lazy_take_while :<, 2 expect( one.head ).to eq 1 expect( one.tail ).to be_empty end it "can take more" do many = subject.lazy_take_while ->(a){ a < 42 } expect( many.entries ).to eq [*three] end end # context "finite" context "infinite" do subject do iterate 0, :succ end it 'can take many (while)' do many = subject.drop(10).lazy_take_while{ |n| n < 35 } expect( many.entries ).to eq([*10..34]) end it 'can take many (until)' do many = subject.drop(10).lazy_take_until{ |n| n > 34} expect( many.entries ).to eq([*10..34]) end end # context "infinite" end # context 'lazy_take' end # describe Lab42::Stream
import 'package:flutter_mvp/bean/hot_bean_entity.dart'; import 'package:flutter_mvp/bean/header_bean_entity.dart'; import 'package:flutter_mvp/bean/home_bean_entity.dart'; import 'package:flutter_mvp/bean/catetory_bean_entity.dart'; class EntityFactory { static T generateOBJ<T>(json) { if (1 == 0) { return null; } else if (T.toString() == "HotBeanEntity") { return HotBeanEntity.fromJson(json) as T; } else if (T.toString() == "HeaderBeanEntity") { return HeaderBeanEntity.fromJson(json) as T; } else if (T.toString() == "HomeBeanEntity") { return HomeBeanEntity.fromJson(json) as T; } else if (T.toString() == "CategoryBeanEntity") { return CategoryBeanEntity.fromJson(json) as T; } else if (T.toString() == "HomeItemIssuelist") { return HomeItemIssuelist.fromJson(json) as T; } else { return null; } } }
using System; namespace REFrostedViewController { /// <summary> /// Direction enum /// </summary> public enum REFrostedViewControllerDirection { Left = 0, Right = 1, Top = 2, Bottom = 3, } /// <summary> /// Style enum /// </summary> public enum REFrostedViewControllerLiveBackgroundStyle { Light = 0, Dark = 1, } }
--- title: "Managing disk partitions in Linux" description: "" author: "John Paul" date: "2019-01-31" tags: ["linux"] --- The `fdisk` (format disk/fixed disk) command is used to view, create, resize, delete, change, copy and/or move partitions on a hard-drive. You must use the command as root. To list all disk partitions: `fdisk -l` To view a specific disk partion, use a command such as the one below: `fdisk -l /dev/sda` To check the size of a partition, use the command illustrated below: `fdisk -s /dev/sda2` To get full information on disk space usage, the `df` command comes in handy. `df` `df -a` To get the results in a more human readable form: `df -h` To get the information in bytes or MB, use either one of the commands below. `df -k` `df -m`
package typingsSlinky.typeorm.typingsMod import typingsSlinky.node.Buffer import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait MongoClientOptions extends StObject { /** * A hash of options to set on the db object, see Db constructor. */ var db: js.UndefOr[DbCreateOptions] = js.native /** * A hash of options to set on the mongos object, see Mongos constructor**. */ var mongos: js.UndefOr[MongosOptions] = js.native /** * The maximum size of the individual server pool. */ var poolSize: js.UndefOr[scala.Double] = js.native /** * A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible. */ var promiseLibrary: js.UndefOr[js.Object] = js.native /** * A hash of options to set on the replSet object, see ReplSet constructor**. */ var replSet: js.UndefOr[ReplSetOptions] = js.native /** * A hash of options to set on the server objects, see Server constructor**. */ var server: js.UndefOr[ServerOptions] = js.native /** * Enable SSL connection. */ var ssl: js.UndefOr[Boolean] = js.native /** * SSL Certificate store binary buffer. */ var sslCA: js.UndefOr[Buffer] = js.native /** * Uri decode the user name and password for authentication. */ var uri_decode_auth: js.UndefOr[Boolean] = js.native } object MongoClientOptions { @scala.inline def apply(): MongoClientOptions = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[MongoClientOptions] } @scala.inline implicit class MongoClientOptionsMutableBuilder[Self <: MongoClientOptions] (val x: Self) extends AnyVal { @scala.inline def setDb(value: DbCreateOptions): Self = StObject.set(x, "db", value.asInstanceOf[js.Any]) @scala.inline def setDbUndefined: Self = StObject.set(x, "db", js.undefined) @scala.inline def setMongos(value: MongosOptions): Self = StObject.set(x, "mongos", value.asInstanceOf[js.Any]) @scala.inline def setMongosUndefined: Self = StObject.set(x, "mongos", js.undefined) @scala.inline def setPoolSize(value: scala.Double): Self = StObject.set(x, "poolSize", value.asInstanceOf[js.Any]) @scala.inline def setPoolSizeUndefined: Self = StObject.set(x, "poolSize", js.undefined) @scala.inline def setPromiseLibrary(value: js.Object): Self = StObject.set(x, "promiseLibrary", value.asInstanceOf[js.Any]) @scala.inline def setPromiseLibraryUndefined: Self = StObject.set(x, "promiseLibrary", js.undefined) @scala.inline def setReplSet(value: ReplSetOptions): Self = StObject.set(x, "replSet", value.asInstanceOf[js.Any]) @scala.inline def setReplSetUndefined: Self = StObject.set(x, "replSet", js.undefined) @scala.inline def setServer(value: ServerOptions): Self = StObject.set(x, "server", value.asInstanceOf[js.Any]) @scala.inline def setServerUndefined: Self = StObject.set(x, "server", js.undefined) @scala.inline def setSsl(value: Boolean): Self = StObject.set(x, "ssl", value.asInstanceOf[js.Any]) @scala.inline def setSslCA(value: Buffer): Self = StObject.set(x, "sslCA", value.asInstanceOf[js.Any]) @scala.inline def setSslCAUndefined: Self = StObject.set(x, "sslCA", js.undefined) @scala.inline def setSslUndefined: Self = StObject.set(x, "ssl", js.undefined) @scala.inline def setUri_decode_auth(value: Boolean): Self = StObject.set(x, "uri_decode_auth", value.asInstanceOf[js.Any]) @scala.inline def setUri_decode_authUndefined: Self = StObject.set(x, "uri_decode_auth", js.undefined) } }
package com.exercise.data.gateway import com.exercise.data.entity.RepositoriesEntity import com.exercise.data.network.service.RepositoriesNetworkService import com.exercise.domain.entity.Repositories import com.exercise.domain.gateway.RepositoriesGateway import com.exercise.domain.mapper.Mapper import io.reactivex.rxjava3.core.Single class RepositoriesGatewayImpl( private val repositoriesNetworkService: RepositoriesNetworkService, private val repositoriesMapper: Mapper<RepositoriesEntity, Repositories> ) : RepositoriesGateway { override fun getRepositories(): Single<Repositories> = repositoriesNetworkService.getRepositories() .map { repositoriesMapper.map(it) } override fun getRepositoriesByUrl(url: String): Single<Repositories> = repositoriesNetworkService.getRepositoriesByUrl(url) .map { repositoriesMapper.map(it) } }
require("dotenv").config(); const Registry = require("../models/registry"); const express = require("express"); const router = require("express").Router({ mergeParams: true }); router.use(express.json()); const { findRegistryById } = require("../middleware"); // GET Registry table router.get("/", async (req, res) => { const { weddingId } = req.params; try { const registries = await Registry.findBy({ wedding_id: weddingId }); res.json(registries); } catch (err) { res.status(500).json({ message: err.message }); } }); //POST to Registry table router.post("/", async (req, res) => { const registry = req.body; const { weddingId } = req.params; try { if (registry) { const newRegistry = await Registry.add({ wedding_id: weddingId, ...registry, }); if (newRegistry) { res.status(201).json(newRegistry); } else { res.status(404).json({ message: "Registry could not be added" }); } } } catch (err) { res.status(500).json({ message: err.message }); } }); // GET Registry table with ID router.get("/:id", findRegistryById, (req, res) => { const { registry } = req; if (registry) { res.status(200).json(registry); } else { res.status(404).json({ message: "could not find registry with given id" }); } }); // DEL request to with ID router.delete("/:id", async (req, res) => { const { id } = req.params; try { const deleted = await Registry.remove(id); if (deleted) { res.json({ removed: deleted }); } else { res .status(404) .json({ message: "could not find registry with given id" }); } } catch (err) { res.status(500).json({ message: "failed to delete registry" }); } }); // EDIT Registry with ID router.put("/:id", async (req, res) => { const { id } = req.params; const changes = req.body; try { const registry = await Registry.findById(id); if (registry) { const updatedRegistry = await Registry.update(changes, id); res.json(updatedRegistry); } else { res .status(404) .json({ message: "could not find registry with given id" }); } } catch (err) { res.status(500).json({ message: "Failed to update Registry" }); } }); module.exports = router;
package typingsSlinky.electron.Electron import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait WebSource extends StObject { // Docs: https://electronjs.org/docs/api/structures/web-source var code: String = js.native /** * Default is 1. */ var startLine: js.UndefOr[Double] = js.native var url: js.UndefOr[String] = js.native } object WebSource { @scala.inline def apply(code: String): WebSource = { val __obj = js.Dynamic.literal(code = code.asInstanceOf[js.Any]) __obj.asInstanceOf[WebSource] } @scala.inline implicit class WebSourceMutableBuilder[Self <: WebSource] (val x: Self) extends AnyVal { @scala.inline def setCode(value: String): Self = StObject.set(x, "code", value.asInstanceOf[js.Any]) @scala.inline def setStartLine(value: Double): Self = StObject.set(x, "startLine", value.asInstanceOf[js.Any]) @scala.inline def setStartLineUndefined: Self = StObject.set(x, "startLine", js.undefined) @scala.inline def setUrl(value: String): Self = StObject.set(x, "url", value.asInstanceOf[js.Any]) @scala.inline def setUrlUndefined: Self = StObject.set(x, "url", js.undefined) } }
Rails.application.routes.draw do get 'gem-versions' => 'viscera/viscera#index' end
require 'spec_helper' describe SalsaLabs::ObjectsFetcher do let(:client) do double( 'API client', fetch: File.read('spec/fixtures/getObjects.sjs_action.xml') ) end describe "#fetch" do before(:each) do allow(SalsaLabs::ApiClient).to receive(:new) { client } end it "calls the getObjects API endpoint" do SalsaLabs::ObjectsFetcher.fetch(type: 'Action') expect(client).to have_received(:fetch). with('/api/getObjects.sjs', {object: 'Action'}) end it "returns an array of SalsaLabs::Action objects" do results = SalsaLabs::ObjectsFetcher.fetch(type: 'Action', item_class: SalsaLabs::Action) expect(results).to be_a(Array) expect(results.first).to be_a(SalsaLabs::Action) end end it "parses actions" do client = double('API Client', fetch: File.read('spec/fixtures/getObjects.sjs_action.xml')) action = SalsaLabs::ObjectsFetcher.new(type: 'Action', item_class: SalsaLabs::Action, filters: {}, client: client).fetch.first expect(action.action_key).to eq(6656) expect(action.description).to eq("<p>&#160;</p>") expect(action.title).to eq("My Action Title") expect(action.reference_name).to eq("My TItle") end it "parses supporters" do client = double('API Client', fetch: File.read('spec/fixtures/getObjects.sjs_supporter.xml')) supporter = SalsaLabs::ObjectsFetcher.new(type: 'supporter', item_class: SalsaLabs::Supporter, filters: {}, client: client).fetch.first expect(supporter.supporter_key).to eq(31752865) expect(supporter.email).to eq("chris@example.com") end it "parses supporter actions" do client = double('API Client', fetch: File.read('spec/fixtures/getObjects.sjs_supporter_actions.xml')) supporter_action = SalsaLabs::ObjectsFetcher.new(type: 'supporter_action', item_class: SalsaLabs::SupporterAction, filters: {}, client: client).fetch.first expect(supporter_action.supporter_action_key).to eq(898207) expect(supporter_action.supporter_key).to eq(123) expect(supporter_action.action_key).to eq(234) end end
package me.vovak.astminer.examples import astminer.common.model.Node import astminer.parse.java.GumTreeJavaParser import java.io.File const val INPUT_PATH = "input.java" data class ParameterDefinition(val type: String, val name: String) { override fun toString() = "$type $name" } data class ReturnStatements(val statements: List<String>) { override fun toString(): String = statements.joinToString(" | ") } data class MethodMetadata( val comment: String, val identifier: String, val parameters: List<ParameterDefinition>, val returnStatements: ReturnStatements ) fun Node.findChildrenOfType(type: String): List<Node> { if (this.getChildren().isEmpty()) return emptyList() return this.getChildrenOfType(type) + this.getChildren().map { it.findChildrenOfType(type) }.flatten() } fun Node.getName(): String { return this.getChildOfType("SimpleName")!!.getToken() } fun Node.getParameters(): List<ParameterDefinition> { return this.getChildrenOfType("SingleVariableDeclaration").map { val type = it.getChildOfType("SimpleType")?.getToken() ?: it.getChildOfType("ParameterizedType")?.getToken() val name = it.getChildOfType("SimpleName")?.getToken() ParameterDefinition(type!!, name!!) } } // Would need a bit of extra handling for more complex return statements fun Node.getReturnStatements(): ReturnStatements = ReturnStatements( this.findChildrenOfType("ReturnStatement") .map { it.getChildren().first().getToken() } ) fun getComment(file: File): String { return String(file.readBytes()).substringAfterLast("/*").substringBeforeLast("*/").trim() } fun main(args: Array<String>) { val inputFile = File(INPUT_PATH) val tree = GumTreeJavaParser().parseFile(inputFile).root!! println(tree.prettyPrint()) val methodNode = tree.getChildren()[0].getChildrenOfType("MethodDeclaration")[0] val methodName = methodNode.getName() val methodParameters = methodNode.getParameters() val methodReturnStatements = methodNode.getReturnStatements() // Comments are not part of the AST, so it's easier to extract them separately val comment = getComment(inputFile) val metadata = MethodMetadata(comment, methodName, methodParameters, methodReturnStatements) println(metadata) }
CREATE PROCEDURE dbo.sp_crm_table_restore @ProcessId INT, @BackupTablePrefix NVARCHAR(36), @ControlSchemaName NVARCHAR(36), @ControlTableName NVARCHAR(100), @LastUpdate DATETIME2(3) AS DECLARE @SinkSchemaName NVARCHAR(36); DECLARE @SinkTableName NVARCHAR(100); DECLARE @sql NVARCHAR(MAX) = ' SELECT SinkSchemaName ,SinkTableName INTO #SinkTempTbl FROM ' + @ControlSchemaName + '.' + @ControlTableName + ' WHERE ProcessId = ' + convert(varchar(10), @ProcessId) EXEC sp_executesql @sql SELECT @SinkSchemaName=[SinkSchemaName] ,@SinkTableName=[SinkTableName] FROM #SinkTempTbl -- Check that both the primary table and backup table exist before dropping and renaming. DECLARE @RenameSQL NVARCHAR(MAX) = ' IF OBJECT_ID (' + char(39) + @SinkSchemaName + '.' + @SinkTableName + char(39) + ') IS NOT NULL AND OBJECT_ID (' + char(39) + @SinkSchemaName + '.' + @BackupTablePrefix + @SinkTableName + char(39) + ') IS NOT NULL DROP TABLE ' + @SinkSchemaName + '.' + @SinkTableName + ' RENAME OBJECT ' + @SinkSchemaName + '.' + @BackupTablePrefix + @SinkTableName + ' TO ' + @SinkTableName EXEC sp_executesql @RenameSQL; -- SET LastUpdate back to previous watermark value before rollback DECLARE @UpdateWatermarkSQL NVARCHAR(MAX); SET @UpdateWatermarkSQL = 'UPDATE ' + @ControlSchemaName + '.' + @ControlTableName + ' SET LastUpdate = ' + '''' + convert(varchar(25), @LastUpdate, 121) + '''' + ' WHERE ProcessId = ' + convert(varchar(10), @ProcessId); -- Execute the UPDATE statement from above EXEC sp_executesql @UpdateWatermarkSQL;
from api.node.messages import LOG_NODE_UPDATE from api.task.utils import callback, task_log_error, mgmt_lock from api.task.internal import InternalTask from vms.models import Node, DefaultDc from que import TG_DC_UNBOUND from que.tasks import cq, execute, get_task_logger from que.mgmt import MgmtCallbackTask __all__ = ('node_authorized_keys_sync', 'node_authorized_keys_sync_cb') logger = get_task_logger(__name__) ERIGONES_TASK_USER = cq.conf.ERIGONES_TASK_USER def run_node_authorized_keys_sync(): """ Create and update authorized_keys on every compute node. """ dc1_settings = DefaultDc().settings # erigones.conf.settings if not dc1_settings.VMS_NODE_SSH_KEYS_SYNC: logger.warn('Node authorized_keys synchronization is disabled!') return nodes = Node.objects.all().order_by('hostname') # Create one authorized_keys list authorized_keys = [node.sshkey for node in nodes if node.sshkey] # Add user specified compute node SSH keys authorized_keys.extend(dc1_settings.VMS_NODE_SSH_KEYS_DEFAULT) # Save the authorized_keys file on every compute node to persistent /usbkey/config.inc/ and /root/.ssh locations files = '/usbkey/config.inc/authorized_keys /root/.ssh/authorized_keys' cmd = 'tee %s; chmod 640 %s' % (files, files) stdin = '\n'.join(authorized_keys) for node in nodes: if node.authorized_keys == stdin: logger.info('authorized_keys already synced for node %s - skipping update', node) continue # We update authorized_keys only on online nodes # But we will also run this whenever node status is changed to online if not node.is_online(): logger.warn('Excluding node %s from updating authorized_keys because it is not in online state', node) continue lock = 'node %s authorized_keys' % node.uuid cb = ('api.node.sshkey.tasks.node_authorized_keys_sync_cb', {'node_uuid': node.uuid}) tid, err = execute(ERIGONES_TASK_USER, None, cmd, stdin=stdin, callback=cb, lock=lock, queue=node.fast_queue, expires=180, nolog=True, tg=TG_DC_UNBOUND, ping_worker=False, check_user_tasks=False) if err: logger.error('Got error (%s) when running task %s for updating authorized_keys on node %s', err, tid, node) else: logger.info('Created task %s for updating authorized_keys on node %s', tid, node) # noinspection PyUnusedLocal @cq.task(name='api.node.sshkey.tasks.node_authorized_keys_sync', base=InternalTask) @mgmt_lock(timeout=3600, wait_for_release=True) def node_authorized_keys_sync(task_id, sender, **kwargs): """ Task for updating authorized_keys on each compute node (called via node_online signal). """ run_node_authorized_keys_sync() @cq.task(name='api.node.sshkey.tasks.node_authorized_keys_sync_cb', base=MgmtCallbackTask, bind=True) @callback(log_exception=False, update_user_tasks=False) def node_authorized_keys_sync_cb(result, task_id, node_uuid=None): """ Callback for run_node_authorized_keys_sync(). """ node = Node.objects.get(uuid=node_uuid) if result['returncode'] == 0: node.save_authorized_keys(result['stdout']) else: result['message'] = 'Compute node SSH key sync error - got bad return code (%s). Error: %s' % \ (result['returncode'], result.get('stderr', '')) task_log_error(task_id, msg=LOG_NODE_UPDATE, obj=node, task_result=result, update_user_tasks=False) return result
function Install-LabModule { <# .SYNOPSIS Installs Lability PowerShell and DSC resource modules. .DESCRIPTION The Install-LabModule cmdlet installs PowerShell modules and/or DSC resource modules from Lability's module cache in to the local system. The DSC resources and/or PowerShell module can be installed into either the current user's or the local machine's module path. .PARAMETER ConfigurationData Specifies a PowerShell DSC configuration data hashtable or a path to an existing PowerShell DSC .psd1 configuration document that contains ability'srequired media definition. .PARAMETER ModuleType Specifies the module type(s) defined in a PowerShell DSC configuration (.psd1) document to install. .PARAMETER NodeName Specifies only modules that target the node(s) specified are installed. .PARAMETER Scope Specifies the scope to install module(s) in to. The default value is 'CurrentUser'. .EXAMPLE Install-LabModule -ConfigurationData .\Config.psd1 -ModuleType -DscResource Installs all DSC resource modules defined in the 'Config.psd1' document into the user's module scope. .EXAMPLE Install-LabModule -ConfigurationData .\Config.psd1 -ModuleType -Module -Scope AllUsers Installs all PowerShell modules defined in the 'Config.psd1' document into the local machine's module scope. #> [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] param ( [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [System.String] $ConfigurationData, [Parameter(Mandatory, ValueFromPipelineByPropertyName)] [ValidateSet('Module','DscResource')] [System.String[]] $ModuleType, [Parameter(ValueFromPipelineByPropertyName)] [System.String] $NodeName, [Parameter(ValueFromPipelineByPropertyName)] [ValidateSet('AllUsers','CurrentUser')] [System.String] $Scope = 'CurrentUser' ) process { if ($Scope -eq 'AllUsers') { $localizedProgramFiles = Resolve-ProgramFilesFolder -Path $env:SystemRoot; $DestinationPath = Join-Path -Path $localizedProgramFiles -ChildPath 'WindowsPowerShell\Modules'; } elseif ($Scope -eq 'CurrentUser') { $userDocuments = [System.Environment]::GetFolderPath('MyDocuments'); $DestinationPath = Join-Path -Path $userDocuments -ChildPath 'WindowsPowerShell\Modules'; } $copyLabModuleParams = @{ ConfigurationData = $ConfigurationData; ModuleType = $ModuleType; DestinationPath = $DestinationPath; } Copy-LabModule @copyLabModuleParams; } #end process } #end function