repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
google/dokka
core/src/test/kotlin/TestAPI.kt
1
11001
package org.jetbrains.dokka.tests import com.google.inject.Guice import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.rt.execution.junit.FileComparisonFailure import org.jetbrains.dokka.* import org.jetbrains.dokka.Utilities.DokkaAnalysisModule import org.jetbrains.kotlin.cli.common.config.ContentRoot import org.jetbrains.kotlin.cli.common.config.KotlinSourceRoot import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.MessageCollector import org.jetbrains.kotlin.cli.jvm.config.JavaSourceRoot import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.junit.Assert import org.junit.Assert.fail import java.io.File fun verifyModel(vararg roots: ContentRoot, withJdk: Boolean = false, withKotlinRuntime: Boolean = false, format: String = "html", includeNonPublic: Boolean = true, perPackageOptions: List<DokkaConfiguration.PackageOptions> = emptyList(), noStdlibLink: Boolean = true, collectInheritedExtensionsFromLibraries: Boolean = false, verifier: (DocumentationModule) -> Unit) { val documentation = DocumentationModule("test") val options = DocumentationOptions( "", format, includeNonPublic = includeNonPublic, skipEmptyPackages = false, includeRootPackage = true, sourceLinks = listOf(), perPackageOptions = perPackageOptions, generateClassIndexPage = false, generatePackageIndexPage = false, noStdlibLink = noStdlibLink, noJdkLink = false, cacheRoot = "default", languageVersion = null, apiVersion = null, collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries ) appendDocumentation(documentation, *roots, withJdk = withJdk, withKotlinRuntime = withKotlinRuntime, options = options) documentation.prepareForGeneration(options) verifier(documentation) } fun appendDocumentation(documentation: DocumentationModule, vararg roots: ContentRoot, withJdk: Boolean = false, withKotlinRuntime: Boolean = false, options: DocumentationOptions, defaultPlatforms: List<String> = emptyList()) { val messageCollector = object : MessageCollector { override fun clear() { } override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) { when (severity) { CompilerMessageSeverity.STRONG_WARNING, CompilerMessageSeverity.WARNING, CompilerMessageSeverity.LOGGING, CompilerMessageSeverity.OUTPUT, CompilerMessageSeverity.INFO, CompilerMessageSeverity.ERROR -> { println("$severity: $message at $location") } CompilerMessageSeverity.EXCEPTION -> { fail("$severity: $message at $location") } } } override fun hasErrors() = false } val environment = AnalysisEnvironment(messageCollector) environment.apply { if (withJdk || withKotlinRuntime) { val stringRoot = PathManager.getResourceRoot(String::class.java, "/java/lang/String.class") addClasspath(File(stringRoot)) } if (withKotlinRuntime) { val kotlinStrictfpRoot = PathManager.getResourceRoot(Strictfp::class.java, "/kotlin/jvm/Strictfp.class") addClasspath(File(kotlinStrictfpRoot)) } addRoots(roots.toList()) loadLanguageVersionSettings(options.languageVersion, options.apiVersion) } val defaultPlatformsProvider = object : DefaultPlatformsProvider { override fun getDefaultPlatforms(descriptor: DeclarationDescriptor) = defaultPlatforms } val injector = Guice.createInjector( DokkaAnalysisModule(environment, options, defaultPlatformsProvider, documentation.nodeRefGraph, DokkaConsoleLogger)) buildDocumentationModule(injector, documentation) Disposer.dispose(environment) } fun verifyModel(source: String, withJdk: Boolean = false, withKotlinRuntime: Boolean = false, format: String = "html", includeNonPublic: Boolean = true, verifier: (DocumentationModule) -> Unit) { if (!File(source).exists()) { throw IllegalArgumentException("Can't find test data file $source") } verifyModel(contentRootFromPath(source), withJdk = withJdk, withKotlinRuntime = withKotlinRuntime, format = format, includeNonPublic = includeNonPublic, verifier = verifier) } fun verifyPackageMember(source: String, withJdk: Boolean = false, withKotlinRuntime: Boolean = false, verifier: (DocumentationNode) -> Unit) { verifyModel(source, withJdk = withJdk, withKotlinRuntime = withKotlinRuntime) { model -> val pkg = model.members.single() verifier(pkg.members.single()) } } fun verifyJavaModel(source: String, withKotlinRuntime: Boolean = false, verifier: (DocumentationModule) -> Unit) { val tempDir = FileUtil.createTempDirectory("dokka", "") try { val sourceFile = File(source) FileUtil.copy(sourceFile, File(tempDir, sourceFile.name)) verifyModel(JavaSourceRoot(tempDir, null), withJdk = true, withKotlinRuntime = withKotlinRuntime, verifier = verifier) } finally { FileUtil.delete(tempDir) } } fun verifyJavaPackageMember(source: String, withKotlinRuntime: Boolean = false, verifier: (DocumentationNode) -> Unit) { verifyJavaModel(source, withKotlinRuntime) { model -> val pkg = model.members.single() verifier(pkg.members.single()) } } fun verifyOutput(roots: Array<ContentRoot>, outputExtension: String, withJdk: Boolean = false, withKotlinRuntime: Boolean = false, format: String = "html", includeNonPublic: Boolean = true, noStdlibLink: Boolean = true, collectInheritedExtensionsFromLibraries: Boolean = false, outputGenerator: (DocumentationModule, StringBuilder) -> Unit) { verifyModel( *roots, withJdk = withJdk, withKotlinRuntime = withKotlinRuntime, format = format, includeNonPublic = includeNonPublic, noStdlibLink = noStdlibLink, collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries ) { verifyModelOutput(it, outputExtension, roots.first().path, outputGenerator) } } fun verifyModelOutput(it: DocumentationModule, outputExtension: String, sourcePath: String, outputGenerator: (DocumentationModule, StringBuilder) -> Unit) { val output = StringBuilder() outputGenerator(it, output) val ext = outputExtension.removePrefix(".") val expectedFile = File(sourcePath.replaceAfterLast(".", ext, sourcePath + "." + ext)) assertEqualsIgnoringSeparators(expectedFile, output.toString()) } fun verifyOutput( path: String, outputExtension: String, withJdk: Boolean = false, withKotlinRuntime: Boolean = false, format: String = "html", includeNonPublic: Boolean = true, noStdlibLink: Boolean = true, collectInheritedExtensionsFromLibraries: Boolean = false, outputGenerator: (DocumentationModule, StringBuilder) -> Unit ) { verifyOutput( arrayOf(contentRootFromPath(path)), outputExtension, withJdk, withKotlinRuntime, format, includeNonPublic, noStdlibLink, collectInheritedExtensionsFromLibraries, outputGenerator ) } fun verifyJavaOutput(path: String, outputExtension: String, withKotlinRuntime: Boolean = false, outputGenerator: (DocumentationModule, StringBuilder) -> Unit) { verifyJavaModel(path, withKotlinRuntime) { model -> verifyModelOutput(model, outputExtension, path, outputGenerator) } } fun assertEqualsIgnoringSeparators(expectedFile: File, output: String) { if (!expectedFile.exists()) expectedFile.createNewFile() val expectedText = expectedFile.readText().replace("\r\n", "\n") val actualText = output.replace("\r\n", "\n") if(expectedText != actualText) throw FileComparisonFailure("", expectedText, actualText, expectedFile.canonicalPath) } fun assertEqualsIgnoringSeparators(expectedOutput: String, output: String) { Assert.assertEquals(expectedOutput.replace("\r\n", "\n"), output.replace("\r\n", "\n")) } fun StringBuilder.appendChildren(node: ContentBlock): StringBuilder { for (child in node.children) { val childText = child.toTestString() append(childText) } return this } fun StringBuilder.appendNode(node: ContentNode): StringBuilder { when (node) { is ContentText -> { append(node.text) } is ContentEmphasis -> append("*").appendChildren(node).append("*") is ContentBlockCode -> { if (node.language.isNotBlank()) appendln("[code lang=${node.language}]") else appendln("[code]") appendChildren(node) appendln() appendln("[/code]") } is ContentNodeLink -> { append("[") appendChildren(node) append(" -> ") append(node.node.toString()) append("]") } is ContentBlock -> { appendChildren(node) } is NodeRenderContent -> { append("render(") append(node.node) append(",") append(node.mode) append(")") } is ContentSymbol -> { append(node.text) } is ContentEmpty -> { /* nothing */ } else -> throw IllegalStateException("Don't know how to format node $node") } return this } fun ContentNode.toTestString(): String { val node = this return StringBuilder().apply { appendNode(node) }.toString() } val ContentRoot.path: String get() = when(this) { is KotlinSourceRoot -> path is JavaSourceRoot -> file.path else -> throw UnsupportedOperationException() }
apache-2.0
f3cc43abe4fadc5faaf32ba977220447
35.67
128
0.63367
5.547655
false
false
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/application/fragments/JappMapFragment.kt
1
39937
package nl.rsdt.japp.application.fragments import android.app.Fragment import android.content.ActivityNotFoundException import android.content.Intent import android.content.IntentSender import android.content.SharedPreferences import android.graphics.Bitmap import android.graphics.Color import android.net.Uri import android.os.Bundle import android.preference.PreferenceManager import android.util.Log import android.util.Pair import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.clans.fab.FloatingActionButton import com.github.clans.fab.FloatingActionMenu import com.google.android.gms.common.api.Status import com.google.android.gms.maps.MapView import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.google.android.gms.maps.model.PolygonOptions import com.google.android.material.snackbar.Snackbar import com.google.gson.Gson import nl.rsdt.japp.R import nl.rsdt.japp.application.Japp import nl.rsdt.japp.application.JappPreferences import nl.rsdt.japp.jotial.data.bodies.VosPostBody import nl.rsdt.japp.jotial.data.nav.Location import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo import nl.rsdt.japp.jotial.maps.MapManager import nl.rsdt.japp.jotial.maps.NavigationLocationManager import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied import nl.rsdt.japp.jotial.maps.management.MarkerIdentifier import nl.rsdt.japp.jotial.maps.movement.MovementManager import nl.rsdt.japp.jotial.maps.pinning.Pin import nl.rsdt.japp.jotial.maps.pinning.PinningManager import nl.rsdt.japp.jotial.maps.pinning.PinningSession import nl.rsdt.japp.jotial.maps.sighting.SightingIcon import nl.rsdt.japp.jotial.maps.sighting.SightingSession import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap import nl.rsdt.japp.jotial.maps.wrapper.IPolygon import nl.rsdt.japp.jotial.maps.wrapper.google.GoogleJotiMap import nl.rsdt.japp.jotial.maps.wrapper.osm.OsmJotiMap import nl.rsdt.japp.jotial.navigation.NavigationSession import nl.rsdt.japp.jotial.net.apis.AutoApi import nl.rsdt.japp.jotial.net.apis.VosApi import nl.rsdt.japp.service.AutoSocketHandler import nl.rsdt.japp.service.LocationService import nl.rsdt.japp.service.ServiceManager import org.acra.ktx.sendWithAcra import org.osmdroid.config.Configuration import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.GeoPoint import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.File import java.util.* /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 8-7-2016 * Description... */ class JappMapFragment : Fragment(), IJotiMap.OnMapReadyCallback, SharedPreferences.OnSharedPreferenceChangeListener,Deelgebied.OnColorChangeListener { private val serviceManager = ServiceManager<LocationService, LocationService.LocationBinder>(LocationService::class.java) var jotiMap: IJotiMap? = null private set private var googleMapView: MapView? = null private var navigationLocationManager: NavigationLocationManager? = null private var callback: IJotiMap.OnMapReadyCallback? = null private val pinningManager = PinningManager() var movementManager: MovementManager? = MovementManager() private set private val areas = HashMap<String, IPolygon>() private var osmActive = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) navigationLocationManager = NavigationLocationManager() JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { pinningManager.intialize(activity) pinningManager.onCreate(savedInstanceState) movementManager!!.onCreate(savedInstanceState) // Inflate the layout for this fragment val v = inflater.inflate(R.layout.fragment_map, container, false) return createMap(savedInstanceState, v) } private fun createMap(savedInstanceState: Bundle?, v: View): View { val useOSM = JappPreferences.useOSM() val view: View view = if (useOSM) { createOSMMap(savedInstanceState, v) } else { createGoogleMap(savedInstanceState, v) } val menu = view.findViewById<FloatingActionMenu>(R.id.fab_menu) menu.bringToFront() return view } private fun createOSMMap(savedInstanceState: Bundle?, v: View): View { osmActive = true val osmView = org.osmdroid.views.MapView(activity) (v as ViewGroup).addView(osmView) val ctx = activity.application Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx)) when (JappPreferences.osmMapSource) { JappPreferences.OsmMapType.Mapnik -> osmView.setTileSource(TileSourceFactory.MAPNIK) JappPreferences.OsmMapType.OpenSeaMap -> osmView.setTileSource(TileSourceFactory.OPEN_SEAMAP) JappPreferences.OsmMapType.HikeBike -> osmView.setTileSource(TileSourceFactory.HIKEBIKEMAP) JappPreferences.OsmMapType.OpenTopo -> osmView.setTileSource(TileSourceFactory.OpenTopo) JappPreferences.OsmMapType.Fiets_NL -> osmView.setTileSource(TileSourceFactory.FIETS_OVERLAY_NL) JappPreferences.OsmMapType.Default -> osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE) JappPreferences.OsmMapType.CloudMade_Normal -> osmView.setTileSource(TileSourceFactory.CLOUDMADESTANDARDTILES) JappPreferences.OsmMapType.CloudMade_Small -> osmView.setTileSource(TileSourceFactory.CLOUDMADESMALLTILES) JappPreferences.OsmMapType.ChartBundle_ENRH -> osmView.setTileSource(TileSourceFactory.ChartbundleENRH) JappPreferences.OsmMapType.ChartBundle_ENRL -> osmView.setTileSource(TileSourceFactory.ChartbundleENRH) JappPreferences.OsmMapType.ChartBundle_WAC -> osmView.setTileSource(TileSourceFactory.ChartbundleWAC) JappPreferences.OsmMapType.USGS_Sat -> osmView.setTileSource(TileSourceFactory.USGS_SAT) JappPreferences.OsmMapType.USGS_Topo -> osmView.setTileSource(TileSourceFactory.USGS_TOPO) JappPreferences.OsmMapType.Public_Transport -> osmView.setTileSource(TileSourceFactory.PUBLIC_TRANSPORT) JappPreferences.OsmMapType.Road_NL -> osmView.setTileSource(TileSourceFactory.ROADS_OVERLAY_NL) JappPreferences.OsmMapType.Base_NL -> osmView.setTileSource(TileSourceFactory.BASE_OVERLAY_NL) else -> osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE) } osmView.controller.setCenter(GeoPoint(51.958852, 5.954517)) osmView.controller.setZoom(11) osmView.setBuiltInZoomControls(true) osmView.setMultiTouchControls(true) osmView.isFlingEnabled = true osmView.isTilesScaledToDpi = true if (savedInstanceState != null) { val osmbundle = savedInstanceState.getBundle(OSM_BUNDLE) if (osmbundle != null) { osmView.controller.setZoom(osmbundle.getInt(OSM_ZOOM)) osmView.controller.setCenter(GeoPoint(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG))) osmView.rotation = osmbundle.getFloat(OSM_OR) } } movementManager!!.setSnackBarView(osmView) setupHuntButton(v).isEnabled = true setupSpotButton(v).isEnabled = true setupPinButton(v).isEnabled = true setupFollowButton(v) setupNavigationButton(v) jotiMap = OsmJotiMap.getJotiMapInstance(osmView) Configuration.getInstance().load(activity, PreferenceManager.getDefaultSharedPreferences(activity)) return v } private fun createGoogleMap(savedInstanceState: Bundle?, v: View): View { osmActive = false googleMapView = MapView(activity) (v as ViewGroup).addView(googleMapView) val ctx = activity.application Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx)) if (savedInstanceState != null) { if (savedInstanceState.containsKey(BUNDLE_MAP)) { googleMapView!!.onCreate(savedInstanceState.getBundle(BUNDLE_MAP)) } else { googleMapView!!.onCreate(null) } } else { googleMapView!!.onCreate(null) } movementManager!!.setSnackBarView(googleMapView!!) setupHuntButton(v) setupSpotButton(v) setupPinButton(v) setupFollowButton(v) setupNavigationButton(v) jotiMap = GoogleJotiMap.getJotiMapInstance(googleMapView!!) if (savedInstanceState != null) { val osmbundle = savedInstanceState.getBundle(OSM_BUNDLE) if (osmbundle != null) { jotiMap!!.setPreviousZoom(osmbundle.getInt(OSM_ZOOM)) jotiMap!!.setPreviousCameraPosition(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG)) jotiMap!!.setPreviousRotation(osmbundle.getFloat(OSM_OR)) } } return v } override fun onSaveInstanceState(savedInstanceState: Bundle?) { movementManager!!.onSaveInstanceState(savedInstanceState) pinningManager.onSaveInstanceState(savedInstanceState) savedInstanceState?.putBoolean(BUNDLE_OSM_ACTIVE, osmActive) if (!osmActive) { val mapBundle = Bundle() googleMapView!!.onSaveInstanceState(mapBundle) savedInstanceState?.putBundle(BUNDLE_MAP, mapBundle) } else if (jotiMap is OsmJotiMap) { val osmMap = (jotiMap as OsmJotiMap).osmMap val osmMapBundle = Bundle() osmMapBundle.putInt(OSM_ZOOM, osmMap.zoomLevel) osmMapBundle.putDouble(OSM_LAT, osmMap.mapCenter.latitude) osmMapBundle.putDouble(OSM_LNG, osmMap.mapCenter.longitude) osmMapBundle.putFloat(OSM_OR, osmMap.mapOrientation) savedInstanceState?.putBundle(OSM_BUNDLE, osmMapBundle) } // Always call the superclass so it can save the view hierarchy state super.onSaveInstanceState(savedInstanceState) } fun getMapAsync(callback: IJotiMap.OnMapReadyCallback) { this.callback = callback jotiMap!!.getMapAsync(this) } override fun onStart() { super.onStart() if (!osmActive) { googleMapView!!.onStart() } } override fun onStop() { super.onStop() if (!osmActive) { googleMapView!!.onStop() } } override fun onResume() { super.onResume() if (!osmActive) { googleMapView!!.onResume() } else { Configuration.getInstance().load(activity, PreferenceManager.getDefaultSharedPreferences(activity)) } movementManager!!.setListener(object:LocationService.OnResolutionRequiredListener{ override fun onResolutionRequired(status: Status) { try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult( activity, REQUEST_CHECK_SETTINGS) } catch (e: IntentSender.SendIntentException) { // Ignore the error. e.sendWithAcra() } } }) serviceManager.add(movementManager!!) movementManager!!.onResume() if (!serviceManager.isBound) { serviceManager.bind(this.activity) } } override fun onPause() { super.onPause() if (!osmActive && googleMapView != null) { googleMapView!!.onPause() } movementManager!!.onPause() } override fun onDestroy() { super.onDestroy() if (!osmActive) { googleMapView!!.onDestroy() } if (movementManager != null) { movementManager!!.onDestroy() serviceManager.remove(movementManager!!) movementManager = null } JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this) serviceManager.unbind(activity) } override fun onLowMemory() { super.onLowMemory() if (!osmActive) { googleMapView!!.onLowMemory() } } override fun onMapReady(jotiMap: IJotiMap) { this.jotiMap = jotiMap jotiMap.clear() movementManager?.onMapReady(jotiMap) setupDeelgebieden() pinningManager.onMapReady(jotiMap) callback?.onMapReady(jotiMap) val markerOptions = MarkerOptions() .position(LatLng(0.0, 0.0)) .visible(false) val icon: Bitmap? = null val marker = jotiMap.addMarker(Pair(markerOptions, icon)) navigationLocationManager?.setCallback(object : NavigationLocationManager.OnNewLocation { override fun onNewLocation(location: Location) { val identifier = MarkerIdentifier.Builder() identifier.setType(MarkerIdentifier.TYPE_NAVIGATE_CAR) identifier.add("addedBy", location.username) identifier.add("createdOn", location.createdOn.toString()) marker.title = Gson().toJson(identifier.create()) marker.isVisible = true marker.position = LatLng(location.latitude, location.longitude) } override fun onNotInCar() { marker.isVisible = false marker.position = LatLng(0.0, 0.0) } }) } private fun setupDeelgebieden() { val enabled = JappPreferences.areasEnabled for (area in enabled) { if (!areas.containsKey(area)) { setupDeelgebied(Deelgebied.parse(area)) } else { // vraag me niet hoe maar dit fixed #112 val poly = areas[area] poly!!.remove() areas.remove(area) setupDeelgebied(Deelgebied.parse(area)) } } if (jotiMap is OsmJotiMap) { (jotiMap as OsmJotiMap).osmMap.invalidate() } } fun setupDeelgebied(deelgebied: Deelgebied?) { if (!deelgebied!!.coordinates.isEmpty()) { setUpDeelgebiedReal(deelgebied) } else { deelgebied.getDeelgebiedAsync(object : Deelgebied.OnInitialized{ override fun onInitialized(deelgebied: Deelgebied) { setUpDeelgebiedReal(deelgebied) } }) } } private fun setUpDeelgebiedReal(deelgebied: Deelgebied) { val options = PolygonOptions().addAll(deelgebied.coordinates) if (JappPreferences.areasColorEnabled) { val alphaPercent = JappPreferences.areasColorAlpha val alpha = (100 - alphaPercent).toFloat() / 100 * 255 options.fillColor(deelgebied.alphaled(Math.round(alpha))) } else { options.fillColor(Color.TRANSPARENT) } options.strokeColor(deelgebied.color) if (JappPreferences.areasEdgesEnabled) { options.strokeWidth(JappPreferences.areasEdgesWidth.toFloat()) } else { options.strokeWidth(0f) } options.visible(true) areas[deelgebied.name] = jotiMap!!.addPolygon(options) } override fun onColorChange(deelgebied: Deelgebied) { setUpDeelgebiedReal(deelgebied) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { var polygon: IPolygon when (key) { JappPreferences.OSM_MAP_TYPE -> { val lJotiMap = jotiMap if(lJotiMap is OsmJotiMap) { val osmView = lJotiMap.osmMap when (JappPreferences.osmMapSource) { JappPreferences.OsmMapType.Mapnik -> osmView.setTileSource(TileSourceFactory.MAPNIK) JappPreferences.OsmMapType.OpenSeaMap -> osmView.setTileSource(TileSourceFactory.OPEN_SEAMAP) JappPreferences.OsmMapType.HikeBike -> osmView.setTileSource(TileSourceFactory.HIKEBIKEMAP) JappPreferences.OsmMapType.OpenTopo -> osmView.setTileSource(TileSourceFactory.OpenTopo) JappPreferences.OsmMapType.Fiets_NL -> osmView.setTileSource(TileSourceFactory.FIETS_OVERLAY_NL) JappPreferences.OsmMapType.Default -> osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE) JappPreferences.OsmMapType.CloudMade_Normal -> osmView.setTileSource(TileSourceFactory.CLOUDMADESTANDARDTILES) JappPreferences.OsmMapType.CloudMade_Small -> osmView.setTileSource(TileSourceFactory.CLOUDMADESMALLTILES) JappPreferences.OsmMapType.ChartBundle_ENRH -> osmView.setTileSource(TileSourceFactory.ChartbundleENRH) JappPreferences.OsmMapType.ChartBundle_ENRL -> osmView.setTileSource(TileSourceFactory.ChartbundleENRH) JappPreferences.OsmMapType.ChartBundle_WAC -> osmView.setTileSource(TileSourceFactory.ChartbundleWAC) JappPreferences.OsmMapType.USGS_Sat -> osmView.setTileSource(TileSourceFactory.USGS_SAT) JappPreferences.OsmMapType.USGS_Topo -> osmView.setTileSource(TileSourceFactory.USGS_TOPO) JappPreferences.OsmMapType.Public_Transport -> osmView.setTileSource(TileSourceFactory.PUBLIC_TRANSPORT) JappPreferences.OsmMapType.Road_NL -> osmView.setTileSource(TileSourceFactory.ROADS_OVERLAY_NL) JappPreferences.OsmMapType.Base_NL -> osmView.setTileSource(TileSourceFactory.BASE_OVERLAY_NL) else -> osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE) } osmView.invalidate() } } JappPreferences.USE_OSM -> { } JappPreferences.AREAS -> { if (jotiMap != null) { val enabled = JappPreferences.areasEnabled for (area in enabled) { if (!areas.containsKey(area)) { setupDeelgebied(Deelgebied.parse(area)) } } val toBeRemoved = ArrayList<String>() for (area in areas.keys) { if (!enabled.contains(area)) { val poly = areas[area] poly!!.remove() toBeRemoved.add(area) } } for (area in toBeRemoved) { areas.remove(area) } if (jotiMap is OsmJotiMap) { (jotiMap as OsmJotiMap).osmMap.invalidate() } } } JappPreferences.AREAS_EDGES -> { val edges = JappPreferences.areasEdgesEnabled for ((_, value) in areas) { polygon = value if (edges) { polygon.setStrokeWidth(JappPreferences.areasEdgesWidth) } else { polygon.setStrokeWidth(0) } } } JappPreferences.AREAS_EDGES_WIDTH -> { val edgesEnabled = JappPreferences.areasEdgesEnabled for ((_, value) in areas) { polygon = value if (edgesEnabled) { polygon.setStrokeWidth(JappPreferences.areasEdgesWidth) } } } JappPreferences.AREAS_COLOR -> { val color = JappPreferences.areasColorEnabled for ((key1, value) in areas) { polygon = value if (color) { val alphaPercent = JappPreferences.areasColorAlpha val alpha = (100 - alphaPercent).toFloat() / 100 * 255 polygon.setFillColor(Deelgebied.parse(key1)!!.alphaled(Math.round(alpha))) } else { polygon.setFillColor(Color.TRANSPARENT) } } } JappPreferences.AREAS_COLOR_ALPHA -> { val areasColorEnabled = JappPreferences.areasColorEnabled for ((key1, value) in areas) { polygon = value if (areasColorEnabled) { val alphaPercent = JappPreferences.areasColorAlpha val alpha = (100 - alphaPercent).toFloat() / 100 * 255 polygon.setFillColor(Deelgebied.parse(key1)!!.alphaled(Math.round(alpha))) } } } } } fun setupSpotButton(v: View): FloatingActionButton { val spotButton = v.findViewById<FloatingActionButton>(R.id.fab_spot) spotButton.setOnClickListener(object : View.OnClickListener { var session: SightingSession? = null override fun onClick(view: View) { /*--- Hide the menu ---*/ val v = getView() val menu = v!!.findViewById<FloatingActionMenu>(R.id.fab_menu) menu.hideMenu(true) /*--- Build a SightingSession and start it ---*/ session = SightingSession.Builder() .setType(SightingSession.SIGHT_SPOT) .setGoogleMap(jotiMap) .setTargetView([email protected](R.id.container)) .setDialogContext([email protected]) .setOnSightingCompletedCallback(object:SightingSession.OnSightingCompletedCallback{ override fun onSightingCompleted(chosen: LatLng?, deelgebied: Deelgebied?, optionalInfo: String?) { /*--- Show the menu ---*/ val menu = getView()!!.findViewById<FloatingActionMenu>(R.id.fab_menu) menu.showMenu(true) if (chosen != null) { /*--- Construct a JSON string with the data ---*/ val builder = VosPostBody.default builder.setIcon(SightingIcon.SPOT) builder.setLatLng(chosen) builder.setTeam(deelgebied?.name?.substring(0, 1)?:"x") builder.setInfo(optionalInfo) val api = Japp.getApi(VosApi::class.java) api.post(builder).enqueue(object : Callback<Void> { override fun onResponse(call: Call<Void>, response: Response<Void>) { val snackbarView = [email protected]<View>(R.id.container) when (response.code()) { 200 -> Snackbar.make(snackbarView, getString(R.string.sent_succesfull), Snackbar.LENGTH_LONG).show() 404 -> Snackbar.make(snackbarView, R.string.wrong_data, Snackbar.LENGTH_LONG).show() else -> Snackbar.make(snackbarView, getString(R.string.problem_with_sending, Integer.toString(response.code())), Snackbar.LENGTH_LONG).show() } MapManager.instance.update() } override fun onFailure(call: Call<Void>, t: Throwable) { t.sendWithAcra() val snackbarView = [email protected]<View>(R.id.container) Snackbar.make(snackbarView, getString(R.string.problem_with_sending, t.toString()), Snackbar.LENGTH_LONG).show() } }) } session = null } }) .create() session!!.start() } }) return spotButton } fun setupFollowButton(v: View): FloatingActionButton { val followButton = v.findViewById<FloatingActionButton>(R.id.fab_follow) followButton.setOnClickListener(object : View.OnClickListener { var session: MovementManager.FollowSession? = null override fun onClick(view: View) { val v = getView() val followButton = v!!.findViewById<FloatingActionButton>(R.id.fab_follow) /*--- Hide the menu ---*/ val menu = v.findViewById<FloatingActionMenu>(R.id.fab_menu) /** * TODO: use color to identify follow state? */ if (session != null) { // followButton.setColorNormal(Color.parseColor("#DA4336")); followButton.labelText = getString(R.string.follow_me) session!!.end() session = null } else { menu.close(true) //followButton.setColorNormal(Color.parseColor("#5cd65c")); followButton.labelText = [email protected](R.string.stop_following) session = movementManager!!.newSession(jotiMap!!,jotiMap!!.previousCameraPosition, JappPreferences.followZoom, JappPreferences.followAngleOfAttack) } } }) return followButton } private fun setupPinButton(v: View): FloatingActionButton { val pinButton = v.findViewById<FloatingActionButton>(R.id.fab_mark) pinButton.setOnClickListener(object : View.OnClickListener { var session: PinningSession? = null override fun onClick(view: View) { val v = getView() val menu = v!!.findViewById<FloatingActionMenu>(R.id.fab_menu) if (session != null) { /*--- Show the menu ---*/ menu.showMenu(true) session!!.end() session = null } else { /*--- Hide the menu ---*/ menu.hideMenu(true) session = PinningSession.Builder() .setJotiMap(jotiMap) .setCallback(object : PinningSession.OnPinningCompletedCallback{ override fun onPinningCompleted(pin: Pin?) { if (pin != null) { pinningManager.add(pin) } val menu = getView()!!.findViewById<FloatingActionMenu>(R.id.fab_menu) menu.showMenu(true) session!!.end() session = null } }) .setTargetView([email protected](R.id.container)) .setDialogContext([email protected]) .create() session!!.start() } } }) return pinButton } private fun setupNavigationButton(v: View): FloatingActionButton { val navigationButton = v.findViewById<FloatingActionButton>(R.id.fab_nav) navigationButton.setOnClickListener(object : View.OnClickListener { var session: NavigationSession? = null override fun onClick(view: View) { val v = getView() val menu = v!!.findViewById<FloatingActionMenu>(R.id.fab_menu) if (session != null) { /*--- Show the menu ---*/ menu.showMenu(true) session!!.end() session = null } else { /*--- Hide the menu ---*/ menu.hideMenu(true) session = NavigationSession.Builder() .setJotiMap(jotiMap) .setDialogContext(v.context) .setTargetView(v) .setCallback(object : NavigationSession.OnNavigationCompletedCallback { override fun onNavigationCompleted(navigateTo: LatLng?, toNavigationPhone: Boolean) { val menu = getView()!!.findViewById<FloatingActionMenu>(R.id.fab_menu) menu.showMenu(true) session!!.end() session = null if (navigateTo != null) { if (!toNavigationPhone) { try { when (JappPreferences.navigationApp()) { JappPreferences.NavigationApp.GoogleMaps -> { val uristr = getString(R.string.google_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude)) val gmmIntentUri = Uri.parse(uristr) val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri) mapIntent.setPackage("com.google.android.apps.maps") startActivity(mapIntent) } JappPreferences.NavigationApp.Waze -> { val uri = getString(R.string.waze_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude)) startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(uri))) } JappPreferences.NavigationApp.OSMAnd -> { val osmuri = getString(R.string.osmand_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude)) startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(osmuri))) } JappPreferences.NavigationApp.OSMAndWalk -> { val osmuriwalk = getString(R.string.osmandwalk_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude)) startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(osmuriwalk))) } JappPreferences.NavigationApp.Geo -> { val geouri = getString(R.string.geo_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude)) startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(geouri))) } } } catch (e: ActivityNotFoundException) { println(e.toString()) e.sendWithAcra() val snackbarView = [email protected]<View>(R.id.container) Snackbar.make(snackbarView, getString(R.string.navigation_app_not_installed, JappPreferences.navigationApp().toString()), Snackbar.LENGTH_LONG).show() } } else { val id = JappPreferences.accountId if (id >= 0) { val autoApi = Japp.getApi(AutoApi::class.java) autoApi.getInfoById(JappPreferences.accountKey, id).enqueue(object : Callback<AutoInzittendeInfo> { override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) { if (response.code() == 200) { val autoInfo = response.body() if (autoInfo != null) { val auto = autoInfo.autoEigenaar!! AutoSocketHandler.location(Location(navigateTo, auto, JappPreferences.accountUsername)) } } if (response.code() == 404) { val snackbarView = [email protected]<View>(R.id.container) Snackbar.make(snackbarView, getString(R.string.fout_not_in_car), Snackbar.LENGTH_LONG).show() } } override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) { t.sendWithAcra() } }) } } } } }).create() session?.start() } } }) return navigationButton } private fun setupHuntButton(v: View): FloatingActionButton { val huntButton = v.findViewById<FloatingActionButton>(R.id.fab_hunt) huntButton.setOnClickListener(object : View.OnClickListener { override fun onClick(view: View) { val session: SightingSession /*--- Hide the menu ---*/ val v = getView() val menu = v!!.findViewById<FloatingActionMenu>(R.id.fab_menu) menu.hideMenu(true) /*--- Build a SightingSession and start it ---*/ session = SightingSession.Builder() .setType(SightingSession.SIGHT_HUNT) .setGoogleMap(jotiMap) .setTargetView([email protected](R.id.container)) .setDialogContext([email protected]) .setOnSightingCompletedCallback(object: SightingSession.OnSightingCompletedCallback{ override fun onSightingCompleted(chosen: LatLng?, deelgebied: Deelgebied?, optionalInfo: String?) { /*--- Show the menu ---*/ val menu = getView()!!.findViewById<FloatingActionMenu>(R.id.fab_menu) menu.showMenu(true) if (chosen != null) { /*--- Construct a JSON string with the data ---*/ val builder = VosPostBody.default builder.setIcon(SightingIcon.HUNT) builder.setLatLng(chosen) builder.setTeam(deelgebied?.name?.substring(0, 1)?:"x") builder.setInfo(optionalInfo) val api = Japp.getApi(VosApi::class.java) api.post(builder).enqueue(object : Callback<Void> { override fun onResponse(call: Call<Void>, response: Response<Void>) { val snackbarView = [email protected]<View>(R.id.container) when (response.code()) { 200 -> Snackbar.make(snackbarView, R.string.sent_succesfull, Snackbar.LENGTH_LONG).show() 404 -> Snackbar.make(snackbarView, getString(R.string.wrong_data), Snackbar.LENGTH_LONG).show() else -> Snackbar.make(snackbarView, getString(R.string.problem_sending, Integer.toString(response.code())), Snackbar.LENGTH_LONG).show() } } override fun onFailure(call: Call<Void>, t: Throwable) { val snackbarView = [email protected]<View>(R.id.container) Snackbar.make(snackbarView, getString(R.string.problem_sending, t.toString()), Snackbar.LENGTH_LONG).show() t.sendWithAcra() } }) } } }) .create() session.start() } }) return huntButton } companion object { val TAG = "JappMapFragment" private val BUNDLE_MAP = "BUNDLE_MAP" private val BUNDLE_OSM_ACTIVE = "BUNDLE_OSM_ACTIVE_B" private val OSM_ZOOM = "OSM_ZOOM" private val OSM_LAT = "OSM_LAT" private val OSM_LNG = "OSM_LNG" private val OSM_OR = "OSM_OR" private val OSM_BUNDLE = "OSM_BUNDLE" val REQUEST_CHECK_SETTINGS = 32 } }
apache-2.0
e79376536a810d75f766e745619ce612
46.657518
204
0.539074
5.843014
false
false
false
false
vincentvalenlee/nineshop
src/main/kotlin/org/open/openstore/file/internal/AbstractFileName.kt
1
8434
package org.open.openstore.file.internal import org.open.openstore.file.FilePlatform import org.open.openstore.file.FileType import org.open.openstore.file.IFileName import org.open.openstore.file.NameScope /** * 默认的文件名实现 */ abstract class AbstractFileName(private val scheme: String, private var absPath:String?, private var type:FileType): IFileName { private var uri: String? = null private var baseName: String? = null private var rootUri: String? = null private var extension: String? = null private var decodedAbsPath: String? = null private var key: String? = null init { absPath?.let { if (it.isNotEmpty()) { if (it.length > 1 && it.endsWith("/")) { this.absPath = it.substring(0, it.length - 1) } else { this.absPath = it } } else { this.absPath = IFileName.ROOT_PATH } } } override fun equals(o: Any?): Boolean { if (this === o) { return true } if (o == null || javaClass != o.javaClass) { return false } val that = o as AbstractFileName? return getKey() == that!!.getKey() } override fun hashCode(): Int { return getKey().hashCode() } override operator fun compareTo(obj: IFileName): Int { return getKey().compareTo((obj as AbstractFileName)?.getKey()) } override fun toString(): String { return getURI() } /** * 创建名称实例的工厂模板方法 */ abstract fun createName(absolutePath: String, fileType: FileType): IFileName /** * 为此文件名实例构建根URI的模板方法,root URI不以分隔符结尾 */ protected abstract fun appendRootUri(buffer: StringBuilder, addPassword: Boolean) override fun getBaseName(): String { if (baseName == null) { val idx = getPath().lastIndexOf(IFileName.SEPARATOR_CHAR) if (idx == -1) { baseName = getPath() } else { baseName = getPath().substring(idx + 1) } } return baseName!! } override fun getPath(): String { if (FilePlatform.URL_STYPE) { return absPath + getUriTrailer() } return absPath!! } protected fun getUriTrailer(): String { return if (getType().hasChildren()) "/" else "" } /** * 获取编码后的path */ fun getPathDecoded(): String { if (decodedAbsPath == null) { decodedAbsPath = FilePlatform.UriParser.decode(getPath()) } return decodedAbsPath!! } override fun getParent(): IFileName { val parentPath: String val idx = getPath().lastIndexOf(IFileName.SEPARATOR_CHAR) if (idx == -1 || idx == getPath().length - 1) { // No parent return IFileName.NO_NAME } else if (idx == 0) { // Root is the parent parentPath = IFileName.SEPARATOR } else { parentPath = getPath().substring(0, idx) } return createName(parentPath, FileType.FOLDER) } override fun getRoot(): IFileName { var root: IFileName = this while (root.getParent() != IFileName.NO_NAME) { root = root.getParent() } return root } override fun getScheme(): String { return scheme } override fun getURI(): String { if (uri == null) { uri = createURI() } return uri!! } protected fun createURI(): String { return createURI(false, true) } private fun getKey(): String { if (key == null) { key = getURI() } return key!! } override fun getFriendlyURI(): String { return createURI(false, false) } private fun createURI(useAbsolutePath: Boolean, usePassword: Boolean): String { val buffer = StringBuilder() appendRootUri(buffer, usePassword) buffer.append(if (useAbsolutePath) absPath else getPath()) return buffer.toString() } /** * 将指定文件名转换为相对此文件名的相对名称 */ override fun getRelativeName(name: IFileName): String { val path = name.getPath() // Calculate the common prefix val basePathLen = getPath().length val pathLen = path.length // Deal with root if (basePathLen == 1 && pathLen == 1) { return "." } else if (basePathLen == 1) { return path.substring(1) } val maxlen = Math.min(basePathLen, pathLen) var pos = 0 while (pos < maxlen && getPath()[pos] == path.get(pos)) { pos++ } if (pos == basePathLen && pos == pathLen) { // Same names return "." } else if (pos == basePathLen && pos < pathLen && path.get(pos) == IFileName.SEPARATOR_CHAR) { // A descendent of the base path return path.substring(pos + 1) } // Strip the common prefix off the path val buffer = StringBuilder() if (pathLen > 1 && (pos < pathLen || getPath()[pos] != IFileName.SEPARATOR_CHAR)) { // Not a direct ancestor, need to back up pos = getPath().lastIndexOf(IFileName.SEPARATOR_CHAR, pos) buffer.append(path.substring(pos)) } // Prepend a '../' for each element in the base path past the common // prefix buffer.insert(0, "..") pos = getPath().indexOf(IFileName.SEPARATOR_CHAR, pos + 1) while (pos != -1) { buffer.insert(0, "../") pos = getPath().indexOf(IFileName.SEPARATOR_CHAR, pos + 1) } return buffer.toString() } override fun getRootURI(): String { if (rootUri == null) { val buffer = StringBuilder() appendRootUri(buffer, true) buffer.append(IFileName.SEPARATOR_CHAR) rootUri = buffer.toString().intern() } return rootUri!! } override fun getDepth(): Int { val len = getPath().length if (len == 0 || len == 1 && getPath()[0] == IFileName.SEPARATOR_CHAR) { return 0 } var depth = 1 var pos = 0 while (pos > -1 && pos < len) { pos = getPath().indexOf(IFileName.SEPARATOR_CHAR, pos + 1) depth++ } return depth } override fun getExtension(): String { if (extension == null) { getBaseName() val pos = baseName!!.lastIndexOf('.') // if ((pos == -1) || (pos == baseName.length() - 1)) // [email protected]: Review of patch from [email protected] // do not treat filenames like // .bashrc c:\windows\.java c:\windows\.javaws c:\windows\.jedit c:\windows\.appletviewer // as extension if (pos < 1 || pos == baseName!!.length - 1) { // No extension extension = "" } else { extension = baseName!!.substring(pos + 1).intern() } } return extension!! } override fun isAncestor(ancestor: IFileName): Boolean { if (!ancestor.getRootURI().equals(getRootURI())) { return false } return IFileName.checkName(ancestor.getPath(), getPath(), NameScope.DESCENDENT) } override fun isDescendent(descendent: IFileName, scope: NameScope): Boolean { if (!descendent.getRootURI().equals(getRootURI())) { return false } return IFileName.checkName(getPath(), descendent.getPath(), scope) } override fun isFile(): Boolean { // Use equals instead of == to avoid any class loader worries. return FileType.FILE.equals(this.getType()) } override fun getType(): FileType { return type } /** * 文件名的状态可设置 */ fun setType(type:FileType) { if (type != FileType.FOLDER && type != FileType.FILE && type != FileType.FILE_OR_FOLDER && type != FileType.LINK) { throw org.open.openstore.file.FileSystemException("filename-type.error") } this.type = type } }
gpl-3.0
b7fb1b0be3120f8c98d5be6577664947
27.057627
128
0.542412
4.492942
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/OVR_multiview.kt
1
5148
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val OVR_multiview = "OVRMultiview".nativeClassGL("OVR_multiview", postfix = OVR) { documentation = """ Native bindings to the $registryLink extension. The method of stereo rendering supported in OpenGL is currently achieved by rendering to the two eye buffers sequentially. This typically incurs double the application and driver overhead, despite the fact that the command streams and render states are almost identical. This extension seeks to address the inefficiency of sequential multiview rendering by adding a means to render to multiple elements of a 2D texture array simultaneously. In multiview rendering, draw calls are instanced into each corresponding element of the texture array. The vertex program uses a new ViewID variable to compute per-view values, typically the vertex position and view-dependent variables like reflection. The formulation of this extension is high level in order to allow implementation freedom. On existing hardware, applications and drivers can realize the benefits of a single scene traversal, even if all GPU work is fully duplicated per-view. But future support could enable simultaneous rendering via multi-GPU, tile-based architectures could sort geometry into tiles for multiple views in a single pass, and the implementation could even choose to interleave at the fragment level for better texture cache utilization and more coherent fragment shader branching. The most obvious use case in this model is to support two simultaneous views: one view for each eye. However, we also anticipate a usage where two views are rendered per eye, where one has a wide field of view and the other has a narrow one. The nature of wide field of view planar projection is that the sample density can become unacceptably low in the view direction. By rendering two inset eye views per eye, we can get the required sample density in the center of projection without wasting samples, memory, and time by oversampling in the periphery. Requires ${GL30.core}. """ IntConstant( "Accepted by the {@code pname} parameter of GetFramebufferAttachmentParameteriv.", "FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR"..0x9630, "FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR"..0x9632 ) IntConstant( "Accepted by the {@code pname} parameter of GetIntegerv.", "MAX_VIEWS_OVR"..0x9631 ) IntConstant( "Returned by CheckFramebufferStatus.", "FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR"..0x9633 ) val FramebufferTextureLayer = GL30["FramebufferTextureLayer"] void( "FramebufferTextureMultiviewOVR", """ Operates similarly to GL30#FramebufferTextureLayer(), except that {@code baseViewIndex} and {@code numViews} selects a range of texture array elements that will be targeted when rendering. The command ${codeBlock(""" View( uint id );""")} does not exist in the GL, but is used here to describe the multi-view functionality in this section. The effect of this hypothetical function is to set the value of the shader built-in input uint {@code gl_ViewID_OVR}. When multi-view rendering is enabled, drawing commands have the same effect as: ${codeBlock(""" for( int i = 0; i < numViews; i++ ) { FramebufferTextureLayer( target, attachment, texture, level, baseViewIndex + i ); View( i ); &lt;drawing-command&gt; }""")} The result is that every drawing command is broadcast into every active view. The shader uses {@code gl_ViewID_OVR} to compute view dependent outputs. The number of views, as specified by {@code numViews}, must be the same for all framebuffer attachments points where the value of GL30#FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is not GL11#NONE or the framebuffer is incomplete. In this mode there are several restrictions: ${ul( "in vertex shader {@code gl_Position} is the only output that can depend on {@code ViewID}", "no transform feedback", "no tessellation control or evaluation shaders", "no geometry shader", "no timer query", "occlusion query results must be between max and sum of per-view queries, inclusive" )} <h5>Errors</h5> $INVALID_OPERATION is generated by FramebufferTextureMultiviewOVR if target is GL30#READ_FRAMEBUFFER. $INVALID_VALUE is generated by FramebufferTextureMultiviewOVR if {@code numViews} is less than 1, if {@code numViews} is more than #MAX_VIEWS_OVR or if ${code("(baseViewIndex + numViews)")} exceeds GL30#MAX_ARRAY_TEXTURE_LAYERS. $INVALID_OPERATION is generated if a rendering command is issued and the number of views in the current draw framebuffer is not equal to the number of views declared in the currently bound program. """, FramebufferTextureLayer["target"], FramebufferTextureLayer["attachment"], FramebufferTextureLayer["texture"], FramebufferTextureLayer["level"], GLint.IN("baseViewIndex", "the base framebuffer texture layer index"), GLsizei.IN("numViews", "the number of views to target when rendering") ) }
bsd-3-clause
22d180eef822d550049d53b2e97116d8
46.666667
159
0.766511
4.30795
false
false
false
false
Snawoot/jsonsurfer
JSONReader.kt
1
2312
import org.json.simple.parser.ContentHandler import java.util.Stack enum class ContainerType { ObjectContainer, ArrayContainer } enum class ValueType { TrueValue, FalseValue, NullValue, StringValue, NumberValue } interface PassJSONValue { fun passJSONValue(path: String, valtype: ValueType, strval: String) : Boolean } class JSONReader(val cb: PassJSONValue): ContentHandler { val ctx = Stack<Triple<ContainerType,Long,String>>() fun pushResult(t: ValueType, e: String): Boolean { cb.passJSONValue(getPath(), t, e) return true; } fun getPath() : String { val paths = arrayListOf<String>() for (c in ctx) { val p = when(c.first) { ContainerType.ObjectContainer -> c.third ContainerType.ArrayContainer -> (c.second-1).toString() } paths.add(p) } return paths.joinToString(".") } fun incStack() { if (!ctx.isEmpty()) { val (t, i, k) = ctx.pop() val ni = when(t) { ContainerType.ArrayContainer -> i + 1 ContainerType.ObjectContainer -> i } ctx.push(Triple(t,ni,k)) } } override fun startObject() : Boolean { incStack() ctx.push(Triple(ContainerType.ObjectContainer, 0, "")) return true; } override fun startObjectEntry(name: String) : Boolean { val (t, i, k) = ctx.pop() ctx.push(Triple(t,i,name)) return true; } override fun endObject() : Boolean { ctx.pop() return true; } override fun startArray() : Boolean { incStack() ctx.push(Triple(ContainerType.ArrayContainer, 0, "")) return true; } override fun endArray() : Boolean { ctx.pop() return true; } override fun primitive(value: Any?) : Boolean { incStack() val (valtype, strval) = when(value) { is String -> Pair(ValueType.StringValue, value) is Number -> Pair(ValueType.NumberValue, value.toString()) is Boolean -> Pair(if (value) ValueType.TrueValue else ValueType.FalseValue, value.toString()) null -> Pair(ValueType.NullValue, "null") else -> { throw Exception("Unknown type of value ${value.toString()}") } } return pushResult(valtype, strval) } override fun endJSON() { } override fun startJSON() { } override fun endObjectEntry() : Boolean { return true; } }
mit
a757ab7442d7dc5e519f445d87027814
23.595745
100
0.635381
3.821488
false
false
false
false
mplatvoet/progress
projects/core/src/test/kotlin/example/default.kt
1
2856
/* * Copyright (c) 2015 Mark Platvoet<[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package example.default import nl.komponents.progress.OutOfRangeException import nl.komponents.progress.Progress import java.text.DecimalFormat import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty fun main(args: Array<String>) { val masterControl = Progress.containerControl() masterControl.progress.update { println("${value.percentage}%") } val firstChild = masterControl.child(0.1) val secondChild = masterControl.containerChild(5.0) val secondChildFirstChild = secondChild.child() val secondChildSecondChild = secondChild.child() val thirdChild = masterControl.child() val fourthChild = masterControl.child(2.0) firstChild.value = 0.25 firstChild.value = 0.50 firstChild.value = 0.75 firstChild.value = 1.0 secondChildFirstChild.markAsDone() secondChildSecondChild.value = 0.5 secondChildSecondChild.value = 1.0 thirdChild.value = 0.25 thirdChild.value = 0.50 thirdChild.value = 0.75 thirdChild.value = 1.0 fourthChild.value = 0.25 fourthChild.value = 0.50 fourthChild.value = 0.75 fourthChild.value = 1.0 } private val percentageFormat by ThreadLocalVal { DecimalFormat("##0.00") } val Double.percentage: String get() = if (this in (0.0..1.0)) percentageFormat.format(this * 100) else throw OutOfRangeException("[$this] must be within bounds (0.0 .. 1.0)") private class ThreadLocalVal<T>(private val initializer: () -> T) : ReadOnlyProperty<Any?, T> { private val threadLocal = object : ThreadLocal<T>() { override fun initialValue(): T = initializer() } public override fun getValue(thisRef: Any?, property: KProperty<*>): T = threadLocal.get() }
mit
3085c2fcd2837108c53283eb0e321048
36.090909
148
0.732493
4.301205
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/editor/completion/LuaCompletionContributor.kt
2
7731
/* * Copyright (c) 2017. tangzx([email protected]) * * 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.tang.intellij.lua.editor.completion import com.intellij.codeInsight.completion.* import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.icons.AllIcons import com.intellij.lang.findUsages.LanguageFindUsages import com.intellij.patterns.PatternCondition import com.intellij.patterns.PlatformPatterns.psiElement import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.tree.TokenSet import com.intellij.util.ProcessingContext import com.tang.intellij.lua.comment.LuaCommentUtil import com.tang.intellij.lua.lang.LuaIcons import com.tang.intellij.lua.lang.LuaLanguage import com.tang.intellij.lua.project.LuaSettings import com.tang.intellij.lua.psi.* import com.tang.intellij.lua.refactoring.LuaRefactoringUtil /** * Created by tangzx on 2016/11/27. */ class LuaCompletionContributor : CompletionContributor() { private var suggestWords = true init { //可以override extend(CompletionType.BASIC, SHOW_OVERRIDE, OverrideCompletionProvider()) extend(CompletionType.BASIC, IN_CLASS_METHOD, SuggestSelfMemberProvider()) //提示属性, 提示方法 extend(CompletionType.BASIC, SHOW_CLASS_FIELD, ClassMemberCompletionProvider()) extend(CompletionType.BASIC, SHOW_REQUIRE_PATH, RequirePathCompletionProvider()) extend(CompletionType.BASIC, LuaStringArgHistoryProvider.STRING_ARG, LuaStringArgHistoryProvider()) //提示全局函数,local变量,local函数 extend(CompletionType.BASIC, IN_NAME_EXPR, LocalAndGlobalCompletionProvider(LocalAndGlobalCompletionProvider.ALL)) extend(CompletionType.BASIC, IN_CLASS_METHOD_NAME, LocalAndGlobalCompletionProvider(LocalAndGlobalCompletionProvider.VARS)) extend(CompletionType.BASIC, GOTO, object : CompletionProvider<CompletionParameters>(){ override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, resultSet: CompletionResultSet) { LuaPsiTreeUtil.walkUpLabel(parameters.position) { val name = it.name if (name != null) { resultSet.addElement(LookupElementBuilder.create(name).withIcon(AllIcons.Actions.Rollback)) } return@walkUpLabel true } resultSet.stopHere() } }) extend(CompletionType.BASIC, psiElement(LuaTypes.ID).withParent(LuaNameDef::class.java), SuggestLocalNameProvider()) extend(CompletionType.BASIC, IN_TABLE_FIELD, TableCompletionProvider()) extend(CompletionType.BASIC, ATTRIBUTE, AttributeCompletionProvider()) } override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) { val session = CompletionSession(parameters, result) parameters.editor.putUserData(CompletionSession.KEY, session) super.fillCompletionVariants(parameters, result) if (LuaSettings.instance.isShowWordsInFile && suggestWords && session.isSuggestWords && !result.isStopped) { suggestWordsInFile(parameters) } } override fun beforeCompletion(context: CompletionInitializationContext) { suggestWords = true val file = context.file if (file is LuaPsiFile) { val element = file.findElementAt(context.caret.offset - 1) if (element != null) { if (element.parent is LuaLabelStat) { suggestWords = false context.dummyIdentifier = "" } else if (!LuaCommentUtil.isComment(element)) { val type = element.node.elementType if (type in IGNORE_SET) { suggestWords = false context.dummyIdentifier = "" } } } } } companion object { private val IGNORE_SET = TokenSet.create(LuaTypes.STRING, LuaTypes.NUMBER, LuaTypes.CONCAT) private val SHOW_CLASS_FIELD = psiElement(LuaTypes.ID) .withParent(LuaIndexExpr::class.java) private val IN_FUNC_NAME = psiElement(LuaTypes.ID) .withParent(LuaIndexExpr::class.java) .inside(LuaClassMethodName::class.java) private val AFTER_FUNCTION = psiElement() .afterLeaf(psiElement(LuaTypes.FUNCTION)) private val IN_CLASS_METHOD_NAME = psiElement().andOr(IN_FUNC_NAME, AFTER_FUNCTION) private val IN_NAME_EXPR = psiElement(LuaTypes.ID) .withParent(LuaNameExpr::class.java) private val SHOW_OVERRIDE = psiElement() .withParent(LuaClassMethodName::class.java) private val IN_CLASS_METHOD = psiElement(LuaTypes.ID) .withParent(LuaNameExpr::class.java) .inside(LuaClassMethodDef::class.java) private val SHOW_REQUIRE_PATH = psiElement(LuaTypes.STRING) .withParent( psiElement(LuaTypes.LITERAL_EXPR).withParent( psiElement(LuaArgs::class.java).afterSibling( psiElement().with(RequireLikePatternCondition()) ) ) ) private val GOTO = psiElement(LuaTypes.ID).withParent(LuaGotoStat::class.java) private val IN_TABLE_FIELD = psiElement().andOr( psiElement().withParent( psiElement(LuaTypes.NAME_EXPR).withParent(LuaTableField::class.java) ), psiElement(LuaTypes.ID).withParent(LuaTableField::class.java) ) private val ATTRIBUTE = psiElement(LuaTypes.ID).withParent(LuaAttribute::class.java) private fun suggestWordsInFile(parameters: CompletionParameters) { val session = CompletionSession[parameters] val originalPosition = parameters.originalPosition if (originalPosition != null) session.addWord(originalPosition.text) val wordsScanner = LanguageFindUsages.INSTANCE.forLanguage(LuaLanguage.INSTANCE).wordsScanner wordsScanner?.processWords(parameters.editor.document.charsSequence) { val word = it.baseText.subSequence(it.start, it.end).toString() if (word.length > 2 && LuaRefactoringUtil.isLuaIdentifier(word) && session.addWord(word)) { session.resultSet.addElement(PrioritizedLookupElement.withPriority(LookupElementBuilder .create(word) .withIcon(LuaIcons.WORD), -1.0) ) } true } } } } class RequireLikePatternCondition : PatternCondition<PsiElement>("requireLike"){ override fun accepts(psi: PsiElement, context: ProcessingContext?): Boolean { val name = (psi as? PsiNamedElement)?.name return if (name != null) LuaSettings.isRequireLikeFunctionName(name) else false } }
apache-2.0
573942714642e86a21814ee5187ff9c5
42.704545
135
0.657002
4.990915
false
false
false
false
konrad-jamrozik/utilities
src/main/kotlin/com/konradjamrozik/IterableExtensions.kt
1
2253
// Author: Konrad Jamrozik, github.com/konrad-jamrozik package com.konradjamrozik import com.google.common.collect.ArrayListMultimap import com.google.common.collect.LinkedListMultimap /** * @return * Map of counts of how many times given elements appears in this receiver [Iterable]. */ val <T> Iterable<T>.frequencies: Map<T, Int> get() { val grouped: Map<T, List<T>> = this.groupBy { it } val frequencies: Map<T, Int> = grouped.mapValues { it.value.size } return frequencies } /** * @return * A map from unique items to the index of first element in the receiver [Iterable] from which given unique item was * obtained. The indexing starts at 0. * * @param extractItems * A function that is applied to each element of the receiver iterable, converting it to an iterable of items. * * @param extractUniqueString * A function used to remove duplicates from all the items extracted from receiver iterable using [extractItems]. * */ fun <T, TItem> Iterable<T>.uniqueItemsWithFirstOccurrenceIndex( extractItems: (T) -> Iterable<TItem>, extractUniqueString: (TItem) -> String ): Map<TItem, Int> { return this.foldIndexed( mapOf<String, Pair<TItem, Int>>(), { index, accumulatedMap, elem -> val uniqueStringsToItemsWithIndexes: Map<String, Pair<TItem, Int>> = extractItems(elem).associate { Pair( extractUniqueString(it), Pair(it, index + 1) ) } val newUniqueStrings = uniqueStringsToItemsWithIndexes.keys.subtract(accumulatedMap.keys) val uniqueStringsToNewItemsWithIndexes = uniqueStringsToItemsWithIndexes.filterKeys { it in newUniqueStrings } accumulatedMap.plus(uniqueStringsToNewItemsWithIndexes) }).map { it.value }.toMap() } inline fun <T, K, V> Iterable<T>.associateMany(transform: (T) -> Pair<K, V>): Map<K, Iterable<V>> { val multimap = ArrayListMultimap.create<K, V>() this.forEach { val pair = transform(it); multimap.put(pair.first, pair.second) } return multimap.asMap() } fun <K, V> Iterable<Map<K, Iterable<V>>>.flatten(): Map<K, Iterable<V>> { val multimap = LinkedListMultimap.create<K, V>() this.forEach { map -> map.forEach { multimap.putAll(it.key, it.value) } } return multimap.asMap() }
mit
858219af4804bfd739fea1cba66c2a63
32.147059
118
0.703506
3.812183
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/vfs/TarGzArchive.kt
1
928
package org.jetbrains.haskell.vfs import java.io.File import java.io.BufferedInputStream import java.io.InputStream import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream import org.apache.commons.compress.archivers.tar.TarArchiveInputStream import java.io.FileInputStream import java.util.ArrayList /** * Created by atsky on 12/12/14. */ class TarGzArchive(val file : File) { val filesList : List<String> init { val bin = BufferedInputStream(FileInputStream(file)) val gzIn = GzipCompressorInputStream(bin); val tarArchiveInputStream = TarArchiveInputStream(gzIn) var file = ArrayList<String>() while (true) { val entry = tarArchiveInputStream.getNextTarEntry(); if (entry == null) { break } file.add(entry.getName()) } filesList = file; bin.close() } }
apache-2.0
e18452a160e2a259ad6fc9387f6baf14
23.447368
77
0.664871
4.483092
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/ui/view/CommonPopupWindow.kt
1
2487
package com.intfocus.template.ui.view import android.app.Activity import android.graphics.drawable.BitmapDrawable import android.support.v4.content.ContextCompat import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.PopupWindow import android.widget.TextView import com.intfocus.template.R /** * Created by CANC on 2017/8/1. */ class CommonPopupWindow : PopupWindow() { lateinit var conentView: View lateinit var tvBtn1: TextView lateinit var tvBtn2: TextView lateinit var minePop: PopupWindow /** * */ fun showPopupWindow(activity: Activity, str1: String, colorId1: Int, str2: String, colorId2: Int, lisenter: ButtonLisenter) { val inflater = LayoutInflater.from(activity) conentView = inflater.inflate(R.layout.popup_common, null) tvBtn1 = conentView.findViewById(R.id.tv_btn1) tvBtn2 = conentView.findViewById(R.id.tv_btn2) tvBtn1.text = str1 tvBtn2.text = str2 tvBtn1.setTextColor(ContextCompat.getColor(activity, colorId1)) tvBtn2.setTextColor(ContextCompat.getColor(activity, colorId2)) // tvBtn1.setOnClickListener { lisenter.btn1Click() minePop.dismiss() } tvBtn2.setOnClickListener { lisenter.btn2Click() minePop.dismiss() } minePop = PopupWindow(conentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) minePop.isFocusable = true// 取得焦点 //注意 要是点击外部空白处弹框消息 那么必须给弹框设置一个背景色 不然是不起作用的 minePop.setBackgroundDrawable(BitmapDrawable()) val params = activity.window.attributes params.alpha = 0.7f activity.window.attributes = params //点击外部消失 minePop.isOutsideTouchable = true //设置可以点击 minePop.isTouchable = true //进入退出的动画 minePop.animationStyle = R.style.anim_popup_bottombar minePop.showAtLocation(conentView, Gravity.BOTTOM, 0, 0) minePop.setOnDismissListener { val paramsa = activity.window.attributes paramsa.alpha = 1f activity.window.attributes = paramsa } } interface ButtonLisenter { fun btn1Click() fun btn2Click() } }
gpl-3.0
f1c58019f8b4d8d1d681974be2fec39a
30.56
129
0.665822
4.174603
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/purchase_notification/interactor/PurchaseReminderInteractor.kt
2
2196
package org.stepik.android.domain.purchase_notification.interactor import io.reactivex.Completable import org.stepic.droid.util.AppConstants import org.stepic.droid.util.DateTimeHelper import org.stepik.android.data.purchase_notification.model.PurchaseNotificationScheduled import org.stepik.android.domain.purchase_notification.repository.PurchaseNotificationRepository import org.stepik.android.view.purchase_notification.notification.PurchaseNotificationDelegate import java.util.Calendar import javax.inject.Inject class PurchaseReminderInteractor @Inject constructor( private val purchaseNotificationDelegate: PurchaseNotificationDelegate, private val purchaseNotificationRepository: PurchaseNotificationRepository ) { companion object { private const val MILLIS_IN_1_HOUR = 3600000L } fun savePurchaseNotificationSchedule(courseId: Long): Completable = purchaseNotificationRepository .getClosestTimeStamp() .flatMapCompletable { timeStamp -> val baseTime = if (timeStamp > DateTimeHelper.nowUtc()) { timeStamp } else { DateTimeHelper.nowUtc() } purchaseNotificationRepository.savePurchaseNotificationSchedule( PurchaseNotificationScheduled(courseId, calculateScheduleOffset(baseTime)) ) } .doOnComplete { purchaseNotificationDelegate.schedulePurchaseNotification() } private fun calculateScheduleOffset(timeStamp: Long): Long { val scheduledTime = timeStamp + MILLIS_IN_1_HOUR val calendar = Calendar.getInstance() calendar.timeInMillis = scheduledTime val scheduledHour = calendar.get(Calendar.HOUR_OF_DAY) calendar.set(Calendar.HOUR_OF_DAY, 12) calendar.set(Calendar.MINUTE, 0) calendar.set(Calendar.MILLISECOND, 0) val nowAt12 = calendar.timeInMillis return when { scheduledHour < 12 -> nowAt12 scheduledHour >= 21 -> nowAt12 + AppConstants.MILLIS_IN_24HOURS else -> scheduledTime } } }
apache-2.0
0453c49cb62765f8ceef14d74c2ed5ac
38.232143
96
0.688525
5.49
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/personal_deadlines/resolver/DeadlinesResolverImpl.kt
1
4149
package org.stepik.android.domain.personal_deadlines.resolver import io.reactivex.Single import org.stepic.droid.util.AppConstants import ru.nobird.android.core.model.mapToLongArray import org.stepik.android.domain.course.repository.CourseRepository import org.stepik.android.domain.lesson.repository.LessonRepository import org.stepik.android.domain.personal_deadlines.model.Deadline import org.stepik.android.domain.personal_deadlines.model.DeadlinesWrapper import org.stepik.android.domain.personal_deadlines.model.LearningRate import org.stepik.android.domain.section.repository.SectionRepository import org.stepik.android.domain.unit.repository.UnitRepository import org.stepik.android.model.Lesson import org.stepik.android.model.Section import org.stepik.android.model.Unit import java.util.Calendar import java.util.Date import javax.inject.Inject class DeadlinesResolverImpl @Inject constructor( private val courseRepository: CourseRepository, private val sectionRepository: SectionRepository, private val unitRepository: UnitRepository, private val lessonRepository: LessonRepository ) : DeadlinesResolver { companion object { private const val DEFAULT_STEP_LENGTH_IN_SECONDS = 60L private const val TIME_MULTIPLIER = 1.3 } override fun calculateDeadlinesForCourse(courseId: Long, learningRate: LearningRate): Single<DeadlinesWrapper> = courseRepository.getCourse(courseId) .flatMapSingle { course -> sectionRepository.getSections(course.sections ?: listOf()) } .flatMap { sections -> val unitIds = sections .flatMap(Section::units) .fold(listOf(), List<Long>::plus) unitRepository .getUnits(unitIds) .map { units -> sections to units } } .flatMap { (sections, units) -> val lessonIds = units.mapToLongArray(Unit::lesson) lessonRepository .getLessons(*lessonIds) .map { lessons -> sections.map { section -> getTimeToCompleteForSection(section, units, lessons) } } } .map { val offset = Calendar.getInstance() offset.add(Calendar.HOUR_OF_DAY, 24) offset.set(Calendar.HOUR_OF_DAY, 0) offset.set(Calendar.MINUTE, 0) val deadlines = it.map { (sectionId, timeToComplete) -> val deadlineDate = getDeadlineDate(offset, timeToComplete, learningRate) Deadline(sectionId, deadlineDate) } DeadlinesWrapper(courseId, deadlines) } private fun getTimeToCompleteForSection(section: Section, units: List<Unit>, lessons: List<Lesson>): Pair<Long, Long> = section .units .fold(0L) { acc, unitId -> val unit = units.find { it.id == unitId } val timeToComplete: Long = lessons .find { it.id == unit?.lesson } ?.let { lesson -> lesson .timeToComplete .takeIf { it != 0L } ?: lesson.steps.size * DEFAULT_STEP_LENGTH_IN_SECONDS } ?: 0L acc + timeToComplete } .let { section.id to it } private fun getDeadlineDate(calendar: Calendar, timeToComplete: Long, learningRate: LearningRate): Date { val timePerWeek = learningRate.millisPerWeek val time = timeToComplete * 1000 * TIME_MULTIPLIER / timePerWeek * AppConstants.MILLIS_IN_SEVEN_DAYS calendar.timeInMillis += time.toLong() calendar.set(Calendar.HOUR_OF_DAY, 23) calendar.set(Calendar.MINUTE, 59) val date = calendar.time calendar.add(Calendar.MINUTE, 1) // set time at 00:00 of the next day return date } }
apache-2.0
edd9c7897cff9b91299f31a718643d3c
39.291262
123
0.603278
4.97482
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/course_calendar/interactor/CourseCalendarInteractor.kt
1
3416
package org.stepik.android.domain.course_calendar.interactor import android.content.Context import io.reactivex.Completable import io.reactivex.Single import io.reactivex.rxkotlin.toObservable import org.stepic.droid.R import ru.nobird.android.domain.rx.doCompletableOnSuccess import ru.nobird.android.core.model.mapToLongArray import org.stepik.android.domain.calendar.model.CalendarEventData import org.stepik.android.domain.calendar.model.CalendarItem import org.stepik.android.domain.calendar.repository.CalendarRepository import org.stepik.android.domain.course_calendar.model.SectionDateEvent import org.stepik.android.domain.course_calendar.repository.CourseCalendarRepository import org.stepik.android.view.course_content.model.CourseContentItem import org.stepik.android.view.course_content.model.CourseContentSectionDate import javax.inject.Inject class CourseCalendarInteractor @Inject constructor( private val context: Context, private val calendarRepository: CalendarRepository, private val courseCalendarRepository: CourseCalendarRepository ) { fun getCalendarItems(): Single<List<CalendarItem>> = calendarRepository.getCalendarItems() fun exportScheduleToCalendar(courseContentItems: List<CourseContentItem>, calendarItem: CalendarItem): Completable = Single .fromCallable { courseContentItems .filterIsInstance<CourseContentItem.SectionItem>() } .doCompletableOnSuccess(::removeOldSchedule) .flatMapObservable { sectionItems -> sectionItems .flatMap { sectionItem -> sectionItem.dates.map { date -> mapDateToCalendarEventData(sectionItem, date) } } .toObservable() } .flatMapSingle { (sectionId, eventData) -> calendarRepository .saveCalendarEventData(eventData, calendarItem) .map { eventId -> SectionDateEvent(eventId, sectionId) } } .toList() .flatMapCompletable(courseCalendarRepository::saveSectionDateEvents) private fun removeOldSchedule(sectionItems: List<CourseContentItem.SectionItem>): Completable = courseCalendarRepository .getSectionDateEventsByIds(*sectionItems.mapToLongArray { it.section.id }) .flatMapCompletable { dateEvents -> calendarRepository .removeCalendarEventDataByIds(*dateEvents.mapToLongArray(SectionDateEvent::eventId)) // mapToLongArray for varargs .andThen(courseCalendarRepository .removeSectionDateEventsByIds(*dateEvents.mapToLongArray(SectionDateEvent::sectionId))) } private fun mapDateToCalendarEventData( sectionItem: CourseContentItem.SectionItem, date: CourseContentSectionDate ): Pair<Long, CalendarEventData> = sectionItem.section.id to CalendarEventData( title = context .getString( R.string.course_content_calendar_title, sectionItem.section.title, context.getString(date.titleRes) ), date = date.date ) }
apache-2.0
f9f89715ab762ff0379a15a561746642
43.376623
134
0.661885
5.76054
false
false
false
false
soulnothing/HarmonyGen
src/main/kotlin/HarmonyGen/MessageBus/dispatchers.kt
1
3882
package HarmonyGen.MessageBus import HarmonyGen.DB.DBArtist import HarmonyGen.DB.Genre import HarmonyGen.DB.PlayListByMap import HarmonyGen.DB.getDBConn import HarmonyGen.MusicAbstractor.getSimilarArtists import HarmonyGen.Util.ArtistQuery import HarmonyGen.Util.getArtist import HarmonyGen.Util.getQueryBase import HarmonyGen.Util.logger import co.paralleluniverse.kotlin.fiber import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.registerKotlinModule import java.time.OffsetDateTime /** * Created by on 9/6/16. */ data class SimilarPlayListMapping( val artist: DBArtist, val from : String? ) fun dispatchInitializePlayList(event: InitializePlayList, branchDepth: Int = 2) { logger.info("Dispatching initialization of playlist") val rsp = getQueryBase("playlists").get(event.playlist).run<Map<String, Any?>>(getDBConn()) println(rsp) val playlist = PlayListByMap(rsp) val artists = playlist.seedArtists.map { getQueryBase("artists").get(it).run<DBArtist, DBArtist>(getDBConn(), DBArtist::class.java).let { rcrd -> try { rcrd!! } catch (e: NullPointerException) { getSimilarArtists(ArtistQuery.ByMBID(it!!), initiateSimilar = true) } } } val genres = playlist.seedGenres.map { getQueryBase("genres").get(it).run<Genre, Genre>(getDBConn(), Genre::class.java) } val similarMap = mutableMapOf<Int, MutableList<SimilarPlayListMapping>>() for (a in artists) { if (similarMap.containsKey(0)) { similarMap[0]?.add(SimilarPlayListMapping(artist=a, from=null)) } else { similarMap[0] = mutableListOf<SimilarPlayListMapping>(SimilarPlayListMapping(artist=a, from=null)) } similarMap.putAll(getSimilarArtistsRecursive(a.similar!!, a, similarMap, branch = 0)) } logger.debug("Scanned to depths of ${similarMap.keys}") } /** * This is a recursive wrapper around getSimilarArtist. * * Given a list of MusicBrainz identifiers. Taking an inbound similarMap, which * is branch level as key, and a similarmapping as the value. Iterate to match the breakAt points. * * Note we count in computer science/array terms. 0 is the origin point. It will stop when * branch == breakAt. * * This will return the hashmap, and build out a nesting hierarchy. * * **ToDo** * * * This is introducing a side effect, the map is being modified. Make it sanitary and have it only return the map not modify * * Adjust the inbound list to match ArtistQuery * * @see HarmonyGen.MessageBus.SimilarPlayListMapping * @see HarmonyGen.DB.DBArtist * * @param breakAt:Int */ fun getSimilarArtistsRecursive(mbid:List<String>, from: DBArtist, similarMap:MutableMap<Int, MutableList<SimilarPlayListMapping>>, branch: Int = 0, breakAt: Int = 2) : MutableMap<Int, MutableList<SimilarPlayListMapping>>{ logger.info("Beginning to recursively discover similar artists") if (branch == breakAt) return similarMap val artists = mbid.map { getSimilarArtists(ArtistQuery.ByMBID(it), initiateSimilar = true)} for (artist in artists) { if (similarMap.containsKey(branch)) { similarMap[branch]?.add(SimilarPlayListMapping(artist=artist, from=from.id)) } else { similarMap[branch] = mutableListOf(SimilarPlayListMapping(artist=artist, from=from.id)) } val rcrd = getSimilarArtists(ArtistQuery.ByMBID(artist.id!!), initiateSimilar=true ) similarMap.putAll(getSimilarArtistsRecursive(rcrd.similar!!, artist, similarMap, branch=branch+1, breakAt = breakAt)) } return similarMap } fun dispatchGetArtist(event: GetArtist) { fiber { val name = event.artist if (name != null) { var artist = getArtist(ArtistQuery.ByName(name), addIfNotExist = true, populateGenres = true) event.completed = true event.finished = OffsetDateTime.now() updateEvent<GetArtist, GetArtist>(event) } } }
bsd-3-clause
b9be61dbe5b3ccdf402cb24f4603074a
36.699029
165
0.738022
4.031153
false
false
false
false
Heiner1/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralSetUserTimeChangeFlagClear.kt
1
927
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption class DanaRSPacketGeneralSetUserTimeChangeFlagClear( injector: HasAndroidInjector ) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR aapsLogger.debug(LTag.PUMPCOMM, "New message") } override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false } else { aapsLogger.error("Result Error: $result") failed = true } } override val friendlyName: String = "REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR" }
agpl-3.0
af1014f17a1058c70d3df5c87017d458
31
91
0.683927
4.456731
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinTasksPropertyUtils.kt
7
4287
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradleTooling import org.gradle.api.Task import org.gradle.api.file.SourceDirectorySet import org.gradle.api.internal.FactoryNamedDomainObjectContainer import org.gradle.api.plugins.JavaPluginConvention import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.getSourceSetName import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.kotlinPluginWrapper import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.kotlinProjectExtensionClass import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.kotlinSourceSetClass import org.jetbrains.kotlin.idea.projectModel.KotlinTaskProperties import java.io.File data class KotlinTaskPropertiesImpl( override val incremental: Boolean?, override val packagePrefix: String?, override val pureKotlinSourceFolders: List<File>?, override val pluginVersion: String? ) : KotlinTaskProperties { constructor(kotlinTaskProperties: KotlinTaskProperties) : this( kotlinTaskProperties.incremental, kotlinTaskProperties.packagePrefix, kotlinTaskProperties.pureKotlinSourceFolders?.map { it }?.toList(), kotlinTaskProperties.pluginVersion ) } typealias KotlinTaskPropertiesBySourceSet = MutableMap<String, KotlinTaskProperties> private fun Task.getPackagePrefix(): String? { try { val getJavaPackagePrefix = this.javaClass.getMethod("getJavaPackagePrefix") return (getJavaPackagePrefix.invoke(this) as? String) } catch (e: Exception) { } return null } private fun Task.getIsIncremental(): Boolean? { try { val abstractKotlinCompileClass = javaClass.classLoader.loadClass(AbstractKotlinGradleModelBuilder.ABSTRACT_KOTLIN_COMPILE_CLASS) val getIncremental = abstractKotlinCompileClass.getDeclaredMethod("getIncremental") return (getIncremental.invoke(this) as? Boolean) } catch (e: Exception) { } return null } private fun Task.getPureKotlinSourceRoots(sourceSet: String, disambiguationClassifier: String? = null): List<File>? { try { val kotlinExtensionClass = project.extensions.findByType(javaClass.classLoader.loadClass(kotlinProjectExtensionClass)) val getKotlinMethod = javaClass.classLoader.loadClass(kotlinSourceSetClass).getMethod("getKotlin") val classifier = if (disambiguationClassifier == "metadata") "common" else disambiguationClassifier val kotlinSourceSet = (kotlinExtensionClass?.javaClass?.getMethod("getSourceSets")?.invoke(kotlinExtensionClass) as? FactoryNamedDomainObjectContainer<Any>)?.asMap?.get(compilationFullName(sourceSet, classifier)) ?: return null val javaSourceSet = (project.convention.getPlugin(JavaPluginConvention::class.java) as JavaPluginConvention).sourceSets.asMap[sourceSet] val pureJava = javaSourceSet?.java?.srcDirs return (getKotlinMethod.invoke(kotlinSourceSet) as? SourceDirectorySet)?.srcDirs?.filter { !(pureJava?.contains(it) ?: false) }?.toList() } catch (e: Exception) { } return null } private fun Task.getKotlinPluginVersion(): String? { try { val pluginWrapperClass = javaClass.classLoader.loadClass(kotlinPluginWrapper) val getVersionMethod = pluginWrapperClass.getMethod("getKotlinPluginVersion", javaClass.classLoader.loadClass("org.gradle.api.Project")) return getVersionMethod.invoke(null, this.project) as String } catch (e: Exception) { } return null } fun KotlinTaskPropertiesBySourceSet.acknowledgeTask(compileTask: Task, classifier: String?) { this[compileTask.getSourceSetName()] = getKotlinTaskProperties(compileTask, classifier) } fun getKotlinTaskProperties(compileTask: Task, classifier: String?): KotlinTaskPropertiesImpl { return KotlinTaskPropertiesImpl( compileTask.getIsIncremental(), compileTask.getPackagePrefix(), compileTask.getPureKotlinSourceRoots(compileTask.getSourceSetName(), classifier), compileTask.getKotlinPluginVersion() ) }
apache-2.0
f78b27e6ef5486e82c0224cf0af963df
45.096774
136
0.76767
5.318859
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/util/lexer/regex/Regex.kt
1
17179
package com.bajdcc.util.lexer.regex import com.bajdcc.util.lexer.automata.dfa.DFA import com.bajdcc.util.lexer.error.RegexException import com.bajdcc.util.lexer.error.RegexException.RegexError import com.bajdcc.util.lexer.stringify.RegexToString import com.bajdcc.util.lexer.token.MetaType import com.bajdcc.util.lexer.token.TokenUtility /** * 【词法分析】## 正则表达式分析工具 ##<br></br> * 用于生成语法树<br></br> * 语法同一般的正则表达式,只有贪婪模式,没有前/后向匹配, 没有捕获功能,仅用于匹配。 * * @author bajdcc */ class Regex @Throws(RegexException::class) @JvmOverloads constructor(pattern: String, val debug: Boolean = false) : RegexStringIterator(pattern) { /** * 表达式树根结点 */ private lateinit var expression: IRegexComponent /** * DFA */ private lateinit var dfa: DFA /** * DFA状态转换表 */ private lateinit var transition: Array<IntArray> /** * 终态表 */ private val setFinalStatus = mutableSetOf<Int>() /** * 字符区间表 */ private lateinit var charMap: CharacterMap /** * 字符串过滤接口 */ var filter: IRegexStringFilter? = null /** * 获取字符区间描述 * * @return 字符区间描述 */ val statusString: String get() = dfa.statusString /** * 获取NFA描述 * * @return NFA描述 */ val nfaString: String get() = dfa.nfaString /** * 获取DFA描述 * * @return DFA描述 */ val dfaString: String get() = dfa.dfaString /** * 获取DFATable描述 * * @return DFATable描述 */ val dfaTableString: String get() = dfa.dfaTableString init { compile() } /** * ## 编译表达式 ##<br></br> * * @throws RegexException 正则表达式错误 */ @Throws(RegexException::class) private fun compile() { translate() /* String->AST */ expression = analysis(MetaType.END.char, MetaType.END) if (debug) { println("#### 正则表达式语法树 ####") println(toString()) } /* AST->ENFA->NFA->DFA */ dfa = DFA(expression, debug) /* DFA Transfer Table */ buildTransition() } /** * 建立DFA状态转换表 */ private fun buildTransition() { /* 字符区间映射表 */ charMap = dfa.characterMap /* DFA状态转移表 */ transition = dfa.buildTransition(setFinalStatus) } /** * 匹配 * * @param string 被匹配的字符串 * @param greed 是否贪婪匹配 * @return 匹配结果(若不成功则返回空) */ @JvmOverloads fun match(string: String, greed: Boolean = true): String? { var matchString: String? = null val attr = object : IRegexStringAttribute { override var result: String = "" override val greedMode: Boolean get() = greed } if (match(RegexStringIterator(string), attr)) { matchString = attr.result } return matchString } /** * 匹配算法(DFA状态表) * * @param iterator 字符串遍历接口 * @param attr 输出的匹配字符串 * @return 是否匹配成功 */ fun match(iterator: IRegexStringIterator, attr: IRegexStringAttribute): Boolean { /* 使用全局字符映射表 */ val charMap = charMap.status /* 保存当前位置 */ iterator.snapshot() /* 当前状态 */ var status = 0 /* 上次经过的终态 */ var lastFinalStatus = -1 /* 上次经过的终态位置 */ var lastIndex = -1 /* 是否为贪婪模式 */ val greed = attr.greedMode /* 存放匹配字符串 */ val sb = StringBuilder() /* 是否允许通过终态结束识别 */ var allowFinal = false while (true) { if (setFinalStatus.contains(status)) {// 经过终态 if (greed) {// 贪婪模式 if (lastFinalStatus == -1) { iterator.snapshot()// 保存位置 } else { iterator.cover()// 覆盖位置 } lastFinalStatus = status// 记录上次状态 lastIndex = sb.length } else if (!allowFinal) {// 非贪婪模式,则匹配完成 iterator.discard()// 匹配成功,丢弃位置 attr.result = sb.toString() return true } } val local: Char var skipStore = false// 取消存储当前字符 /* 获得当前字符 */ if (filter != null) { val (_, current, _, meta) = filter!!.filter(iterator)// 过滤 local = current skipStore = meta === MetaType.NULL allowFinal = meta === MetaType.MUST_SAVE// 强制跳过终态 } else { if (!iterator.available()) { local = 0.toChar() } else { local = iterator.current() iterator.next() } } /* 存储字符 */ if (!skipStore) { sb.append(if (data.zero) '\u0000' else local) } /* 获得字符区间索引 */ val charClass = charMap[local.toInt()] /* 状态转移 */ var refer = -1 if (charClass != -1) {// 区间有效,尝试转移 refer = transition[status][charClass] } if (refer == -1) {// 失败 iterator.restore() if (lastFinalStatus == -1) {// 匹配失败 return false } else {// 使用上次经过的终态匹配结果 iterator.discard()// 匹配成功,丢弃位置 attr.result = sb.substring(0, lastIndex) return true } } else { status = refer// 更新状态 } } } @Throws(RegexException::class) private fun analysis(terminal: Char, meta: MetaType): IRegexComponent { var sequence = Constructure(false)// 建立序列以存储表达式 var branch: Constructure? = null// 建立分支以存储'|'型表达式,是否是分支有待预测 var result = sequence while (true) { if (data.meta === meta && data.current == terminal) {// 结束字符 if (data.index == 0) {// 表达式为空 err(RegexError.NULL) } else if (sequence.arrComponents.isEmpty()) {// 部件为空 err(RegexError.INCOMPLETE) } else { next() break// 正常终止 } } else if (data.meta === MetaType.END) { err(RegexError.INCOMPLETE) } var expression: IRegexComponent? = null// 当前待赋值的表达式 if (data.meta == MetaType.BAR) {// '|' next() if (sequence.arrComponents.isEmpty()) // 在此之前没有存储表达式 (|...) { err(RegexError.INCOMPLETE) } else { if (branch == null) {// 分支为空,则建立分支 branch = Constructure(true) branch.arrComponents.add(sequence)// 用新建的分支包含并替代当前序列 result = branch } sequence = Constructure(false)// 新建一个序列 branch.arrComponents.add(sequence) continue } } else if (data.meta == MetaType.LPARAN) {// '(' next() expression = analysis(MetaType.RPARAN.char, MetaType.RPARAN)// 递归分析 } if (expression == null) {// 当前不是表达式,则作为字符 val charset = Charset()// 当前待分析的字符集 expression = charset when (data.meta) { MetaType.ESCAPE// '\\' -> { next() escape(charset, true)// 处理转义 } MetaType.DOT// '.' -> { data.meta = MetaType.CHARACTER escape(charset, true) } MetaType.LSQUARE // '[' -> { next() range(charset) } MetaType.END // '\0' -> return result else -> { if (!charset.addChar(data.current)) { err(RegexError.RANGE) } next() } } } val rep: Repetition// 循环 when (data.meta) { MetaType.QUERY// '?' -> { next() rep = Repetition(expression, 0, 1) sequence.arrComponents.add(rep) } MetaType.PLUS// '+' -> { next() rep = Repetition(expression, 1, -1) sequence.arrComponents.add(rep) } MetaType.STAR// '*' -> { next() rep = Repetition(expression, 0, -1) sequence.arrComponents.add(rep) } MetaType.LBRACE // '{' -> { next() rep = Repetition(expression, 0, -1) quantity(rep) sequence.arrComponents.add(rep) } else -> sequence.arrComponents.add(expression) } } return result } /** * 处理转义字符 * * @param charset 字符集 * @param extend 是否支持扩展如\d \w等 * @throws RegexException 正则表达式错误 */ @Throws(RegexException::class) private fun escape(charset: Charset, extend: Boolean) { var ch = data.current if (data.meta === MetaType.CHARACTER) {// 字符 next() if (extend) { if (TokenUtility.isUpperLetter(ch) || ch == '.') { charset.bReverse = true// 大写则取反 } val cl = Character.toLowerCase(ch) when (cl) { 'd'// 数字 -> { charset.addRange('0', '9') return } 'a'// 字母 -> { charset.addRange('a', 'z') charset.addRange('A', 'Z') return } 'w'// 标识符 -> { charset.addRange('a', 'z') charset.addRange('A', 'Z') charset.addRange('0', '9') charset.addChar('_') return } 's'// 空白字符 -> { charset.addChar('\r') charset.addChar('\n') charset.addChar('\t') charset.addChar('\b') charset.addChar('\u000c') charset.addChar(' ') return } else -> { } } } if (TokenUtility.isLetter(ch)) {// 如果为字母 ch = utility.fromEscape(ch, RegexError.ESCAPE) if (!charset.addChar(ch)) { err(RegexError.RANGE) } } } else if (data.meta === MetaType.END) { err(RegexError.INCOMPLETE) } else {// 功能字符则转义 next() if (!charset.addChar(ch)) { err(RegexError.RANGE) } } } /** * 处理字符集合 * * @param charset 字符集 * @throws RegexException 正则表达式错误 */ @Throws(RegexException::class) private fun range(charset: Charset) { if (data.meta === MetaType.CARET) {// '^'取反 next() charset.bReverse = true } while (data.meta !== MetaType.RSQUARE) {// ']' if (data.meta === MetaType.CHARACTER) { character(charset) val lower = data.current // lower bound next() if (data.meta === MetaType.DASH) {// '-' next() character(charset) val upper = data.current // upper bound next() if (lower > upper) {// check bound err(RegexError.RANGE) } if (!charset.addRange(lower, upper)) { err(RegexError.RANGE) } } else { if (!charset.addChar(lower)) { err(RegexError.RANGE) } } } else if (data.meta === MetaType.ESCAPE) { next() escape(charset, false) } else if (data.meta === MetaType.END) { err(RegexError.INCOMPLETE) } else { charset.addChar(data.current) next() } } next() } /** * 处理字符 * * @param charset 字符集 * @throws RegexException 正则表达式错误 */ @Throws(RegexException::class) private fun character(charset: Charset) { if (data.meta === MetaType.ESCAPE) {// '\\' next() escape(charset, false) } else if (data.meta === MetaType.END) {// '\0' err(RegexError.INCOMPLETE) } else if (data.meta !== MetaType.CHARACTER && data.meta !== MetaType.DASH) { err(RegexError.CTYPE) } } /** * 处理量词 * * @throws RegexException 正则表达式错误 */ @Throws(RegexException::class) private fun quantity(rep: Repetition) { val lower: Int var upper: Int upper = digit() lower = upper// 循环下界 if (lower == -1) { err(RegexError.BRACE) } if (data.meta === MetaType.COMMA) {// ',' next() if (data.meta === MetaType.RBRACE) {// '}' upper = -1// 上界为无穷大 } else { upper = digit()// 得到循环上界 if (upper == -1) { err(RegexError.BRACE) } } } if (upper != -1 && upper < lower) { err(RegexError.RANGE) } expect(MetaType.RBRACE, RegexError.BRACE) rep.lowerBound = lower rep.upperBound = upper } /** * 十进制数字转换 * * @return 数字 */ private fun digit(): Int { val index = data.index while (Character.isDigit(data.current)) { next() } return try { Integer.valueOf(context.substring(index, data.index), 10) } catch (e: NumberFormatException) { -1 } } override fun transform() { // 一般字符 data.meta = g_mapMeta.getOrDefault(data.current, MetaType.CHARACTER)// 功能字符 } override fun toString(): String { val alg = RegexToString()// 表达式树序列化算法初始化 expression.visit(alg)// 遍历树 return alg.toString() } companion object { private val g_mapMeta = mutableMapOf<Char, MetaType>() init { val metaTypes = arrayOf(MetaType.LPARAN, MetaType.RPARAN, MetaType.STAR, MetaType.PLUS, MetaType.QUERY, MetaType.CARET, MetaType.LSQUARE, MetaType.RSQUARE, MetaType.BAR, MetaType.ESCAPE, MetaType.DASH, MetaType.LBRACE, MetaType.RBRACE, MetaType.COMMA, MetaType.DOT, MetaType.NEW_LINE, MetaType.CARRIAGE_RETURN, MetaType.BACKSPACE) metaTypes.forEach { meta -> g_mapMeta[meta.char] = meta } } } }
mit
06815a29f52e1e263fe38354fa62fd22
28.634831
103
0.432291
4.711224
false
false
false
false
Maccimo/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownFrontMatterHeader.kt
3
2485
package org.intellij.plugins.markdown.lang.psi.impl import com.intellij.openapi.util.TextRange import com.intellij.psi.AbstractElementManipulator import com.intellij.psi.ElementManipulators import com.intellij.psi.LiteralTextEscaper import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.psi.impl.source.tree.CompositePsiElement import com.intellij.psi.tree.IElementType import com.intellij.psi.util.siblings import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElementFactory import org.intellij.plugins.markdown.lang.psi.util.hasType import org.intellij.plugins.markdown.util.MarkdownPsiUtil import org.jetbrains.annotations.ApiStatus @ApiStatus.Experimental class MarkdownFrontMatterHeader(type: IElementType): CompositePsiElement(type), PsiLanguageInjectionHost, MarkdownPsiElement { override fun isValidHost(): Boolean { val children = firstChild.siblings(forward = true, withSelf = true) val newlines = children.count { MarkdownPsiUtil.WhiteSpaces.isNewLine(it) } return newlines >= 2 && children.find { it.hasType(MarkdownElementTypes.FRONT_MATTER_HEADER_CONTENT) } != null } override fun updateText(text: String): PsiLanguageInjectionHost { return ElementManipulators.handleContentChange(this, text) } override fun createLiteralTextEscaper(): LiteralTextEscaper<out PsiLanguageInjectionHost> { return LiteralTextEscaper.createSimple(this) } internal class Manipulator: AbstractElementManipulator<MarkdownFrontMatterHeader>() { override fun handleContentChange(element: MarkdownFrontMatterHeader, range: TextRange, content: String): MarkdownFrontMatterHeader? { if (content.contains("---")) { val textElement = MarkdownPsiElementFactory.createTextElement(element.project, content) return if (textElement is MarkdownFrontMatterHeader) { element.replace(textElement) as MarkdownFrontMatterHeader } else null } val children = element.firstChild.siblings(forward = true, withSelf = true) val contentElement = children.filterIsInstance<MarkdownFrontMatterHeaderContent>().firstOrNull() ?: return null val shiftedRange = range.shiftLeft(contentElement.startOffsetInParent) val updatedText = shiftedRange.replace(contentElement.text, content) contentElement.replaceWithText(updatedText) return element } } }
apache-2.0
f9eb01c79d50b49da491f779a21c08de
48.7
137
0.798793
5.113169
false
false
false
false
Hexworks/zircon
zircon.core/src/jvmMain/kotlin/org/hexworks/zircon/internal/util/Decompressor.kt
1
1735
package org.hexworks.zircon.internal.util.rex import java.io.* // ktlint-disable no-wildcard-imports import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File import java.util.zip.GZIPInputStream import java.util.zip.ZipEntry import java.util.zip.ZipInputStream /** * Takes a GZIP-compressed [ByteArray] and returns it decompressed. This * function can only be used on the **JVM**. */ fun decompressGZIPByteArray(compressedData: ByteArray): ByteArray { ByteArrayInputStream(compressedData).use { bin -> GZIPInputStream(bin).use { gzipper -> val buffer = ByteArray(1024) val out = ByteArrayOutputStream() var len = gzipper.read(buffer) while (len > 0) { out.write(buffer, 0, len) len = gzipper.read(buffer) } gzipper.close() out.close() return out.toByteArray() } } } fun unZipIt(zipSource: InputStream, outputFolder: File): List<File> { val buffer = ByteArray(1024) val outputFolderPath = outputFolder.absolutePath val result = mutableListOf<File>() val zis = ZipInputStream(zipSource) var ze: ZipEntry? = zis.nextEntry while (ze != null) { val fileName = ze.name val newFile = File(outputFolderPath + File.separator + fileName) File(newFile.parent).mkdirs() val fos = FileOutputStream(newFile) result.add(newFile) var len = zis.read(buffer) while (len > 0) { fos.write(buffer, 0, len) len = zis.read(buffer) } fos.close() ze = zis.nextEntry } zis.closeEntry() zis.close() return result }
apache-2.0
c2de6325ddfaf617b32126734c45081a
26.109375
72
0.624784
4.252451
false
false
false
false
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/vimscript/model/commands/GlobalCommand.kt
1
7086
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.commands import com.intellij.openapi.editor.RangeMarker import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.getLineStartForOffset import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.ex.ranges.LineRange import com.maddyhome.idea.vim.ex.ranges.Ranges import com.maddyhome.idea.vim.group.SearchGroup.RE_BOTH import com.maddyhome.idea.vim.group.SearchGroup.RE_LAST import com.maddyhome.idea.vim.group.SearchGroup.RE_SEARCH import com.maddyhome.idea.vim.group.SearchGroup.RE_SUBST import com.maddyhome.idea.vim.helper.MessageHelper.message import com.maddyhome.idea.vim.helper.Msg import com.maddyhome.idea.vim.newapi.ij import com.maddyhome.idea.vim.regexp.CharPointer import com.maddyhome.idea.vim.regexp.RegExp import com.maddyhome.idea.vim.vimscript.model.ExecutionResult /** * see "h :global" / "h :vglobal" */ data class GlobalCommand(val ranges: Ranges, val argument: String, val invert: Boolean) : Command.SingleExecution(ranges, argument) { override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.SELF_SYNCHRONIZED) override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult { var result: ExecutionResult = ExecutionResult.Success editor.removeSecondaryCarets() val caret = editor.currentCaret() // For :g command the default range is % val lineRange: LineRange = if (ranges.size() == 0) { LineRange(0, editor.lineCount() - 1) } else { getLineRange(editor, caret) } if (!processGlobalCommand(editor, context, lineRange)) { result = ExecutionResult.Error } return result } private fun processGlobalCommand( editor: VimEditor, context: ExecutionContext, range: LineRange, ): Boolean { // When nesting the command works on one line. This allows for // ":g/found/v/notfound/command". if (globalBusy && (range.startLine != 0 || range.endLine != editor.lineCount() - 1)) { VimPlugin.showMessage(message("E147")) VimPlugin.indicateError() return false } var cmd = CharPointer(StringBuffer(argument)) val pat: CharPointer val delimiter: Char var whichPat = RE_LAST /* * undocumented vi feature: * "\/" and "\?": use previous search pattern. * "\&": use previous substitute pattern. */ if (argument.isEmpty()) { VimPlugin.showMessage(message("E148")) VimPlugin.indicateError() return false } else if (cmd.charAt() == '\\') { cmd.inc() if ("/?&".indexOf(cmd.charAt()) == -1) { VimPlugin.showMessage(message(Msg.e_backslash)) return false } whichPat = if (cmd.charAt() == '&') RE_SUBST else RE_SEARCH cmd.inc() pat = CharPointer("") /* empty search pattern */ } else { delimiter = cmd.charAt() /* get the delimiter */ cmd.inc() pat = cmd.ref(0) /* remember start of pattern */ cmd = RegExp.skip_regexp(cmd, delimiter, true) if (cmd.charAt() == delimiter) { /* end delimiter found */ cmd.set('\u0000').inc() /* replace it with a NUL */ } } val (first, second) = injector.searchGroup.search_regcomp(pat, whichPat, RE_BOTH) if (!first) { VimPlugin.showMessage(message(Msg.e_invcmd)) VimPlugin.indicateError() return false } val regmatch = second.first as RegExp.regmmatch_T val sp = second.third as RegExp var match: Int val lcount = editor.lineCount() val searchcol = 0 if (globalBusy) { val offset = editor.currentCaret().offset val lineStartOffset = editor.getLineStartForOffset(offset.point) match = sp.vim_regexec_multi(regmatch, editor, lcount, editor.currentCaret().getLine().line, searchcol) if ((!invert && match > 0) || (invert && match <= 0)) { globalExecuteOne(editor, context, lineStartOffset, cmd.toString()) } } else { // pass 1: set marks for each (not) matching line val line1 = range.startLine val line2 = range.endLine //region search_regcomp implementation // We don't need to worry about lastIgnoreSmartCase, it's always false. Vim resets after checking, and it only sets // it to true when searching for a word with `*`, `#`, `g*`, etc. if (line1 < 0 || line2 < 0) { return false } var ndone = 0 val marks = mutableListOf<RangeMarker>() for (lnum in line1..line2) { if (gotInt) break // a match on this line? match = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, searchcol) if ((!invert && match > 0) || (invert && match <= 0)) { val lineStartOffset = editor.getLineStartOffset(lnum) marks += editor.ij.document.createRangeMarker(lineStartOffset, lineStartOffset) ndone += 1 } // TODO: 25.05.2021 Check break } // pass 2: execute the command for each line that has been marked if (gotInt) { VimPlugin.showMessage(message("e_interr")) } else if (ndone == 0) { if (invert) { VimPlugin.showMessage(message("global.command.not.found.v", pat.toString())) } else { VimPlugin.showMessage(message("global.command.not.found.g", pat.toString())) } } else { globalExe(editor, context, marks, cmd.toString()) } } return true } private fun globalExe(editor: VimEditor, context: ExecutionContext, marks: List<RangeMarker>, cmd: String) { globalBusy = true try { for (mark in marks) { if (gotInt) break if (!globalBusy) break val startOffset = mark.startOffset mark.dispose() globalExecuteOne(editor, context, startOffset, cmd) // TODO: 26.05.2021 break check } } catch (e: Exception) { throw e } finally { globalBusy = false } // TODO: 26.05.2021 Add other staff } private fun globalExecuteOne(editor: VimEditor, context: ExecutionContext, lineStartOffset: Int, cmd: String?) { // TODO: 26.05.2021 What about folds? editor.currentCaret().moveToOffset(lineStartOffset) if (cmd == null || cmd.isEmpty() || (cmd.length == 1 && cmd[0] == '\n')) { injector.vimscriptExecutor.execute("p", editor, context, skipHistory = true, indicateErrors = true, this.vimContext) } else { injector.vimscriptExecutor.execute(cmd, editor, context, skipHistory = true, indicateErrors = true, this.vimContext) } } companion object { private var globalBusy = false // Interrupted. Not used at the moment var gotInt: Boolean = false } }
mit
b72c33c207bd4694941dbc613e7fd3e3
34.969543
133
0.660739
3.998871
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/posts/PostTimePickerDialogFragment.kt
1
2842
package org.wordpress.android.ui.posts import android.app.Dialog import android.app.TimePickerDialog import android.app.TimePickerDialog.OnTimeSetListener import android.content.Context import android.os.Bundle import android.text.format.DateFormat import androidx.appcompat.view.ContextThemeWrapper import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import org.wordpress.android.R.style import org.wordpress.android.WordPress import org.wordpress.android.ui.posts.prepublishing.PrepublishingPublishSettingsViewModel import javax.inject.Inject class PostTimePickerDialogFragment : DialogFragment() { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: PublishSettingsViewModel override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val publishSettingsFragmentType = arguments?.getParcelable<PublishSettingsFragmentType>( ARG_PUBLISH_SETTINGS_FRAGMENT_TYPE ) viewModel = when (publishSettingsFragmentType) { PublishSettingsFragmentType.EDIT_POST -> ViewModelProvider(requireActivity(), viewModelFactory) .get(EditPostPublishSettingsViewModel::class.java) PublishSettingsFragmentType.PREPUBLISHING_NUDGES -> ViewModelProvider(requireActivity(), viewModelFactory) .get(PrepublishingPublishSettingsViewModel::class.java) null -> error("PublishSettingsViewModel not initialized") } val is24HrFormat = DateFormat.is24HourFormat(activity) val context = ContextThemeWrapper(activity, style.PostSettingsCalendar) val timePickerDialog = TimePickerDialog( context, OnTimeSetListener { _, selectedHour, selectedMinute -> viewModel.onTimeSelected(selectedHour, selectedMinute) }, viewModel.hour ?: 0, viewModel.minute ?: 0, is24HrFormat ) return timePickerDialog } override fun onAttach(context: Context) { super.onAttach(context) (requireActivity().applicationContext as WordPress).component().inject(this) } companion object { const val TAG = "post_time_picker_dialog_fragment" const val ARG_PUBLISH_SETTINGS_FRAGMENT_TYPE = "publish_settings_fragment_type" fun newInstance(publishSettingsFragmentType: PublishSettingsFragmentType): PostTimePickerDialogFragment { return PostTimePickerDialogFragment().apply { arguments = Bundle().apply { putParcelable( ARG_PUBLISH_SETTINGS_FRAGMENT_TYPE, publishSettingsFragmentType ) } } } } }
gpl-2.0
2fdc362fabb34aea8da0e21d7dd11cab
40.188406
118
0.687896
5.847737
false
false
false
false
KotlinNLP/SimpleDNN
examples/SparseInputTest.kt
1
2531
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ import com.kotlinnlp.simplednn.core.functionalities.activations.Softmax import com.kotlinnlp.simplednn.core.functionalities.activations.Softsign import com.kotlinnlp.simplednn.core.functionalities.losses.SoftmaxCrossEntropyCalculator import com.kotlinnlp.simplednn.core.functionalities.outputevaluation.ClassificationEvaluation import com.kotlinnlp.simplednn.core.functionalities.updatemethods.adagrad.AdaGradMethod import com.kotlinnlp.simplednn.core.layers.LayerType import com.kotlinnlp.simplednn.core.neuralnetwork.preset.FeedforwardNeuralNetwork import utils.Corpus import utils.SimpleExample import traininghelpers.training.FeedforwardTrainer import traininghelpers.validation.FeedforwardEvaluator import com.kotlinnlp.simplednn.simplemath.ndarray.sparsebinary.SparseBinaryNDArray import utils.CorpusReader import utils.exampleextractor.ClassificationSparseExampleExtractor fun main() { println("Start 'Sparse Input Test'") val dataset = CorpusReader<SimpleExample<SparseBinaryNDArray>>().read( corpusPath = Configuration.loadFromFile().sparse_input.datasets_paths, exampleExtractor = ClassificationSparseExampleExtractor(inputSize = 356425, outputSize = 86), perLine = true) SparseInputTest(dataset).start() println("\nEnd.") } /** * */ class SparseInputTest(val dataset: Corpus<SimpleExample<SparseBinaryNDArray>>) { /** * */ private val neuralNetwork = FeedforwardNeuralNetwork( inputSize = 356425, inputType = LayerType.Input.SparseBinary, hiddenSize = 200, hiddenActivation = Softsign, outputSize = 86, outputActivation = Softmax()) /** * */ fun start() { this.train() } /** * */ private fun train() { println("\n-- TRAINING") FeedforwardTrainer( model = this.neuralNetwork, updateMethod = AdaGradMethod(learningRate = 0.1), lossCalculator = SoftmaxCrossEntropyCalculator, examples = this.dataset.training, epochs = 3, batchSize = 1, evaluator = FeedforwardEvaluator( model = this.neuralNetwork, examples = this.dataset.validation, outputEvaluationFunction = ClassificationEvaluation) ).train() } }
mpl-2.0
75263f6b40de2709589e6dd122e8fe57
30.6375
97
0.734492
4.463845
false
false
false
false
plusCubed/velociraptor
app/src/main/java/com/pluscubed/velociraptor/settings/ProvidersFragment.kt
1
17078
package com.pluscubed.velociraptor.settings import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.appcompat.content.res.AppCompatResources import androidx.core.text.parseAsHtml import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import butterknife.BindView import butterknife.ButterKnife import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.list.listItems import com.android.billingclient.api.BillingClient import com.android.billingclient.api.Purchase import com.android.billingclient.api.SkuDetails import com.google.android.gms.location.LocationServices import com.google.android.material.snackbar.Snackbar import com.google.firebase.crashlytics.FirebaseCrashlytics import com.pluscubed.velociraptor.R import com.pluscubed.velociraptor.billing.BillingConstants import com.pluscubed.velociraptor.billing.BillingManager import com.pluscubed.velociraptor.utils.PrefUtils import com.pluscubed.velociraptor.utils.Utils import kotlinx.coroutines.* import java.util.* import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine class ProvidersFragment : Fragment() { //Providers @BindView(R.id.here_container) lateinit var hereContainer: View @BindView(R.id.here_title) lateinit var hereTitle: TextView @BindView(R.id.here_provider_desc) lateinit var herePriceDesc: TextView @BindView(R.id.here_subscribe) lateinit var hereSubscribeButton: Button @BindView(R.id.here_editdata) lateinit var hereEditDataButton: Button @BindView(R.id.tomtom_container) lateinit var tomtomContainer: View @BindView(R.id.tomtom_title) lateinit var tomtomTitle: TextView @BindView(R.id.tomtom_provider_desc) lateinit var tomtomPriceDesc: TextView @BindView(R.id.tomtom_subscribe) lateinit var tomtomSubscribeButton: Button @BindView(R.id.tomtom_editdata) lateinit var tomtomEditDataButton: Button @BindView(R.id.osm_title) lateinit var osmTitle: TextView @BindView(R.id.osm_editdata) lateinit var osmEditDataButton: Button @BindView(R.id.osm_donate) lateinit var osmDonateButton: Button @BindView(R.id.osm_coverage) lateinit var osmCoverageButton: Button private var billingManager: BillingManager? = null private val isBillingManagerReady: Boolean get() = billingManager != null && billingManager!!.billingClientResponseCode == BillingClient.BillingResponse.OK override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onDestroy() { super.onDestroy() if (billingManager != null) { billingManager!!.destroy() } } override fun onResume() { super.onResume() if (billingManager != null && billingManager!!.billingClientResponseCode == BillingClient.BillingResponse.OK) { billingManager!!.queryPurchases() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_providers, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) ButterKnife.bind(this, view) hereEditDataButton.setOnClickListener { Utils.openLink(activity, view, HERE_EDITDATA_URL) } hereSubscribeButton.setOnClickListener { if (!isBillingManagerReady) { Snackbar.make( view, R.string.in_app_unavailable, Snackbar.LENGTH_SHORT ).show() return@setOnClickListener } billingManager?.initiatePurchaseFlow( BillingConstants.SKU_HERE, BillingClient.SkuType.SUBS ) } tomtomSubscribeButton.setOnClickListener { if (!isBillingManagerReady) { Snackbar.make( view, R.string.in_app_unavailable, Snackbar.LENGTH_SHORT ).show() return@setOnClickListener; } billingManager?.initiatePurchaseFlow( BillingConstants.SKU_TOMTOM, BillingClient.SkuType.SUBS ) } tomtomEditDataButton.setOnClickListener { Utils.openLink(activity, view, TOMTOM_EDITDATA_URL) } osmCoverageButton.setOnClickListener { openOsmCoverage() } osmEditDataButton.setOnClickListener { activity?.let { activity -> MaterialDialog(activity) .show { var text = getString(R.string.osm_edit) if (text.contains("%s")) { text = text.format("<b>$OSM_EDITDATA_URL</b>") } message(text = text.parseAsHtml()) { lineSpacing(1.2f) } positiveButton(R.string.share_link) { _ -> val shareIntent = Intent() shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, OSM_EDITDATA_URL) startActivity( Intent.createChooser( shareIntent, getString(R.string.share_link) ) ) } } } } osmDonateButton.setOnClickListener { Utils.openLink(activity, view, OSM_DONATE_URL) } val checkIcon = activity?.let { AppCompatResources.getDrawable(it, R.drawable.ic_done_green_20dp) } val crossIcon = activity?.let { AppCompatResources.getDrawable(it, R.drawable.ic_cross_red_20dp) } osmTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, checkIcon, null) hereTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, crossIcon, null) tomtomTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, crossIcon, null) billingManager = BillingManager(activity, object : BillingManager.BillingUpdatesListener { override fun onBillingClientSetupFinished() { try { billingManager?.querySkuDetailsAsync( BillingClient.SkuType.SUBS, Arrays.asList(BillingConstants.SKU_HERE, BillingConstants.SKU_TOMTOM) ) { responseCode, skuDetailsList -> if (responseCode != BillingClient.BillingResponse.OK) { return@querySkuDetailsAsync } for (details in skuDetailsList) { if (details.sku == BillingConstants.SKU_HERE) { herePriceDesc.text = getString( R.string.here_desc, getString(R.string.per_month, details.price) ) } if (details.sku == BillingConstants.SKU_TOMTOM) { tomtomPriceDesc.text = getString( R.string.tomtom_desc, getString(R.string.per_month, details.price) ) } } } } catch (e: Exception) { FirebaseCrashlytics.getInstance().recordException(e); } } override fun onConsumeFinished(token: String, result: Int) { PrefUtils.setSupported(activity, true) } override fun onPurchasesUpdated(purchases: List<Purchase>) { val purchased = HashSet<String>() if (purchased.size > 0) { PrefUtils.setSupported(activity, true) } val onetime = BillingConstants.getSkuList(BillingClient.SkuType.INAPP) for (purchase in purchases) { if (purchase.sku in onetime) { try { billingManager?.consumeAsync(purchase.purchaseToken); } catch (e: Exception) { FirebaseCrashlytics.getInstance().recordException(e); } } else { purchased.add(purchase.sku) } } val hereSubscribed = purchased.contains(BillingConstants.SKU_HERE) if (hereSubscribed) { hereContainer.isVisible = true } setButtonSubscriptionState( hereSubscribeButton, hereTitle, purchased.contains(BillingConstants.SKU_HERE), BillingConstants.SKU_HERE ) val tomtomSubscribed = purchased.contains(BillingConstants.SKU_TOMTOM) if (tomtomSubscribed) { tomtomContainer.isVisible = true } setButtonSubscriptionState( tomtomSubscribeButton, tomtomTitle, tomtomSubscribed, BillingConstants.SKU_TOMTOM ) } }) } private fun setButtonSubscriptionState(button: Button?, title: TextView?, subscribed: Boolean, sku: String) { if (subscribed) { button?.setText(R.string.unsubscribe) button?.setOnClickListener { Utils.openLink(context, it, "http://play.google.com/store/account/subscriptions?package=com.pluscubed.velociraptor&sku=${sku}") } val checkIcon = activity?.let { AppCompatResources.getDrawable(it, R.drawable.ic_done_green_20dp) } title?.setCompoundDrawablesWithIntrinsicBounds(null, null, checkIcon, null) } else { button?.setText(R.string.subscribe) button?.setOnClickListener { if (!isBillingManagerReady) { Snackbar.make( requireView(), R.string.in_app_unavailable, Snackbar.LENGTH_SHORT ).show() return@setOnClickListener } billingManager?.initiatePurchaseFlow( sku, BillingClient.SkuType.SUBS ) } val crossIcon = activity?.let { AppCompatResources.getDrawable(it, R.drawable.ic_cross_red_20dp) } title?.setCompoundDrawablesWithIntrinsicBounds(null, null, crossIcon, null) } } private suspend fun querySkuDetails( manager: BillingManager?, itemType: String, vararg skuList: String ): List<SkuDetails> = suspendCoroutine { cont -> manager?.querySkuDetailsAsync( itemType, Arrays.asList(*skuList) ) { responseCode, skuDetailsList -> if (responseCode != BillingClient.BillingResponse.OK) { cont.resumeWithException(Exception("Billing error: $responseCode")) } else { cont.resume(skuDetailsList) } } } fun showSupportDialog() { if (!isBillingManagerReady) { view?.let { Snackbar.make(it, R.string.in_app_unavailable, Snackbar.LENGTH_SHORT).show() } return } viewLifecycleOwner.lifecycleScope.launch { supervisorScope { try { val monthlyDonations = async(Dispatchers.IO) { querySkuDetails( billingManager, BillingClient.SkuType.SUBS, BillingConstants.SKU_D1_MONTHLY, BillingConstants.SKU_D3_MONTHLY ) } val oneTimeDonations = async(Dispatchers.IO) { querySkuDetails( billingManager, BillingClient.SkuType.INAPP, BillingConstants.SKU_D1, BillingConstants.SKU_D3, BillingConstants.SKU_D5, BillingConstants.SKU_D10, BillingConstants.SKU_D20 ) } val skuDetailsList = monthlyDonations.await() + oneTimeDonations.await() @Suppress("DEPRECATION") var text = getString(R.string.support_dev_dialog) if (PrefUtils.hasSupported(activity)) { text += "\n\n\uD83C\uDF89 " + getString(R.string.support_dev_dialog_badge) + " \uD83C\uDF89" } var dialog = activity?.let { MaterialDialog(it) .icon( drawable = AppCompatResources.getDrawable( it, R.drawable.ic_favorite_black_24dp ) ) .title(R.string.support_development) .message(text = text) { lineSpacing(1.2f) } } val purchaseDisplay = ArrayList<String>() for (details in skuDetailsList) { var amount = details.price if (details.type == BillingClient.SkuType.SUBS) amount = getString(R.string.per_month, amount) else { amount = getString(R.string.one_time, amount) } purchaseDisplay.add(amount) } dialog = dialog?.listItems(items = purchaseDisplay) { _, which, _ -> val skuDetails = skuDetailsList[which] billingManager!!.initiatePurchaseFlow(skuDetails.sku, skuDetails.type) } dialog?.show() } catch (e: Exception) { view?.let { Snackbar.make(it, R.string.in_app_unavailable, Snackbar.LENGTH_SHORT).show() } e.printStackTrace() } } } } @SuppressLint("MissingPermission") private fun openOsmCoverage() { if (Utils.isLocationPermissionGranted(activity)) { activity?.let { val fusedLocationProvider = LocationServices.getFusedLocationProviderClient(it) fusedLocationProvider.lastLocation.addOnCompleteListener(it) { task -> var uriString = OSM_COVERAGE_URL if (task.isSuccessful && task.result != null) { val lastLocation = task.result uriString += "?lon=${lastLocation?.longitude}&lat=${lastLocation?.latitude}&zoom=12" } Utils.openLink(activity, view, uriString) } } } else { Utils.openLink(activity, view, OSM_COVERAGE_URL) } } companion object { const val OSM_EDITDATA_URL = "https://openstreetmap.org" const val OSM_COVERAGE_URL = "https://product.itoworld.com/map/124" const val OSM_DONATE_URL = "https://donate.openstreetmap.org" const val HERE_EDITDATA_URL = "https://mapcreator.here.com/mapcreator" const val TOMTOM_EDITDATA_URL = "https://www.tomtom.com/mapshare/tools" } }
gpl-3.0
8f804fa597cba1581cc6d3278aa2e639
38.352535
123
0.525237
5.828669
false
false
false
false
michaelkourlas/voipms-sms-client
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/notifications/Notifications.kt
1
40382
/* * VoIP.ms SMS * Copyright (C) 2017-2021 Michael Kourlas * * 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 net.kourlas.voipms_sms.notifications import android.annotation.SuppressLint import android.app.* import android.content.ComponentName import android.content.Context import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Build import android.widget.Toast import androidx.core.app.* import androidx.core.app.Person import androidx.core.app.RemoteInput import androidx.core.app.TaskStackBuilder import androidx.core.content.LocusIdCompat import androidx.core.graphics.drawable.IconCompat import androidx.work.WorkManager import net.kourlas.voipms_sms.BuildConfig import net.kourlas.voipms_sms.CustomApplication import net.kourlas.voipms_sms.R import net.kourlas.voipms_sms.conversation.ConversationActivity import net.kourlas.voipms_sms.conversation.ConversationBubbleActivity import net.kourlas.voipms_sms.conversations.ConversationsActivity import net.kourlas.voipms_sms.database.Database import net.kourlas.voipms_sms.preferences.* import net.kourlas.voipms_sms.sms.ConversationId import net.kourlas.voipms_sms.sms.Message import net.kourlas.voipms_sms.sms.receivers.MarkReadReceiver import net.kourlas.voipms_sms.sms.receivers.SendMessageReceiver import net.kourlas.voipms_sms.utils.* import java.util.* /** * Single-instance class used to send notifications when new SMS messages * are received. */ class Notifications private constructor(private val context: Context) { // Helper variables private val notificationManager = context.getSystemService( Context.NOTIFICATION_SERVICE ) as NotificationManager // Information associated with active notifications private val notificationIds = mutableMapOf<ConversationId, Int>() private val notificationMessages = mutableMapOf<ConversationId, List<NotificationCompat.MessagingStyle.Message>>() private var notificationIdCount = MESSAGE_START_NOTIFICATION_ID /** * Attempts to create a notification channel for the specified DID. */ fun createDidNotificationChannel(did: String, contact: String) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create the default notification channel if it doesn't already // exist createDefaultNotificationChannel() val defaultChannel = notificationManager.getNotificationChannel( context.getString(R.string.notifications_channel_default) ) val channelGroup = NotificationChannelGroup( context.getString( R.string.notifications_channel_group_did, did ), getFormattedPhoneNumber(did) ) notificationManager.createNotificationChannelGroup(channelGroup) val contactName = getContactName(context, contact) val channel = NotificationChannel( context.getString( R.string.notifications_channel_contact, did, contact ), contactName ?: getFormattedPhoneNumber(contact), defaultChannel.importance ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { channel.setConversationId( context.getString(R.string.notifications_channel_default), ConversationId(did, contact).getId() ) } channel.enableLights(defaultChannel.shouldShowLights()) channel.lightColor = defaultChannel.lightColor channel.enableVibration(defaultChannel.shouldVibrate()) channel.vibrationPattern = defaultChannel.vibrationPattern channel.lockscreenVisibility = defaultChannel.lockscreenVisibility channel.setBypassDnd(defaultChannel.canBypassDnd()) channel.setSound( defaultChannel.sound, defaultChannel.audioAttributes ) channel.setShowBadge(defaultChannel.canShowBadge()) channel.group = context.getString( R.string.notifications_channel_group_did, did ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { channel.setAllowBubbles(true) } notificationManager.createNotificationChannel(channel) } } /** * Attempts to create the default notification channel. */ fun createDefaultNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createOtherNotificationChannelGroup() val channel = NotificationChannel( context.getString(R.string.notifications_channel_default), context.getString(R.string.notifications_channel_default_title), NotificationManager.IMPORTANCE_HIGH ) channel.enableLights(true) channel.lightColor = Color.RED channel.enableVibration(true) channel.vibrationPattern = longArrayOf(0, 250, 250, 250) channel.setShowBadge(true) channel.group = context.getString( R.string.notifications_channel_group_other ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { channel.setAllowBubbles(true) } notificationManager.createNotificationChannel(channel) } } /** * Creates the notification channel for the notification displayed during * database synchronization. */ private fun createSyncNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createOtherNotificationChannelGroup() val channel = NotificationChannel( context.getString(R.string.notifications_channel_sync), context.getString(R.string.notifications_channel_sync_title), NotificationManager.IMPORTANCE_LOW ) channel.group = context.getString( R.string.notifications_channel_group_other ) notificationManager.createNotificationChannel(channel) } } /** * Creates the notification channel group for non-conversation related * notifications. */ private fun createOtherNotificationChannelGroup() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelGroup = NotificationChannelGroup( context.getString(R.string.notifications_channel_group_other), context.getString( R.string.notifications_channel_group_other_title ) ) notificationManager.createNotificationChannelGroup(channelGroup) } } /** * Rename notification channels for changed contact numbers. */ fun renameNotificationChannels() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Rename all channels for (channel in notificationManager.notificationChannels) { if (channel.id.startsWith( context.getString( R.string.notifications_channel_contact_prefix ) ) ) { val contact = channel.id.split("_")[4] val contactName = getContactName(context, contact) channel.name = contactName ?: getFormattedPhoneNumber( contact ) notificationManager.createNotificationChannel(channel) } } } } /** * Delete notification channels for conversations that are no longer active. */ suspend fun deleteNotificationChannelsAndGroups() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Remove any channel for which there is no conversation with // notifications enabled in the database val conversationIds = Database.getInstance(context) .getConversationIds( getDids(context, onlyShowNotifications = true) ) for (channel in notificationManager.notificationChannels) { if (channel.id.startsWith( context.getString( R.string.notifications_channel_contact_prefix ) ) ) { val splitId = channel.id.split(":")[0].trim().split("_") val conversationId = ConversationId(splitId[3], splitId[4]) if (conversationId !in conversationIds) { notificationManager.deleteNotificationChannel( channel.id ) validateGroupNotification() } } } // Remove any channel for which there is no conversation with // notifications enabled in the database val dids = conversationIds.map { it.did }.toSet() for (group in notificationManager.notificationChannelGroups) { if (group.id.startsWith( context.getString( R.string.notifications_channel_group_did, "" ) ) ) { val did = group.id.split("_")[3] if (did !in dids) { notificationManager.deleteNotificationChannelGroup( group.id ) validateGroupNotification() } } } } } /** * Gets the notification displayed during synchronization. */ fun getSyncDatabaseNotification(id: UUID, progress: Int = 0): Notification { createSyncNotificationChannel() val builder = NotificationCompat.Builder( context, context.getString(R.string.notifications_channel_sync) ) builder.setCategory(NotificationCompat.CATEGORY_PROGRESS) builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp) builder.setContentTitle( context.getString( R.string.notifications_sync_database_message ) ) builder.setContentText("$progress%") builder.setProgress(100, progress, false) builder.setOngoing(true) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { @Suppress("DEPRECATION") builder.priority = Notification.PRIORITY_LOW } // Cancel action val cancelPendingIntent = WorkManager.getInstance(context).createCancelPendingIntent(id) val cancelAction = NotificationCompat.Action.Builder( R.drawable.ic_delete_toolbar_24dp, context.getString(R.string.notifications_button_cancel), cancelPendingIntent ) .setShowsUserInterface(false) .build() builder.addAction(cancelAction) return builder.build() } /** * Gets the notification displayed during message sending. */ fun getSyncMessageSendNotification(): Notification { createSyncNotificationChannel() val builder = NotificationCompat.Builder( context, context.getString(R.string.notifications_channel_sync) ) builder.setCategory(NotificationCompat.CATEGORY_SERVICE) builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp) builder.setContentTitle( context.getString( R.string.notifications_sync_send_message_message ) ) builder.setOngoing(true) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { @Suppress("DEPRECATION") builder.priority = Notification.PRIORITY_LOW } return builder.build() } /** * Gets the notification displayed during verification of credentials. */ fun getSyncVerifyCredentialsNotification(): Notification { createSyncNotificationChannel() val builder = NotificationCompat.Builder( context, context.getString(R.string.notifications_channel_sync) ) builder.setCategory(NotificationCompat.CATEGORY_SERVICE) builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp) builder.setContentTitle( context.getString( R.string.notifications_sync_verify_credentials_message ) ) builder.setOngoing(true) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { @Suppress("DEPRECATION") builder.priority = Notification.PRIORITY_LOW } return builder.build() } /** * Gets the notification displayed during verification of credentials. */ fun getSyncRetrieveDidsNotification(): Notification { createSyncNotificationChannel() val builder = NotificationCompat.Builder( context, context.getString(R.string.notifications_channel_sync) ) builder.setCategory(NotificationCompat.CATEGORY_SERVICE) builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp) builder.setContentTitle( context.getString( R.string.notifications_sync_retrieve_dids_message ) ) builder.setOngoing(true) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { @Suppress("DEPRECATION") builder.priority = Notification.PRIORITY_LOW } return builder.build() } /** * Gets the notification displayed during verification of credentials. */ fun getSyncRegisterPushNotificationsNotification(): Notification { createSyncNotificationChannel() val builder = NotificationCompat.Builder( context, context.getString(R.string.notifications_channel_sync) ) builder.setCategory(NotificationCompat.CATEGORY_SERVICE) builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp) builder.setContentTitle( context.getString( R.string.notifications_sync_register_push_message ) ) builder.setOngoing(true) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { @Suppress("DEPRECATION") builder.priority = Notification.PRIORITY_LOW } return builder.build() } /** * Returns whether notifications are enabled globally and for the * conversation ID if one is specified. */ fun getNotificationsEnabled( conversationId: ConversationId? = null ): Boolean { // Prior to Android O, check the global notification settings; // otherwise we can just rely on the system to block the notifications if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { @Suppress("DEPRECATION") if (!getNotificationsEnabled(context)) { return false } if (!NotificationManagerCompat.from( context ).areNotificationsEnabled() ) { return false } } else { removePreference( context, context.getString( R.string.preferences_notifications_enable_key ) ) } // However, we do check to see if notifications are enabled for a // particular DID, since the Android O interface doesn't really work // with this use case if (conversationId != null) { if (!getDidShowNotifications(context, conversationId.did)) { return false } } return true } /** * Show notifications for new messages for the specified conversations. */ suspend fun showNotifications( conversationIds: Set<ConversationId>, bubbleOnly: Boolean = false, autoLaunchBubble: Boolean = false, inlineReplyMessages: List<Message> = emptyList() ) { // Do not show notifications when the conversations view is open, // unless this is for a bubble only. if (CustomApplication.getApplication() .conversationsActivityVisible() && !bubbleOnly ) { return } for (conversationId in conversationIds) { // Do not show notifications when notifications are disabled. if (!getNotificationsEnabled(conversationId)) { continue } // Do not show notifications when the conversation view is // open, unless this is for a bubble only. if (CustomApplication.getApplication() .conversationActivityVisible(conversationId) && !bubbleOnly ) { continue } showNotification( conversationId, if (bubbleOnly || inlineReplyMessages.isNotEmpty()) emptyList() else Database.getInstance(context) .getConversationMessagesUnread(conversationId), inlineReplyMessages, bubbleOnly, autoLaunchBubble ) } } /** * Shows a notification for the specified message, bypassing all normal * checks. Only used for demo purposes. */ fun showDemoNotification(message: Message) = showNotification( message.conversationId, listOf(message), inlineReplyMessages = emptyList(), bubbleOnly = false, autoLaunchBubble = false ) /** * Returns true if a notification for the provided DID and contact would * be allowed to bubble. */ fun canBubble(did: String, contact: String): Boolean { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val channel = getNotificationChannelId(did, contact) val notificationManager: NotificationManager = context.getSystemService( Context.NOTIFICATION_SERVICE ) as NotificationManager val bubblesAllowed = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { notificationManager.bubblePreference == NotificationManager.BUBBLE_PREFERENCE_ALL } else { @Suppress("DEPRECATION") notificationManager.areBubblesAllowed() } if (!bubblesAllowed) { val notificationChannel = notificationManager.getNotificationChannel(channel) return notificationChannel != null && notificationChannel.canBubble() } return true } return false } /** * Shows a notification with the specified messages. */ private fun showNotification( conversationId: ConversationId, messages: List<Message>, inlineReplyMessages: List<Message>, bubbleOnly: Boolean, autoLaunchBubble: Boolean ) { // Do not show notification if there are no messages, unless this is // for a bubble notification. if (messages.isEmpty() && inlineReplyMessages.isEmpty() && !bubbleOnly ) { return } // However, if this is not Android R or later, there is no such thing // as a "bubble only" notification, so we should just return. if (bubbleOnly && Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { return } // Notification metadata val did = conversationId.did val contact = conversationId.contact // Do not show bubble-only notifications if we're not allowed to // bubble. if (bubbleOnly && !canBubble(did, contact)) { return } @Suppress("ConstantConditionIf") val contactName = if (!BuildConfig.IS_DEMO) { getContactName(context, contact) ?: getFormattedPhoneNumber(contact) } else { net.kourlas.voipms_sms.demo.getContactName(contact) } val largeIcon = applyCircularMask( getContactPhotoBitmap( context, contactName, contact, context.resources.getDimensionPixelSize( android.R.dimen.notification_large_icon_height ) ) ) val adaptiveIcon = IconCompat.createWithAdaptiveBitmap( getContactPhotoAdaptiveBitmap(context, contactName, contact) ) // Notification channel val channel = getNotificationChannelId(did, contact) // General notification properties val notification = NotificationCompat.Builder(context, channel) notification.setSmallIcon(R.drawable.ic_chat_toolbar_24dp) notification.setLargeIcon(largeIcon) notification.setAutoCancel(true) notification.addPerson( Person.Builder() .setName(contactName) .setKey(contact) .setIcon(adaptiveIcon) .setUri("tel:${contact}") .build() ) notification.setCategory(Notification.CATEGORY_MESSAGE) notification.color = 0xFFAA0000.toInt() if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { @Suppress("DEPRECATION") notification.priority = Notification.PRIORITY_HIGH notification.setLights(0xFFAA0000.toInt(), 1000, 5000) @Suppress("DEPRECATION") val notificationSound = getNotificationSound(context) if (notificationSound != "") { @Suppress("DEPRECATION") notification.setSound(Uri.parse(getNotificationSound(context))) } @Suppress("DEPRECATION") if (getNotificationVibrateEnabled(context)) { notification.setVibrate(longArrayOf(0, 250, 250, 250)) } } else { removePreference( context, context.getString( R.string.preferences_notifications_sound_key ) ) removePreference( context, context.getString( R.string.preferences_notifications_vibrate_key ) ) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { notification.setGroup( context.getString( R.string.notifications_group_key ) ) } notification.setGroupAlertBehavior( NotificationCompat.GROUP_ALERT_CHILDREN ) notification.setShortcutId(conversationId.getId()) notification.setLocusId(LocusIdCompat(conversationId.getId())) if (bubbleOnly || inlineReplyMessages.isNotEmpty()) { // This means no new messages were received, so we should avoid // notifying the user if we can. notification.setOnlyAlertOnce(true) } // Notification text val person = Person.Builder().setName( context.getString(R.string.notifications_current_user) ).build() val style = NotificationCompat.MessagingStyle(person) val existingMessages = notificationMessages[conversationId] ?: emptyList() for (existingMessage in existingMessages) { style.addHistoricMessage(existingMessage) } val messagesToAdd = mutableListOf<Message>() if (messages.isNotEmpty()) { for (message in messages.reversed()) { if (existingMessages.isNotEmpty() && existingMessages.last().text == message.text && existingMessages.last().person != null && existingMessages.last().timestamp == message.date.time ) { break } messagesToAdd.add(message) } messagesToAdd.reverse() } if (inlineReplyMessages.isNotEmpty()) { for (message in inlineReplyMessages) { style.addMessage(message.text, Date().time, null as Person?) } } else if (messagesToAdd.isNotEmpty()) { val notificationMessages = messagesToAdd.map { NotificationCompat.MessagingStyle.Message( it.text, it.date.time, if (it.isIncoming) Person.Builder() .setName(contactName) .setKey(contact) .setIcon(adaptiveIcon) .setUri("tel:${it.contact}") .build() else null ) } for (message in notificationMessages) { style.addMessage(message) } notification.setShowWhen(true) notification.setWhen(messagesToAdd.last().date.time) } notificationMessages[conversationId] = (style.historicMessages.toMutableList() + style.messages.toMutableList()) notification.setStyle(style) // Mark as read button val markReadIntent = MarkReadReceiver.getIntent(context, did, contact) markReadIntent.component = ComponentName( context, MarkReadReceiver::class.java ) val markReadFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_CANCEL_CURRENT } val markReadPendingIntent = PendingIntent.getBroadcast( context, (did + contact + "markRead").hashCode(), markReadIntent, markReadFlags ) val markReadAction = NotificationCompat.Action.Builder( R.drawable.ic_drafts_toolbar_24dp, context.getString(R.string.notifications_button_mark_read), markReadPendingIntent ) .setSemanticAction( NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ ) .setShowsUserInterface(false) .build() notification.addAction(markReadAction) // Reply button val replyIntent = SendMessageReceiver.getIntent( context, did, contact ) replyIntent.component = ComponentName( context, SendMessageReceiver::class.java ) val replyFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_MUTABLE } else { PendingIntent.FLAG_CANCEL_CURRENT } val replyPendingIntent = PendingIntent.getBroadcast( context, (did + contact + "reply").hashCode(), replyIntent, replyFlags ) val remoteInput = RemoteInput.Builder( context.getString( R.string.notifications_reply_key ) ) .setLabel(context.getString(R.string.notifications_button_reply)) .build() val replyActionBuilder = NotificationCompat.Action.Builder( R.drawable.ic_reply_toolbar_24dp, context.getString(R.string.notifications_button_reply), replyPendingIntent ) .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY) .setShowsUserInterface(false) .setAllowGeneratedReplies(true) .addRemoteInput(remoteInput) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { notification.addAction(replyActionBuilder.build()) } else { notification.addInvisibleAction(replyActionBuilder.build()) // Inline reply is not supported, so just show the conversation // activity val visibleReplyIntent = Intent( context, ConversationActivity::class.java ) visibleReplyIntent.putExtra( context.getString( R.string.conversation_did ), did ) visibleReplyIntent.putExtra( context.getString( R.string.conversation_contact ), contact ) visibleReplyIntent.putExtra( context.getString( R.string.conversation_extra_focus ), true ) visibleReplyIntent.flags = Intent.FLAG_ACTIVITY_NEW_DOCUMENT val visibleReplyFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_MUTABLE } else { PendingIntent.FLAG_CANCEL_CURRENT } val visibleReplyPendingIntent = PendingIntent.getActivity( context, (did + contact + "replyVisible").hashCode(), visibleReplyIntent, visibleReplyFlags ) val visibleReplyActionBuilder = NotificationCompat.Action.Builder( R.drawable.ic_reply_toolbar_24dp, context.getString(R.string.notifications_button_reply), visibleReplyPendingIntent ) .setSemanticAction( NotificationCompat.Action.SEMANTIC_ACTION_REPLY ) .setShowsUserInterface(true) .addRemoteInput(remoteInput) notification.addAction(visibleReplyActionBuilder.build()) } // Group notification if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val groupNotification = NotificationCompat.Builder(context, channel) groupNotification.setSmallIcon(R.drawable.ic_chat_toolbar_24dp) groupNotification.setGroup( context.getString( R.string.notifications_group_key ) ) groupNotification.setGroupSummary(true) groupNotification.setAutoCancel(true) groupNotification.setGroupAlertBehavior( NotificationCompat.GROUP_ALERT_CHILDREN ) val intent = Intent(context, ConversationsActivity::class.java) val stackBuilder = TaskStackBuilder.create(context) stackBuilder.addNextIntentWithParentStack(intent) val groupFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_CANCEL_CURRENT } groupNotification.setContentIntent( stackBuilder.getPendingIntent( "group".hashCode(), groupFlags ) ) try { NotificationManagerCompat.from(context).notify( GROUP_NOTIFICATION_ID, groupNotification.build() ) } catch (e: SecurityException) { Toast.makeText( context, context.getString(R.string.notifications_security_error), Toast.LENGTH_LONG ).show() } } // Primary notification action val intent = Intent(context, ConversationActivity::class.java) intent.putExtra( context.getString( R.string.conversation_did ), did ) intent.putExtra( context.getString( R.string.conversation_contact ), contact ) val stackBuilder = TaskStackBuilder.create(context) stackBuilder.addNextIntentWithParentStack(intent) val primaryFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_CANCEL_CURRENT } notification.setContentIntent( stackBuilder.getPendingIntent( (did + contact).hashCode(), primaryFlags ) ) // Bubble if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val bubbleIntent = Intent( context, ConversationBubbleActivity::class.java ) bubbleIntent.putExtra( context.getString( R.string.conversation_did ), did ) bubbleIntent.putExtra( context.getString( R.string.conversation_contact ), contact ) val bubbleFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_MUTABLE } else { 0 } val bubblePendingIntent = PendingIntent.getActivity( context, 0, bubbleIntent, bubbleFlags ) val bubbleMetadata = NotificationCompat.BubbleMetadata.Builder( bubblePendingIntent, adaptiveIcon ) .setDesiredHeight(600) .setSuppressNotification(bubbleOnly) .setAutoExpandBubble(autoLaunchBubble) .build() notification.bubbleMetadata = bubbleMetadata } // Notification ID var id = notificationIds[conversationId] if (id == null) { id = notificationIdCount++ if (notificationIdCount == Int.MAX_VALUE) { notificationIdCount = MESSAGE_START_NOTIFICATION_ID } notificationIds[conversationId] = id } try { NotificationManagerCompat.from(context).notify( id, notification.build() ) } catch (e: SecurityException) { logException(e) } } /** * Cancels the notification associated with the specified conversation ID. */ fun cancelNotification(conversationId: ConversationId) { val id = notificationIds[conversationId] ?: return NotificationManagerCompat.from(context).cancel(id) clearNotificationState(conversationId) } /** * Clears our internal state associated with a notification, cancelling * the group notification if required. */ fun clearNotificationState(conversationId: ConversationId) { notificationMessages.remove(conversationId) validateGroupNotification() } /** * Gets the notification channel ID for the provided DID and contact. The * channel is guaranteed to exist. */ private fun getNotificationChannelId(did: String, contact: String): String { createDefaultNotificationChannel() return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { // Prior to Android O, this doesn't matter. context.getString(R.string.notifications_channel_default) } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) { // Prior to Android R, conversations did not have a separate // section in the notification settings, so we only create the // conversation specific channel if the user requested it. val channel = notificationManager.getNotificationChannel( context.getString( R.string.notifications_channel_contact, did, contact ) ) if (channel == null) { context.getString(R.string.notifications_channel_default) } else { context.getString( R.string.notifications_channel_contact, did, contact ) } } else { // As of Android R, conversations have a separate section in the // notification settings, so we always create the conversation // specific channel. createDidNotificationChannel(did, contact) context.getString( R.string.notifications_channel_contact, did, contact ) } } /** * Cancels the group notification if required. */ private fun validateGroupNotification() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val noOtherNotifications = notificationManager.activeNotifications .filter { it.id != SYNC_DATABASE_NOTIFICATION_ID && it.id != SYNC_SEND_MESSAGE_NOTIFICATION_ID && it.id != SYNC_VERIFY_CREDENTIALS_NOTIFICATION_ID && it.id != SYNC_RETRIEVE_DIDS_NOTIFICATION_ID && it.id != SYNC_REGISTER_PUSH_NOTIFICATION_ID && it.id != GROUP_NOTIFICATION_ID } .none() if (noOtherNotifications) { NotificationManagerCompat.from(context).cancel( GROUP_NOTIFICATION_ID ) } } } companion object { // It is not a leak to store an instance to the application context, // since it has the same lifetime as the application itself @SuppressLint("StaticFieldLeak") private var instance: Notifications? = null // Notification ID for the database synchronization notification. const val SYNC_DATABASE_NOTIFICATION_ID = 1 // Notification ID for the send message notification. const val SYNC_SEND_MESSAGE_NOTIFICATION_ID = SYNC_DATABASE_NOTIFICATION_ID + 1 // Notification ID for the verify credentials notification. const val SYNC_VERIFY_CREDENTIALS_NOTIFICATION_ID = SYNC_SEND_MESSAGE_NOTIFICATION_ID + 1 // Notification ID for the retrieve DIDs notification. const val SYNC_RETRIEVE_DIDS_NOTIFICATION_ID = SYNC_VERIFY_CREDENTIALS_NOTIFICATION_ID + 1 // Notification ID for the register for push notifications notification. const val SYNC_REGISTER_PUSH_NOTIFICATION_ID = SYNC_RETRIEVE_DIDS_NOTIFICATION_ID + 1 // Notification ID for the group notification, which contains all other // notifications const val GROUP_NOTIFICATION_ID = SYNC_REGISTER_PUSH_NOTIFICATION_ID + 1 // Starting notification ID for ordinary message notifications const val MESSAGE_START_NOTIFICATION_ID = GROUP_NOTIFICATION_ID + 1 /** * Gets the sole instance of the Notifications class. Initializes the * instance if it does not already exist. */ fun getInstance(context: Context): Notifications = instance ?: synchronized(this) { instance ?: Notifications( context.applicationContext ).also { instance = it } } } }
apache-2.0
7ec2f63e3823c633760e4f2fb6e1247c
36.775491
101
0.582834
5.61485
false
false
false
false
MER-GROUP/intellij-community
platform/vcs-log/graph/test/com/intellij/vcs/log/graph/impl/FragmentGeneratorTest.kt
2
4951
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.vcs.log.graph.impl import com.intellij.vcs.log.graph.api.LinearGraph import com.intellij.vcs.log.graph.api.LiteLinearGraph import com.intellij.vcs.log.graph.collapsing.FragmentGenerator import com.intellij.vcs.log.graph.graph import com.intellij.vcs.log.graph.utils.LinearGraphUtils import org.junit.Assert.assertEquals import org.junit.Test private val LinearGraph.lite: LiteLinearGraph get() = LinearGraphUtils.asLiteLinearGraph(this) private fun LinearGraph.getMiddleNodes(upNode: Int, downNode: Int) = FragmentGenerator(lite) { false }.getMiddleNodes(upNode, downNode, false) private infix fun Collection<Int>.assert(s: String) = assertEquals(s, sorted().joinToString(",")) private infix fun Int?.assert(i: Int?) = assertEquals(i, this) private fun LinearGraph.redNodes(vararg redNode: Int = IntArray(0)): FragmentGenerator { val redNodes = redNode.toSet() return FragmentGenerator(lite) { getNodeId(it) in redNodes } } private val Int?.s: String get() = if (this == null) "n" else toString() private infix fun FragmentGenerator.GreenFragment.assert(s: String) = assertEquals(s, "${getUpRedNode().s}|${getDownRedNode().s}|${getMiddleGreenNodes().sorted().joinToString(",")}") /* 0 | 1 | 2 */ val simple = graph { 0(1, 2) 1(2) 2() } /* 0 | 1 |/ 2 */ val twoBranch = graph { 0(2) 1(2) 2() } /* 0 |\ 1 2 |\|\ 3 4 5 */ val downTree = graph { 0(1, 2) 1(3, 4) 2(4, 5) 3() 4() 5() } /* 0 1 2 \/\/ 3 4 \/ 5 */ val upTree = graph { 0(3) 1(3, 4) 2(4) 3(5) 4(5) 5() } /* 0 |\ | 1 2 |\ | | 3 | 4 | |/ 5 6 /| |\/ / |7 / \ / 8 */ val difficult = graph { 0(1, 2) 1(3, 4) 2(6) 3(5) 4(6) 5(7, 8) 6(7, 8) 7() 8() } class FragmentGeneratorTest { class MiddleNodesTest { @Test fun simple() = simple.getMiddleNodes(0, 2) assert "0,1,2" @Test fun empty() = twoBranch.getMiddleNodes(0, 1) assert "" @Test fun withDownRedundantBranches() = downTree.getMiddleNodes(0, 4) assert "0,1,2,4" @Test fun withUpRedundantBranches() = upTree.getMiddleNodes(1, 5) assert "1,3,4,5" @Test fun difficult1() = difficult.getMiddleNodes(1, 7) assert "1,3,4,5,6,7" @Test fun difficult2() = difficult.getMiddleNodes(0, 5) assert "0,1,3,5" @Test fun difficult3() = difficult.getMiddleNodes(1, 8) assert "1,3,4,5,6,8" } class NearRedNode { @Test fun simple1() = simple.redNodes(0).getNearRedNode(2, 10, true) assert 0 @Test fun simple2() = simple.redNodes(2).getNearRedNode(0, 10, false) assert 2 @Test fun simple3() = simple.redNodes(2, 1).getNearRedNode(0, 10, false) assert 1 @Test fun simple4() = simple.redNodes(0, 1).getNearRedNode(0, 10, false) assert 0 @Test fun simple5() = simple.redNodes(0, 1).getNearRedNode(2, 10, true) assert 1 @Test fun downTree1() = downTree.redNodes(4, 5).getNearRedNode(0, 10, false) assert 4 @Test fun downTree2() = downTree.redNodes(2, 3).getNearRedNode(0, 10, false) assert 2 @Test fun upTree1() = upTree.redNodes(1, 2).getNearRedNode(5, 10, true) assert 2 @Test fun upTree2() = upTree.redNodes(4, 0).getNearRedNode(5, 10, true) assert 4 @Test fun difficult1() = difficult.redNodes(4, 5, 6).getNearRedNode(0, 10, false) assert 4 @Test fun difficult2() = difficult.redNodes(2, 5, 6).getNearRedNode(1, 10, false) assert 5 @Test fun nullAnswer1() = difficult.redNodes(8).getNearRedNode(0, 6, false) assert null @Test fun nullAnswer2() = difficult.redNodes(8).getNearRedNode(0, 7, false) assert 8 } class GreenFragment { @Test fun simple1() = simple.redNodes(0).getGreenFragmentForCollapse(2, 10) assert "0|n|1,2" @Test fun simple2() = simple.redNodes(0, 2).getGreenFragmentForCollapse(1, 10) assert "0|2|1" @Test fun simple3() = simple.redNodes(0, 2).getGreenFragmentForCollapse(0, 10) assert "n|n|" @Test fun downTree1() = downTree.redNodes(4).getGreenFragmentForCollapse(2, 10) assert "n|4|0,2" @Test fun downTree2() = downTree.redNodes(4).getGreenFragmentForCollapse(1, 10) assert "n|4|0,1" @Test fun difficult1() = difficult.redNodes(1, 7).getGreenFragmentForCollapse(3, 10) assert "1|7|3,5" @Test fun difficult2() = difficult.redNodes(1, 7).getGreenFragmentForCollapse(8, 10) assert "1|n|3,4,5,6,8" @Test fun difficult3() = difficult.redNodes(1, 7).getGreenFragmentForCollapse(2, 10) assert "n|7|0,2,6" } }
apache-2.0
971dea447cee567ac45c65dec6dbe731
27.45977
142
0.683296
3.171685
false
true
false
false
mdaniel/intellij-community
platform/lang-impl/src/com/intellij/codeInspection/incorrectFormatting/IncorrectFormattingInspection.kt
1
2984
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.incorrectFormatting import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ui.InspectionOptionsPanel import com.intellij.ide.plugins.PluginManagerCore import com.intellij.lang.LangBundle import com.intellij.lang.Language import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.util.Key import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile val INSPECTION_KEY = Key.create<IncorrectFormattingInspection>(IncorrectFormattingInspection().shortName) class IncorrectFormattingInspection( @JvmField var reportPerFile: Boolean = false, // generate only one warning per file @JvmField var kotlinOnly: Boolean = false // process kotlin files normally even in silent mode, compatibility ) : LocalInspectionTool() { val isKotlinPlugged: Boolean by lazy { PluginManagerCore.getPlugin(PluginId.getId("org.jetbrains.kotlin")) != null } override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? { // Skip files we are not able to fix if (!file.isWritable) return null // Skip injections val host = InjectedLanguageManager.getInstance(file.project).getInjectionHost(file) if (host != null) { return null } // Perform only for main PSI tree val baseLanguage: Language = file.viewProvider.baseLanguage val mainFile = file.viewProvider.getPsi(baseLanguage) if (file != mainFile) { return null } if (isKotlinPlugged && kotlinOnly && file.language.id != "kotlin") { return null } val document = PsiDocumentManager.getInstance(file.project).getDocument(file) ?: return null val scope = CheckingScope(file, document, manager, isOnTheFly) val changes = scope .getChanges() .takeIf { it.isNotEmpty() } ?: return null return if (reportPerFile) { arrayOf(scope.createGlobalReport()) } else { scope.createAllReports(changes) } } override fun createOptionsPanel() = object : InspectionOptionsPanel(this) { init { addCheckbox(LangBundle.message("inspection.incorrect.formatting.setting.report.per.file"), "reportPerFile") if (isKotlinPlugged) { addCheckbox(LangBundle.message("inspection.incorrect.formatting.setting.kotlin.only"), "kotlinOnly") } } } override fun runForWholeFile() = true override fun getDefaultLevel(): HighlightDisplayLevel = HighlightDisplayLevel.WEAK_WARNING override fun isEnabledByDefault() = false }
apache-2.0
92b83c1c4e6e8e5ebbb572f926381a09
37.753247
158
0.746984
4.805153
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/FacetEntityImpl.kt
1
15311
package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToManyParent import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class FacetEntityImpl: FacetEntity, WorkspaceEntityBase() { companion object { internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, FacetEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) internal val UNDERLYINGFACET_CONNECTION_ID: ConnectionId = ConnectionId.create(FacetEntity::class.java, FacetEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true) val connections = listOf<ConnectionId>( MODULE_CONNECTION_ID, UNDERLYINGFACET_CONNECTION_ID, ) } @JvmField var _name: String? = null override val name: String get() = _name!! override val module: ModuleEntity get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!! @JvmField var _facetType: String? = null override val facetType: String get() = _facetType!! @JvmField var _configurationXmlTag: String? = null override val configurationXmlTag: String? get() = _configurationXmlTag @JvmField var _moduleId: ModuleId? = null override val moduleId: ModuleId get() = _moduleId!! override val underlyingFacet: FacetEntity? get() = snapshot.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this) override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: FacetEntityData?): ModifiableWorkspaceEntityBase<FacetEntity>(), FacetEntity.Builder { constructor(): this(FacetEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity FacetEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isNameInitialized()) { error("Field FacetEntity#name should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field FacetEntity#entitySource should be initialized") } if (_diff != null) { if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) { error("Field FacetEntity#module should be initialized") } } else { if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) { error("Field FacetEntity#module should be initialized") } } if (!getEntityData().isFacetTypeInitialized()) { error("Field FacetEntity#facetType should be initialized") } if (!getEntityData().isModuleIdInitialized()) { error("Field FacetEntity#moduleId should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var name: String get() = getEntityData().name set(value) { checkModificationAllowed() getEntityData().name = value changedProperty.add("name") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var module: ModuleEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } else { this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value } changedProperty.add("module") } override var facetType: String get() = getEntityData().facetType set(value) { checkModificationAllowed() getEntityData().facetType = value changedProperty.add("facetType") } override var configurationXmlTag: String? get() = getEntityData().configurationXmlTag set(value) { checkModificationAllowed() getEntityData().configurationXmlTag = value changedProperty.add("configurationXmlTag") } override var moduleId: ModuleId get() = getEntityData().moduleId set(value) { checkModificationAllowed() getEntityData().moduleId = value changedProperty.add("moduleId") } override var underlyingFacet: FacetEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity } else { this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToManyParentOfChild(UNDERLYINGFACET_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] = value } changedProperty.add("underlyingFacet") } override fun getEntityData(): FacetEntityData = result ?: super.getEntityData() as FacetEntityData override fun getEntityClass(): Class<FacetEntity> = FacetEntity::class.java } } class FacetEntityData : WorkspaceEntityData.WithCalculablePersistentId<FacetEntity>(), SoftLinkable { lateinit var name: String lateinit var facetType: String var configurationXmlTag: String? = null lateinit var moduleId: ModuleId fun isNameInitialized(): Boolean = ::name.isInitialized fun isFacetTypeInitialized(): Boolean = ::facetType.isInitialized fun isModuleIdInitialized(): Boolean = ::moduleId.isInitialized override fun getLinks(): Set<PersistentEntityId<*>> { val result = HashSet<PersistentEntityId<*>>() result.add(moduleId) return result } override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) { index.index(this, moduleId) } override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val removedItem_moduleId = mutablePreviousSet.remove(moduleId) if (!removedItem_moduleId) { index.index(this, moduleId) } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean { var changed = false val moduleId_data = if (moduleId == oldLink) { changed = true newLink as ModuleId } else { null } if (moduleId_data != null) { moduleId = moduleId_data } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FacetEntity> { val modifiable = FacetEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): FacetEntity { val entity = FacetEntityImpl() entity._name = name entity._facetType = facetType entity._configurationXmlTag = configurationXmlTag entity._moduleId = moduleId entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun persistentId(): PersistentEntityId<*> { return FacetId(name, facetType, moduleId) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return FacetEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as FacetEntityData if (this.name != other.name) return false if (this.entitySource != other.entitySource) return false if (this.facetType != other.facetType) return false if (this.configurationXmlTag != other.configurationXmlTag) return false if (this.moduleId != other.moduleId) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as FacetEntityData if (this.name != other.name) return false if (this.facetType != other.facetType) return false if (this.configurationXmlTag != other.configurationXmlTag) return false if (this.moduleId != other.moduleId) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + name.hashCode() result = 31 * result + facetType.hashCode() result = 31 * result + configurationXmlTag.hashCode() result = 31 * result + moduleId.hashCode() return result } }
apache-2.0
e06b5d4140d0001c942c902517a2fbe2
41.181818
183
0.602051
5.92531
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/code-insight/api/src/org/jetbrains/kotlin/idea/codeinsight/api/applicators/AbstractKotlinApplicatorBasedIntention.kt
3
3026
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeinsight.api.applicators import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.analyzeWithReadAction import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical import org.jetbrains.kotlin.psi.KtElement import kotlin.reflect.KClass abstract class AbstractKotlinApplicatorBasedIntention<PSI : KtElement, INPUT : KotlinApplicatorInput>( elementType: KClass<PSI>, ) : SelfTargetingIntention<PSI>(elementType.java, { "" }) { abstract fun getApplicator(): KotlinApplicator<PSI, INPUT> abstract fun getApplicabilityRange(): KotlinApplicabilityRange<PSI> abstract fun getInputProvider(): KotlinApplicatorInputProvider<PSI, INPUT> init { setFamilyNameGetter { getApplicator().getFamilyName() } } final override fun isApplicableTo(element: PSI, caretOffset: Int): Boolean { val project = element.project// TODO expensive operation, may require traversing the tree up to containing PsiFile val applicator = getApplicator() if (!applicator.isApplicableByPsi(element, project)) return false val ranges = getApplicabilityRange().getApplicabilityRanges(element) if (ranges.isEmpty()) return false // An KotlinApplicabilityRange should be relative to the element, while `caretOffset` is absolute val relativeCaretOffset = caretOffset - element.textRange.startOffset if (ranges.none { it.containsOffset(relativeCaretOffset) }) return false val input = getInput(element) if (input != null && input.isValidFor(element)) { val actionText = applicator.getActionName(element, input) val familyName = applicator.getFamilyName() setFamilyNameGetter { familyName } setTextGetter { actionText } return true } return false } final override fun applyTo(element: PSI, project: Project, editor: Editor?) { val input = getInput(element) ?: return if (input.isValidFor(element)) { val applicator = getApplicator() // TODO reuse existing applicator runWriteActionIfPhysical(element) { applicator.applyTo(element, input, project, editor) } } } final override fun applyTo(element: PSI, editor: Editor?) { applyTo(element, element.project, editor) } @OptIn(KtAllowAnalysisOnEdt::class) private fun getInput(element: PSI): INPUT? = allowAnalysisOnEdt { analyzeWithReadAction(element) { with(getInputProvider()) { provideInput(element) } } } }
apache-2.0
da26af4b8787c08d66e8eb94a184a37b
40.452055
122
0.716127
5.051753
false
false
false
false
team401/SnakeSkin
SnakeSkin-FRC/src/main/kotlin/org/snakeskin/auto/AutoManager.kt
1
1779
package org.snakeskin.auto import org.snakeskin.executor.ExceptionHandlingRunnable import org.snakeskin.executor.IExecutorTaskHandle import org.snakeskin.measure.time.TimeMeasureSeconds import org.snakeskin.runtime.SnakeskinRuntime /** * @author Cameron Earle * @version 4/3/18 */ object AutoManager { private val executor = SnakeskinRuntime.primaryExecutor private var autoTaskHandle: IExecutorTaskHandle? = null private var wasRunning = false private var time: TimeMeasureSeconds = TimeMeasureSeconds(0.0) private var lastTime: TimeMeasureSeconds = TimeMeasureSeconds(0.0) private var auto: AutoLoop = object : AutoLoop() { override val rate = TimeMeasureSeconds(0.02) override fun startTasks() {} override fun stopTasks() {} override fun entry(currentTime: TimeMeasureSeconds) {} override fun action(currentTime: TimeMeasureSeconds, lastTime: TimeMeasureSeconds) {} override fun exit(currentTime: TimeMeasureSeconds) {} } fun setAutoLoop(loop: AutoLoop) { auto.stopTasks() auto = loop auto.startTasks() } private fun tick() { time = SnakeskinRuntime.timestamp if (auto.tick(time, lastTime)) { stop() } lastTime = time } @Synchronized fun start() { time = SnakeskinRuntime.timestamp auto.entry(time) wasRunning = true lastTime = TimeMeasureSeconds(0.0) autoTaskHandle = executor.schedulePeriodicTask(ExceptionHandlingRunnable(::tick), auto.rate) } @Synchronized fun stop() { time = SnakeskinRuntime.timestamp autoTaskHandle?.stopTask(true) if (wasRunning) { auto.exit(time) } wasRunning = false } }
gpl-3.0
04a0d489b3d8b3d00475da521fba6308
29.169492
100
0.671164
4.887363
false
false
false
false
squanchy-dev/squanchy-android
app/src/main/java/net/squanchy/settings/preferences/LocalPreferences.kt
1
984
package net.squanchy.settings.preferences import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import io.reactivex.Observable fun showFavoritesInScheduleObservable(context: Context) = context.defaultSharedPreferences.observeFlag("favorites_in_schedule_preference_key", false) private val Context.defaultSharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(this) private fun SharedPreferences.observeFlag(key: String, defaultValue: Boolean = false): Observable<Boolean> = Observable.create { emitter -> val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, changedKey -> if (key == changedKey) { emitter.onNext(getBoolean(key, defaultValue)) } } emitter.onNext(getBoolean(key, defaultValue)) registerOnSharedPreferenceChangeListener(listener) emitter.setCancellable { unregisterOnSharedPreferenceChangeListener(listener) } }
apache-2.0
91b237e3285a78d4b4419537c541348c
40
139
0.792683
5.347826
false
false
false
false
GunoH/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/ProprietaryBuildTools.kt
2
2896
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.collections.immutable.PersistentMap import org.jetbrains.intellij.build.fus.FeatureUsageStatisticsProperties import java.nio.file.Path /** * Describes proprietary tools which are used to build the product. Pass the instance of this class to {@link BuildContext#createContext} method. */ class ProprietaryBuildTools( /** * This tool is required to sign *.exe files in Windows distribution. If it is {@code null} the files won't be signed and Windows may show * a warning when user tries to run them. */ val signTool: SignTool, /** * This tool is used to scramble the main product JAR file if {@link ProductProperties#scrambleMainJar} is {@code true} */ val scrambleTool: ScrambleTool?, /** * Describes address and credentials of Mac machine which is used to sign and build *.dmg installer for macOS. If {@code null} only *.sit * archive will be built. */ val macHostProperties: MacHostProperties?, /** * Describes a server that can be used to download built artifacts to install plugins into IDE */ val artifactsServer: ArtifactsServer?, /** * Properties required to bundle a default version of feature usage statistics white list into IDE */ val featureUsageStatisticsProperties: FeatureUsageStatisticsProperties?, /** * Generation of shared indexes and other tasks may require a valid license to run, * specify the license server URL to avoid hard-coding any license. */ val licenseServerHost: String? ) { companion object { val DUMMY = ProprietaryBuildTools( signTool = object : SignTool { override val usePresignedNativeFiles: Boolean get() = false override suspend fun signFiles(files: List<Path>, context: BuildContext?, options: PersistentMap<String, String>) { Span.current().addEvent("files won't be signed", Attributes.of( AttributeKey.stringArrayKey("files"), files.map(Path::toString), AttributeKey.stringKey("reason"), "sign tool isn't defined", )) } override suspend fun getPresignedLibraryFile(path: String, libName: String, libVersion: String, context: BuildContext): Path? { error("Must be not called if usePresignedNativeFiles is false") } override suspend fun commandLineClient(context: BuildContext, os: OsFamily, arch: JvmArchitecture): Path? { return null } }, scrambleTool = null, macHostProperties = null, artifactsServer = null, featureUsageStatisticsProperties = null, licenseServerHost = null ) } }
apache-2.0
b3e6900ba307749563c3b1e19b54db23
37.105263
145
0.713398
4.701299
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/checker/ReturnTypeMismatchOnOverride.fir.kt
10
601
interface Base { fun foo(): Int var bar: Int val qux: Int } class Derived : Base { override fun foo(): <error descr="[RETURN_TYPE_MISMATCH_ON_OVERRIDE] Return type of 'foo' is not a subtype of the return type of the overridden member 'foo'">String</error> = "" override var bar: <error descr="[VAR_TYPE_MISMATCH_ON_OVERRIDE] Type of 'bar' doesn't match the type of the overridden var-property 'bar'">String</error> = "" override val qux: <error descr="[PROPERTY_TYPE_MISMATCH_ON_OVERRIDE] Type of 'qux' is not a subtype of the overridden property 'qux'">String</error> = "" }
apache-2.0
4e94cb1c1ec43a9d38a96d331fe9ffde
53.636364
181
0.690516
3.732919
false
false
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/cargo/project/workspace/CargoWorkspace.kt
1
8119
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.project.workspace import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import org.rust.cargo.toolchain.impl.CleanCargoMetadata import org.rust.cargo.util.StdLibType import java.util.* import java.util.concurrent.atomic.AtomicReference /** * Rust project model represented roughly in the same way as in Cargo itself. * * [CargoProjectWorkspaceService] is responsible for providing a [CargoWorkspace] for * an IDEA module. */ class CargoWorkspace private constructor( val packages: Collection<Package> ) { class Package( private val contentRootUrl: String, val name: String, val version: String, val targets: Collection<Target>, val source: String?, val origin: PackageOrigin ) { val normName = name.replace('-', '_') val dependencies: MutableList<Package> = ArrayList() val libTarget: Target? get() = targets.find { it.isLib } val contentRoot: VirtualFile? get() = VirtualFileManager.getInstance().findFileByUrl(contentRootUrl) override fun toString() = "Package(contentRootUrl='$contentRootUrl', name='$name')" fun initTargets(): Package { targets.forEach { it.initPackage(this) } return this } fun findCrateByName(normName: String): Target? = if (this.normName == normName) libTarget else dependencies.findLibrary(normName) } class Target( /** * Absolute path to the crate root file */ internal val crateRootUrl: String, val name: String, val kind: TargetKind ) { // target name must be a valid Rust identifier, so normalize it by mapping `-` to `_` // https://github.com/rust-lang/cargo/blob/ece4e963a3054cdd078a46449ef0270b88f74d45/src/cargo/core/manifest.rs#L299 val normName = name.replace('-', '_') val isLib: Boolean get() = kind == TargetKind.LIB val isBin: Boolean get() = kind == TargetKind.BIN val isExample: Boolean get() = kind == TargetKind.EXAMPLE private val crateRootCache = AtomicReference<VirtualFile>() val crateRoot: VirtualFile? get() { val cached = crateRootCache.get() if (cached != null && cached.isValid) return cached val file = VirtualFileManager.getInstance().findFileByUrl(crateRootUrl) crateRootCache.set(file) return file } private lateinit var myPackage: Package fun initPackage(pkg: Package) { myPackage = pkg } val pkg: Package get() = myPackage override fun toString(): String = "Target(crateRootUrl='$crateRootUrl', name='$name', kind=$kind)" } enum class TargetKind { LIB, BIN, TEST, EXAMPLE, BENCH, UNKNOWN } private val targetByCrateRootUrl = packages.flatMap { it.targets }.associateBy { it.crateRootUrl } fun findCrateByNameApproximately(normName: String): Target? = packages.findLibrary(normName) /** * If the [file] is a crate root, returns the corresponding [Target] */ fun findTargetForCrateRootFile(file: VirtualFile): Target? { val canonicalFile = file.canonicalFile ?: return null return targetByCrateRootUrl[canonicalFile.url] } fun findPackage(name: String): Package? = packages.find { it.name == name } fun isCrateRoot(file: VirtualFile): Boolean = findTargetForCrateRootFile(file) != null fun withStdlib(libs: List<StandardLibrary.StdCrate>): CargoWorkspace { val stdlib = libs.map { crate -> val pkg = Package( contentRootUrl = crate.packageRootUrl, name = crate.name, version = "", targets = listOf(Target(crate.crateRootUrl, name = crate.name, kind = TargetKind.LIB)), source = null, origin = PackageOrigin.STDLIB ).initTargets() (crate.name to pkg) }.toMap() // Bind dependencies and collect roots val roots = ArrayList<Package>() val featureGated = ArrayList<Package>() libs.forEach { lib -> val slib = stdlib[lib.name] ?: error("Std lib ${lib.name} not found") val depPackages = lib.dependencies.mapNotNull { stdlib[it] } slib.dependencies.addAll(depPackages) if (lib.type == StdLibType.ROOT) { roots.add(slib) } else if (lib.type == StdLibType.FEATURE_GATED) { featureGated.add(slib) } } roots.forEach { it.dependencies.addAll(roots) } packages.forEach { pkg -> // Only add feature gated crates which names don't conflict with own dependencies val packageFeatureGated = featureGated.filter { o -> pkg.dependencies.none { it.name == o.name } } pkg.dependencies.addAll(roots + packageFeatureGated) } return CargoWorkspace(packages + roots) } val hasStandardLibrary: Boolean get() = packages.any { it.origin == PackageOrigin.STDLIB } companion object { fun deserialize(data: CleanCargoMetadata): CargoWorkspace { // Packages form mostly a DAG. "Why mostly?", you say. // Well, a dev-dependency `X` of package `P` can depend on the `P` itself. // This is ok, because cargo can compile `P` (without `X`, because dev-deps // are used only for tests), then `X`, and then `P`s tests. So we need to // handle cycles here. // Figure out packages origins: // - if a package is a workspace member, or if it resides inside a workspace member directory, it's WORKSPACE // - if a package is a direct dependency of a workspace member, it's DEPENDENCY // - otherwise, it's TRANSITIVE_DEPENDENCY val idToOrigin = HashMap<String, PackageOrigin>(data.packages.size) val workspacePaths = data.packages .filter { it.isWorkspaceMember } .map { it.manifestPath.substringBeforeLast("Cargo.toml", "") } .filter(String::isNotEmpty) .toList() data.packages.forEachIndexed pkgs@ { index, pkg -> if (pkg.isWorkspaceMember || workspacePaths.any { pkg.manifestPath.startsWith(it) }) { idToOrigin[pkg.id] = PackageOrigin.WORKSPACE val depNode = data.dependencies.getOrNull(index) ?: return@pkgs depNode.dependenciesIndexes .mapNotNull { data.packages.getOrNull(it) } .forEach { idToOrigin.merge(it.id, PackageOrigin.DEPENDENCY, { o1, o2 -> PackageOrigin.min(o1, o2) }) } } else { idToOrigin.putIfAbsent(pkg.id, PackageOrigin.TRANSITIVE_DEPENDENCY) } } val packages = data.packages.map { pkg -> val origin = idToOrigin[pkg.id] ?: error("Origin is undefined for package ${pkg.name}") Package( pkg.url, pkg.name, pkg.version, pkg.targets.map { Target(it.url, it.name, it.kind) }, pkg.source, origin ).initTargets() }.toList() // Fill package dependencies packages.forEachIndexed pkgs@ { index, pkg -> val depNode = data.dependencies.getOrNull(index) ?: return@pkgs pkg.dependencies.addAll(depNode.dependenciesIndexes.map { packages[it] }) } return CargoWorkspace(packages) } } } private fun Collection<CargoWorkspace.Package>.findLibrary(normName: String): CargoWorkspace.Target? = filter { it.normName == normName } .mapNotNull { it.libTarget } .firstOrNull()
mit
1471e22b748dbc84df4bb506c98dd8cc
39.393035
123
0.601798
4.720349
false
false
false
false
roylanceMichael/yaclib
core/src/main/java/org/roylance/yaclib/core/services/typescript/TypeScriptServiceBuilder.kt
1
1480
package org.roylance.yaclib.core.services.typescript import org.roylance.common.service.IBuilder import org.roylance.yaclib.YaclibModel import org.roylance.yaclib.core.enums.CommonTokens import org.roylance.yaclib.core.utilities.StringUtilities import org.roylance.yaclib.core.utilities.TypeScriptUtilities class TypeScriptServiceBuilder( private val controller: YaclibModel.Controller) : IBuilder<YaclibModel.File> { override fun build(): YaclibModel.File { val workspace = StringBuilder() val interfaceName = StringUtilities.convertServiceNameToInterfaceName(controller) val initialTemplate = """${CommonTokens.DoNotAlterMessage} export interface $interfaceName { """ workspace.append(initialTemplate) controller.actionsList.forEach { action -> val colonSeparatedInputs = action.inputsList.map { input -> "${input.argumentName}: ${input.filePackage}.${input.messageClass}" }.joinToString() val actionTemplate = "\t${action.name}($colonSeparatedInputs, onSuccess:(response: ${action.output.filePackage}.${action.output.messageClass})=>void, onError:(response:any)=>void)\n" workspace.append(actionTemplate) } workspace.append("}") val returnFile = YaclibModel.File.newBuilder() .setFileToWrite(workspace.toString()) .setFileExtension(YaclibModel.FileExtension.TS_EXT) .setFileName(interfaceName) .setFullDirectoryLocation("") .build() return returnFile } }
mit
96b7e25971f08d0b9ea79043ac1dc4c3
36.974359
188
0.746622
4.639498
false
false
false
false
Novatec-Consulting-GmbH/testit-testutils
logrecorder/logrecorder-assertions/src/test/kotlin/info/novatec/testit/logrecorder/assertion/blocks/MessagesAssertionBlockDslElementsTests.kt
1
7997
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package info.novatec.testit.logrecorder.assertion.blocks import info.novatec.testit.logrecorder.api.LogLevel import info.novatec.testit.logrecorder.api.LogLevel.* import info.novatec.testit.logrecorder.assertion.LogRecordAssertion.Companion.assertThat import info.novatec.testit.logrecorder.assertion.containsExactly import info.novatec.testit.logrecorder.assertion.logEntry import info.novatec.testit.logrecorder.assertion.logRecord import org.junit.jupiter.api.* import org.junit.jupiter.api.DynamicTest.dynamicTest import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource internal class MessagesAssertionBlockDslElementsTests { val exampleLogRecord = logRecord( logEntry(INFO, "start"), logEntry(TRACE, "trace message"), logEntry(DEBUG, "debug message"), logEntry(INFO, "info message"), logEntry(WARN, "warn message"), logEntry(ERROR, "error message"), logEntry(INFO, "end") ) @Test fun `smoke test example`() { assertThat(exampleLogRecord) { containsExactly { info("start") trace("trace message") debug("debug message") info("info message") warn("warn message") error("error message") info("end") } containsExactly { info(startsWith("start")) trace(contains("trace")) debug(equalTo("debug message")) info(matches(".+")) warn(containsInOrder("w", "ar", "n")) error(contains("error", "message")) info(endsWith("end")) } } } @Test fun `anything matcher matches all log levels and messages`() { assertThat(exampleLogRecord) { containsExactly { info("start") anything() anything() anything() anything() anything() info("end") } } } @Nested inner class LogLevelMatcherDslElements { val logLevelsAndCorrespondingMatchers: List<Pair<LogLevel, MessagesAssertionBlock.() -> Unit>> = listOf( TRACE to { trace() }, DEBUG to { debug() }, INFO to { info() }, WARN to { warn() }, ERROR to { error() }, ) @TestFactory fun `specific level matchers match entries with expected log level`() = logLevelsAndCorrespondingMatchers.map { (level, matcher) -> dynamicTest("$level") { val log = logRecord(logEntry(level = level)) assertThat(log) { containsExactly(matcher) } } } @TestFactory fun `specific level matchers do not match entries with different log levels`() = logLevelsAndCorrespondingMatchers.flatMap { (level, matcher) -> LogLevel.values() .filter { it != level } .map { wrongLevel -> dynamicTest("$level != $wrongLevel") { assertThrows<AssertionError> { val log = logRecord(logEntry(level = wrongLevel)) assertThat(log) { containsExactly(matcher) } } } } } @ParameterizedTest @EnumSource(LogLevel::class) fun `any matcher matches all log levels`(logLevel: LogLevel) { assertThat(logRecord(logEntry(logLevel))) { containsExactly { any() } } assertThat(logRecord(logEntry(logLevel, "foo"))) { containsExactly { any("foo") } } assertThat(logRecord(logEntry(logLevel, "bar"))) { containsExactly { any(equalTo("bar")) } } } } @Nested inner class MessageMatcherDslElements { val log = logRecord(logEntry(message = "Foo bar XUR")) @Nested @DisplayName("equalTo(..)") inner class EqualTo { @Test fun `exactly matching message is OK`() { assertThat(log) { containsExactly { any(equalTo("Foo bar XUR")) } } } @Test fun `not matching message throws assertion error`() { assertThrows<AssertionError> { assertThat(log) { containsExactly { any(equalTo("something else")) } } } } } @Nested @DisplayName("matches(..)") inner class Matches { @Test fun `message matching the RegEx is OK`() { assertThat(log) { containsExactly { any(matches("Foo.+")) } } } @Test fun `message not matching the RegEx throws assertion error`() { assertThrows<AssertionError> { assertThat(log) { containsExactly { any(matches("Bar.+")) } } } } } @Nested @DisplayName("contains(..)") inner class Contains { @Test fun `message containing all supplied parts in any order is OK`() { assertThat(log) { containsExactly { any(contains("XUR", "Foo")) } } } @Test fun `message containing non of the parts throws assertion error`() { assertThrows<AssertionError> { assertThat(log) { containsExactly { any(contains("message")) } } } } } @Nested @DisplayName("containsInOrder(..)") inner class ContainsInOrderTests { @Test fun `message containing all supplied parts in order is OK`() { assertThat(log) { containsExactly { any(containsInOrder("Foo", "XUR")) } } } @Test fun `message containing all supplied parts but not in order throws assertion error`() { assertThrows<AssertionError> { assertThat(log) { containsExactly { any(containsInOrder("XUR", "Foo")) } } } } } @Nested @DisplayName("startsWith(..)") inner class StartsWith { @Test fun `message starting with prefix is OK`() { assertThat(log) { containsExactly { any(startsWith("Foo ")) } } } @Test fun `message not starting with prefix throws assertion error`() { assertThrows<AssertionError> { assertThat(log) { containsExactly { any(startsWith("message")) } } } } } @Nested @DisplayName("endsWith(..)") inner class EndsWith { @Test fun `message starting with prefix is OK`() { assertThat(log) { containsExactly { any(endsWith(" XUR")) } } } @Test fun `message not starting with prefix throws assertion error`() { assertThrows<AssertionError> { assertThat(log) { containsExactly { any(endsWith("message")) } } } } } } }
apache-2.0
89d0cf1a3f848cee31070358ea2891a1
31.909465
104
0.535201
5.363514
false
true
false
false
Scavi/BrainSqueeze
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day5BinaryBoarding.kt
1
1297
package com.scavi.brainsqueeze.adventofcode class Day5BinaryBoarding { private fun next(value: Int) = if (value % 2 == 1) (value / 2) + 1 else (value / 2) fun solve(boardingPasses: List<String>, mySeat: Boolean = false): Int { val seatIds = mutableListOf<Int>() for (boardingPass in boardingPasses) { val row = calculate(boardingPass, 127, 0, boardingPass.length - 3) val column = calculate(boardingPass, 7, boardingPass.length - 3, boardingPass.length) seatIds.add((row * 8) + column) } seatIds.sort() if (mySeat) { for (i in seatIds[0] until seatIds[seatIds.size - 1]) { if (!seatIds.contains(i) && seatIds.contains(i - 1) && seatIds.contains(i + 1)) { return i } } } return seatIds[seatIds.size - 1] } private fun calculate(boardingPass: String, hi: Int, from: Int, till: Int): Int { var low = 0 var high = hi var reminder = high for (i in from until till) { reminder = next(reminder) when (boardingPass[i]) { 'F', 'L' -> high -= reminder 'B', 'R' -> low += reminder } } return high } }
apache-2.0
b1c545d2da8c527969c1f965ad5b0365
34.054054
97
0.525829
4.065831
false
false
false
false
songful/PocketHub
app/src/main/java/com/github/pockethub/android/ui/issue/LabelDrawableSpan.kt
1
6558
/* * Copyright (c) 2015 PocketHub * * 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.github.pockethub.android.ui.issue import android.content.res.Resources import android.graphics.Canvas import android.graphics.Color import android.graphics.Color.WHITE import android.graphics.Paint import android.graphics.Rect import android.graphics.Typeface.DEFAULT_BOLD import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.graphics.drawable.LayerDrawable import android.graphics.drawable.PaintDrawable import android.text.style.DynamicDrawableSpan import android.widget.TextView import androidx.text.buildSpannedString import androidx.text.inSpans import com.github.pockethub.android.R import com.github.pockethub.android.util.ServiceUtils import com.meisolsson.githubsdk.model.Label import java.lang.Integer.MIN_VALUE import java.lang.String.CASE_INSENSITIVE_ORDER import java.util.* import java.util.Locale.US /** * Span that draws a [Label] * * @constructor Create background span for label */ class LabelDrawableSpan(private val resources: Resources, private val textSize: Float, color: String, private val paddingLeft: Float, private val textHeight: Float, private val bounds: Rect, private val name: String) : DynamicDrawableSpan() { private val color = Color.parseColor("#$color") /** * @constructor Create drawable for labels */ private class LabelDrawable(private val paddingLeft: Float, private val textHeight: Float, bounds: Rect, resources: Resources, textSize: Float, private val name: String, bg: Int) : PaintDrawable() { private val height = bounds.height().toFloat() private val textColor: Int private val layers: LayerDrawable init { val hsv = FloatArray(3) Color.colorToHSV(bg, hsv) if (hsv[2] > 0.6 && hsv[1] < 0.4 || hsv[2] > 0.7 && hsv[0] > 40 && hsv[0] < 200) { hsv[2] = 0.4f textColor = Color.HSVToColor(hsv) } else { textColor = WHITE } layers = resources.getDrawable(R.drawable.label_background) as LayerDrawable ((layers .findDrawableByLayerId(R.id.item_outer_layer) as LayerDrawable) .findDrawableByLayerId(R.id.item_outer) as GradientDrawable).setColor(bg) ((layers .findDrawableByLayerId(R.id.item_inner_layer) as LayerDrawable) .findDrawableByLayerId(R.id.item_inner) as GradientDrawable).setColor(bg) (layers.findDrawableByLayerId(R.id.item_bg) as GradientDrawable) .setColor(bg) paint.apply { isAntiAlias = true color = resources.getColor(android.R.color.transparent) typeface = DEFAULT_BOLD this.textSize = textSize } layers.bounds = bounds setBounds(bounds) } override fun draw(canvas: Canvas) { super.draw(canvas) layers.draw(canvas) val paint = paint val original = paint.color paint.color = textColor canvas.drawText(name, paddingLeft, height - (height - textHeight) / 2, paint) paint.color = original } } override fun getDrawable(): Drawable = LabelDrawable(paddingLeft, textHeight, bounds, resources, textSize, name, color) companion object { /** * Set text on view to be given labels * * @param view * @param labels */ @JvmStatic fun setText(view: TextView, labels: Collection<Label>) { val sortedLabels = labels.toTypedArray() Arrays.sort(sortedLabels) { lhs, rhs -> CASE_INSENSITIVE_ORDER.compare(lhs.name(), rhs.name()) } setText(view, sortedLabels) } /** * Set text on view to be given label * * @param view * @param label */ @JvmStatic fun setText(view: TextView, label: Label) { setText(view, arrayOf(label)) } private fun setText(view: TextView, labels: Array<Label>) { val resources = view.resources val paddingTop = resources.getDimension(R.dimen.label_padding_top) val paddingLeft = resources.getDimension(R.dimen.label_padding_left) val paddingRight = resources.getDimension(R.dimen.label_padding_right) val paddingBottom = resources.getDimension(R.dimen.label_padding_bottom) val p = Paint() p.typeface = DEFAULT_BOLD p.textSize = view.textSize val textBounds = Rect() val names = arrayOfNulls<String>(labels.size) val nameWidths = IntArray(labels.size) var textHeight = MIN_VALUE for (i in labels.indices) { val name = labels[i].name()!!.toUpperCase(US) textBounds.setEmpty() p.getTextBounds(name, 0, name.length, textBounds) names[i] = name textHeight = Math.max(textBounds.height(), textHeight) nameWidths[i] = textBounds.width() } val textSize = view.textSize view.text = buildSpannedString { for (i in labels.indices) { val bounds = Rect() bounds.right = Math.round(nameWidths[i].toFloat() + paddingLeft + paddingRight + 0.5f) bounds.bottom = Math.round(textHeight.toFloat() + paddingTop + paddingBottom + 0.5f) inSpans(LabelDrawableSpan(resources, textSize, labels[i].color()!!, paddingLeft, textHeight.toFloat(), bounds, names[i]!!)) { append('\uFFFC') } if (i + 1 < labels.size) { append(' ') } } } } } }
apache-2.0
69e5527ef7680a89f87add61b624928b
35.636872
242
0.611467
4.624824
false
false
false
false
programmerr47/ganalytics
ganalytics-core/src/main/java/com/github/programmerr47/ganalytics/core/argsmanagers.kt
1
4454
package com.github.programmerr47.ganalytics.core import java.lang.reflect.Method import kotlin.reflect.KClass interface ArgsManager { fun manage(method: Method, args: Array<Any>?): Pair<String?, Number?> } class LabelArgsManager( private val convention: NamingConvention) : ArgsManager { override fun manage(method: Method, args: Array<Any>?) = when (args?.size) { in arrayOf(0, null) -> buildPair(method, null) 1 -> buildPair(method, manageArgAsValue(method, args)) else -> throw IllegalArgumentException("Method ${method.name} are label, so it can have up to 1 parameter, which is value") } private fun buildPair(method: Method, value: Number?) = Pair(buildLabel(method), value) private fun buildLabel(method: Method): String { return method.getAnnotation(LabelFun::class.java)?.label?.takeNotEmpty() ?: applyConvention(convention, method.name) } private fun manageArgAsValue(method: Method, args: Array<Any>): Number? { return manageValueArg(method, args[0], method.parameterAnnotations[0].label()) } private fun manageValueArg(method: Method, vArg: Any, vArgA: Label?) = if (vArgA != null) { throw IllegalArgumentException("Method ${method.name} can not have @Label annotation on parameters, since it is already a label") } else { vArg as? Number ?: throw IllegalArgumentException("Method ${method.name} can have only 1 parameter which must be a Number") } } class ActionArgsManager( private val globalSettings: GanalyticsSettings) : ArgsManager { override fun manage(method: Method, args: Array<Any>?) = when (args?.size) { in arrayOf(0, null) -> Pair(null, null) 1 -> Pair(convertLabelArg(args[0], method.parameterAnnotations[0]), null) 2 -> manageTwoArgs(args, method.parameterAnnotations) else -> throw IllegalArgumentException("Method ${method.name} have ${method.parameterCount} parameter(s). You can have up to 2 parameters in ordinary methods.") } private fun manageTwoArgs(args: Array<Any>, annotations: Array<Array<Annotation>>): Pair<String, Number> { return manageTwoArgs(args[0], annotations[0].label(), args[1], annotations[1].label()) } private fun manageTwoArgs(arg1: Any, argA1: Label?, arg2: Any, argA2: Label?): Pair<String, Number> { return manageArgAsValue(arg2, argA2, arg1, argA1) { manageArgAsValue(arg1, argA1, arg2, argA2) { throw IllegalArgumentException("For methods with 2 parameters one of them have to be Number without Label annotation") } } } private inline fun manageArgAsValue(vArg: Any, vArgA: Label?, lArg: Any, lArgA: Label?, defaultAction: () -> Pair<String, Number>): Pair<String, Number> { return if (vArg is Number && vArgA == null) { Pair(convertLabelArg(lArg, lArgA), vArg) } else { defaultAction() } } private fun convertLabelArg(label: Any, annotations: Array<Annotation>): String { return convertLabelArg(label, annotations.firstOrNull(Label::class)) } private fun convertLabelArg(label: Any, annotation: Label?): String { return chooseConverter(label, annotation).convert(label) } private fun chooseConverter(label: Any, annotation: Label?): LabelConverter { return annotation?.converter?.init() ?: lookupGlobalConverter(label) ?: SimpleLabelConverter } private fun lookupGlobalConverter(label: Any): LabelConverter? { label.converterClasses().forEach { val converter = globalSettings.labelTypeConverters.lookup(it) if (converter != null) return converter } return null } private fun Any.converterClasses() = if (globalSettings.useTypeConvertersForSubType) javaClass.classHierarchy() else arrayListOf(javaClass) private fun Class<in Any>.classHierarchy() = ArrayList<Class<Any>>().also { var clazz: Class<in Any>? = this do { it.add(clazz!!) clazz = clazz.superclass } while (clazz != null) } private fun KClass<out LabelConverter>.init() = objectInstance ?: java.newInstance() } private fun Array<Annotation>.label() = firstOrNull(Label::class) private fun <R : Any> Array<*>.firstOrNull(klass: KClass<R>): R? { return filterIsInstance(klass.java).firstOrNull() }
mit
0a4a98e12c8a15552929fb4318ae3a6a
40.626168
168
0.668837
4.307544
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/util/ConvertedList.kt
1
4306
/* * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * Copyright (C) 2012 Kristian S. Stangeland * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ /* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.util abstract class ConvertedList<VI, VO>( private val inner: MutableList<VI> ) : ConvertedCollection<VI, VO>(inner), MutableList<VO> { override fun add(index: Int, element: VO) = inner.add(index, toIn(element)) override fun addAll(index: Int, elements: Collection<VO>): Boolean = inner.addAll(index, getInnerCollection(elements.toMutableList())) override fun get(index: Int): VO = toOut(inner[index]) override fun indexOf(element: VO): Int = inner.indexOf(toIn(element)) override fun lastIndexOf(element: VO): Int = inner.lastIndexOf(toIn(element)) override fun listIterator(): MutableListIterator<VO> = listIterator(0) override fun listIterator(index: Int): MutableListIterator<VO> { val innerIterator = inner.listIterator(index) return object: MutableListIterator<VO> { override fun hasPrevious(): Boolean = innerIterator.hasPrevious() override fun nextIndex(): Int = innerIterator.nextIndex() override fun previous(): VO = toOut(innerIterator.previous()) override fun previousIndex(): Int = innerIterator.previousIndex() override fun add(element: VO) = innerIterator.add(toIn(element)) override fun hasNext(): Boolean = innerIterator.hasNext() override fun next(): VO = toOut(innerIterator.next()) override fun remove() = innerIterator.remove() override fun set(element: VO) = innerIterator.set(toIn(element)) } } override fun removeAt(index: Int): VO = toOut(inner.removeAt(index)) override fun set(index: Int, element: VO): VO = toOut(inner.set(index, toIn(element))) override fun subList(fromIndex: Int, toIndex: Int): MutableList<VO> { return object: ConvertedList<VI, VO>(inner.subList(fromIndex, toIndex)) { override fun toIn(outer: VO): VI = [email protected](outer) override fun toOut(inner: VI): VO = [email protected](inner) } } private fun getInnerCollection(elements: MutableCollection<VO>): ConvertedCollection<VO, VI> { return object: ConvertedCollection<VO, VI>(elements) { override fun toIn(outer: VI): VO = [email protected](outer) override fun toOut(inner: VO): VI = [email protected](inner) } } }
gpl-3.0
40bdf69aa8d55681ca20de941aaa01d4
39.242991
98
0.642127
4.610278
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/Suppressions.kt
8
2583
// WITH_STDLIB fun assertCall(x: Int, b: Boolean, c: Boolean) { if (x < 0) return if (Math.random() > 0.5) { assert(x >= 0) } if (Math.random() > 0.5) { assert(b && x >= 0) } if (Math.random() > 0.5) { assert(b || x >= 0) } if (Math.random() > 0.5) { assert(<warning descr="Condition 'c && !(b || x >= 0)' is always false">c && <warning descr="Condition '!(b || x >= 0)' is always false when reached">!(b || <warning descr="Condition 'x >= 0' is always true when reached">x >= 0</warning>)</warning></warning>) } if (Math.random() > 0.5) { assert(c && !(b || x < 0)) } if (Math.random() > 0.5) { assert(<warning descr="Condition 'x < 0' is always false">x < 0</warning>) } } fun requireCall(x: Int) { if (x < 0) return require(x >= 0) require(<warning descr="Condition 'x < 0' is always false">x < 0</warning>) } fun compilerWarningSuppression() { val x: Int = 1 @Suppress("SENSELESS_COMPARISON") if (x == null) {} } fun compilerWarningDuplicate(x : Int) { // Reported as a compiler warning: suppress if (<warning descr="[SENSELESS_COMPARISON] Condition 'x != null' is always 'true'">x != null</warning>) { } } fun compilerWarningDuplicateWhen(x : X) { // Reported as a compiler warning: suppress when (x) { <warning descr="[USELESS_IS_CHECK] Check for instance is always 'true'">is X</warning> -> {} } } fun nothingOrNull(s: String?): String? { return s?.let { if (it.isEmpty()) return null return s } } fun nothingOrNullToElvis(s: String?): Boolean { return s?.let { if (it.isEmpty()) return false return s.hashCode() < 0 } ?: false } // f.get() always returns null but it's inevitable: we cannot return anything else, hence suppress the warning fun alwaysNull(f : MyFuture<Void>) = f.get() fun unusedResult(x: Int) { // Whole condition is always true but reporting it is not very useful x > 0 || return } interface MyFuture<T> { fun get():T? } class X fun updateChain(b: Boolean, c: Boolean): Int { var x = 0 if (b) x = x or 1 if (c) x = x or 2 return x } fun updateChainBoolean(b: Boolean, c: Boolean): Boolean { var x = false x = x || b x = x || c return x } fun updateChainInterrupted(b: Boolean, c: Boolean): Int { var x = 0 x++ <warning descr="Value of 'x--' is always zero">x--</warning> if (b) x = <weak_warning descr="Value of 'x' is always zero">x</weak_warning> or 1 if (c) x = x or 2 return x }
apache-2.0
a72e265135c982f358e7e183fb4b3613
28.689655
267
0.577623
3.277919
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/type/GenericTypeBuilder.kt
1
5029
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.type import java.lang.reflect.Type /** * Builder of a [GenericType]. * * Examples: * * List of String: * `GenericTypeBuilder().withType(List::class.codeType).addOfBound(String::class.codeType).build()` * * T extends List of wildcard extends CharSequence: `<T: List<out CharSequence>>` or `<T extends List<? extends CharSequence>>` * ``` * GenericTypeBuilder().withName("T").withExtendsBound( * GenericTypeBuilder().withType(List::class.codeType).withExtendsBound( * GenericTypeBuilder().wildcard().withExtendsBound(CharSequence::class.codeType).build() * ).build() * ) * ``` * * You may also prefer the [Generic] style: * ``` * Generic.type("T").extends_( * Generic.type(List::class.codeType).extends_( * Generic.wildcard().extends_(CharSequence::class.codeType) * ) * ) * ``` * * **Attention: All calls of the methods of [Generic] class creates a copy of the `bound` array (except the first call), if you mind performance use the [GenericTypeBuilder]** * */ class GenericTypeBuilder() : GenericType.Builder<GenericType, GenericTypeBuilder> { var name: String? = null var type: KoresType? = null var bounds: MutableList<GenericType.Bound> = mutableListOf() constructor(defaults: GenericType) : this() { if (!defaults.isType) this.name = defaults.name else this.type = defaults.resolvedType this.bounds = defaults.bounds.toMutableList() } override fun name(value: String): GenericType.Builder<GenericType, GenericTypeBuilder> { this.name = value this.type = null return this } override fun wildcard(): GenericType.Builder<GenericType, GenericTypeBuilder> { this.name = "*" this.type = null return this } override fun type(value: Type): GenericType.Builder<GenericType, GenericTypeBuilder> { this.name = null this.type = value.koresType return this } override fun bounds(value: Array<GenericType.Bound>): GenericType.Builder<GenericType, GenericTypeBuilder> { this.bounds = value.toMutableList() return this } override fun addBounds(bounds: Array<GenericType.Bound>): GenericType.Builder<GenericType, GenericTypeBuilder> { bounds.forEach { this.bounds.add(it) } return this } override fun addBounds(bounds: Collection<GenericType.Bound>): GenericType.Builder<GenericType, GenericTypeBuilder> { this.bounds.addAll(bounds) return this } override fun addBound(bound: GenericType.Bound): GenericType.Builder<GenericType, GenericTypeBuilder> { this.bounds.add(bound) return this } override fun addExtendsBound(value: Type): GenericType.Builder<GenericType, GenericTypeBuilder> { this.bounds.add(GenericType.Extends(value.koresType)) return this } override fun addSuperBound(value: Type): GenericType.Builder<GenericType, GenericTypeBuilder> { this.bounds.add(GenericType.Super(value.koresType)) return this } override fun addOfBound(value: Type): GenericType.Builder<GenericType, GenericTypeBuilder> { this.bounds.add(GenericType.GenericBound(value.koresType)) return this } override fun build(): GenericType = GenericTypeImpl( name = this.name, codeType = this.type, bounds = this.bounds.toTypedArray() ) companion object { @JvmStatic fun builder() = GenericTypeBuilder() } }
mit
8aecfa4959f0a0f2309ae02ff7b39c96
34.174825
175
0.679857
4.506272
false
false
false
false
JoelMarcey/buck
tools/ideabuck/tests/unit/com/facebook/buck/intellij/ideabuck/actions/select/BuckKotlinTestFunctionDetectorTest.kt
1
6805
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.facebook.buck.intellij.ideabuck.actions.select import com.facebook.buck.intellij.ideabuck.actions.select.BuckKotlinTestClassDetectorTest.MockPotentialTestClass import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test /** Tests [BuckKotlinTestDetector] */ class BuckKotlinTestFunctionDetectorTest { @Test fun testSimpleClassNotATest() { val notATestClass = MockPotentialTestClass() val notATestFunction = MockPotentialTestFunction(containingClass = notATestClass) assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction)) } @Test fun testAbstractClassNotATest() { val notATestClass = MockPotentialTestClass(isAbstract = true) val notATestFunction = MockPotentialTestFunction(containingClass = notATestClass, isAbstract = true) assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction)) } @Test fun testJUnit3TestCase() { val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase") val notATestFunction = MockPotentialTestFunction(containingClass = testClass) assertTrue(BuckKotlinTestDetector.isTestFunction(notATestFunction)) } @Test fun testJUnit3TestCaseNotTestWrongFunctionName() { val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase") val notATestFunction = MockPotentialTestFunction( containingClass = testClass, functionName = "doesn'tStartWithTest") assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction)) } @Test fun testJUnit3TestCaseNotTestPrivateFunction() { val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase") val notATestFunction = MockPotentialTestFunction(containingClass = testClass, isPublic = false) assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction)) } @Test fun testJUnit3TestCaseNotTestAbstractFunction() { val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase") val notATestFunction = MockPotentialTestFunction(containingClass = testClass, isAbstract = true) assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction)) } @Test fun testJUnit3TestCaseNotTestFunctionHasParameters() { val testClass = MockPotentialTestClass(superClass = "junit.framework.TestCase") val notATestFunction = MockPotentialTestFunction(containingClass = testClass, hasParameters = true) assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction)) } @Test fun testPrivateJUnit3TestCaseNotATest() { val notATestClass = MockPotentialTestClass(superClass = "junit.framework.TestCase", isPrivate = true) val notATestFunction = MockPotentialTestFunction(containingClass = notATestClass) assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction)) } @Test fun testNotAccessibleJUnit3TestCaseNotATest() { val notATestClass = MockPotentialTestClass(superClass = "junit.framework.TestCase", isData = true) val notATestFunction = MockPotentialTestFunction(containingClass = notATestClass) assertFalse(BuckKotlinTestDetector.isTestFunction(notATestFunction)) } @Test fun testJUnit4TestFunctionWithTestAnnotation() { val plainClass = MockPotentialTestClass() val testFunction = MockPotentialTestFunction( containingClass = plainClass, functionAnnotations = listOf("org.junit.Test")) assertTrue(BuckKotlinTestDetector.isTestFunction(testFunction)) } @Test fun testJUnit4TestFunctionWithParameters() { val plainClass = MockPotentialTestClass() val testFunction = MockPotentialTestFunction( containingClass = plainClass, hasParameters = true, // it's ok to have that in JUnit4 functionAnnotations = listOf("org.junit.Test")) assertTrue(BuckKotlinTestDetector.isTestFunction(testFunction)) } @Test fun testJUnit4FunctionWithRunWithAnnotations() { val testClass = MockPotentialTestClass(classAnnotations = listOf("org.junit.runner.RunWith")) val testFunction = MockPotentialTestFunction( containingClass = testClass, functionAnnotations = listOf("org.junit.Test")) assertTrue(BuckKotlinTestDetector.isTestFunction(testFunction)) } @Test fun testJUnit4FunctionWithPartialAnnotations() { val testClass = MockPotentialTestClass(classAnnotations = listOf("org.junit.runner.RunWith")) val testFunction = MockPotentialTestFunction(containingClass = testClass) // missing @Test assertFalse(BuckKotlinTestDetector.isTestFunction(testFunction)) } @Test fun testJUnit4TestFunctionWithNGAnnotation() { val testFunction = MockPotentialTestFunction( containingClass = MockPotentialTestClass(), functionAnnotations = listOf("org.testng.annotations.Test")) assertTrue(BuckKotlinTestDetector.isTestFunction(testFunction)) } @Test fun testJUnit4TestAbstractFunctionWithNGAnnotation() { val testFunction = MockPotentialTestFunction( containingClass = MockPotentialTestClass(), isAbstract = true, functionAnnotations = listOf("org.testng.annotations.Test")) assertFalse(BuckKotlinTestDetector.isTestFunction(testFunction)) } } class MockPotentialTestFunction( private val functionAnnotations: List<String> = emptyList(), private val functionName: String = "testJunit3Function", private val isAbstract: Boolean = false, private val isPublic: Boolean = true, private val hasReturnType: Boolean = false, private val hasParameters: Boolean = false, private val containingClass: PotentialTestClass ) : PotentialTestFunction { override fun getContainingClass(): PotentialTestClass? { return containingClass } override fun isPotentialTestFunction(): Boolean = !isAbstract override fun hasAnnotation(annotationName: String): Boolean = functionAnnotations.contains(annotationName) override fun isJUnit3TestMethod(): Boolean { return isPublic && !isAbstract && !hasReturnType && !hasParameters && functionName.startsWith("test") } }
apache-2.0
d89aa9bd4bdfdc9c3636138a21ff9ead
37.664773
112
0.760029
5.685046
false
true
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/glue/system/SystemLogGlueImpl.kt
1
7869
package top.zbeboy.isy.glue.system import com.alibaba.fastjson.JSONObject import org.elasticsearch.index.query.QueryBuilder import org.elasticsearch.index.query.QueryBuilders import org.elasticsearch.search.sort.SortBuilders import org.elasticsearch.search.sort.SortOrder import org.springframework.data.domain.Page import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Repository import org.springframework.util.ObjectUtils import org.springframework.util.StringUtils import top.zbeboy.isy.elastic.pojo.SystemLogElastic import top.zbeboy.isy.elastic.repository.SystemLogElasticRepository import top.zbeboy.isy.glue.plugin.ElasticPlugin import top.zbeboy.isy.glue.util.ResultUtils import top.zbeboy.isy.service.util.DateTimeUtils import top.zbeboy.isy.service.util.SQLQueryUtils import top.zbeboy.isy.web.bean.system.log.SystemLogBean import top.zbeboy.isy.web.util.DataTablesUtils import java.util.* import javax.annotation.Resource /** * Created by zbeboy 2017-10-31 . **/ @Repository("systemLogGlue") open class SystemLogGlueImpl : ElasticPlugin<SystemLogBean>(), SystemLogGlue { @Resource open lateinit var systemLogElasticRepository: SystemLogElasticRepository override fun findAllByPage(dataTablesUtils: DataTablesUtils<SystemLogBean>): ResultUtils<List<SystemLogBean>> { val search = dataTablesUtils.search val resultUtils = ResultUtils<List<SystemLogBean>>() val systemLogElasticPage = systemLogElasticRepository.search(buildSearchQuery(search, dataTablesUtils, false)) return resultUtils.data(dataBuilder(systemLogElasticPage)).totalElements(systemLogElasticPage.totalElements) } override fun countAll(): Long { return systemLogElasticRepository.count() } @Async override fun save(systemLogElastic: SystemLogElastic) { systemLogElasticRepository.save(systemLogElastic) } /** * 构建新数据 * * @param systemLogElasticPage 分页数据 * @return 新数据 */ private fun dataBuilder(systemLogElasticPage: Page<SystemLogElastic>): List<SystemLogBean> { val systemLogs = ArrayList<SystemLogBean>() systemLogElasticPage.content.forEach { s -> val systemLogBean = SystemLogBean() systemLogBean.systemLogId = s.systemLogId systemLogBean.behavior = s.behavior systemLogBean.operatingTime = s.operatingTime systemLogBean.username = s.username systemLogBean.ipAddress = s.ipAddress val date = DateTimeUtils.timestampToDate(s.operatingTime!!) systemLogBean.operatingTimeNew = DateTimeUtils.formatDate(date) systemLogs.add(systemLogBean) } return systemLogs } /** * 系统日志全局搜索条件 * * @param search 搜索参数 * @return 搜索条件 */ override fun searchCondition(search: JSONObject?): QueryBuilder? { val bluerBuilder = QueryBuilders.boolQuery() if (!ObjectUtils.isEmpty(search)) { val username = StringUtils.trimWhitespace(search!!.getString("username")) val behavior = StringUtils.trimWhitespace(search.getString("behavior")) val ipAddress = StringUtils.trimWhitespace(search.getString("ipAddress")) if (StringUtils.hasLength(username)) { val wildcardQueryBuilder = QueryBuilders.wildcardQuery("username", SQLQueryUtils.elasticLikeAllParam(username)) bluerBuilder.must(wildcardQueryBuilder) } if (StringUtils.hasLength(behavior)) { val matchQueryBuilder = QueryBuilders.matchPhraseQuery("behavior", behavior) bluerBuilder.must(matchQueryBuilder) } if (StringUtils.hasLength(ipAddress)) { val wildcardQueryBuilder = QueryBuilders.wildcardQuery("ipAddress", SQLQueryUtils.elasticLikeAllParam(ipAddress)) bluerBuilder.must(wildcardQueryBuilder) } } return bluerBuilder } /** * 系统日志排序 * * @param dataTablesUtils datatables工具类 * @param nativeSearchQueryBuilder 查询器 */ override fun sortCondition(dataTablesUtils: DataTablesUtils<SystemLogBean>, nativeSearchQueryBuilder: NativeSearchQueryBuilder): NativeSearchQueryBuilder? { val orderColumnName = dataTablesUtils.orderColumnName val orderDir = dataTablesUtils.orderDir val isAsc = "asc".equals(orderDir, ignoreCase = true) if (StringUtils.hasLength(orderColumnName)) { if ("system_log_id".equals(orderColumnName, ignoreCase = true)) { if (isAsc) { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.ASC).unmappedType("string")) } else { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.DESC).unmappedType("string")) } } if ("username".equals(orderColumnName, ignoreCase = true)) { if (isAsc) { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("username.keyword").order(SortOrder.ASC).unmappedType("string")) nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.ASC).unmappedType("string")) } else { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("username.keyword").order(SortOrder.DESC).unmappedType("string")) nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.DESC).unmappedType("string")) } } if ("behavior".equals(orderColumnName, ignoreCase = true)) { if (isAsc) { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("behavior.keyword").order(SortOrder.ASC).unmappedType("string")) nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.ASC).unmappedType("string")) } else { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("behavior.keyword").order(SortOrder.DESC).unmappedType("string")) nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.DESC).unmappedType("string")) } } if ("operating_time".equals(orderColumnName, ignoreCase = true)) { if (isAsc) { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("operatingTime").order(SortOrder.ASC).unmappedType("long")) } else { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("operatingTime").order(SortOrder.DESC).unmappedType("long")) } } if ("ip_address".equals(orderColumnName, ignoreCase = true)) { if (isAsc) { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ipAddress.keyword").order(SortOrder.ASC).unmappedType("string")) nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.ASC).unmappedType("string")) } else { nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("ipAddress.keyword").order(SortOrder.DESC).unmappedType("string")) nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("systemLogId.keyword").order(SortOrder.DESC).unmappedType("string")) } } } return nativeSearchQueryBuilder } }
mit
11ce2a894e917f412f0a85128fd5ba4f
47.061728
160
0.684136
5.474684
false
false
false
false
FireZenk/Kartographer
library/src/test/java/org/firezenk/kartographer/library/core/CoreTest.kt
1
2452
package org.firezenk.kartographer.library.core import org.firezenk.kartographer.library.Logger import org.firezenk.kartographer.library.core.util.TargetRoute import org.firezenk.kartographer.library.dsl.route import org.firezenk.kartographer.library.types.Path import org.junit.Assert.* import org.junit.Before import org.junit.Test /** * Created by Jorge Garrido Oval, aka firezenk on 14/01/18. * Project: Kartographer */ class CoreTest { lateinit var core: Core lateinit var move: Move @Before fun setup() { core = Core(Any(), Logger()) move = Move(core) } @Test fun `given a history with one route on default path, the current route is correct`() { val route = route { target = TargetRoute() anchor = Any() } move.routeTo(route) val currentRoute = core.current() assertEquals(route, currentRoute) } @Test fun `given a history with one route on default path, the current route payload is correct`() { val route = route { target = TargetRoute() params = mapOf("param1" to 1, "param2" to "hi!") anchor = Any() } move.routeTo(route) val currentParam1 = core.payload<Int>("param1") val currentParam2 = core.payload<String>("param2") assertEquals(currentParam1, 1) assertEquals(currentParam2, "hi!") } @Test fun `given a history with some route in a custom path, check if exist will return valid`() { val validRoute = route { target = TargetRoute() path = Path("NOTE") anchor = Any() } val invalidRoute = route { target = TargetRoute() path = Path("NONE") anchor = Any() } move.routeTo(validRoute) assertTrue(core.pathExists(validRoute)) assertFalse(core.pathExists(invalidRoute)) } @Test fun `given two routes, the second is valid if don't have the same path than the previous one`() { val validRoute = route { target = TargetRoute() path = Path("ONE") anchor = Any() } val invalidRoute = route { target = TargetRoute() path = Path("TWO") anchor = Any() } assertTrue(core.pathIsValid(validRoute, invalidRoute)) assertFalse(core.pathIsValid(validRoute, validRoute)) } }
mit
442e5c541a8e8e34d0eafe3ddad6ea19
27.858824
107
0.599511
4.339823
false
true
false
false
paplorinc/intellij-community
plugins/stats-collector/log-events/test/com/intellij/stats/completion/ValidatorTest.kt
2
2550
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.stats.completion import com.intellij.stats.validation.EventLine import com.intellij.stats.validation.InputSessionValidator import com.intellij.stats.validation.SessionValidationResult import org.junit.Assert import org.junit.Before import org.junit.Test import java.io.File class ValidatorTest { private companion object { const val SESSION_ID = "d09b94c2c1aa" } lateinit var validator: InputSessionValidator val sessionStatuses = hashMapOf<String, Boolean>() @Before fun setup() { sessionStatuses.clear() val result = object : SessionValidationResult { override fun addErrorSession(errorSession: List<EventLine>) { val sessionUid = errorSession.first().sessionUid ?: return sessionStatuses[sessionUid] = false } override fun addValidSession(validSession: List<EventLine>) { val sessionUid = validSession.first().sessionUid ?: return sessionStatuses[sessionUid] = true } } validator = InputSessionValidator(result) } private fun file(path: String): File { return File(javaClass.classLoader.getResource(path).file) } private fun doTest(fileName: String, isValid: Boolean) { val file = file("data/$fileName") validator.validate(file.readLines()) Assert.assertEquals(isValid, sessionStatuses[SESSION_ID]) } @Test fun testValidData() = doTest("valid_data.txt", true) @Test fun testDataWithAbsentFieldInvalid() = doTest("absent_field.txt", false) @Test fun testInvalidWithoutBacket() = doTest("no_bucket.txt", false) @Test fun testInvalidWithoutVersion() = doTest("no_version.txt", false) @Test fun testDataWithExtraFieldInvalid() = doTest("extra_field.txt", false) @Test fun testWrongFactorsDiff() = doTest("wrong_factors_diff.txt", false) }
apache-2.0
d2dfcdd10637b549cd75779c542a3ff2
30.8875
76
0.691765
4.434783
false
true
false
false
PlanBase/PdfLayoutMgr2
src/test/java/com/planbase/pdf/lm2/attributes/PaddingTest.kt
1
2484
package com.planbase.pdf.lm2.attributes import com.planbase.pdf.lm2.attributes.Padding.Companion.DEFAULT_TEXT_PADDING import com.planbase.pdf.lm2.attributes.Padding.Companion.NO_PADDING import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.organicdesign.testUtils.EqualsContract.equalsDistinctHashCode import kotlin.test.Test class PaddingTest { @Test fun staticFactoryTest() { assertTrue(NO_PADDING == Padding(0.0)) assertTrue(NO_PADDING == Padding(0.0, 0.0, 0.0, 0.0)) assertTrue(DEFAULT_TEXT_PADDING == Padding(1.5, 1.5, 2.0, 1.5)) val (top, right, bottom, left) = Padding(2.0) assertEquals(2.0, top, 0.0) assertEquals(2.0, right, 0.0) assertEquals(2.0, bottom, 0.0) assertEquals(2.0, left, 0.0) val (top1, right1, bottom1, left1) = Padding(3.0, 5.0, 7.0, 11.0) assertEquals(3.0, top1, 0.0) assertEquals(5.0, right1, 0.0) assertEquals(7.0, bottom1, 0.0) assertEquals(11.0, left1, 0.0) } @Test fun equalHashTest() { // Test first item different equalsDistinctHashCode(Padding(1.0), Padding(1.0, 1.0), Padding(1.0), Padding(2.0, 1.0, 1.0, 1.0)) // Test transposed middle items are different (but have same hashcode) equalsDistinctHashCode(Padding(3.0, 5.0, 7.0, 1.1), Padding(3.0, 5.0, 7.0, 1.1), Padding(3.0, 5.0, 7.0, 1.1), Padding(3.0, 7.0, 5.0, 1.1)) // Padding values that differ by less than 0.1 have the same hashcode // but are not equal. Prove it (also tests last item is different): equalsDistinctHashCode(Padding(1.0), Padding(1.0, 1.0, 1.0, 1.0), Padding(1.0), Padding(1.0, 1.0, 1.0, 1.0001)) } @Test fun withModifiersTest() { val pad = NO_PADDING assertEquals(Padding(0.0, 0.0, 0.0, 0.0), pad) assertEquals(Padding(1.0, 0.0, 0.0, 0.0), pad.withTop(1.0)) assertEquals(Padding(0.0, 3.0, 0.0, 0.0), pad.withRight(3.0)) assertEquals(Padding(0.0, 0.0, 5.0, 0.0), pad.withBottom(5.0)) assertEquals(Padding(0.0, 0.0, 0.0, 7.0), pad.withLeft(7.0)) assertEquals(Padding(7.0, 5.0, 3.0, 1.0), pad.withTop(7.0) .withRight(5.0) .withBottom(3.0) .withLeft(1.0)) } }
agpl-3.0
43bd4939386e42ea3e9e6420c18ffd13
39.737705
88
0.570853
3.124528
false
true
false
false
georocket/georocket
src/main/kotlin/io/georocket/output/geojson/GeoJsonMerger.kt
1
4529
package io.georocket.output.geojson import io.georocket.output.Merger import io.georocket.storage.GeoJsonChunkMeta import io.vertx.core.buffer.Buffer import io.vertx.core.json.Json import io.vertx.core.json.JsonObject import io.vertx.core.streams.WriteStream import io.vertx.kotlin.core.json.jsonObjectOf /** * Merges chunks to valid GeoJSON documents * @param optimistic `true` if chunks should be merged optimistically * without prior initialization. In this mode, the merger will always return * `FeatureCollection`s. * @author Michel Kraemer */ class GeoJsonMerger(optimistic: Boolean, private val extensionProperties: JsonObject = jsonObjectOf()) : Merger<GeoJsonChunkMeta> { companion object { private const val NOT_SPECIFIED = 0 private const val GEOMETRY_COLLECTION = 1 private const val FEATURE_COLLECTION = 2 private val TRANSITIONS = listOf( listOf(FEATURE_COLLECTION, GEOMETRY_COLLECTION), listOf(FEATURE_COLLECTION, GEOMETRY_COLLECTION), listOf(FEATURE_COLLECTION, FEATURE_COLLECTION) ) private val RESERVED_PROPERTY_NAMES = listOf("type", "features", "geometries") } /** * `true` if [merge] has been called at least once */ private var mergeStarted = false /** * True if the header has already been written in [merge] */ private var headerWritten = false /** * The GeoJSON object type the merged result should have */ private var mergedType = if (optimistic) FEATURE_COLLECTION else NOT_SPECIFIED init { // check, that all passed extension properties are valid. val usesReservedProperty = RESERVED_PROPERTY_NAMES.any { extensionProperties.containsKey(it) } if (usesReservedProperty) { throw IllegalArgumentException("One of the extension properties is invalid, because the property " + "names \"${RESERVED_PROPERTY_NAMES.joinToString("\", \"")}\" are reserved.") } } private fun writeExtensionProperties(outputStream: WriteStream<Buffer>) { for ((key, value) in extensionProperties) { outputStream.write(Json.encodeToBuffer(key)) outputStream.write(Buffer.buffer(":")) outputStream.write(Json.encodeToBuffer(value)) outputStream.write(Buffer.buffer(",")) } } /** * Write the header to the given [outputStream] */ private fun writeHeader(outputStream: WriteStream<Buffer>) { outputStream.write(Buffer.buffer("{")) writeExtensionProperties(outputStream) if (mergedType == FEATURE_COLLECTION) { outputStream.write(Buffer.buffer("\"type\":\"FeatureCollection\",\"features\":[")) } else if (mergedType == GEOMETRY_COLLECTION) { outputStream.write(Buffer.buffer("\"type\":\"GeometryCollection\",\"geometries\":[")) } } override fun init(chunkMetadata: GeoJsonChunkMeta) { if (mergeStarted) { throw IllegalStateException( "You cannot initialize the merger anymore " + "after merging has begun" ) } if (mergedType == FEATURE_COLLECTION) { // shortcut: we don't need to analyse the other chunks anymore, // we already reached the most generic type return } // calculate the type of the merged document mergedType = if ("Feature" == chunkMetadata.type) { TRANSITIONS[mergedType][0] } else { TRANSITIONS[mergedType][1] } } override suspend fun merge( chunk: Buffer, chunkMetadata: GeoJsonChunkMeta, outputStream: WriteStream<Buffer> ) { mergeStarted = true if (!headerWritten) { writeHeader(outputStream) headerWritten = true } else { if (mergedType == FEATURE_COLLECTION || mergedType == GEOMETRY_COLLECTION) { outputStream.write(Buffer.buffer(",")) } else { throw IllegalStateException( "Trying to merge two or more chunks but " + "the merger has only been initialized with one chunk." ) } } // check if we have to wrap a geometry into a feature val wrap = mergedType == FEATURE_COLLECTION && "Feature" != chunkMetadata.type if (wrap) { outputStream.write(Buffer.buffer("{\"type\":\"Feature\",\"geometry\":")) } outputStream.write(chunk) if (wrap) { outputStream.write(Buffer.buffer("}")) } } override fun finish(outputStream: WriteStream<Buffer>) { if (!headerWritten) { writeHeader(outputStream) } if (mergedType == FEATURE_COLLECTION || mergedType == GEOMETRY_COLLECTION) { outputStream.write(Buffer.buffer("]}")) } } }
apache-2.0
1203286a839fa3a7352a1f7fc6199903
31.120567
106
0.678516
4.560926
false
false
false
false
lisuperhong/ModularityApp
KaiyanModule/src/main/java/com/lisuperhong/openeye/ui/adapter/CategoryAdapter.kt
1
3414
package com.lisuperhong.openeye.ui.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import com.google.gson.Gson import com.lisuperhong.openeye.R import com.lisuperhong.openeye.mvp.model.bean.BaseBean import com.lisuperhong.openeye.mvp.model.bean.SquareCard import com.lisuperhong.openeye.utils.DensityUtil import com.lisuperhong.openeye.utils.ImageLoad import com.lisuperhong.openeye.utils.JumpActivityUtil import com.lisuperhong.openeye.utils.TypefaceUtil import com.orhanobut.logger.Logger import kotlinx.android.synthetic.main.item_squarecard.view.* import org.json.JSONException import org.json.JSONObject /** * Author: lisuperhong * Time: Create on 2018/9/17 10:21 * Github: https://github.com/lisuperhong * Desc: */ class CategoryAdapter(context: Context, dataList: ArrayList<BaseBean.Item>) : RecyclerView.Adapter<CategoryAdapter.ItemHolder>() { private var context: Context? = null private var dataList: ArrayList<BaseBean.Item> init { this.context = context this.dataList = dataList } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryAdapter.ItemHolder { val view = LayoutInflater.from(context) .inflate(R.layout.item_squarecard, parent, false) return ItemHolder(view) } override fun getItemCount(): Int { return dataList.size } override fun onBindViewHolder(holder: CategoryAdapter.ItemHolder, position: Int) { val item = dataList[position] val gson = Gson() val dataMap = item.data as Map<*, *> var dataJson: JSONObject? = null try { dataJson = JSONObject(dataMap) } catch (e: JSONException) { Logger.d(e.printStackTrace()) } val squareCard = gson.fromJson(dataJson.toString(), SquareCard::class.java) holder.squareCardTv.typeface = TypefaceUtil.getTypefaceFromAsset(TypefaceUtil.FZLanTingCuHei) holder.squareCardTv.text = squareCard.title if (item.type == "squareCard") { val width = (DensityUtil.getScreenWidth(context!!) - DensityUtil.dip2px(context!!, 8f)) / 2 ImageLoad.loadImage(holder.squareCardIv, squareCard.image, width, width) } else if (item.type == "rectangleCard") { val width = DensityUtil.getScreenWidth(context!!) - DensityUtil.dip2px(context!!, 4f) ImageLoad.loadImage(holder.squareCardIv, squareCard.image, width, width / 2) } holder.squareCardRl.setOnClickListener { JumpActivityUtil.parseActionUrl(context!!, squareCard.actionUrl) } } private fun clearAll() = dataList.clear() /** * 初始化或刷新数据 */ fun setRefreshData(datas: ArrayList<BaseBean.Item>) { notifyItemRangeRemoved(0, itemCount) clearAll() dataList.addAll(datas) notifyItemRangeInserted(0, datas.size) } class ItemHolder(view: View) : RecyclerView.ViewHolder(view) { var squareCardRl: RelativeLayout = view.squareCardRl var squareCardIv: ImageView = view.squareCardIv var squareCardTv: TextView = view.squareCardTv } }
apache-2.0
e2bc53fb468f499bed3e67c430912a51
34.041237
99
0.698352
4.367609
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/forge/inspections/sideonly/VariableUseSideOnlyInspection.kt
1
7764
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.inspections.sideonly import com.demonwav.mcdev.util.findContainingClass import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.impl.source.PsiFieldImpl import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import org.jetbrains.annotations.Nls class VariableUseSideOnlyInspection : BaseInspection() { @Nls override fun getDisplayName() = "Invalid usage of variable annotated with @SideOnly" override fun buildErrorString(vararg infos: Any): String { val error = infos[0] as Error return error.getErrorString(*SideOnlyUtil.getSubArray(infos)) } override fun getStaticDescription() = "Variables which are declared with a @SideOnly annotation can only be used " + "in matching @SideOnly classes and methods." override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitReferenceExpression(expression: PsiReferenceExpression?) { if (!SideOnlyUtil.beginningCheck(expression!!)) { return } val declaration = expression.resolve() as? PsiFieldImpl ?: return var elementSide = SideOnlyUtil.checkField(declaration) // Check the class(es) the element is declared in val declarationContainingClass = declaration.containingClass ?: return val declarationClassHierarchySides = SideOnlyUtil.checkClassHierarchy(declarationContainingClass) val declarationClassSide = SideOnlyUtil.getFirstSide(declarationClassHierarchySides) // The element inherits the @SideOnly from it's parent class if it doesn't explicitly set it itself var inherited = false if (declarationClassSide !== Side.NONE && (elementSide === Side.INVALID || elementSide === Side.NONE)) { inherited = true elementSide = declarationClassSide } if (elementSide === Side.INVALID || elementSide === Side.NONE) { return } // Check the class(es) the element is in val containingClass = expression.findContainingClass() ?: return val classSide = SideOnlyUtil.getSideForClass(containingClass) var classAnnotated = false if (classSide !== Side.NONE && classSide !== Side.INVALID) { if (classSide !== elementSide) { if (inherited) { registerError( expression.element, Error.ANNOTATED_CLASS_VAR_IN_CROSS_ANNOTATED_CLASS_METHOD, elementSide.annotation, classSide.annotation, declaration ) } else { registerError( expression.element, Error.ANNOTATED_VAR_IN_CROSS_ANNOTATED_CLASS_METHOD, elementSide.annotation, classSide.annotation, declaration ) } } classAnnotated = true } // Check the method the element is in val methodSide = SideOnlyUtil.checkElementInMethod(expression) // Put error on for method if (elementSide !== methodSide && methodSide !== Side.INVALID) { if (methodSide === Side.NONE) { // If the class is properly annotated the method doesn't need to also be annotated if (!classAnnotated) { if (inherited) { registerError( expression.element, Error.ANNOTATED_CLASS_VAR_IN_UNANNOTATED_METHOD, elementSide.annotation, null, declaration ) } else { registerError( expression.element, Error.ANNOTATED_VAR_IN_UNANNOTATED_METHOD, elementSide.annotation, null, declaration ) } } } else { if (inherited) { registerError( expression.element, Error.ANNOTATED_CLASS_VAR_IN_CROSS_ANNOTATED_METHOD, elementSide.annotation, methodSide.annotation, declaration ) } else { registerError( expression.element, Error.ANNOTATED_VAR_IN_CROSS_ANNOTATED_METHOD, elementSide.annotation, methodSide.annotation, declaration ) } } } } } } enum class Error { ANNOTATED_VAR_IN_UNANNOTATED_METHOD { override fun getErrorString(vararg infos: Any): String { return "Variable annotated with ${infos[0]} cannot be referenced in an un-annotated method." } }, ANNOTATED_CLASS_VAR_IN_UNANNOTATED_METHOD { override fun getErrorString(vararg infos: Any): String { return "Variable declared in a class annotated with ${infos[0]} " + "cannot be referenced in an un-annotated method." } }, ANNOTATED_VAR_IN_CROSS_ANNOTATED_METHOD { override fun getErrorString(vararg infos: Any): String { return "Variable annotated with ${infos[0]} " + "cannot be referenced in a method annotated with ${infos[1]}." } }, ANNOTATED_CLASS_VAR_IN_CROSS_ANNOTATED_METHOD { override fun getErrorString(vararg infos: Any): String { return "Variable declared in a class annotated with ${infos[0]} " + "cannot be referenced in a method annotated with ${infos[1]}." } }, ANNOTATED_VAR_IN_CROSS_ANNOTATED_CLASS_METHOD { override fun getErrorString(vararg infos: Any): String { return "Variable annotated with ${infos[0]} " + "cannot be referenced in a class annotated with ${infos[1]}." } }, ANNOTATED_CLASS_VAR_IN_CROSS_ANNOTATED_CLASS_METHOD { override fun getErrorString(vararg infos: Any): String { return "Variable declared in a class annotated with ${infos[0]}" + " cannot be referenced in a class annotated with ${infos[1]}." } }; abstract fun getErrorString(vararg infos: Any): String } }
mit
df0faa0d38db56388e9372201baab909
41.659341
120
0.494719
6.343137
false
false
false
false
cd1/motofretado
app/src/main/java/com/gmail/cristiandeives/motofretado/TrackBusPresenterLoader.kt
1
1063
package com.gmail.cristiandeives.motofretado import android.content.Context import android.support.annotation.MainThread import android.support.v4.content.Loader import android.util.Log @MainThread internal class TrackBusPresenterLoader(context: Context) : Loader<TrackBusMvp.Presenter>(context) { companion object { private val TAG = TrackBusPresenterLoader::class.java.simpleName } private var mPresenter: TrackBusMvp.Presenter? = null override fun onStartLoading() { Log.v(TAG, "> onStartLoading()") if (mPresenter == null) { forceLoad() } else { deliverResult(mPresenter) } Log.v(TAG, "< onStartLoading()") } override fun onForceLoad() { Log.v(TAG, "> onForceLoad()") mPresenter = TrackBusPresenter(context.applicationContext) deliverResult(mPresenter) Log.v(TAG, "< onForceLoad()") } override fun onReset() { Log.v(TAG, "> onReset()") mPresenter = null Log.v(TAG, "< onReset()") } }
gpl-3.0
e68033674003d4a0ecddbce2bd5f619f
23.181818
99
0.64064
4.410788
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/mapper/impl/CheatDataMapperImpl.kt
1
1355
package com.github.vhromada.catalog.mapper.impl import com.github.vhromada.catalog.domain.CheatData import com.github.vhromada.catalog.entity.ChangeCheatData import com.github.vhromada.catalog.mapper.CheatDataMapper import org.springframework.stereotype.Component /** * A class represents implementation of mapper for cheat's data. * * @author Vladimir Hromada */ @Component("cheatDataMapper") class CheatDataMapperImpl : CheatDataMapper { override fun mapCheatDataList(source: List<CheatData>): List<com.github.vhromada.catalog.entity.CheatData> { return source.map { mapCheatData(source = it) } } override fun mapRequest(source: ChangeCheatData): CheatData { return CheatData( id = null, action = source.action!!, description = source.description!! ) } override fun mapRequests(source: List<ChangeCheatData>): List<CheatData> { return source.map { mapRequest(source = it) } } /** * Maps cheat's data. * * @param source cheat's data * @return mapped cheat's data */ private fun mapCheatData(source: CheatData): com.github.vhromada.catalog.entity.CheatData { return com.github.vhromada.catalog.entity.CheatData( action = source.action, description = source.description ) } }
mit
110eed633f0ee04a4114ad75d7ae033f
29.111111
112
0.682657
4.370968
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/expectactual/AddActualFix.kt
1
4452
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.expectactual import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.quickfix.TypeAccessibilityChecker import org.jetbrains.kotlin.idea.refactoring.getExpressionShortText import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.utils.addToStdlib.safeAs class AddActualFix( actualClassOrObject: KtClassOrObject, missedDeclarations: List<KtDeclaration> ) : KotlinQuickFixAction<KtClassOrObject>(actualClassOrObject) { private val missedDeclarationPointers = missedDeclarations.map { it.createSmartPointer() } override fun getFamilyName() = text override fun getText() = KotlinBundle.message("fix.create.missing.actual.members") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val psiFactory = KtPsiFactory(project) val codeStyleManager = CodeStyleManager.getInstance(project) fun PsiElement.clean() { ShortenReferences.DEFAULT.process(codeStyleManager.reformat(this) as KtElement) } val module = element.module ?: return val checker = TypeAccessibilityChecker.create(project, module) val errors = linkedMapOf<KtDeclaration, KotlinTypeInaccessibleException>() for (missedDeclaration in missedDeclarationPointers.mapNotNull { it.element }) { val actualDeclaration = try { when (missedDeclaration) { is KtClassOrObject -> psiFactory.generateClassOrObject(project, false, missedDeclaration, checker) is KtFunction, is KtProperty -> missedDeclaration.toDescriptor()?.safeAs<CallableMemberDescriptor>()?.let { generateCallable(project, false, missedDeclaration, it, element, checker = checker) } else -> null } ?: continue } catch (e: KotlinTypeInaccessibleException) { errors += missedDeclaration to e continue } if (actualDeclaration is KtPrimaryConstructor) { if (element.primaryConstructor == null) element.addAfter(actualDeclaration, element.nameIdentifier).clean() } else { element.addDeclaration(actualDeclaration).clean() } } if (errors.isNotEmpty()) { val message = errors.entries.joinToString( separator = "\n", prefix = KotlinBundle.message("fix.create.declaration.error.some.types.inaccessible") + "\n" ) { (declaration, error) -> getExpressionShortText(declaration) + " -> " + error.message } showInaccessibleDeclarationError(element, message, editor) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val missedDeclarations = DiagnosticFactory.cast(diagnostic, Errors.NO_ACTUAL_CLASS_MEMBER_FOR_EXPECTED_CLASS).b.mapNotNull { DescriptorToSourceUtils.descriptorToDeclaration(it.first) as? KtDeclaration }.ifEmpty { return null } return (diagnostic.psiElement as? KtClassOrObject)?.let { AddActualFix(it, missedDeclarations) } } } }
apache-2.0
996f1f0639219b77e028a84174f39e29
46.37234
158
0.706424
5.331737
false
false
false
false
google/iosched
shared/src/main/java/com/google/samples/apps/iosched/shared/data/userevent/DefaultSessionAndUserEventRepository.kt
1
11411
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.data.userevent import androidx.annotation.WorkerThread import com.google.samples.apps.iosched.model.ConferenceDay import com.google.samples.apps.iosched.model.Session import com.google.samples.apps.iosched.model.SessionId import com.google.samples.apps.iosched.model.userdata.UserEvent import com.google.samples.apps.iosched.model.userdata.UserSession import com.google.samples.apps.iosched.shared.data.session.SessionRepository import com.google.samples.apps.iosched.shared.domain.sessions.LoadUserSessionUseCaseResult import com.google.samples.apps.iosched.shared.domain.users.ReservationRequestAction import com.google.samples.apps.iosched.shared.domain.users.ReservationRequestAction.RequestAction import com.google.samples.apps.iosched.shared.domain.users.ReservationRequestAction.SwapAction import com.google.samples.apps.iosched.shared.domain.users.StarUpdatedStatus import com.google.samples.apps.iosched.shared.domain.users.SwapRequestAction import com.google.samples.apps.iosched.shared.domain.users.SwapRequestParameters import com.google.samples.apps.iosched.shared.result.Result import kotlinx.coroutines.ExperimentalCoroutinesApi import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import timber.log.Timber /** * Single point of access to user events data associated with a user for the presentation layer. */ @ExperimentalCoroutinesApi @Singleton open class DefaultSessionAndUserEventRepository @Inject constructor( private val userEventDataSource: UserEventDataSource, private val sessionRepository: SessionRepository ) : SessionAndUserEventRepository { @WorkerThread override fun getObservableUserEvents( userId: String? ): Flow<Result<ObservableUserEvents>> { return flow { emit(Result.Loading) // If there is no logged-in user, return the map with null UserEvents if (userId == null) { Timber.d( """EventRepository: No user logged in, |returning sessions without user events.""".trimMargin() ) val allSessions = sessionRepository.getSessions() val userSessions = mergeUserDataAndSessions(null, allSessions) emit( Result.Success( ObservableUserEvents( userSessions = userSessions ) ) ) } else { emitAll( userEventDataSource.getObservableUserEvents(userId).map { userEvents -> Timber.d( """EventRepository: Received ${userEvents.userEvents.size} |user events changes""".trimMargin() ) // Get the sessions, synchronously val allSessions = sessionRepository.getSessions() val userSessions = mergeUserDataAndSessions(userEvents, allSessions) // TODO(b/122306429) expose user events messages separately val userEventsMessageSession = allSessions.firstOrNull { it.id == userEvents.userEventsMessage?.sessionId } Result.Success( ObservableUserEvents( userSessions = userSessions, userMessage = userEvents.userEventsMessage, userMessageSession = userEventsMessageSession ) ) } ) } } } override fun getObservableUserEvent( userId: String?, eventId: SessionId ): Flow<Result<LoadUserSessionUseCaseResult>> { // If there is no logged-in user, return the session with a null UserEvent if (userId == null) { Timber.d("EventRepository: No user logged in, returning session without user event") return flow { val session = sessionRepository.getSession(eventId) emit( Result.Success( LoadUserSessionUseCaseResult( userSession = UserSession(session, createDefaultUserEvent(session)) ) ) ) } } // Observes the user events and merges them with session data. return userEventDataSource.getObservableUserEvent(userId, eventId).map { userEventResult -> Timber.d("EventRepository: Received user event changes") // Get the session, synchronously val event = sessionRepository.getSession(eventId) // Merges session with user data and emits the result val userSession = UserSession( event, userEventResult.userEvent ?: createDefaultUserEvent(event) ) Result.Success(LoadUserSessionUseCaseResult(userSession = userSession)) } } override fun getUserEvents(userId: String?): List<UserEvent> { return userEventDataSource.getUserEvents(userId ?: "") } override fun getUserSession(userId: String, sessionId: SessionId): UserSession { val session = sessionRepository.getSession(sessionId) val userEvent = userEventDataSource.getUserEvent(userId, sessionId) ?: throw Exception("UserEvent not found") return UserSession( session = session, userEvent = userEvent ) } override suspend fun starEvent( userId: String, userEvent: UserEvent ): Result<StarUpdatedStatus> = userEventDataSource.starEvent(userId, userEvent) override suspend fun recordFeedbackSent(userId: String, userEvent: UserEvent): Result<Unit> { return userEventDataSource.recordFeedbackSent(userId, userEvent) } override suspend fun changeReservation( userId: String, sessionId: SessionId, action: ReservationRequestAction ): Result<ReservationRequestAction> { val sessions = sessionRepository.getSessions().associateBy { it.id } val userEvents = getUserEvents(userId) val session = sessionRepository.getSession(sessionId) val overlappingId = findOverlappingReservationId(session, action, sessions, userEvents) if (overlappingId != null) { // If there is already an overlapping reservation, return the result as // SwapAction is needed. val overlappingSession = sessionRepository.getSession(overlappingId) Timber.d( """User is trying to reserve a session that overlaps with the |session id: $overlappingId, title: ${overlappingSession.title}""".trimMargin() ) return Result.Success( SwapAction( SwapRequestParameters( userId, fromId = overlappingId, fromTitle = overlappingSession.title, toId = sessionId, toTitle = session.title ) ) ) } return userEventDataSource.requestReservation(userId, session, action) } override suspend fun swapReservation( userId: String, fromId: SessionId, toId: SessionId ): Result<SwapRequestAction> { val toSession = sessionRepository.getSession(toId) val fromSession = sessionRepository.getSession(fromId) return userEventDataSource.swapReservation(userId, fromSession, toSession) } private fun findOverlappingReservationId( session: Session, action: ReservationRequestAction, sessions: Map<String, Session>, userEvents: List<UserEvent> ): String? { if (action !is RequestAction) return null val overlappingUserEvent = userEvents.find { sessions[it.id]?.isOverlapping(session) == true && (it.isReserved() || it.isWaitlisted()) } return overlappingUserEvent?.id } private fun createDefaultUserEvent(session: Session): UserEvent { return UserEvent(id = session.id) } /** * Merges user data with sessions. */ @WorkerThread private fun mergeUserDataAndSessions( userData: UserEventsResult?, allSessions: List<Session> ): List<UserSession> { // If there is no logged-in user, return the map with null UserEvents if (userData == null) { return allSessions.map { UserSession(it, createDefaultUserEvent(it)) } } val (userEvents, _) = userData val eventIdToUserEvent = userEvents.associateBy { it.id } return allSessions.map { UserSession(it, eventIdToUserEvent[it.id] ?: createDefaultUserEvent(it)) } } override fun getConferenceDays(): List<ConferenceDay> = sessionRepository.getConferenceDays() } interface SessionAndUserEventRepository { // TODO(b/122112739): Repository should not have source dependency on UseCase result fun getObservableUserEvents( userId: String? ): Flow<Result<ObservableUserEvents>> // TODO(b/122112739): Repository should not have source dependency on UseCase result fun getObservableUserEvent( userId: String?, eventId: SessionId ): Flow<Result<LoadUserSessionUseCaseResult>> fun getUserEvents(userId: String?): List<UserEvent> suspend fun changeReservation( userId: String, sessionId: SessionId, action: ReservationRequestAction ): Result<ReservationRequestAction> suspend fun swapReservation( userId: String, fromId: SessionId, toId: SessionId ): Result<SwapRequestAction> suspend fun starEvent(userId: String, userEvent: UserEvent): Result<StarUpdatedStatus> suspend fun recordFeedbackSent( userId: String, userEvent: UserEvent ): Result<Unit> fun getConferenceDays(): List<ConferenceDay> fun getUserSession(userId: String, sessionId: SessionId): UserSession } data class ObservableUserEvents( val userSessions: List<UserSession>, /** A message to show to the user with important changes like reservation confirmations */ val userMessage: UserEventMessage? = null, /** The session the user message is about, if any. */ val userMessageSession: Session? = null )
apache-2.0
cc3d0a0fc638a546a6a6986293ee20b3
38.484429
99
0.641662
5.528585
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/feature/AbstractResolveTagFeature.kt
1
1515
package no.skatteetaten.aurora.boober.feature import mu.KotlinLogging import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec import no.skatteetaten.aurora.boober.service.CantusService import no.skatteetaten.aurora.boober.service.ImageMetadata private const val IMAGE_METADATA_CONTEXT_KEY = "imageMetadata" private val logger = KotlinLogging.logger {} abstract class AbstractResolveTagFeature(open val cantusService: CantusService) : Feature { internal val FeatureContext.imageMetadata: ImageMetadata get() = this.getContextKey( IMAGE_METADATA_CONTEXT_KEY ) abstract fun isActive(spec: AuroraDeploymentSpec): Boolean fun dockerDigestExistsWarning(context: FeatureContext): String? { val imageMetadata = context.imageMetadata return if (imageMetadata.dockerDigest == null) { "Was unable to resolve dockerDigest for image=${imageMetadata.getFullImagePath()}. Using tag instead." } else { null } } fun createImageMetadataContext(repo: String, name: String, tag: String): FeatureContext { logger.debug("Asking cantus about /$repo/$name/$tag") val imageInformationResult = cantusService.getImageMetadata(repo, name, tag) logger.debug("Cantus says: ${imageInformationResult.imagePath} / ${imageInformationResult.imageTag} / ${imageInformationResult.getFullImagePath()}") return mapOf( IMAGE_METADATA_CONTEXT_KEY to imageInformationResult ) } }
apache-2.0
9169a37c15eb7922dabb48aa76e9da1c
37.846154
156
0.727393
4.871383
false
false
false
false
allotria/intellij-community
platform/statistics/uploader/src/com/intellij/internal/statistic/eventLog/EventLogFilesProvider.kt
2
1029
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.eventLog import com.intellij.internal.statistic.StatisticsStringUtil import java.io.File import java.nio.file.Path interface EventLogRecorderConfig { fun getRecorderId(): String fun isSendEnabled(): Boolean fun getLogFilesProvider(): EventLogFilesProvider } interface EventLogFilesProvider { fun getLogFilesDir(): Path? fun getLogFiles(): List<EventLogFile> } class DefaultEventLogFilesProvider(private val dir: Path, private val activeFileProvider: () -> String?): EventLogFilesProvider { override fun getLogFilesDir(): Path = dir override fun getLogFiles(): List<EventLogFile> { val activeFile = activeFileProvider() val files = File(dir.toUri()).listFiles { f: File -> activeFile == null || !StatisticsStringUtil.equals(f.name, activeFile) } return files?.map { EventLogFile(it) }?.toList() ?: emptyList() } }
apache-2.0
bee74e92af5b132c6b561c6be5f07e62
33.333333
140
0.758017
4.360169
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/completion/widget/WidgetVariantsProvider.kt
1
4589
package com.aemtools.completion.widget import com.aemtools.common.constant.const import com.aemtools.completion.model.WidgetMember import com.aemtools.completion.model.psi.PsiWidgetDefinition import com.aemtools.common.util.PsiXmlUtil import com.aemtools.service.ServiceFacade import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.XmlAttributeInsertHandler import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.xml.XmlToken /** * @author Dmytro_Troynikov. */ object WidgetVariantsProvider { val DEFAULT_ATTRIBUTES = listOf("jcr:primaryType", const.XTYPE) val JCR_PRIMARY_TYPE_VALUES = listOf("nt:unstructured", "cq:Widget", "cq:WidgetCollection", "cq:Dialog", "cq:TabPanel", "cq:Panel") /** * Generate variants for given completion parameters and widget definition. * * @param parameters the completion parameters * @param widgetDefinition the widget definition * @return collection of lookup elements */ fun generateVariants(parameters: CompletionParameters, widgetDefinition: PsiWidgetDefinition?) : Collection<LookupElement> { val currentElement = parameters.position as XmlToken val currentPositionType = currentElement.tokenType.toString() if (widgetXtypeUnknown(widgetDefinition)) { when (currentPositionType) { const.xml.XML_ATTRIBUTE_NAME -> { val collection = genericForName() if (widgetDefinition != null) { return collection.filter { it -> widgetDefinition .getFieldValue(it.lookupString) == null } } else { return collection } } const.xml.XML_ATTRIBUTE_VALUE -> { return when (PsiXmlUtil.nameOfAttribute(currentElement)) { const.XTYPE -> variantsForXTypeValue(currentElement) const.JCR_PRIMARY_TYPE -> variantsForJcrPrimaryType() else -> variantsForValue(parameters, widgetDefinition as PsiWidgetDefinition) } } else -> return listOf() } } when (currentPositionType) { const.xml.XML_ATTRIBUTE_NAME -> return variantsForName(widgetDefinition as PsiWidgetDefinition) .filter { it -> widgetDefinition.getFieldValue(it.lookupString) == null } const.xml.XML_ATTRIBUTE_VALUE -> { return when (PsiXmlUtil.nameOfAttribute(currentElement)) { const.XTYPE -> variantsForXTypeValue(currentElement) const.JCR_PRIMARY_TYPE -> variantsForJcrPrimaryType() else -> variantsForValue(parameters, widgetDefinition as PsiWidgetDefinition) } } } return listOf() } private fun widgetXtypeUnknown(widgetDefinition: PsiWidgetDefinition?): Boolean = widgetDefinition?.getFieldValue(const.XTYPE) == null private fun genericForName(): Collection<LookupElement> { return DEFAULT_ATTRIBUTES.map { it -> LookupElementBuilder.create(it) .withInsertHandler(XmlAttributeInsertHandler()) } } private fun variantsForXTypeValue(currentToken: XmlToken): Collection<LookupElement> { val widgetDocRepository = ServiceFacade.getWidgetRepository() val query: String? = PsiXmlUtil.removeCaretPlaceholder(currentToken.text) val xtypes: List<String> = widgetDocRepository.findXTypes(query) return xtypes.map { it -> LookupElementBuilder.create(it) } } private fun variantsForJcrPrimaryType(): Collection<LookupElement> = JCR_PRIMARY_TYPE_VALUES.map { it -> LookupElementBuilder.create(it) } /** * Give variants for attribute name */ private fun variantsForName(widgetDefinition: PsiWidgetDefinition): Collection<LookupElement> { val widgetDocRepository = ServiceFacade.getWidgetRepository() val xtype = widgetDefinition.getFieldValue("xtype") ?: return listOf() val doc = widgetDocRepository.findByXType(xtype) ?: return listOf() val result = doc.members .filter { it.memberType != WidgetMember.MemberType.PUBLIC_METHOD } .map { LookupElementBuilder.create(it.name) .withTypeText(it.type) .withInsertHandler(XmlAttributeInsertHandler()) } return result } /** * Give variants for attribute value */ private fun variantsForValue(parameters: CompletionParameters, widgetDefinition: PsiWidgetDefinition): Collection<LookupElement> = listOf() }
gpl-3.0
7a5fd3d34f312986f35ca92d10e7e407
34.851563
107
0.695794
5.015301
false
false
false
false
allotria/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypingInspectionExtension.kt
3
3083
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.jetbrains.python.codeInsight.typing import com.intellij.psi.PsiReference import com.jetbrains.python.PyNames import com.jetbrains.python.inspections.PyInspectionExtension import com.jetbrains.python.psi.PyElement import com.jetbrains.python.psi.PyReferenceExpression import com.jetbrains.python.psi.PySubscriptionExpression import com.jetbrains.python.psi.PyTargetExpression import com.jetbrains.python.psi.impl.PyBuiltinCache import com.jetbrains.python.psi.impl.references.PyOperatorReference import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.types.PyClassLikeType import com.jetbrains.python.psi.types.PyClassType import com.jetbrains.python.psi.types.TypeEvalContext class PyTypingInspectionExtension : PyInspectionExtension() { override fun ignoreUnresolvedReference(node: PyElement, reference: PsiReference, context: TypeEvalContext): Boolean { if (node is PySubscriptionExpression && reference is PyOperatorReference && node.referencedName == PyNames.GETITEM) { val operand = node.operand val type = context.getType(operand) if (type is PyClassLikeType && type.isDefinition && isGenericItselfOrDescendant(type, context)) { // `true` is not returned for the cases like `typing.List[int]` // because these types contain builtins as a class if (!isBuiltin(type)) return true // here is the check that current element is like `typing.List[int]` // but be careful: builtin collections inherit `typing.Generic` in typeshed if (operand is PyReferenceExpression) { val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context) val resolveResults = operand.getReference(resolveContext).multiResolve(false) if (resolveResults .asSequence() .map { it.element } .any { it is PyTargetExpression && PyTypingTypeProvider.BUILTIN_COLLECTION_CLASSES.containsKey(it.qualifiedName) }) { return true } } } } return false } private fun isGenericItselfOrDescendant(type: PyClassLikeType, context: TypeEvalContext): Boolean { return PyTypingTypeProvider.GENERIC_CLASSES.contains(type.classQName) || PyTypingTypeProvider.isGeneric(type, context) } private fun isBuiltin(type: PyClassLikeType): Boolean { return if (type is PyClassType) PyBuiltinCache.getInstance(type.pyClass).isBuiltin(type.pyClass) else false } }
apache-2.0
7231da8385bbad2914c132c1ab060236
42.422535
129
0.752189
4.68541
false
false
false
false
allotria/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/server/MavenDistribution.kt
1
2296
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.server import com.intellij.execution.wsl.WSLDistribution import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent import org.jetbrains.idea.maven.utils.MavenUtil import java.io.File interface MavenDistribution { val name: String val mavenHome: File val version: String? fun isValid(): Boolean fun compatibleWith(mavenDistribution: MavenDistribution): Boolean companion object { @JvmStatic fun fromSettings(project: Project?): MavenDistribution? { val mavenHome = MavenWorkspaceSettingsComponent.getInstance(project).settings.generalSettings.mavenHome return MavenDistributionConverter().fromString(mavenHome) } } } class LocalMavenDistribution(override val mavenHome: File, override val name: String) : MavenDistribution { override val version: String? by lazy { MavenUtil.getMavenVersion(mavenHome) } override fun compatibleWith(mavenDistribution: MavenDistribution): Boolean { return mavenDistribution == this || FileUtil.filesEqual(mavenDistribution.mavenHome, mavenHome) } override fun isValid() = version != null override fun toString(): String { return name + "(" + mavenHome + ") v " + version } } class WslMavenDistribution(private val wslDistribution: WSLDistribution, val pathToMaven: String, override val name: String) : MavenDistribution { override val version: String? by lazy { MavenUtil.getMavenVersion(wslDistribution.getWindowsPath(pathToMaven)) } override val mavenHome = File(wslDistribution.getWindowsPath(pathToMaven)!!) override fun compatibleWith(mavenDistribution: MavenDistribution): Boolean { if (mavenDistribution == this) return true val another = mavenDistribution as? WslMavenDistribution ?: return false; return another.wslDistribution == wslDistribution && another.pathToMaven == pathToMaven } override fun isValid() = version != null override fun toString(): String { return name + "(" + mavenHome + ") v " + version } }
apache-2.0
a999fd0dde14c6564dd5b8cbadbc5c1d
36.048387
140
0.747387
4.980477
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/util/ui/cloneDialog/VcsCloneDialog.kt
1
4873
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.ui.cloneDialog import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.Project import com.intellij.openapi.rd.attachChild import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.vcs.CheckoutProvider import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogComponentStateListener import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtension import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame import com.intellij.ui.* import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import com.intellij.util.ui.cloneDialog.RepositoryUrlCloneDialogExtension.RepositoryUrlMainExtensionComponent import java.awt.CardLayout import java.util.* import javax.swing.JComponent import javax.swing.JPanel import javax.swing.event.ListSelectionListener /** * Top-level UI-component for new clone/checkout dialog */ class VcsCloneDialog private constructor(private val project: Project, initialExtensionClass: Class<out VcsCloneDialogExtension>, private var initialVcs: Class<out CheckoutProvider>? = null) : DialogWrapper(project) { private lateinit var extensionList: VcsCloneDialogExtensionList private val cardLayout = CardLayout() private val mainPanel = JPanel(cardLayout) private val extensionComponents: MutableMap<String, VcsCloneDialogExtensionComponent> = HashMap() private val listModel = CollectionListModel<VcsCloneDialogExtension>(VcsCloneDialogExtension.EP_NAME.extensionList) private val listener = object : VcsCloneDialogComponentStateListener { override fun onOkActionNameChanged(name: String) = setOKButtonText(name) override fun onOkActionEnabled(enabled: Boolean) { isOKActionEnabled = enabled } override fun onListItemChanged() = listModel.allContentsChanged() } init { init() title = VcsBundle.message("get.from.version.control") JBUI.size(FlatWelcomeFrame.MAX_DEFAULT_WIDTH, FlatWelcomeFrame.DEFAULT_HEIGHT).let { rootPane.minimumSize = it rootPane.preferredSize = it } VcsCloneDialogExtension.EP_NAME.findExtension(initialExtensionClass)?.let { ScrollingUtil.selectItem(extensionList, it) } } override fun getStyle() = DialogStyle.COMPACT override fun createCenterPanel(): JComponent { extensionList = VcsCloneDialogExtensionList(listModel).apply { addListSelectionListener(ListSelectionListener { e -> val source = e.source as VcsCloneDialogExtensionList switchComponent(source.selectedValue) }) preferredSize = JBDimension(200, 0) // width fixed by design } val scrollableList = ScrollPaneFactory.createScrollPane(extensionList, true).apply { border = IdeBorderFactory.createBorder(SideBorder.RIGHT) } return JBUI.Panels.simplePanel() .addToCenter(mainPanel) .addToLeft(scrollableList) } override fun doValidateAll(): List<ValidationInfo> { return getSelectedComponent()?.doValidateAll() ?: emptyList() } override fun getPreferredFocusedComponent(): JComponent? = getSelectedComponent()?.getPreferredFocusedComponent() fun doClone(checkoutListener: CheckoutProvider.Listener) { getSelectedComponent()?.doClone(checkoutListener) } private fun switchComponent(extension: VcsCloneDialogExtension) { val extensionId = extension.javaClass.name val mainComponent = extensionComponents.getOrPut(extensionId, { val component = extension.createMainComponent(project, ModalityState.stateForComponent(window)) mainPanel.add(component.getView(), extensionId) disposable.attachChild(component) component.addComponentStateListener(listener) component }) if (mainComponent is RepositoryUrlMainExtensionComponent) { initialVcs?.let { mainComponent.openForVcs(it) } } mainComponent.onComponentSelected() cardLayout.show(mainPanel, extensionId) } private fun getSelectedComponent(): VcsCloneDialogExtensionComponent? { return extensionComponents[extensionList.selectedValue.javaClass.name] } class Builder(private val project: Project) { fun forExtension(clazz: Class<out VcsCloneDialogExtension> = RepositoryUrlCloneDialogExtension::class.java): VcsCloneDialog { return VcsCloneDialog(project, clazz, null) } fun forVcs(clazz: Class<out CheckoutProvider>): VcsCloneDialog { return VcsCloneDialog(project, RepositoryUrlCloneDialogExtension::class.java, clazz) } } }
apache-2.0
658d640c910f761699f00b6ddb906b04
39.957983
140
0.770983
5.145723
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/config/MacExecutableProblemHandler.kt
1
6757
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.config import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import git4idea.i18n.GitBundle import java.io.File class MacExecutableProblemHandler(val project: Project) : GitExecutableProblemHandler { companion object { val LOG = logger<MacExecutableProblemHandler>() } private val tempPath = FileUtil.createTempDirectory("git-install", null) private val mountPoint = File(tempPath, "mount") override fun showError(exception: Throwable, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) { when { isXcodeLicenseError(exception) -> showXCodeLicenseError(errorNotifier) isInvalidActiveDeveloperPath(exception) -> showInvalidActiveDeveloperPathError(errorNotifier) else -> showGenericError(exception, errorNotifier, onErrorResolved) } } private fun showGenericError(exception: Throwable, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) { errorNotifier.showError(GitBundle.message("executable.error.git.not.installed"), ErrorNotifier.FixOption.Standard(GitBundle.message("install.download.and.install.action")) { errorNotifier.executeTask(GitBundle.message("install.downloading.progress"), false) { try { val installer = fetchInstaller(errorNotifier) { it.os == "macOS" && it.pkgFileName != null} if (installer != null) { val fileName = installer.fileName val dmgFile = File(tempPath, fileName) val pkgFileName = installer.pkgFileName!! if (downloadGit(installer, dmgFile, project, errorNotifier)) { errorNotifier.changeProgressTitle(GitBundle.message("install.installing.progress")) installGit(dmgFile, pkgFileName, errorNotifier, onErrorResolved) } } } finally { FileUtil.delete(tempPath) } } }) } private fun installGit(dmgFile: File, pkgFileName: String, errorNotifier: ErrorNotifier, onErrorResolved: () -> Unit) { if (attachVolume(dmgFile, errorNotifier)) { try { if (installPackageOrShowError(pkgFileName, errorNotifier)) { errorNotifier.showMessage(GitBundle.message("install.success.message")) onErrorResolved() errorNotifier.resetGitExecutable() } } finally { detachVolume() } } } private fun attachVolume(file: File, errorNotifier: ErrorNotifier): Boolean { val cmd = GeneralCommandLine("hdiutil", "attach", "-readonly", "-noautoopen", "-noautofsck", "-nobrowse", "-mountpoint", mountPoint.path, file.path) return runOrShowError(cmd, errorNotifier, sudo = false) } private fun installPackageOrShowError(pkgFileName: String, errorNotifier: ErrorNotifier) = runOrShowError(GeneralCommandLine("installer", "-package", "${mountPoint}/$pkgFileName", "-target", "/"), errorNotifier, sudo = true) private fun detachVolume() { runCommand(GeneralCommandLine("hdiutil", "detach", mountPoint.path), sudo = false, onError = {}) } private fun runOrShowError(commandLine: GeneralCommandLine, errorNotifier: ErrorNotifier, sudo: Boolean): Boolean { return runCommand(commandLine, sudo) { showCouldntInstallError(errorNotifier) } } private fun runCommand(commandLine: GeneralCommandLine, sudo: Boolean, onError: () -> Unit): Boolean { try { val cmd = if (sudo) ExecUtil.sudoCommand(commandLine, "Install Git") else commandLine val output = ExecUtil.execAndGetOutput(cmd) if (output.checkSuccess(LOG)) { return true } LOG.warn(output.stderr) onError() return false } catch (e: Exception) { LOG.warn(e) onError() return false } } private fun showCouldntInstallError(errorNotifier: ErrorNotifier) { errorNotifier.showError(GitBundle.message("install.general.error"), getLinkToConfigure(project)) } private fun showCouldntStartInstallerError(errorNotifier: ErrorNotifier) { errorNotifier.showError(GitBundle.message("install.mac.error.couldnt.start.command.line.tools"), getLinkToConfigure(project)) } private fun showXCodeLicenseError(errorNotifier: ErrorNotifier) { errorNotifier.showError(GitBundle.getString("git.executable.validation.error.xcode.title"), GitBundle.getString("git.executable.validation.error.xcode.message"), getLinkToConfigure(project)) } private fun showInvalidActiveDeveloperPathError(errorNotifier: ErrorNotifier) { val fixPathOption = ErrorNotifier.FixOption.Standard(GitBundle.message("executable.mac.fix.path.action")) { errorNotifier.executeTask(GitBundle.message("install.mac.requesting.command.line.tools") + StringUtil.ELLIPSIS, false) { execXCodeSelectInstall(errorNotifier) } } errorNotifier.showError(GitBundle.message("executable.mac.error.invalid.path.to.command.line.tools"), fixPathOption) } /** * Check if validation failed because the XCode license was not accepted yet */ private fun isXcodeLicenseError(exception: Throwable): Boolean = isXcodeError(exception) { it.contains("Agreeing to the Xcode/iOS license") } /** * Check if validation failed because the XCode command line tools were not found */ private fun isInvalidActiveDeveloperPath(exception: Throwable): Boolean = isXcodeError(exception) { it.contains("invalid active developer path") && it.contains("xcrun") } private fun isXcodeError(exception: Throwable, messageIndicator: (String) -> Boolean): Boolean { val message = if (exception is GitVersionIdentificationException) { exception.cause?.message } else { exception.message } return (message != null && messageIndicator(message)) } private fun execXCodeSelectInstall(errorNotifier: ErrorNotifier) { try { val cmd = GeneralCommandLine("xcode-select", "--install") val output = ExecUtil.execAndGetOutput(cmd) errorNotifier.hideProgress() if (!output.checkSuccess(LOG)) { LOG.warn(output.stderr) showCouldntStartInstallerError(errorNotifier) } else { errorNotifier.resetGitExecutable() } } catch (e: Exception) { LOG.warn(e) showCouldntStartInstallerError(errorNotifier) } } }
apache-2.0
6d143a7ab49b9ee61974e187505623bd
39.22619
140
0.701051
4.725175
false
false
false
false
JuliusKunze/kotlin-native
runtime/src/main/kotlin/kotlin/coroutines/experimental/CoroutinesLibrary.kt
2
4433
/* * Copyright 2010-2017 JetBrains s.r.o. * * 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 kotlin.coroutines.experimental import kotlin.coroutines.experimental.intrinsics.COROUTINE_SUSPENDED import kotlin.coroutines.experimental.intrinsics.suspendCoroutineOrReturn import kotlin.coroutines.experimental.intrinsics.createCoroutineUnchecked import konan.internal.SafeContinuation /** * Starts coroutine with receiver type [R] and result type [T]. * This function creates and start a new, fresh instance of suspendable computation every time it is invoked. * The [completion] continuation is invoked when coroutine completes with result or exception. */ @Suppress("UNCHECKED_CAST") public fun <R, T> (suspend R.() -> T).startCoroutine( receiver: R, completion: Continuation<T> ) { createCoroutineUnchecked(receiver, completion).resume(Unit) } /** * Starts coroutine without receiver and with result type [T]. * This function creates and start a new, fresh instance of suspendable computation every time it is invoked. * The [completion] continuation is invoked when coroutine completes with result or exception. */ @Suppress("UNCHECKED_CAST") public fun <T> (suspend () -> T).startCoroutine( completion: Continuation<T> ) { createCoroutineUnchecked(completion).resume(Unit) } /** * Creates a coroutine with receiver type [R] and result type [T]. * This function creates a new, fresh instance of suspendable computation every time it is invoked. * * To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance. * The [completion] continuation is invoked when coroutine completes with result or exception. * Repeated invocation of any resume function on the resulting continuation produces [IllegalStateException]. */ @Suppress("UNCHECKED_CAST") public fun <R, T> (suspend R.() -> T).createCoroutine( receiver: R, completion: Continuation<T> ): Continuation<Unit> = SafeContinuation(createCoroutineUnchecked(receiver, completion), COROUTINE_SUSPENDED) /** * Creates a coroutine without receiver and with result type [T]. * This function creates a new, fresh instance of suspendable computation every time it is invoked. * * To start executing the created coroutine, invoke `resume(Unit)` on the returned [Continuation] instance. * The [completion] continuation is invoked when coroutine completes with result or exception. * Repeated invocation of any resume function on the resulting continuation produces [IllegalStateException]. */ @Suppress("UNCHECKED_CAST") public fun <T> (suspend () -> T).createCoroutine( completion: Continuation<T> ): Continuation<Unit> = SafeContinuation(createCoroutineUnchecked(completion), COROUTINE_SUSPENDED) /** * Obtains the current continuation instance inside suspend functions and suspends * currently running coroutine. * * In this function both [Continuation.resume] and [Continuation.resumeWithException] can be used either synchronously in * the same stack-frame where suspension function is run or asynchronously later in the same thread or * from a different thread of execution. Repeated invocation of any resume function produces [IllegalStateException]. */ public inline suspend fun <T> suspendCoroutine(crossinline block: (Continuation<T>) -> Unit): T = suspendCoroutineOrReturn { c: Continuation<T> -> val safe = SafeContinuation(c) block(safe) safe.getResult() } // INTERNAL DECLARATIONS @kotlin.internal.InlineOnly internal inline fun processBareContinuationResume(completion: Continuation<*>, block: () -> Any?) { try { val result = block() if (result !== COROUTINE_SUSPENDED) { @Suppress("UNCHECKED_CAST") (completion as Continuation<Any?>).resume(result) } } catch (t: Throwable) { completion.resumeWithException(t) } }
apache-2.0
30da4b74e55184fef61882df091d33f2
42.038835
121
0.744642
4.651626
false
false
false
false
nextras/orm-intellij
src/main/kotlin/org/nextras/orm/intellij/completion/PropertyNameCompletionProvider.kt
1
1779
package org.nextras.orm.intellij.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.util.ProcessingContext import com.jetbrains.php.PhpIcons import com.jetbrains.php.PhpIndex import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocProperty import com.jetbrains.php.lang.psi.elements.MethodReference import com.jetbrains.php.lang.psi.elements.ParameterList import org.nextras.orm.intellij.utils.OrmUtils import org.nextras.orm.intellij.utils.PhpIndexUtils class PropertyNameCompletionProvider : CompletionProvider<CompletionParameters>() { companion object { private val METHODS = arrayOf("setValue", "setReadOnlyValue", "getValue", "hasValue", "getProperty", "getRawProperty") } override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val el = parameters.position if (el.parent?.parent !is ParameterList || (el.parent.parent as ParameterList).parameters[0] !== el.parent) { return } val methodReference = el.parent?.parent?.parent as? MethodReference ?: return if (methodReference.name !in METHODS) { return } val phpIndex = PhpIndex.getInstance(el.project) val classes = PhpIndexUtils.getByType(methodReference.classReference!!.type, phpIndex) classes .filter { OrmUtils.OrmClass.ENTITY.`is`(it, phpIndex) } .flatMap { it.fields } .filterIsInstance<PhpDocProperty>() .forEach { result.addElement( LookupElementBuilder.create(it.name) .withIcon(PhpIcons.FIELD) .withTypeText(it.type.toString()) ) } } }
mit
e2652d2b9d7ef75b9014db850783f4b6
36.0625
121
0.785273
4.070938
false
false
false
false
smmribeiro/intellij-community
plugins/settings-sync/src/com/intellij/settingsSync/config/SettingsSyncStatusAction.kt
1
1804
package com.intellij.settingsSync.config import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.settingsSync.SettingsSyncBundle.message import com.intellij.settingsSync.SettingsSyncSettings import com.intellij.settingsSync.auth.SettingsSyncAuthService import com.intellij.settingsSync.isSettingsSyncEnabled class SettingsSyncStatusAction : AnAction(message("title.settings.sync")) { override fun actionPerformed(e: AnActionEvent) { ShowSettingsUtil.getInstance().showSettingsDialog(null, SettingsSyncConfigurable::class.java) } override fun update(e: AnActionEvent) { val p = e.presentation if (!isSettingsSyncEnabled()) { p.isEnabledAndVisible = false return } when(getStatus()) { SyncStatus.ON -> { p.icon = AllIcons.General.InspectionsOK // TODO<rv>: Change icon @Suppress("DialogTitleCapitalization") // we use "is", not "Is p.text = message("status.action.settings.sync.is.on") } SyncStatus.OFF -> { p.icon = AllIcons.Actions.Cancel // TODO<rv>: Change icon @Suppress("DialogTitleCapitalization") // we use "is", not "Is p.text = message("status.action.settings.sync.is.off") } SyncStatus.FAILED -> { p.icon = AllIcons.General.Error p.text = message("status.action.settings.sync.failed") } } } private enum class SyncStatus {ON, OFF, FAILED} private fun getStatus() : SyncStatus { // TODO<rv>: Support FAILED status return if (SettingsSyncSettings.getInstance().syncEnabled && SettingsSyncAuthService.getInstance().isLoggedIn()) SyncStatus.ON else SyncStatus.OFF } }
apache-2.0
b9bf334d2b4b58f2bb7001cfda849db5
35.836735
97
0.718958
4.57868
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/core/formatter/KotlinPackageEntry.kt
6
1482
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.core.formatter class KotlinPackageEntry( packageName: String, val withSubpackages: Boolean ) { val packageName = packageName.removeSuffix(".*") companion object { @JvmField val ALL_OTHER_IMPORTS_ENTRY = KotlinPackageEntry("<all other imports>", withSubpackages = true) @JvmField val ALL_OTHER_ALIAS_IMPORTS_ENTRY = KotlinPackageEntry("<all other alias imports>", withSubpackages = true) } fun matchesPackageName(otherPackageName: String): Boolean { if (otherPackageName.startsWith(packageName)) { if (otherPackageName.length == packageName.length) return true if (withSubpackages) { if (otherPackageName[packageName.length] == '.') return true } } return false } val isSpecial: Boolean get() = this == ALL_OTHER_IMPORTS_ENTRY || this == ALL_OTHER_ALIAS_IMPORTS_ENTRY override fun toString(): String { return packageName } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is KotlinPackageEntry) return false return withSubpackages == other.withSubpackages && packageName == other.packageName } override fun hashCode(): Int = packageName.hashCode() }
apache-2.0
52dda829631bec90c7fb8147ed4a4205
33.465116
158
0.666667
4.719745
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/fromJavaToKotlin/delegateToStaticFieldWithNameConflict.kt
24
1265
val staticField = 42 //KT-40835 fun a() { JavaClass().a() val d = JavaClass() d.a() d.let { it.a() } d.also { it.a() } with(d) { a() } with(d) out@{ with(4) { [email protected]() } } } fun a2() { val d: JavaClass? = null d?.a() d?.let { it.a() } d?.also { it.a() } with(d) { this?.a() } with(d) out@{ with(4) { this@out?.a() } } } fun a3() { val d: JavaClass? = null val a1 = d?.a() val a2 = d?.let { it.a() } val a3 = d?.also { it.a() } val a4 = with(d) { this?.a() } val a5 = with(d) out@{ with(4) { this@out?.a() } } } fun a4() { val d: JavaClass? = null d?.a()?.dec() val a2 = d?.let { it.a() } a2?.toLong() d?.also { it.a() }?.a()?.and(4) val a4 = with(d) { this?.a() } val a5 = with(d) out@{ with(4) { this@out?.a() } } val a6 = a4?.let { out -> a5?.let { out + it } } } fun JavaClass.b(): Int? = a() fun JavaClass.c(): Int = this.a() fun d(d: JavaClass) = d.a()
apache-2.0
38d0bbc2c20ca1a66a89e01292728ba5
11.401961
52
0.345455
2.829978
false
false
false
false
smmribeiro/intellij-community
platform/script-debugger/backend/src/debugger/CallFrameBase.kt
13
1472
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.jetbrains.debugger import com.intellij.openapi.util.NotNullLazyValue const val RECEIVER_NAME: String = "this" @Deprecated("") /** * Use kotlin - base class is not required in this case (no boilerplate code) */ /** * You must initialize [.scopes] or override [.getVariableScopes] */ abstract class CallFrameBase(override val functionName: String?, override val line: Int, override val column: Int, override val evaluateContext: EvaluateContext) : CallFrame { protected var scopes: NotNullLazyValue<List<Scope>>? = null override var hasOnlyGlobalScope: Boolean = false protected set(value: Boolean) { field = value } override val variableScopes: List<Scope> get() = scopes!!.value override val asyncFunctionName: String? = null override val isFromAsyncStack: Boolean = false override val returnValue: Variable? = null }
apache-2.0
94652f0f25868654a887925daf3fbb7f
31.733333
175
0.73913
4.304094
false
false
false
false
smmribeiro/intellij-community
xml/impl/src/com/intellij/codeInsight/daemon/impl/tagTreeHighlighting/XmlTagTreeHighlightingConfigurable.kt
1
3215
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.codeInsight.daemon.impl.tagTreeHighlighting import com.intellij.application.options.editor.WebEditorOptions import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.options.UiDslUnnamedConfigurable import com.intellij.openapi.project.ProjectManager import com.intellij.ui.components.JBCheckBox import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.layout.* import com.intellij.xml.XmlBundle import com.intellij.xml.breadcrumbs.BreadcrumbsPanel class XmlTagTreeHighlightingConfigurable : UiDslUnnamedConfigurable.Simple() { override fun Panel.createContent() { val options = WebEditorOptions.getInstance() lateinit var enable: Cell<JBCheckBox> panel { row { enable = checkBox(XmlBundle.message("settings.enable.html.xml.tag.tree.highlighting")) .bindSelected(options::isTagTreeHighlightingEnabled, options::setTagTreeHighlightingEnabled) .onApply { clearTagTreeHighlighting() } } indent { row(XmlBundle.message("settings.levels.to.highlight")) { spinner(1..50) .bindIntValue({ options.tagTreeHighlightingLevelCount }, { options.tagTreeHighlightingLevelCount = it }) .onApply { clearTagTreeHighlighting() } .horizontalAlign(HorizontalAlign.FILL) cell() }.layout(RowLayout.PARENT_GRID) row(XmlBundle.message("settings.opacity")) { spinner(0.0..1.0, step = 0.05) .bind({ ((it.value as Double) * 100).toInt() }, { it, value -> it.value = value * 0.01 }, PropertyBinding(options::getTagTreeHighlightingOpacity, options::setTagTreeHighlightingOpacity)) .onApply { clearTagTreeHighlighting() } .horizontalAlign(HorizontalAlign.FILL) cell() }.layout(RowLayout.PARENT_GRID) .bottomGap(BottomGap.SMALL) }.enabledIf(enable.selected) } } companion object { private fun clearTagTreeHighlighting() { for (project in ProjectManager.getInstance().openProjects) { for (fileEditor in FileEditorManager.getInstance(project).allEditors) { if (fileEditor is TextEditor) { val editor = fileEditor.editor XmlTagTreeHighlightingPass.clearHighlightingAndLineMarkers(editor, project) val breadcrumbs = BreadcrumbsPanel.getBreadcrumbsComponent(editor) breadcrumbs?.queueUpdate() } } } } } }
apache-2.0
eee8bd36301f88d92db0c5424199fe88
40.753247
116
0.711664
4.686589
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/highlighter/KDoc.kt
13
534
/** * @param <info descr="null" textAttributesKey="KDOC_LINK">x</info> foo and <info descr="null" textAttributesKey="KDOC_LINK">[baz]</info> * @param <info descr="null" textAttributesKey="KDOC_LINK">y</info> bar * @return notALink here */ fun <info descr="null">f</info>(<info descr="null">x</info>: <info descr="null">Int</info>, <info descr="null">y</info>: <info descr="null">Int</info>): <info descr="null">Int</info> { return <info descr="null">x</info> + <info descr="null">y</info> } fun <info descr="null">baz</info>() {}
apache-2.0
59cfdd102f203a4c3d82115b1d8b5334
52.5
184
0.655431
3.104651
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/findUsages/kotlin/conventions/components/dataClassInsideDataClass.0.kt
4
382
// PSI_ELEMENT: org.jetbrains.kotlin.psi.KtParameter // OPTIONS: usages data class A(val <caret>x: Int, val y: Int, val z: String) data class B(val a: A, val n: Int) class C { operator fun component1(): A = TODO() operator fun component2() = 0 } fun f(b: B, c: C) { val (a, n) = b val (x, y, z) = a val (a1, n1) = c val (x1, y1, z1) = a1 } // FIR_IGNORE
apache-2.0
c3c210216e0be3ae4b5117cef965279c
18.15
58
0.573298
2.529801
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/sshtestutils/SshTestUtils.kt
2
2757
package com.github.kerubistan.kerub.sshtestutils import com.github.kerubistan.kerub.toInputStream import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.argThat import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.apache.commons.io.input.NullInputStream import org.apache.sshd.client.channel.ChannelExec import org.apache.sshd.client.future.OpenFuture import org.apache.sshd.client.session.ClientSession import java.io.OutputStream fun ClientSession.mockCommandExecution( commandMatcher: String = ".*", output: String = "", error: String = "") : ChannelExec = this.mockCommandExecution(commandMatcher.toRegex(), output, error) fun ClientSession.mockCommandExecution( commandMatcher: Regex, output: String = "", error: String = "") : ChannelExec = mock<ChannelExec>().let {exec -> whenever(this.createExecChannel(argThat { matches(commandMatcher) })).thenReturn(exec) whenever(exec.open()).thenReturn(mock()) whenever(exec.invertedErr).then { error.toInputStream() } whenever(exec.invertedOut).then { output.toInputStream() } exec } fun ClientSession.mockCommandExecutionSequence( commandMatcher: Regex, outputs : List<String> = listOf() ) : ChannelExec = mock<ChannelExec>().let {exec -> val iterator = outputs.iterator() whenever(this.createExecChannel(argThat { matches(commandMatcher) })).thenReturn(exec) whenever(exec.open()).thenReturn(mock()) whenever(exec.invertedOut).then { iterator.next().toInputStream() } whenever(exec.invertedErr).then { NullInputStream(0) } exec } fun ClientSession.verifyCommandExecution(commandMatcher: Regex) { verify(this).createExecChannel(argThat { commandMatcher.matches(this) }) } fun ClientSession.verifyCommandExecution(commandMatcher: Regex, mode: org.mockito.verification.VerificationMode) { verify(this, mode).createExecChannel(argThat { commandMatcher.matches(this) }) } fun ClientSession.mockProcess(commandMatcher: Regex, output: String, stderr : String = "") { val execChannel: ChannelExec = mock() val openFuture : OpenFuture = mock() whenever(this.createExecChannel(argThat { commandMatcher.matches(this) })).thenReturn(execChannel) whenever(execChannel.open()).thenReturn(openFuture) doAnswer { val out = it.arguments[0] as OutputStream output.forEach { chr -> out.write( chr.toInt() ) } null } .whenever(execChannel)!!.out = any() doAnswer { val err = it.arguments[0] as OutputStream stderr.forEach { chr -> err.write( chr.toInt() ) } null } .whenever(execChannel)!!.err = any() whenever(execChannel.invertedErr).thenReturn(NullInputStream(0)) }
apache-2.0
4f289c265024ac2b9395f8de286320cb
33.049383
114
0.755894
3.845188
false
false
false
false
jwren/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/PlaceholderBaseImpl.kt
1
3574
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.dsl.builder.impl import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.putUserData import com.intellij.ui.dsl.builder.CellBase import com.intellij.ui.dsl.builder.DSL_PANEL_HIERARCHY import com.intellij.ui.dsl.builder.SpacingConfiguration import com.intellij.ui.dsl.gridLayout.Constraints import org.jetbrains.annotations.ApiStatus import javax.swing.JComponent @ApiStatus.Internal internal abstract class PlaceholderBaseImpl<T : CellBase<T>>(private val parent: RowImpl) : CellBaseImpl<T>() { protected var placeholderCellData: PlaceholderCellData? = null private set private var visible = true private var enabled = true var component: JComponent? = null set(value) { reinstallComponent(field, value) field = value } override fun enabledFromParent(parentEnabled: Boolean) { doEnabled(parentEnabled && enabled) } override fun enabled(isEnabled: Boolean): CellBase<T> { enabled = isEnabled if (parent.isEnabled()) { doEnabled(enabled) } return this } override fun visibleFromParent(parentVisible: Boolean) { doVisible(parentVisible && visible) } override fun visible(isVisible: Boolean): CellBase<T> { visible = isVisible if (parent.isVisible()) { doVisible(visible) } component?.isVisible = isVisible return this } open fun init(panel: DialogPanel, constraints: Constraints, spacing: SpacingConfiguration) { placeholderCellData = PlaceholderCellData(panel, constraints, spacing) if (component != null) { reinstallComponent(null, component) } } private fun reinstallComponent(oldComponent: JComponent?, newComponent: JComponent?) { oldComponent?.putUserData(DSL_PANEL_HIERARCHY, null) newComponent?.putUserData(DSL_PANEL_HIERARCHY, buildPanelHierarchy(parent)) var invalidate = false if (oldComponent != null) { placeholderCellData?.let { if (oldComponent is DialogPanel) { it.panel.unregisterIntegratedPanel(oldComponent) } it.panel.remove(oldComponent) invalidate = true } } if (newComponent != null) { newComponent.isVisible = visible && parent.isVisible() newComponent.isEnabled = enabled && parent.isEnabled() placeholderCellData?.let { val gaps = customGaps ?: getComponentGaps(it.constraints.gaps.left, it.constraints.gaps.right, newComponent, it.spacing) it.constraints = it.constraints.copy( gaps = gaps, visualPaddings = prepareVisualPaddings(newComponent.origin) ) it.panel.add(newComponent, it.constraints) if (newComponent is DialogPanel) { it.panel.registerIntegratedPanel(newComponent) } invalidate = true } } if (invalidate) { invalidate() } } private fun doVisible(isVisible: Boolean) { component?.let { if (it.isVisible != isVisible) { it.isVisible = isVisible invalidate() } } } private fun doEnabled(isEnabled: Boolean) { component?.let { it.isEnabled = isEnabled } } private fun invalidate() { placeholderCellData?.let { // Force parent to re-layout it.panel.revalidate() it.panel.repaint() } } } @ApiStatus.Internal internal data class PlaceholderCellData(val panel: DialogPanel, var constraints: Constraints, val spacing: SpacingConfiguration)
apache-2.0
b8b349055acbb962c5070fb703a22342
28.056911
128
0.693621
4.635538
false
false
false
false
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/support/database/HouseKeeper.kt
1
3332
package com.maubis.scarlet.base.support.database import android.content.Context import com.maubis.scarlet.base.config.CoreConfig.Companion.foldersDb import com.maubis.scarlet.base.config.CoreConfig.Companion.notesDb import com.maubis.scarlet.base.core.note.NoteImage.Companion.deleteIfExist import com.maubis.scarlet.base.core.note.ReminderInterval import com.maubis.scarlet.base.core.note.getReminderV2 import com.maubis.scarlet.base.core.note.setReminderV2 import com.maubis.scarlet.base.note.delete import com.maubis.scarlet.base.note.reminders.ReminderJob.Companion.nextJobTimestamp import com.maubis.scarlet.base.note.reminders.ReminderJob.Companion.scheduleJob import com.maubis.scarlet.base.note.save import com.maubis.scarlet.base.note.saveWithoutSync import java.io.File import java.util.* import java.util.concurrent.TimeUnit class HouseKeeper(val context: Context) { private val houseKeeperTasks: Array<() -> Unit> = arrayOf( { removeOlderClips() }, { removeDecoupledFolders() }, { removeOldReminders() }, { deleteRedundantImageFiles() }, { migrateZeroUidNotes() } ) fun execute() { for (task in houseKeeperTasks) { task() } } fun removeOlderClips(deltaTimeMs: Long = 604800000L) { val notes = notesDb.database() .getOldTrashedNotes(Calendar.getInstance().timeInMillis - deltaTimeMs) for (note in notes) { note.delete(context) } } private fun removeDecoupledFolders() { val folders = foldersDb.getAll().map { it.uuid } notesDb.getAll() .filter { it.folder.isNotBlank() } .forEach { if (!folders.contains(it.folder)) { it.folder = "" it.save(context) } } } private fun removeOldReminders() { notesDb.getAll().forEach { val reminder = it.getReminderV2() if (reminder === null) { return@forEach } // Some gap to allow delays in alarm if (reminder.timestamp >= System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(30)) { return@forEach } if (reminder.interval == ReminderInterval.ONCE) { it.meta = "" it.saveWithoutSync(context) return@forEach } reminder.timestamp = nextJobTimestamp(reminder.timestamp, System.currentTimeMillis()) reminder.uid = scheduleJob(it.uuid, reminder) it.setReminderV2(reminder) it.saveWithoutSync(context) } } private fun deleteRedundantImageFiles() { val uuids = notesDb.getAllUUIDs() val imagesFolder = File(context.filesDir, "images" + File.separator) val uuidFiles = imagesFolder.listFiles() if (uuidFiles === null || uuidFiles.isEmpty()) { return } val availableDirectories = HashSet<String>() for (file in uuidFiles) { if (file.isDirectory) { availableDirectories.add(file.name) } } for (id in uuids) { availableDirectories.remove(id) } for (uuid in availableDirectories) { val noteFolder = File(imagesFolder, uuid) for (file in noteFolder.listFiles()) { deleteIfExist(file) } } } private fun migrateZeroUidNotes() { val note = notesDb.getByID(0) if (note != null) { notesDb.database().delete(note) notesDb.notifyDelete(note) note.uid = null note.save(context) } } }
gpl-3.0
5cb95c4028b3d4cf669b887e19908505
27.982609
93
0.677971
3.887981
false
false
false
false
nrizzio/Signal-Android
donations/lib/src/main/java/org/signal/donations/StripeIntentAccessor.kt
1
1623
package org.signal.donations import android.net.Uri import android.os.Parcelable import kotlinx.parcelize.Parcelize /** * An object which wraps the necessary information to access a SetupIntent or PaymentIntent * from the Stripe API */ @Parcelize data class StripeIntentAccessor( val objectType: ObjectType, val intentId: String, val intentClientSecret: String ) : Parcelable { enum class ObjectType { NONE, PAYMENT_INTENT, SETUP_INTENT } companion object { /** * noActionRequired is a safe default for when there was no 3DS required, * in order to continue a reactive payment chain. */ val NO_ACTION_REQUIRED = StripeIntentAccessor(ObjectType.NONE,"", "") private const val KEY_PAYMENT_INTENT = "payment_intent" private const val KEY_PAYMENT_INTENT_CLIENT_SECRET = "payment_intent_client_secret" private const val KEY_SETUP_INTENT = "setup_intent" private const val KEY_SETUP_INTENT_CLIENT_SECRET = "setup_intent_client_secret" fun fromUri(uri: String): StripeIntentAccessor { val parsedUri = Uri.parse(uri) return if (parsedUri.queryParameterNames.contains(KEY_PAYMENT_INTENT)) { StripeIntentAccessor( ObjectType.PAYMENT_INTENT, parsedUri.getQueryParameter(KEY_PAYMENT_INTENT)!!, parsedUri.getQueryParameter(KEY_PAYMENT_INTENT_CLIENT_SECRET)!! ) } else { StripeIntentAccessor( ObjectType.SETUP_INTENT, parsedUri.getQueryParameter(KEY_SETUP_INTENT)!!, parsedUri.getQueryParameter(KEY_SETUP_INTENT_CLIENT_SECRET)!! ) } } } }
gpl-3.0
a2ef726a347497ee4bd582b6e5f8c475
29.074074
91
0.697474
4.508333
false
false
false
false
GunoH/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectRefreshAction.kt
5
3596
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.ui.ExternalSystemIconProvider import com.intellij.openapi.externalSystem.util.ExternalSystemBundle import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsActions import javax.swing.Icon class ProjectRefreshAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return refreshProject(project) } override fun update(e: AnActionEvent) { val project = e.project if (project == null) { e.presentation.isEnabledAndVisible = false return } val notificationAware = ExternalSystemProjectNotificationAware.getInstance(project) val systemIds = notificationAware.getSystemIds() if (systemIds.isNotEmpty()) { e.presentation.text = getNotificationText(systemIds) e.presentation.description = getNotificationDescription(systemIds) e.presentation.icon = getNotificationIcon(systemIds) } e.presentation.isEnabled = notificationAware.isNotificationVisible() } override fun getActionUpdateThread() = ActionUpdateThread.BGT @NlsActions.ActionText private fun getNotificationText(systemIds: Set<ProjectSystemId>): String { val systemsPresentation = ExternalSystemUtil.naturalJoinSystemIds(systemIds) return ExternalSystemBundle.message("external.system.reload.notification.action.reload.text", systemsPresentation) } @NlsActions.ActionDescription private fun getNotificationDescription(systemIds: Set<ProjectSystemId>): String { val systemsPresentation = ExternalSystemUtil.naturalJoinSystemIds(systemIds) val productName = ApplicationNamesInfo.getInstance().fullProductName return ExternalSystemBundle.message("external.system.reload.notification.action.reload.description", systemsPresentation, productName) } private fun getNotificationIcon(systemIds: Set<ProjectSystemId>): Icon { val systemId = systemIds.singleOrNull() ?: return AllIcons.Actions.BuildLoadChanges val iconProvider = ExternalSystemIconProvider.getExtension(systemId) return iconProvider.reloadIcon } init { val productName = ApplicationNamesInfo.getInstance().fullProductName templatePresentation.icon = AllIcons.Actions.BuildLoadChanges templatePresentation.text = ExternalSystemBundle.message("external.system.reload.notification.action.reload.text.empty") templatePresentation.description = ExternalSystemBundle.message("external.system.reload.notification.action.reload.description.empty", productName) } companion object { fun refreshProject(project: Project) { val projectNotificationAware = ExternalSystemProjectNotificationAware.getInstance(project) val systemIds = projectNotificationAware.getSystemIds() if (ExternalSystemUtil.confirmLoadingUntrustedProject(project, systemIds)) { val projectTracker = ExternalSystemProjectTracker.getInstance(project) projectTracker.scheduleProjectRefresh() } } } }
apache-2.0
e96f7c8554783fc5c00dddfde2c04fb5
45.115385
158
0.802002
5.383234
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fir/analysis-api-providers/test/org/jetbrains/kotlin/idea/fir/analysis/providers/trackers/KotlinModuleOutOfBlockTrackerTest.kt
2
9153
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.fir.analysis.providers.trackers import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiManager import org.jetbrains.kotlin.analysis.providers.createModuleWithoutDependenciesOutOfBlockModificationTracker import org.jetbrains.kotlin.analysis.providers.createProjectWideOutOfBlockModificationTracker import org.jetbrains.kotlin.idea.base.projectStructure.getMainKtSourceModule import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest import org.jetbrains.kotlin.idea.util.sourceRoots import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtPsiFactory import org.junit.Assert import java.io.File class KotlinModuleOutOfBlockTrackerTest : AbstractMultiModuleTest() { override fun getTestDataDirectory(): File = error("Should not be called") override fun isFirPlugin(): Boolean = true fun testThatModuleOutOfBlockChangeInfluenceOnlySingleModule() { val moduleA = createModuleInTmpDir("a") { listOf( FileWithText("main.kt", "fun main() = 10") ) } val moduleB = createModuleInTmpDir("b") val moduleC = createModuleInTmpDir("c") val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val moduleBWithTracker = ModuleWithModificationTracker(moduleB) val moduleCWithTracker = ModuleWithModificationTracker(moduleC) moduleA.typeInFunctionBody("main.kt", textAfterTyping = "fun main() = hello10") Assert.assertTrue( "Out of block modification count for module A with out of block should change after typing, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for module B without out of block should not change after typing, modification count is ${moduleBWithTracker.modificationCount}", moduleBWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for module C without out of block should not change after typing, modification count is ${moduleCWithTracker.modificationCount}", moduleCWithTracker.changed() ) } fun testThatDeleteSymbolInBodyDoesNotLeadToOutOfBlockChange() { val moduleA = createModuleInTmpDir("a") { listOf( FileWithText( "main.kt", "fun main() {\n" + "val v = <caret>\n" + "}" ) ) } val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val file = "${moduleA.sourceRoots.first().url}/${"main.kt"}" val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!! val ktFile = PsiManager.getInstance(moduleA.project).findFile(virtualFile) as KtFile configureByExistingFile(virtualFile) backspace() PsiDocumentManager.getInstance(moduleA.project).commitAllDocuments() Assert.assertFalse( "Out of block modification count for module A should not change after deleting, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertEquals("fun main() {\n" + "val v =\n" + "}", ktFile.text) } fun testThatAddModifierDoesLeadToOutOfBlockChange() { val moduleA = createModuleInTmpDir("a") { listOf( FileWithText( "main.kt", "<caret>inline fun main() {}" ) ) } val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val file = "${moduleA.sourceRoots.first().url}/${"main.kt"}" val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!! val ktFile = PsiManager.getInstance(moduleA.project).findFile(virtualFile) as KtFile configureByExistingFile(virtualFile) type("private ") PsiDocumentManager.getInstance(moduleA.project).commitAllDocuments() Assert.assertTrue( "Out of block modification count for module A should be changed after specifying return type, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertEquals("private inline fun main() {}", ktFile.text) } fun testThatInEveryModuleOutOfBlockWillHappenAfterContentRootChange() { val moduleA = createModuleInTmpDir("a") val moduleB = createModuleInTmpDir("b") val moduleC = createModuleInTmpDir("c") val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val moduleBWithTracker = ModuleWithModificationTracker(moduleB) val moduleCWithTracker = ModuleWithModificationTracker(moduleC) runWriteAction { moduleA.sourceRoots.first().createChildData(/* requestor = */ null, "file.kt") } Assert.assertTrue( "Out of block modification count for module A should change after content root change, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertTrue( "Out of block modification count for module B should change after content root change, modification count is ${moduleBWithTracker.modificationCount}", moduleBWithTracker.changed() ) Assert.assertTrue( "Out of block modification count for module C should change after content root change modification count is ${moduleCWithTracker.modificationCount}", moduleCWithTracker.changed() ) } fun testThatNonPhysicalFileChangeNotCausingBOOM() { val moduleA = createModuleInTmpDir("a") { listOf( FileWithText("main.kt", "fun main() {}") ) } val moduleB = createModuleInTmpDir("b") val moduleAWithTracker = ModuleWithModificationTracker(moduleA) val moduleBWithTracker = ModuleWithModificationTracker(moduleB) val projectWithModificationTracker = ProjectWithModificationTracker(project) runWriteAction { val nonPhysicalPsi = KtPsiFactory(moduleA.project).createFile("nonPhysical", "val a = c") nonPhysicalPsi.add(KtPsiFactory(moduleA.project).createFunction("fun x(){}")) } Assert.assertFalse( "Out of block modification count for module A should not change after non physical file change, modification count is ${moduleAWithTracker.modificationCount}", moduleAWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for module B should not change after non physical file change, modification count is ${moduleBWithTracker.modificationCount}", moduleBWithTracker.changed() ) Assert.assertFalse( "Out of block modification count for project should not change after non physical file change, modification count is ${projectWithModificationTracker.modificationCount}", projectWithModificationTracker.changed() ) } private fun Module.typeInFunctionBody(fileName: String, textAfterTyping: String) { val file = "${sourceRoots.first().url}/$fileName" val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!! val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as KtFile configureByExistingFile(virtualFile) val singleFunction = ktFile.declarations.single() as KtNamedFunction editor.caretModel.moveToOffset(singleFunction.bodyExpression!!.textOffset) type("hello") PsiDocumentManager.getInstance(project).commitAllDocuments() Assert.assertEquals(textAfterTyping, ktFile.text) } abstract class WithModificationTracker(private val modificationTracker: ModificationTracker) { private val initialModificationCount = modificationTracker.modificationCount val modificationCount: Long get() = modificationTracker.modificationCount fun changed(): Boolean = modificationTracker.modificationCount != initialModificationCount } private class ModuleWithModificationTracker(module: Module) : WithModificationTracker( module.getMainKtSourceModule()!!.createModuleWithoutDependenciesOutOfBlockModificationTracker(module.project) ) private class ProjectWithModificationTracker(project: Project) : WithModificationTracker( project.createProjectWideOutOfBlockModificationTracker() ) }
apache-2.0
5c2d362d2c87d6dab3237f5263b07ebc
44.316832
182
0.695837
5.978445
false
false
false
false
siosio/intellij-community
platform/execution-impl/src/com/intellij/execution/wsl/target/WslTargetEnvironment.kt
1
6273
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.wsl.target import com.intellij.execution.ExecutionException import com.intellij.execution.Platform import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.PtyCommandLine import com.intellij.execution.target.* import com.intellij.execution.wsl.WSLDistribution import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.io.FileUtil import com.intellij.util.io.sizeOrNull import java.io.IOException import java.nio.file.Path import java.util.* class WslTargetEnvironment constructor(override val request: WslTargetEnvironmentRequest, private val distribution: WSLDistribution) : TargetEnvironment(request) { private val myUploadVolumes: MutableMap<UploadRoot, UploadableVolume> = HashMap() private val myDownloadVolumes: MutableMap<DownloadRoot, DownloadableVolume> = HashMap() private val myTargetPortBindings: MutableMap<TargetPortBinding, Int> = HashMap() private val myLocalPortBindings: MutableMap<LocalPortBinding, ResolvedPortBinding> = HashMap() override val uploadVolumes: Map<UploadRoot, UploadableVolume> get() = Collections.unmodifiableMap(myUploadVolumes) override val downloadVolumes: Map<DownloadRoot, DownloadableVolume> get() = Collections.unmodifiableMap(myDownloadVolumes) override val targetPortBindings: Map<TargetPortBinding, Int> get() = Collections.unmodifiableMap(myTargetPortBindings) override val localPortBindings: Map<LocalPortBinding, ResolvedPortBinding> get() = Collections.unmodifiableMap(myLocalPortBindings) override val targetPlatform: TargetPlatform get() = TargetPlatform(Platform.UNIX) init { for (uploadRoot in request.uploadVolumes) { val targetRoot: String? = toLinuxPath(uploadRoot.localRootPath.toAbsolutePath().toString()) if (targetRoot != null) { myUploadVolumes[uploadRoot] = Volume(uploadRoot.localRootPath, targetRoot) } } for (downloadRoot in request.downloadVolumes) { val localRootPath = downloadRoot.localRootPath ?: FileUtil.createTempDirectory("intellij-target.", "").toPath() val targetRoot: String? = toLinuxPath(localRootPath.toAbsolutePath().toString()) if (targetRoot != null) { myDownloadVolumes[downloadRoot] = Volume(localRootPath, targetRoot) } } for (targetPortBinding in request.targetPortBindings) { val theOnlyPort = targetPortBinding.target if (targetPortBinding.local != null && targetPortBinding.local != theOnlyPort) { throw UnsupportedOperationException("Local target's TCP port forwarder is not implemented") } myTargetPortBindings[targetPortBinding] = theOnlyPort } for (localPortBinding in request.localPortBindings) { val host = if (distribution.version == 1) { // Ports bound on localhost in Windows can be accessed by linux apps running in WSL1, but not in WSL2: // https://docs.microsoft.com/en-US/windows/wsl/compare-versions#accessing-network-applications "127.0.0.1" } else { distribution.hostIp } val hostPort = HostPort(host, localPortBinding.local) myLocalPortBindings[localPortBinding] = ResolvedPortBinding(hostPort, hostPort) } } private fun toLinuxPath(localPath: String): String? { val linuxPath = distribution.getWslPath(localPath) if (linuxPath != null) { return linuxPath } return convertUncPathToLinux(localPath) } private fun convertUncPathToLinux(localPath: String): String? { val root: String = WSLDistribution.UNC_PREFIX + distribution.msId val winLocalPath = FileUtil.toSystemDependentName(localPath) if (winLocalPath.startsWith(root)) { val linuxPath = winLocalPath.substring(root.length) if (linuxPath.isEmpty()) { return "/" } if (linuxPath.startsWith("\\")) { return FileUtil.toSystemIndependentName(linuxPath) } } return null } @Throws(ExecutionException::class) override fun createProcess(commandLine: TargetedCommandLine, indicator: ProgressIndicator): Process { val ptyOptions = request.ptyOptions val generalCommandLine = if (ptyOptions != null) { PtyCommandLine(commandLine.collectCommandsSynchronously()).also { it.withOptions(ptyOptions) } } else { GeneralCommandLine(commandLine.collectCommandsSynchronously()) } generalCommandLine.environment.putAll(commandLine.environmentVariables) request.wslOptions.remoteWorkingDirectory = commandLine.workingDirectory distribution.patchCommandLine(generalCommandLine, null, request.wslOptions) return generalCommandLine.createProcess() } override fun shutdown() {} private inner class Volume(override val localRoot: Path, override val targetRoot: String) : UploadableVolume, DownloadableVolume { @Throws(IOException::class) override fun resolveTargetPath(relativePath: String): String { val localPath = FileUtil.toCanonicalPath(FileUtil.join(localRoot.toString(), relativePath)) return toLinuxPath(localPath)!! } @Throws(IOException::class) override fun upload(relativePath: String, targetProgressIndicator: TargetProgressIndicator) { } @Throws(IOException::class) override fun download(relativePath: String, progressIndicator: ProgressIndicator) { // Synchronization may be slow -- let us wait until file size does not change // in a reasonable amount of time // (see https://github.com/microsoft/WSL/issues/4197) val path = localRoot.resolve(relativePath) var previousSize = -2L // sizeOrNull returns -1 if file does not exist var newSize = path.sizeOrNull() while (previousSize < newSize) { Thread.sleep(100) previousSize = newSize newSize = path.sizeOrNull() } if (newSize == -1L) { LOG.warn("Path $path was not found on local filesystem") } } } companion object { val LOG = logger<WslTargetEnvironment>() } }
apache-2.0
19e1e2e6967f4e0736bd88c453f43b5b
40.82
140
0.73378
4.994427
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceAssociateFunctionInspection.kt
1
10696
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING import com.intellij.codeInspection.ProblemHighlightType.INFORMATION import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.getLastLambdaExpression import org.jetbrains.kotlin.idea.inspections.AssociateFunction.* import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ReplaceAssociateFunctionInspection : AbstractKotlinInspection() { companion object { private val associateFunctionNames = listOf("associate", "associateTo") private val associateFqNames = listOf(FqName("kotlin.collections.associate"), FqName("kotlin.sequences.associate")) private val associateToFqNames = listOf(FqName("kotlin.collections.associateTo"), FqName("kotlin.sequences.associateTo")) fun getAssociateFunctionAndProblemHighlightType( dotQualifiedExpression: KtDotQualifiedExpression, context: BindingContext = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL) ): Pair<AssociateFunction, ProblemHighlightType>? { val callExpression = dotQualifiedExpression.callExpression ?: return null val lambda = callExpression.lambda() ?: return null if (lambda.valueParameters.size > 1) return null val functionLiteral = lambda.functionLiteral if (functionLiteral.anyDescendantOfType<KtReturnExpression> { it.labelQualifier != null }) return null val lastStatement = functionLiteral.lastStatement() ?: return null val (keySelector, valueTransform) = lastStatement.pair(context) ?: return null val lambdaParameter = context[BindingContext.FUNCTION, functionLiteral]?.valueParameters?.singleOrNull() ?: return null return when { keySelector.isReferenceTo(lambdaParameter, context) -> { val receiver = dotQualifiedExpression.receiverExpression.getResolvedCall(context)?.resultingDescriptor?.returnType ?: return null if ((KotlinBuiltIns.isArray(receiver) || KotlinBuiltIns.isPrimitiveArray(receiver)) && dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_4 ) return null ASSOCIATE_WITH to GENERIC_ERROR_OR_WARNING } valueTransform.isReferenceTo(lambdaParameter, context) -> ASSOCIATE_BY to GENERIC_ERROR_OR_WARNING else -> { if (functionLiteral.bodyExpression?.statements?.size != 1) return null ASSOCIATE_BY_KEY_AND_VALUE to INFORMATION } } } private fun KtExpression.isReferenceTo(descriptor: ValueParameterDescriptor, context: BindingContext): Boolean { return (this as? KtNameReferenceExpression)?.getResolvedCall(context)?.resultingDescriptor == descriptor } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = dotQualifiedExpressionVisitor(fun(dotQualifiedExpression) { if (dotQualifiedExpression.languageVersionSettings.languageVersion < LanguageVersion.KOTLIN_1_3) return val callExpression = dotQualifiedExpression.callExpression ?: return val calleeExpression = callExpression.calleeExpression ?: return if (calleeExpression.text !in associateFunctionNames) return val context = dotQualifiedExpression.analyze(BodyResolveMode.PARTIAL) val fqName = callExpression.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe ?: return val isAssociate = fqName in associateFqNames val isAssociateTo = fqName in associateToFqNames if (!isAssociate && !isAssociateTo) return val (associateFunction, highlightType) = getAssociateFunctionAndProblemHighlightType(dotQualifiedExpression, context) ?: return holder.registerProblemWithoutOfflineInformation( calleeExpression, KotlinBundle.message("replace.0.with.1", calleeExpression.text, associateFunction.name(isAssociateTo)), isOnTheFly, highlightType, ReplaceAssociateFunctionFix(associateFunction, isAssociateTo) ) }) } class ReplaceAssociateFunctionFix(private val function: AssociateFunction, private val hasDestination: Boolean) : LocalQuickFix { private val functionName = function.name(hasDestination) override fun getName() = KotlinBundle.message("replace.with.0", functionName) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val dotQualifiedExpression = descriptor.psiElement.getStrictParentOfType<KtDotQualifiedExpression>() ?: return val receiverExpression = dotQualifiedExpression.receiverExpression val callExpression = dotQualifiedExpression.callExpression ?: return val lambda = callExpression.lambda() ?: return val lastStatement = lambda.functionLiteral.lastStatement() ?: return val (keySelector, valueTransform) = lastStatement.pair() ?: return val psiFactory = KtPsiFactory(dotQualifiedExpression) if (function == ASSOCIATE_BY_KEY_AND_VALUE) { val destination = if (hasDestination) { callExpression.valueArguments.firstOrNull()?.getArgumentExpression() ?: return } else { null } val newExpression = psiFactory.buildExpression { appendExpression(receiverExpression) appendFixedText(".") appendFixedText(functionName) appendFixedText("(") if (destination != null) { appendExpression(destination) appendFixedText(",") } appendLambda(lambda, keySelector) appendFixedText(",") appendLambda(lambda, valueTransform) appendFixedText(")") } dotQualifiedExpression.replace(newExpression) } else { lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector) val newExpression = psiFactory.buildExpression { appendExpression(receiverExpression) appendFixedText(".") appendFixedText(functionName) val valueArgumentList = callExpression.valueArgumentList if (valueArgumentList != null) { appendValueArgumentList(valueArgumentList) } if (callExpression.lambdaArguments.isNotEmpty()) { appendLambda(lambda) } } dotQualifiedExpression.replace(newExpression) } } private fun BuilderByPattern<KtExpression>.appendLambda(lambda: KtLambdaExpression, body: KtExpression? = lambda.bodyExpression) { appendFixedText("{") lambda.valueParameters.firstOrNull()?.nameAsName?.also { appendName(it) appendFixedText("->") } appendExpression(body) appendFixedText("}") } private fun BuilderByPattern<KtExpression>.appendValueArgumentList(valueArgumentList: KtValueArgumentList) { appendFixedText("(") valueArgumentList.arguments.forEachIndexed { index, argument -> if (index > 0) appendFixedText(",") appendExpression(argument.getArgumentExpression()) } appendFixedText(")") } companion object { fun replaceLastStatementForAssociateFunction(callExpression: KtCallExpression, function: AssociateFunction) { val lastStatement = callExpression.lambda()?.functionLiteral?.lastStatement() ?: return val (keySelector, valueTransform) = lastStatement.pair() ?: return lastStatement.replace(if (function == ASSOCIATE_WITH) valueTransform else keySelector) } } } enum class AssociateFunction(val functionName: String) { ASSOCIATE_WITH("associateWith"), ASSOCIATE_BY("associateBy"), ASSOCIATE_BY_KEY_AND_VALUE("associateBy"); fun name(hasDestination: Boolean): String { return if (hasDestination) "${functionName}To" else functionName } } private fun KtCallExpression.lambda(): KtLambdaExpression? { return lambdaArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression ?: getLastLambdaExpression() } private fun KtFunctionLiteral.lastStatement(): KtExpression? { return bodyExpression?.statements?.lastOrNull() } private fun KtExpression.pair(context: BindingContext = analyze(BodyResolveMode.PARTIAL)): Pair<KtExpression, KtExpression>? { return when (this) { is KtBinaryExpression -> { if (operationReference.text != "to") return null val left = left ?: return null val right = right ?: return null left to right } is KtCallExpression -> { if (calleeExpression?.text != "Pair") return null if (valueArguments.size != 2) return null if (getResolvedCall(context)?.resultingDescriptor?.containingDeclaration?.fqNameSafe != FqName("kotlin.Pair")) return null val first = valueArguments[0]?.getArgumentExpression() ?: return null val second = valueArguments[1]?.getArgumentExpression() ?: return null first to second } else -> return null } }
apache-2.0
237a77386a7897d92382604f3b83543a
49.696682
158
0.695213
6.049774
false
false
false
false
siosio/intellij-community
platform/configuration-store-impl/src/ProjectStoreBase.kt
1
11736
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.highlighter.WorkspaceFileType import com.intellij.ide.impl.TrustedProjectSettings import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.appSystemDir import com.intellij.openapi.components.* import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectCoreUtil import com.intellij.openapi.project.doGetProjectFileName import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.SmartList import com.intellij.util.ThreeState import com.intellij.util.containers.isNullOrEmpty import com.intellij.util.io.Ksuid import com.intellij.util.io.exists import com.intellij.util.io.systemIndependentPath import com.intellij.util.messages.MessageBus import com.intellij.util.text.nullize import org.jetbrains.annotations.NonNls import java.nio.file.Path import java.util.* @NonNls internal const val PROJECT_FILE = "\$PROJECT_FILE$" @NonNls internal const val PROJECT_CONFIG_DIR = "\$PROJECT_CONFIG_DIR$" internal val PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, false) private val DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION = FileStorageAnnotation(PROJECT_FILE, true) // cannot be `internal`, used in Upsource abstract class ProjectStoreBase(final override val project: Project) : ComponentStoreWithExtraComponents(), IProjectStore { private var dirOrFile: Path? = null private var dotIdea: Path? = null internal fun getNameFile(): Path = directoryStorePath!!.resolve(ProjectEx.NAME_FILE) final override var loadPolicy = StateLoadPolicy.LOAD final override fun isOptimiseTestLoadSpeed() = loadPolicy != StateLoadPolicy.LOAD final override fun getStorageScheme() = if (dotIdea == null) StorageScheme.DEFAULT else StorageScheme.DIRECTORY_BASED abstract override val storageManager: StateStorageManagerImpl protected val isDirectoryBased: Boolean get() = dotIdea != null final override fun setOptimiseTestLoadSpeed(value: Boolean) { loadPolicy = if (value) StateLoadPolicy.NOT_LOAD else StateLoadPolicy.LOAD } final override fun getProjectFilePath() = storageManager.expandMacro(PROJECT_FILE) final override fun getWorkspacePath() = storageManager.expandMacro(StoragePathMacros.WORKSPACE_FILE) final override fun clearStorages() = storageManager.clearStorages() private fun loadProjectFromTemplate(defaultProject: Project) { val element = (defaultProject.stateStore as DefaultProjectStoreImpl).getStateCopy() ?: return LOG.runAndLogException { val dotIdea = dotIdea if (dotIdea != null) { normalizeDefaultProjectElement(defaultProject, element, dotIdea) } else { moveComponentConfiguration(defaultProject, element, storagePathResolver = { /* doesn't matter, any path will be resolved as projectFilePath (see fileResolver below) */ PROJECT_FILE }) { if (it == "workspace.xml") { workspacePath } else { dirOrFile!! } } } } } final override fun getProjectBasePath(): Path { val path = dirOrFile ?: throw IllegalStateException("setPath was not yet called") if (isDirectoryBased) { val useParent = System.getProperty("store.basedir.parent.detection", "true").toBoolean() && (path.fileName?.toString()?.startsWith("${Project.DIRECTORY_STORE_FOLDER}.") ?: false) return if (useParent) path.parent.parent else path } else { return path.parent } } override fun getPresentableUrl(): String { if (isDirectoryBased) { return (dirOrFile ?: throw IllegalStateException("setPath was not yet called")).systemIndependentPath } else { return projectFilePath.systemIndependentPath } } override fun getProjectWorkspaceId() = ProjectIdManager.getInstance(project).state.id override fun setPath(file: Path, isRefreshVfsNeeded: Boolean, template: Project?) { dirOrFile = file val storageManager = storageManager val isUnitTestMode = ApplicationManager.getApplication().isUnitTestMode val macros = ArrayList<Macro>(5) if (file.toString().endsWith(ProjectFileType.DOT_DEFAULT_EXTENSION)) { macros.add(Macro(PROJECT_FILE, file)) val workspacePath = file.parent.resolve("${file.fileName.toString().removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)}${WorkspaceFileType.DOT_DEFAULT_EXTENSION}") macros.add(Macro(StoragePathMacros.WORKSPACE_FILE, workspacePath)) if (isUnitTestMode) { // we don't load default state in tests as app store does because // 1) we should not do it // 2) it was so before, so, we preserve old behavior (otherwise RunManager will load template run configurations) // load state only if there are existing files val componentStoreLoadingEnabled = project.getUserData(IProjectStore.COMPONENT_STORE_LOADING_ENABLED) if (if (componentStoreLoadingEnabled == null) !file.exists() else !componentStoreLoadingEnabled) { loadPolicy = StateLoadPolicy.NOT_LOAD } macros.add(Macro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, workspacePath)) } } else { val dotIdea = file.resolve(Project.DIRECTORY_STORE_FOLDER) this.dotIdea = dotIdea // PROJECT_CONFIG_DIR must be first macro macros.add(Macro(PROJECT_CONFIG_DIR, dotIdea)) macros.add(Macro(StoragePathMacros.WORKSPACE_FILE, dotIdea.resolve("workspace.xml"))) macros.add(Macro(PROJECT_FILE, dotIdea.resolve("misc.xml"))) if (isUnitTestMode) { // load state only if there are existing files isOptimiseTestLoadSpeed = !file.exists() macros.add(Macro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, dotIdea.resolve("product-workspace.xml"))) } } val presentableUrl = (if (dotIdea == null) file else projectBasePath) val cacheFileName = doGetProjectFileName(presentableUrl.systemIndependentPath, (presentableUrl.fileName ?: "").toString().toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION), ".", ".xml") macros.add(Macro(StoragePathMacros.CACHE_FILE, appSystemDir.resolve("workspace").resolve(cacheFileName))) storageManager.setMacros(macros) if (template != null) { loadProjectFromTemplate(template) } if (isUnitTestMode) { return } val productSpecificWorkspaceParentDir = PathManager.getConfigDir().resolve("workspace") val projectIdManager = ProjectIdManager.getInstance(project) var projectId = projectIdManager.state.id if (projectId == null) { // do not use project name as part of id, to ensure that project dir renaming also will not cause data loss projectId = Ksuid.generate() projectIdManager.state.id = projectId } val productWorkspaceFile = productSpecificWorkspaceParentDir.resolve("$projectId.xml") macros.add(Macro(StoragePathMacros.PRODUCT_WORKSPACE_FILE, productWorkspaceFile)) storageManager.setMacros(macros) val trustedProjectSettings = project.service<TrustedProjectSettings>() if (trustedProjectSettings.trustedState == ThreeState.UNSURE && !trustedProjectSettings.hasCheckedIfOldProject && productWorkspaceFile.exists()) { LOG.info("Marked the project as trusted because there are settings in $productWorkspaceFile") trustedProjectSettings.trustedState = ThreeState.YES } trustedProjectSettings.hasCheckedIfOldProject = true } override fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): List<Storage> { val storages = stateSpec.storages if (storages.isEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } if (isDirectoryBased) { if (storages.size == 2 && ApplicationManager.getApplication().isUnitTestMode && isSpecialStorage(storages.first()) && storages[1].path == StoragePathMacros.WORKSPACE_FILE) { return listOf(storages.first()) } var result: MutableList<Storage>? = null for (storage in storages) { if (storage.path != PROJECT_FILE) { if (result == null) { result = SmartList() } result.add(storage) } } if (result.isNullOrEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { result!!.sortWith(deprecatedComparator) if (isDirectoryBased) { for (providerFactory in StreamProviderFactory.EP_NAME.getIterable(project)) { LOG.runAndLogException { // yes, DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION is not added in this case providerFactory.customizeStorageSpecs(component, storageManager, stateSpec, result!!, operation)?.let { return it } } } } // if we create project from default, component state written not to own storage file, but to project file, // we don't have time to fix it properly, so, ancient hack restored if (!isSpecialStorage(result.first())) { result.add(DEPRECATED_PROJECT_FILE_STORAGE_ANNOTATION) } return result } } else { var result: MutableList<Storage>? = null // FlexIdeProjectLevelCompilerOptionsHolder, FlexProjectLevelCompilerOptionsHolderImpl and CustomBeanRegistry var hasOnlyDeprecatedStorages = true for (storage in storages) { @Suppress("DEPRECATION") if (storage.path == PROJECT_FILE || storage.path == StoragePathMacros.WORKSPACE_FILE || isSpecialStorage(storage)) { if (result == null) { result = SmartList() } result.add(storage) if (!storage.deprecated) { hasOnlyDeprecatedStorages = false } } } if (result.isNullOrEmpty()) { return listOf(PROJECT_FILE_STORAGE_ANNOTATION) } else { if (hasOnlyDeprecatedStorages) { result!!.add(PROJECT_FILE_STORAGE_ANNOTATION) } result!!.sortWith(deprecatedComparator) return result } } } override fun isProjectFile(file: VirtualFile): Boolean { if (!file.isInLocalFileSystem || !ProjectCoreUtil.isProjectOrWorkspaceFile(file)) { return false } val filePath = file.path if (!isDirectoryBased) { return filePath == projectFilePath.systemIndependentPath || filePath == workspacePath.systemIndependentPath } return VfsUtilCore.isAncestorOrSelf(projectFilePath.parent.systemIndependentPath, file) } override fun getDirectoryStorePath(ignoreProjectStorageScheme: Boolean) = dotIdea?.systemIndependentPath.nullize() final override fun getDirectoryStorePath() = dotIdea final override fun reloadStates(componentNames: Set<String>, messageBus: MessageBus) { runBatchUpdate(project) { reinitComponents(componentNames) } } } private fun isSpecialStorage(storage: Storage) = isSpecialStorage(storage.path) internal fun isSpecialStorage(collapsedPath: String): Boolean { return collapsedPath == StoragePathMacros.CACHE_FILE || collapsedPath == StoragePathMacros.PRODUCT_WORKSPACE_FILE }
apache-2.0
27bec710ff8145b9df6d497fed55087b
39.753472
214
0.716939
5.069546
false
false
false
false
jwren/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/quickfix/ExclExclCallFixes.kt
3
1943
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.daemon.impl.actions.IntentionActionWithFixAllOption import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPostfixExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType abstract class ExclExclCallFix(psiElement: PsiElement) : KotlinPsiOnlyQuickFixAction<PsiElement>(psiElement) { override fun getFamilyName(): String = text override fun startInWriteAction(): Boolean = true } class RemoveExclExclCallFix( psiElement: PsiElement ) : ExclExclCallFix(psiElement), CleanupFix, HighPriorityAction, IntentionActionWithFixAllOption { override fun getText(): String = KotlinBundle.message("fix.remove.non.null.assertion") override fun invoke(project: Project, editor: Editor?, file: KtFile) { val postfixExpression = element as? KtPostfixExpression ?: return val baseExpression = postfixExpression.baseExpression ?: return postfixExpression.replace(baseExpression) } companion object : QuickFixesPsiBasedFactory<PsiElement>(PsiElement::class, PsiElementSuitabilityCheckers.ALWAYS_SUITABLE) { override fun doCreateQuickFix(psiElement: PsiElement): List<IntentionAction> { val postfixExpression = psiElement.getNonStrictParentOfType<KtPostfixExpression>() ?: return emptyList() return listOfNotNull(RemoveExclExclCallFix(postfixExpression)) } } }
apache-2.0
92c56fb63f2764eef28871d3865ad56b
47.6
158
0.796706
5.059896
false
false
false
false
ZhangQinglian/dcapp
src/main/kotlin/com/zqlite/android/diycode/device/utils/FileUtils.kt
1
3437
/* * Copyright 2017 zhangqinglian * * 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.zqlite.android.diycode.device.utils import android.content.Context import android.database.Cursor import android.net.Uri import android.os.Build import android.provider.MediaStore /** * Created by scott on 2017/8/9. */ object FileUtils { fun getFilePathByUri(context: Context, uri: Uri?): String? { if(uri == null) return null var filePath = "unknown"//default fileName var filePathUri: Uri = uri try { if (filePathUri.scheme.compareTo("content") == 0) { if (Build.VERSION.SDK_INT == 22 || Build.VERSION.SDK_INT == 23) { try { val pathUri = uri.path val newUri = pathUri.substring(pathUri.indexOf("content"), pathUri.lastIndexOf("/ACTUAL")) filePathUri = Uri.parse(newUri) } catch (e: Exception) { e.printStackTrace() } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val cursor = context.contentResolver .query(filePathUri, arrayOf(MediaStore.Images.Media.DATA), null, null, null) if (cursor != null) { try { if (cursor.moveToFirst()) { val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) filePath = cursor.getString(column_index) } cursor.close() } catch (e: Exception) { e.printStackTrace() } } } else { val cursor = context.contentResolver.query(uri, arrayOf(MediaStore.Images.Media.DATA), null, null, null) if (cursor != null) { try { if (cursor.moveToFirst()) { val column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) filePathUri = Uri.parse(cursor.getString(column_index)) filePath = filePathUri.path } } catch (e: Exception) { cursor.close() } } } } else if (uri.scheme.compareTo("file") == 0) { filePath = filePathUri.path } else { filePath = filePathUri.path } } catch (e: Exception) { e.printStackTrace() return null } return filePath } }
apache-2.0
ae9fc33518a9760d35082c65ae4be3d6
37.617978
124
0.496945
5.184012
false
false
false
false
GunoH/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/IndexDiagnosticActions.kt
5
6084
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.log.ui.actions import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier import com.intellij.testFramework.LightVirtualFile import com.intellij.util.text.DateFormatUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.data.AbstractDataGetter.Companion.getCommitDetails import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.data.index.IndexDiagnostic.getDiffFor import com.intellij.vcs.log.data.index.IndexDiagnostic.getFirstCommits import com.intellij.vcs.log.data.index.VcsLogPersistentIndex import com.intellij.vcs.log.impl.VcsLogManager import com.intellij.vcs.log.impl.VcsProjectLog import java.util.* import java.util.function.Supplier abstract class IndexDiagnosticActionBase(dynamicText: Supplier<@NlsActions.ActionText String>) : DumbAwareAction(dynamicText) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { val project = e.project if (project == null) { e.presentation.isEnabledAndVisible = false return } val logManager = VcsProjectLog.getInstance(project).logManager if (logManager == null) { e.presentation.isEnabledAndVisible = false return } if (logManager.dataManager.index.dataGetter == null) { e.presentation.isEnabledAndVisible = false return } update(e, logManager) } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val logManager = VcsProjectLog.getInstance(project).logManager ?: return val dataGetter = logManager.dataManager.index.dataGetter ?: return val commitIds = getCommitsToCheck(e, logManager) if (commitIds.isEmpty()) return val report = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { val detailsList = logManager.dataManager.commitDetailsGetter.getCommitDetails(commitIds) return@ThrowableComputable dataGetter.getDiffFor(commitIds, detailsList) }, VcsLogBundle.message("vcs.log.index.diagnostic.progress.title"), false, project) if (report.isBlank()) { VcsBalloonProblemNotifier.showOverVersionControlView(project, VcsLogBundle.message("vcs.log.index.diagnostic.success.message", commitIds.size), MessageType.INFO) return } val reportFile = LightVirtualFile(VcsLogBundle.message("vcs.log.index.diagnostic.report.title", DateFormatUtil.formatDateTime(Date())), report.toString()) OpenFileDescriptor(project, reportFile, 0).navigate(true) } abstract fun update(e: AnActionEvent, logManager: VcsLogManager) abstract fun getCommitsToCheck(e: AnActionEvent, logManager: VcsLogManager): List<Int> } class CheckSelectedCommits : IndexDiagnosticActionBase(VcsLogBundle.messagePointer("vcs.log.index.diagnostic.selected.action.title")) { override fun update(e: AnActionEvent, logManager: VcsLogManager) { val selection = e.getData(VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION) if (selection == null) { e.presentation.isEnabledAndVisible = false return } val selectedCommits = getSelectedCommits(logManager.dataManager, selection, false) e.presentation.isVisible = true e.presentation.isEnabled = selectedCommits.isNotEmpty() } private fun getSelectedCommits(vcsLogData: VcsLogData, selection: VcsLogCommitSelection, reportNotIndexed: Boolean): List<Int> { val selectedCommits = selection.ids if (selectedCommits.isEmpty()) return emptyList() val selectedIndexedCommits = selectedCommits.filter { vcsLogData.index.isIndexed(it) } if (selectedIndexedCommits.isEmpty() && reportNotIndexed) { VcsBalloonProblemNotifier.showOverVersionControlView(vcsLogData.project, VcsLogBundle.message("vcs.log.index.diagnostic.selected.non.indexed.warning.message"), MessageType.WARNING) } return selectedIndexedCommits } override fun getCommitsToCheck(e: AnActionEvent, logManager: VcsLogManager): List<Int> { return getSelectedCommits(logManager.dataManager, e.getRequiredData(VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION), true) } } class CheckOldCommits : IndexDiagnosticActionBase(VcsLogBundle.messagePointer("vcs.log.index.diagnostic.action.title")) { override fun update(e: AnActionEvent, logManager: VcsLogManager) { val rootsForIndexing = VcsLogPersistentIndex.getRootsForIndexing(logManager.dataManager.logProviders) if (rootsForIndexing.isEmpty()) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = logManager.dataManager.dataPack.isFull && rootsForIndexing.any { logManager.dataManager.index.isIndexed(it) } } override fun getCommitsToCheck(e: AnActionEvent, logManager: VcsLogManager): List<Int> { val indexedRoots = VcsLogPersistentIndex.getRootsForIndexing(logManager.dataManager.logProviders).filter { logManager.dataManager.index.isIndexed(it) } if (indexedRoots.isEmpty()) return emptyList() val dataPack = logManager.dataManager.dataPack if (!dataPack.isFull) return emptyList() return dataPack.getFirstCommits(logManager.dataManager.storage, indexedRoots) } }
apache-2.0
2cd629ca6946b06e9367d46fe19f3f8d
45.450382
145
0.735207
4.970588
false
false
false
false
douzifly/clear-todolist
app/src/main/java/douzifly/list/widget/ColorPicker.kt
1
3875
package douzifly.list.widget import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.animation.AccelerateInterpolator import android.widget.LinearLayout import douzifly.list.R import java.util.* /** * Created by liuxiaoyuan on 2015/10/7. */ class ColorPicker(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) { companion object { fun getDimedColor(originColor: Int, dimFactor: Float = 0.94f): Int { val red = Color.red(originColor).toFloat() val green = Color.green(originColor).toFloat() val blue = Color.blue(originColor).toFloat() return Color.rgb((red * dimFactor).toInt(), (green * dimFactor).toInt(), (blue * dimFactor).toInt()) } } // 每一个颜色都是一个声音 val colors: Array<Long> = arrayOf( 0xff4285f4, // google blue 0xffec4536, // google brick red 0xfffbbd06, // google yellow 0xff34a852, // google green 0xffee468b, // pink 0xff3d7685, // steel blue 0xff572704, // chocolate 0xffe8d3a3 // tan ) inline fun randomColor(): Int = colors[Random(System.currentTimeMillis()).nextInt(colors.size)].toInt() var selectedColor: Int = colors[0].toInt() private set(color: Int) { field = color } var selectItem: Item? = null init { orientation = LinearLayout.HORIZONTAL setGravity(Gravity.CENTER_VERTICAL) colors.forEach { colorL -> val color = colorL.toInt() val view = LayoutInflater.from(context).inflate(R.layout.color_picker_item, this, false) val item = Item(view, color) addView(view) view.tag = item view.setOnClickListener { v -> val i = v.tag as Item setSelected(i) } } } fun setSelected(item: Item) { if (item == selectItem) { return } selectItem?.selected = false item.selected = true selectItem = item selectedColor = item.color } fun setSelected(color: Int) { val count = childCount for (i in 0..count-1) { val item = getChildAt(i).tag as Item if (color == item.color) { setSelected(item) break; } } } inner class Item( val view: View, val color: Int ) { init { view.setBackgroundColor(color) } var selected: Boolean = false set(value: Boolean) { if (field == value) return field = value updateUI() } private fun updateUI() { var scale = if (selected) 1.3f else 1.0f val animatorW = ObjectAnimator.ofFloat(view, "scaleX", scale) val animatorH = ObjectAnimator.ofFloat(view, "scaleY", scale) val animators = AnimatorSet() animators.playTogether(animatorH, animatorW) animators.setDuration(150) animators.interpolator = AccelerateInterpolator() animators.start() } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) if (childCount > 0) { val child0 = getChildAt(0) val h = child0.height * 1.6f setMeasuredDimension(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(h.toInt(), View.MeasureSpec.EXACTLY)) } } }
gpl-3.0
16046eafb6438fa2fb1f0320f1ede8e7
27.338235
121
0.577991
4.532941
false
false
false
false
hsz/idea-gitignore
src/main/kotlin/mobi/hsz/idea/gitignore/indexing/IgnoreEntryOccurrence.kt
1
2541
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package mobi.hsz.idea.gitignore.indexing import com.intellij.openapi.util.Pair import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import org.apache.commons.lang.builder.HashCodeBuilder import java.io.DataInput import java.io.DataOutput import java.io.IOException import java.io.Serializable /** * Entry containing information about the [VirtualFile] instance of the ignore file mapped with the collection * of ignore entries for better performance. Class is used for indexing. */ @Suppress("SerialVersionUIDInSerializableClass") class IgnoreEntryOccurrence(private val url: String, val items: List<Pair<String, Boolean>>) : Serializable { /** * Returns current [VirtualFile]. * * @return current file */ var file: VirtualFile? = null get() { if (field == null && url.isNotEmpty()) { field = VirtualFileManager.getInstance().findFileByUrl(url) } return field } private set companion object { @Synchronized @Throws(IOException::class) fun serialize(out: DataOutput, entry: IgnoreEntryOccurrence) { out.run { writeUTF(entry.url) writeInt(entry.items.size) entry.items.forEach { writeUTF(it.first) writeBoolean(it.second) } } } @Synchronized @Throws(IOException::class) fun deserialize(input: DataInput): IgnoreEntryOccurrence { val url = input.readUTF() val items = mutableListOf<Pair<String, Boolean>>() if (url.isNotEmpty()) { val size = input.readInt() repeat((0 until size).count()) { items.add(Pair.create(input.readUTF(), input.readBoolean())) } } return IgnoreEntryOccurrence(url, items) } } override fun hashCode() = HashCodeBuilder().append(url).apply { items.forEach { append(it.first).append(it.second) } }.toHashCode() override fun equals(other: Any?) = when { other !is IgnoreEntryOccurrence -> false url != other.url || items.size != other.items.size -> false else -> items.indices.find { items[it].toString() != other.items[it].toString() } == null } }
mit
a713694504213aeebee44bc26c9c1a9f
33.808219
140
0.615112
4.679558
false
false
false
false
intrigus/jtransc
jtransc-core/src/com/jtransc/gen/common/BaseCompiler.kt
1
524
package com.jtransc.gen.common import com.jtransc.io.ProcessUtils import java.io.File abstract class BaseCompiler(val cmdName: String) { val cmd by lazy { ProcessUtils.which(cmdName) } val available by lazy { cmd != null } abstract fun genCommand(programFile: File, config: Config): List<String> data class Config( val debug: Boolean = false, val libs: List<String> = listOf(), val includeFolders: List<String> = listOf(), val libsFolders: List<String> = listOf(), val defines: List<String> = listOf() ) }
apache-2.0
2169001727c6deb062a39e3318dfcc12
28.111111
73
0.723282
3.358974
false
true
false
false
Austin72/Charlatano
src/main/kotlin/com/charlatano/game/offsets/FirstClassFinder.kt
1
1589
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game.offsets import com.charlatano.game.CSGO.csgoEXE import com.charlatano.game.CSGO.clientDLL import com.charlatano.game.offsets.ClientOffsets.decalname import com.charlatano.utils.extensions.uint fun findDecal(): Long { val mask = ByteArray(4) for (i in 0..3) mask[i] = (((decalname shr 8 * i)) and 0xFF).toByte() val memory = Offset.memoryByModule[clientDLL]!! var skipped = 0 var currentAddress = 0L while (currentAddress < clientDLL.size - mask.size) { if (memory.mask(currentAddress, mask, false)) { if (skipped < 5) { // skips currentAddress += 0xA // skipSize skipped++ continue } return currentAddress + clientDLL.address } currentAddress++ } return -1L } fun findFirstClass() = csgoEXE.uint(findDecal() + 0x3B)
agpl-3.0
72b5804e88ec42f26e778e953f9449f5
31.44898
78
0.726872
3.611364
false
false
false
false
luhaoaimama1/JavaZone
HttpTest3/src/main/java/hook/Instrumentation/premain/ByteChangeTransformerKt.kt
1
2592
package hook.Instrumentation.premain import javassist.ClassPool import javassist.CtClass import java.io.ByteArrayInputStream import java.lang.instrument.ClassFileTransformer import java.lang.instrument.IllegalClassFormatException import java.security.ProtectionDomain class ByteChangeTransformerKt : ClassFileTransformer { @Throws(IllegalClassFormatException::class) override fun transform(loader: ClassLoader, className: String, classBeingRedefined: Class<*>?, protectionDomain: ProtectionDomain, classfileBuffer: ByteArray): ByteArray { // if (!"hook.Instrumentation.premain.TestAgent".equals(className)) { // // 只修改指定的Class // return classfileBuffer; // } println(" passing! className:$className") var transformed: ByteArray? = null var cl: CtClass? = null try { // CtClass、ClassPool、CtMethod、ExprEditor都是javassist提供的字节码操作的类 val pool = ClassPool.getDefault() cl = pool.makeClass(ByteArrayInputStream(classfileBuffer)) val methods = cl.declaredMethods for (i in methods.indices) { val method = methods[i] if (method.methodInfo.codeAttribute != null) { method.insertBefore("System.out.println(\" inserting \t ${className}.${method.name}\");") } // methods[i].insertAfter("System.out.println(\" after\");"); // methods[i].instrument(new ExprEditor() { // @Override // public void edit(MethodCall m) throws CannotCompileException { // // 把方法体直接替换掉,其中 $proceed($$);是javassist的语法,用来表示原方法体的调用 // m.replace("{ long stime = System.currentTimeMillis();" // + " $_ = $proceed($$);" // + "System.out.println(\"" + m.getClassName() + "." + m.getMethodName() // + " cost:\" + (System.currentTimeMillis() - stime) + \" ms\"); }"); // } // }); } // javassist会把输入的Java代码再编译成字节码byte[] transformed = cl.toBytecode() } catch (e: Exception) { e.printStackTrace() } finally { cl?.detach() } return transformed!! } }
epl-1.0
e679afda23f1e2327ccfe19ff60446fc
43.017857
109
0.542614
4.918164
false
false
false
false
like5188/Common
common/src/main/java/com/like/common/view/dragview/animation/AnimationConfig.kt
1
2332
package com.like.common.view.dragview.animation import android.app.Activity import com.like.common.view.dragview.entity.DragInfo import com.like.common.view.dragview.view.BaseDragView class AnimationConfig(info: DragInfo, val view: BaseDragView) { companion object { const val DURATION = 300L } val MAX_CANVAS_TRANSLATION_Y = view.height.toFloat() / 4 var curCanvasBgAlpha = 255 var curCanvasTranslationX = 0f var curCanvasTranslationY = 0f var curCanvasScale = 1f var originScaleX = info.originWidth / view.width.toFloat() var originScaleY = info.originHeight / view.height.toFloat() var originTranslationX = info.originCenterX - view.width / 2 var originTranslationY = info.originCenterY - view.height / 2 var minCanvasScale = info.originWidth / view.width fun setData(info: DragInfo) { curCanvasBgAlpha = 255 curCanvasTranslationX = 0f curCanvasTranslationY = 0f curCanvasScale = 1f originScaleX = info.originWidth / view.width.toFloat() originScaleY = info.originHeight / view.height.toFloat() originTranslationX = info.originCenterX - view.width / 2 originTranslationY = info.originCenterY - view.height / 2 minCanvasScale = info.originWidth / view.width } fun finishActivity() { val activity = view.context if (activity is Activity) { activity.finish() activity.overridePendingTransition(0, 0) } } fun updateCanvasTranslationX(translationX: Float) { curCanvasTranslationX = translationX } fun updateCanvasTranslationY(translationY: Float) { curCanvasTranslationY = translationY } fun updateCanvasScale() { val translateYPercent = Math.abs(curCanvasTranslationY) / view.height val scale = 1 - translateYPercent curCanvasScale = when { scale < minCanvasScale -> minCanvasScale scale > 1f -> 1f else -> scale } } fun updateCanvasBgAlpha() { val translateYPercent = Math.abs(curCanvasTranslationY) / view.height val alpha = (255 * (1 - translateYPercent)).toInt() curCanvasBgAlpha = when { alpha > 255 -> 255 alpha < 0 -> 0 else -> alpha } } }
apache-2.0
2f3d9c25144ed0a337f137c64bbe4e4c
31.84507
77
0.654374
4.528155
false
false
false
false
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/widgets/ListWidgetService.kt
1
10168
package com.orgzly.android.widgets import android.content.Context import android.content.Intent import android.util.Log import android.view.View import android.widget.RemoteViews import android.widget.RemoteViewsService import com.orgzly.BuildConfig import com.orgzly.R import com.orgzly.android.App import com.orgzly.android.AppIntent import com.orgzly.android.data.DataRepository import com.orgzly.android.db.entity.NoteView import com.orgzly.android.prefs.AppPreferences import com.orgzly.android.query.Query import com.orgzly.android.query.user.InternalQueryParser import com.orgzly.android.ui.TimeType import com.orgzly.android.ui.notes.query.agenda.AgendaItem import com.orgzly.android.ui.notes.query.agenda.AgendaItems import com.orgzly.android.ui.util.TitleGenerator import com.orgzly.android.util.LogUtils import com.orgzly.android.util.UserTimeFormatter import com.orgzly.org.datetime.OrgRange import org.joda.time.DateTime import javax.inject.Inject class ListWidgetService : RemoteViewsService() { @Inject lateinit var dataRepository: DataRepository override fun onCreate() { App.appComponent.inject(this) super.onCreate() } override fun onGetViewFactory(intent: Intent): RemoteViewsFactory { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG) val queryString = intent.getStringExtra(AppIntent.EXTRA_QUERY_STRING).orEmpty() return ListWidgetViewsFactory(applicationContext, queryString) } private sealed class WidgetEntry(open val id: Long) { data class Overdue(override val id: Long) : WidgetEntry(id) data class Day(override val id: Long, val day: DateTime) : WidgetEntry(id) data class Note( override val id: Long, val noteView: NoteView, val agendaTimeType: TimeType? = null ) : WidgetEntry(id) } inner class ListWidgetViewsFactory( val context: Context, private val queryString: String ) : RemoteViewsFactory { private val query: Query by lazy { val parser = InternalQueryParser() parser.parse(queryString) } private val userTimeFormatter by lazy { UserTimeFormatter(context) } private var dataList: List<WidgetEntry> = emptyList() override fun onCreate() { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG) } override fun getLoadingView(): RemoteViews? { return null } override fun getItemId(position: Int): Long { return dataList[position].id } override fun onDataSetChanged() { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG) val notes = dataRepository.selectNotesFromQuery(query) if (query.isAgenda()) { val idMap = mutableMapOf<Long, Long>() val agendaItems = AgendaItems.getList(notes, query, idMap) dataList = agendaItems.map { when (it) { is AgendaItem.Overdue -> WidgetEntry.Overdue(it.id) is AgendaItem.Day -> WidgetEntry.Day(it.id, it.day) is AgendaItem.Note -> WidgetEntry.Note(it.id, it.note, it.timeType) } } } else { dataList = notes.map { WidgetEntry.Note(it.note.id, it) } } } override fun hasStableIds(): Boolean { return true } override fun getViewAt(position: Int): RemoteViews? { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, position) if (position >= dataList.size) { Log.e(TAG, "List too small (${dataList.size}) for requested position $position") return null } return when (val entry = dataList[position]) { is WidgetEntry.Overdue -> RemoteViews(context.packageName, R.layout.item_list_widget_divider).apply { setupRemoteViews(this) WidgetStyle.updateDivider(this, context) } is WidgetEntry.Day -> RemoteViews(context.packageName, R.layout.item_list_widget_divider).apply { setupRemoteViews(this, entry) WidgetStyle.updateDivider(this, context) } is WidgetEntry.Note -> RemoteViews(context.packageName, R.layout.item_list_widget).apply { setupRemoteViews(this, entry) WidgetStyle.updateNote(this, context) } } } override fun getCount(): Int { return dataList.size } override fun getViewTypeCount(): Int { return 2 } override fun onDestroy() { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG) } private fun setupRemoteViews(views: RemoteViews) { views.setTextViewText( R.id.widget_list_item_divider_value, context.getString(R.string.overdue)) } private fun setupRemoteViews(views: RemoteViews, entry: WidgetEntry.Day) { views.setTextViewText( R.id.widget_list_item_divider_value, userTimeFormatter.formatDate(entry.day)) } private fun setupRemoteViews(row: RemoteViews, entry: WidgetEntry.Note) { val noteView = entry.noteView val displayPlanningTimes = AppPreferences.displayPlanning(context) val displayBookName = AppPreferences.widgetDisplayBookName(context) val doneStates = AppPreferences.doneKeywordsSet(context) // Title (colors depend on current theme) val titleGenerator = TitleGenerator(context, false, WidgetStyle.getTitleAttributes(context)) row.setTextViewText(R.id.item_list_widget_title, titleGenerator.generateTitle(noteView)) // Notebook name if (displayBookName) { row.setTextViewText(R.id.item_list_widget_book_text, noteView.bookName) row.setViewVisibility(R.id.item_list_widget_book, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_book, View.GONE) } // Closed time if (displayPlanningTimes && noteView.closedRangeString != null) { val time = userTimeFormatter.formatAll(OrgRange.parse(noteView.closedRangeString)) row.setTextViewText(R.id.item_list_widget_closed_text, time) row.setViewVisibility(R.id.item_list_widget_closed, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_closed, View.GONE) } var scheduled = noteView.scheduledRangeString var deadline = noteView.deadlineRangeString var event = noteView.eventString // In Agenda only display time responsible for item's presence when (entry.agendaTimeType) { TimeType.SCHEDULED -> { deadline = null event = null } TimeType.DEADLINE -> { scheduled = null event = null } TimeType.EVENT -> { scheduled = null deadline = null } else -> { } } // Scheduled time if (displayPlanningTimes && scheduled != null) { val time = userTimeFormatter.formatAll(OrgRange.parse(scheduled)) row.setTextViewText(R.id.item_list_widget_scheduled_text, time) row.setViewVisibility(R.id.item_list_widget_scheduled, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_scheduled, View.GONE) } // Deadline time if (displayPlanningTimes && deadline != null) { val time = userTimeFormatter.formatAll(OrgRange.parse(deadline)) row.setTextViewText(R.id.item_list_widget_deadline_text, time) row.setViewVisibility(R.id.item_list_widget_deadline, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_deadline, View.GONE) } // Event time if (displayPlanningTimes && event != null) { val time = userTimeFormatter.formatAll(OrgRange.parse(event)) row.setTextViewText(R.id.item_list_widget_event_text, time) row.setViewVisibility(R.id.item_list_widget_event, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_event, View.GONE) } // Check mark if (!AppPreferences.widgetDisplayCheckmarks(context) || doneStates.contains(noteView.note.state)) { row.setViewVisibility(R.id.item_list_widget_done, View.GONE) } else { row.setViewVisibility(R.id.item_list_widget_done, View.VISIBLE) } // Intent for opening note val openIntent = Intent() openIntent.putExtra(AppIntent.EXTRA_CLICK_TYPE, ListWidgetProvider.OPEN_CLICK_TYPE) openIntent.putExtra(AppIntent.EXTRA_NOTE_ID, noteView.note.id) openIntent.putExtra(AppIntent.EXTRA_BOOK_ID, noteView.note.position.bookId) row.setOnClickFillInIntent(R.id.item_list_widget_layout, openIntent) // Intent for marking note done val doneIntent = Intent() doneIntent.putExtra(AppIntent.EXTRA_CLICK_TYPE, ListWidgetProvider.DONE_CLICK_TYPE) doneIntent.putExtra(AppIntent.EXTRA_NOTE_ID, noteView.note.id) row.setOnClickFillInIntent(R.id.item_list_widget_done, doneIntent) } } companion object { private val TAG = ListWidgetService::class.java.name } }
gpl-3.0
be840551538683cfa713bd5206c9144d
36.659259
111
0.594512
4.841905
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/hle/manager/ThreadManager.kt
1
23380
package com.soywiz.kpspemu.hle.manager import com.soywiz.kds.* import com.soywiz.klock.* import com.soywiz.klogger.* import com.soywiz.kmem.* import com.soywiz.korio.async.* import com.soywiz.korio.error.* import com.soywiz.korio.lang.* import com.soywiz.kpspemu.* import com.soywiz.kpspemu.cpu.* import com.soywiz.kpspemu.cpu.dynarec.* import com.soywiz.kpspemu.cpu.interpreter.* import com.soywiz.kpspemu.mem.* import com.soywiz.kpspemu.util.* import kotlin.collections.set import kotlin.math.* import com.soywiz.kmem.umod import com.soywiz.krypto.encoding.* import kotlinx.coroutines.channels.* import com.soywiz.korio.error.invalidOp as invalidOp1 //const val INSTRUCTIONS_PER_STEP = 500_000 //const val INSTRUCTIONS_PER_STEP = 1_000_000 //const val INSTRUCTIONS_PER_STEP = 2_000_000 //const val INSTRUCTIONS_PER_STEP = 4_000_000 const val INSTRUCTIONS_PER_STEP = 5_000_000 //const val INSTRUCTIONS_PER_STEP = 10_000_000 //const val INSTRUCTIONS_PER_STEP = 100_000_000 class ThreadsWithPriority(val priority: Int) : Comparable<ThreadsWithPriority> { val threads = arrayListOf<PspThread>() var currentIndex = 0 val runningThreads get() = threads.count { it.running } fun next(): PspThread? = when { threads.isNotEmpty() -> threads[currentIndex++ % threads.size] else -> null } fun nextRunning(): PspThread? { for (n in 0 until threads.size) { val n = next() if (n != null && n.running) return n } return null } override fun compareTo(other: ThreadsWithPriority): Int { return this.priority.compareTo(other.priority) } override fun toString(): String = "ThreadsWithPriority(priority=$priority)" } class ThreadManager(emulator: Emulator) : Manager<PspThread>("Thread", emulator) { val logger = Logger("ThreadManager").apply { //level = LogLevel.TRACE } val prioritiesByValue = LinkedHashMap<Int, ThreadsWithPriority>() val priorities = PriorityQueue<ThreadsWithPriority>() val currentPriorities = PriorityQueue<ThreadsWithPriority>() val threads get() = resourcesById.values val waitingThreads: Int get() = resourcesById.count { it.value.waiting } val activeThreads: Int get() = resourcesById.count { it.value.running } val totalThreads: Int get() = resourcesById.size val aliveThreadCount: Int get() = resourcesById.values.count { it.running || it.waiting } val onThreadChanged = Signal<PspThread>() val onThreadChangedChannel = Channel<PspThread>().broadcast() val waitThreadChanged = onThreadChangedChannel.openSubscription() var currentThread: PspThread? = null override fun reset() { super.reset() currentThread = null } fun setThreadPriority(thread: PspThread, priority: Int) { if (thread.priority == priority) return val oldThreadsWithPriority = thread.threadsWithPriority if (oldThreadsWithPriority != null) { oldThreadsWithPriority.threads.remove(thread) if (oldThreadsWithPriority.threads.isEmpty()) { prioritiesByValue.remove(oldThreadsWithPriority.priority) priorities.remove(oldThreadsWithPriority) } } val newThreadsWithPriority = prioritiesByValue.getOrPut(priority) { ThreadsWithPriority(priority).also { priorities.add(it) } } thread.threadsWithPriority = newThreadsWithPriority newThreadsWithPriority.threads.add(thread) } fun create( name: String, entryPoint: Int, initPriority: Int, stackSize: Int, attributes: Int, optionPtr: Ptr ): PspThread { //priorities.sortBy { it.priority } var attr = attributes val ssize = max(stackSize, 0x200).nextAlignedTo(0x100) //val ssize = max(stackSize, 0x20000).nextAlignedTo(0x10000) val stack = memoryManager.stackPartition.allocateHigh(ssize, "${name}_stack") println(stack.toString2()) val thread = PspThread(this, allocId(), name, entryPoint, stack, initPriority, attributes, optionPtr) logger.info { "stack:%08X-%08X (%d)".format(stack.low.toInt(), stack.high.toInt(), stack.size.toInt()) } //memoryManager.userPartition.dump() attr = attr or PspThreadAttributes.User attr = attr or PspThreadAttributes.LowFF if (!(attr hasFlag PspThreadAttributes.NoFillStack)) { logger.trace { "FILLING: $stack" } mem.fill(-1, stack.low.toInt(), stack.size.toInt()) } else { logger.trace { "NOT FILLING: $stack" } } threadManager.onThreadChanged(thread) threadManager.onThreadChangedChannel.trySend(thread) return thread } @Deprecated("USE suspendReturnInt or suspendReturnVoid") fun suspend(): Nothing { throw CpuBreakExceptionCached(CpuBreakException.THREAD_WAIT) } fun suspendReturnInt(value: Int): Nothing { currentThread?.state?.V0 = value throw CpuBreakExceptionCached(CpuBreakException.THREAD_WAIT) } fun suspendReturnVoid(): Nothing { throw CpuBreakExceptionCached(CpuBreakException.THREAD_WAIT) } fun getActiveThreadPriorities(): List<Int> = threads.filter { it.running }.map { it.priority }.distinct().sorted() fun getActiveThreadsWithPriority(priority: Int): List<PspThread> = threads.filter { it.running && it.priority == priority } val lowestThreadPriority get() = threads.minByOrNull { it.priority }?.priority ?: 0 fun getFirstThread(): PspThread? { for (thread in threads) { if (thread.priority == lowestThreadPriority) return thread } return null } fun getNextPriority(priority: Int): Int? { return getActiveThreadPriorities().firstOrNull { it > priority } } fun computeNextThread(prevThread: PspThread?): PspThread? { if (prevThread == null) return getFirstThread() val threadsWithPriority = getActiveThreadsWithPriority(prevThread.priority) val threadsWithPriorityCount = threadsWithPriority.size if (threadsWithPriorityCount > 0) { val index = threadsWithPriority.indexOf(prevThread) umod threadsWithPriorityCount return threadsWithPriority.getOrNull((index + 1) umod threadsWithPriorityCount) } else { val nextPriority = getNextPriority(prevThread.priority) return nextPriority?.let { getActiveThreadsWithPriority(it).firstOrNull() } } } suspend fun waitThreadChange() { //println("[1]") /* kotlinx.coroutines.withTimeout(16L) { waitThreadChanged.receive() } */ delay(1.milliseconds) //onThreadChanged.waitOne() //println("[2]") //coroutineContext.sleep(0) } enum class StepResult { NO_THREAD, BREAKPOINT, TIMEOUT } fun step(): StepResult { val start = DateTime.now() if (emulator.globalTrace) { println("-----") for (thread in threads) { println("- ${thread.name} : ${thread.priority} : running=${thread.running}") } println("-----") } currentPriorities.clear() currentPriorities.addAll(priorities) //Console.error("ThreadManager.STEP") while (currentPriorities.isNotEmpty()) { val threads = currentPriorities.removeHead() //println("threads: $threads") while (true) { val now = DateTime.now() val current = threads.nextRunning() ?: break //println(" Running Thread.STEP: $current") if (emulator.globalTrace) println("Current thread: ${current.name}") try { current.step(now.unixMillisDouble) } catch (e: BreakpointException) { //Console.error("StepResult.BREAKPOINT: $e") return StepResult.BREAKPOINT } if (emulator.globalTrace) println("Next thread: ${current.name}") val elapsed = now - start if (elapsed >= 16.milliseconds) { //coroutineContext.delay(1.milliseconds) Console.error("StepResult.TIMEOUT: $elapsed") return StepResult.TIMEOUT } } } //dump() return StepResult.NO_THREAD } val availablePriorities: List<Int> get() = resourcesById.values.filter { it.running }.map { it.priority }.distinct().sorted() val availableThreadCount get() = resourcesById.values.count { it.running } val availableThreads get() = resourcesById.values.filter { it.running }.sortedBy { it.priority } val traces = hashMapOf<String, Boolean>() fun trace(name: String, trace: Boolean = true) { if (trace) { traces[name] = true } else { traces.remove(name) } tryGetByName(name)?.updateTrace() } fun stopAllThreads() { for (t in resourcesById.values.toList()) { t.exitAndKill() } throw CpuBreakExceptionCached(CpuBreakException.THREAD_EXIT_KILL) } fun executeInterrupt(address: Int, argument: Int) { val gcpustate = emulator.globalCpuState val oldInsideInterrupt = gcpustate.insideInterrupt gcpustate.insideInterrupt = true try { val thread = threads.first() val cpu = thread.state.clone() cpu._thread = thread val interpreter = CpuInterpreter(cpu, emulator.breakpoints, emulator.nameProvider) cpu.setPC(address) cpu.RA = CpuBreakException.INTERRUPT_RETURN_RA cpu.r4 = argument val start = timeManager.getTimeInMicroseconds() while (true) { val now = timeManager.getTimeInMicroseconds() interpreter.steps(10000) if (now - start >= 16.0) { println("Interrupt is taking too long...") break // Rest a bit } } } catch (e: CpuBreakException) { if (e.id != CpuBreakException.INTERRUPT_RETURN) { throw e } } finally { gcpustate.insideInterrupt = oldInsideInterrupt } } fun delayThread(micros: Int) { // @TODO: } fun dump() { println("ThreadManager.dump:") for (thread in threads) { println(" - $thread") } } val summary: String get() = "[" + threads.map { "'${it.name}'#${it.id} P${it.priority} : ${it.phase}" }.joinToString(", ") + "]" } sealed class WaitObject { //data class TIME(val instant: Double) : WaitObject() { // override fun toString(): String = "TIME(${instant.toLong()})" //} //data class PROMISE(val promise: Promise<Unit>, val reason: String) : WaitObject() data class COROUTINE(val reason: String) : WaitObject() //object SLEEP : WaitObject() object VBLANK : WaitObject() } class PspThread internal constructor( val threadManager: ThreadManager, id: Int, name: String, val entryPoint: Int, val stack: MemoryPartition, val initPriority: Int, var attributes: Int, val optionPtr: Ptr ) : Resource(threadManager, id, name), WithEmulator { var threadsWithPriority: ThreadsWithPriority? = null var preemptionCount: Int = 0 val totalExecutedInstructions: Long get() = state.totalExecuted val onEnd = Signal<Unit>() val onWakeUp = Signal<Unit>() val logger = Logger("PspThread") enum class Phase { STOPPED, RUNNING, WAITING, DELETED } override fun toString(): String { return "PspThread(id=$id, name='$name', phase=$phase, status=$status, priority=$priority, waitObject=$waitObject, waitInfo=$waitInfo)" } val status: Int get() { var out: Int = 0 if (running) out = out or ThreadStatus.RUNNING if (waiting) out = out or ThreadStatus.WAIT if (phase == Phase.DELETED) out = out or ThreadStatus.DEAD return out } var acceptingCallbacks: Boolean = false var waitObject: WaitObject? = null var waitInfo: Any? = null var exitStatus: Int = 0 var phase: Phase = Phase.STOPPED set(value) = run { field = value } val priority: Int get() = threadsWithPriority?.priority ?: Int.MAX_VALUE val running: Boolean get() = phase == Phase.RUNNING val waiting: Boolean get() = waitObject != null override val emulator get() = manager.emulator val state = CpuState("state.thread.$name", emulator.globalCpuState, emulator.syscalls).apply { _thread = this@PspThread setPC(entryPoint) SP = stack.high.toInt() RA = CpuBreakException.THREAD_EXIT_KIL_RA println("CREATED THREAD('$name'): PC=${PC.hex}, SP=${SP.hex}") } val interpreter = CpuInterpreter(state, emulator.breakpoints, emulator.nameProvider) val dynarek = DynarekRunner(state, emulator.breakpoints, emulator.nameProvider) //val interpreter = FastCpuInterpreter(state) init { updateTrace() setThreadProps(Phase.STOPPED) threadManager.setThreadPriority(this, initPriority) } fun setThreadProps(phase: Phase, waitObject: WaitObject? = this.waitObject, waitInfo: Any? = this.waitInfo, acceptingCallbacks: Boolean = this.acceptingCallbacks) { this.phase = phase this.waitObject = waitObject this.waitInfo = waitInfo this.acceptingCallbacks = acceptingCallbacks if (phase == Phase.STOPPED) { onEnd(Unit) } if (phase == Phase.DELETED) { manager.freeById(id) logger.warn { "Deleting Thread: $name" } } threadManager.onThreadChanged(this) threadManager.onThreadChangedChannel.trySend(this) } fun updateTrace() { interpreter.trace = threadManager.traces[name] == true } fun putDataInStack(bytes: ByteArray, alignment: Int = 0x10): PtrArray { val blockSize = bytes.size.nextAlignedTo(alignment) state.SP -= blockSize mem.write(state.SP, bytes) return PtrArray(mem.ptr(state.SP), bytes.size) } fun putWordInStack(word: Int, alignment: Int = 0x10): PtrArray { val blockSize = 4.nextAlignedTo(alignment) state.SP -= blockSize mem.sw(state.SP, word) return mem.ptr(state.SP).array(4) } fun putWordsInStack(vararg words: Int, alignment: Int = 0x10): PtrArray { val blockSize = (words.size * 4).nextAlignedTo(alignment) state.SP -= blockSize for (n in 0 until words.size) mem.sw(state.SP + n * 4, words[n]) return mem.ptr(state.SP).array(words.size * 4) } fun start() { resume() } fun resume() { setThreadProps(phase = Phase.RUNNING, waitObject = null, waitInfo = null, acceptingCallbacks = false) } fun stop(reason: String = "generic") { if (phase != Phase.STOPPED) { logger.warn { "Stopping Thread: $name : reason=$reason" } setThreadProps(phase = Phase.STOPPED) } //threadManager.onThreadChanged(this) } fun delete() { stop() setThreadProps(phase = Phase.DELETED) } fun exitAndKill() { stop() delete() } fun step(now: Double, trace: Boolean = tracing): Int { //if (name == "update_thread") { // println("Ignoring: Thread.${this.name}") // stop("ignoring") // return //} //println("Step: Thread.${this.name}") preemptionCount++ try { if (emulator.interpreted) { interpreter.steps(INSTRUCTIONS_PER_STEP, trace) } else { dynarek.steps(INSTRUCTIONS_PER_STEP, trace) } return 0 } catch (e: CpuBreakException) { when (e.id) { CpuBreakException.THREAD_EXIT_KILL -> { logger.info { "BREAK: THREAD_EXIT_KILL ('${this.name}', ${this.id})" } println("BREAK: THREAD_EXIT_KILL ('${this.name}', ${this.id})") exitAndKill() } CpuBreakException.THREAD_WAIT -> { // Do nothing } CpuBreakException.INTERRUPT_RETURN -> { // Do nothing } else -> { println("CPU: ${state.summary}") println("ERROR at PspThread.step") e.printStackTrace() throw e } } return e.id } } fun markWaiting(wait: WaitObject, cb: Boolean) { setThreadProps(phase = Phase.WAITING, waitObject = wait, acceptingCallbacks = cb) } fun suspend(wait: WaitObject, cb: Boolean) { markWaiting(wait, cb) //if (wait is WaitObject.PROMISE) wait.promise.then { resume() } threadManager.suspend() } var pendingAccumulatedMicrosecondsToWait: Int = 0 suspend fun sleepMicro(microseconds: Int) { val totalMicroseconds = pendingAccumulatedMicrosecondsToWait + microseconds pendingAccumulatedMicrosecondsToWait = totalMicroseconds % 1000 val totalMilliseconds = totalMicroseconds / 1000 // @TODO: This makes sceRtc test to be flaky //if (totalMilliseconds < 1) { // pendingAccumulatedMicrosecondsToWait += totalMilliseconds * 1000 //} else { coroutineContext.delay(totalMilliseconds.milliseconds) //} } suspend fun sleepSeconds(seconds: Double) = sleepMicro((seconds * 1_000_000).toInt()) suspend fun sleepSecondsIfRequired(seconds: Double) { if (seconds > 0.0) sleepMicro((seconds * 1_000_000).toInt()) } fun cpuBreakException(e: CpuBreakException) { } var tracing: Boolean = false } var CpuState._thread: PspThread? by Extra.Property { null } val CpuState.thread: PspThread get() = _thread ?: invalidOp1("CpuState doesn't have a thread attached") data class PspEventFlag(override val id: Int) : ResourceItem { var name: String = "" var attributes: Int = 0 var currentPattern: Int = 0 var optionsPtr: Ptr? = null fun poll(bitsToMatch: Int, waitType: Int, outBits: Ptr): Boolean { if (outBits.isNotNull) outBits.sw(0, this.currentPattern) val res = when { (waitType and EventFlagWaitTypeSet.Or) != 0 -> ((this.currentPattern and bitsToMatch) != 0) // one or more bits of the mask else -> (this.currentPattern and bitsToMatch) == bitsToMatch // all the bits of the mask } if (res) { this._doClear(bitsToMatch, waitType) return true } else { return false } } private fun _doClear(bitsToMatch: Int, waitType: Int) { if ((waitType and (EventFlagWaitTypeSet.ClearAll)) != 0) this.clearBits(-1.inv(), false) if ((waitType and (EventFlagWaitTypeSet.Clear)) != 0) this.clearBits(bitsToMatch.inv(), false) } fun clearBits(bitsToClear: Int, doUpdateWaitingThreads: Boolean = true) { this.currentPattern = this.currentPattern and bitsToClear if (doUpdateWaitingThreads) this.updateWaitingThreads() } private fun updateWaitingThreads() { //this.waitingThreads.forEach(waitingThread => { // if (this.poll(waitingThread.bitsToMatch, waitingThread.waitType, waitingThread.outBits)) { // waitingThread.wakeUp(); // } //}); } fun setBits(bits: Int, doUpdateWaitingThreads: Boolean = true) { this.currentPattern = this.currentPattern or bits if (doUpdateWaitingThreads) this.updateWaitingThreads() } } object EventFlagWaitTypeSet { const val And = 0x00 const val Or = 0x01 const val ClearAll = 0x10 const val Clear = 0x20 const val MaskValidBits = Or or Clear or ClearAll } object ThreadStatus { const val RUNNING = 1 const val READY = 2 const val WAIT = 4 const val SUSPEND = 8 const val DORMANT = 16 const val DEAD = 32 const val WAITSUSPEND = WAIT or SUSPEND } class SceKernelThreadInfo( var size: Int = 0, var name: String = "", var attributes: Int = 0, var status: Int = 0, // ThreadStatus var entryPoint: Int = 0, var stackPointer: Int = 0, var stackSize: Int = 0, var GP: Int = 0, var priorityInit: Int = 0, var priority: Int = 0, var waitType: Int = 0, var waitId: Int = 0, var wakeupCount: Int = 0, var exitStatus: Int = 0, var runClocksLow: Int = 0, var runClocksHigh: Int = 0, var interruptPreemptionCount: Int = 0, var threadPreemptionCount: Int = 0, var releaseCount: Int = 0 ) { companion object : Struct<SceKernelThreadInfo>( { SceKernelThreadInfo() }, SceKernelThreadInfo::size AS INT32, SceKernelThreadInfo::name AS STRINGZ(32), SceKernelThreadInfo::attributes AS INT32, SceKernelThreadInfo::status AS INT32, SceKernelThreadInfo::entryPoint AS INT32, SceKernelThreadInfo::stackPointer AS INT32, SceKernelThreadInfo::stackSize AS INT32, SceKernelThreadInfo::GP AS INT32, SceKernelThreadInfo::priorityInit AS INT32, SceKernelThreadInfo::priority AS INT32, SceKernelThreadInfo::waitType AS INT32, SceKernelThreadInfo::waitId AS INT32, SceKernelThreadInfo::wakeupCount AS INT32, SceKernelThreadInfo::exitStatus AS INT32, SceKernelThreadInfo::runClocksLow AS INT32, SceKernelThreadInfo::runClocksHigh AS INT32, SceKernelThreadInfo::interruptPreemptionCount AS INT32, SceKernelThreadInfo::threadPreemptionCount AS INT32, SceKernelThreadInfo::releaseCount AS INT32 ) } object PspThreadAttributes { const val None = 0 const val LowFF = 0x000000FF.toInt() const val Vfpu = 0x00004000.toInt() // Enable VFPU access for the thread. const val V0x2000 = 0x2000.toInt() const val V0x4000 = 0x4000.toInt() const val V0x400000 = 0x400000.toInt() const val V0x800000 = 0x800000.toInt() const val V0xf00000 = 0xf00000.toInt() const val V0x8000000 = 0x8000000.toInt() const val V0xf000000 = 0xf000000.toInt() const val User = 0x80000000.toInt() // Start the thread in user mode (done automatically if the thread creating it is in user mode). const val UsbWlan = 0xa0000000.toInt() // Thread is part of the USB/WLAN API. const val Vsh = 0xc0000000.toInt() // Thread is part of the VSH API. //val ScratchRamEnable = 0x00008000, // Allow using scratchpad memory for a thread, NOT USABLE ON V1.0 const val NoFillStack = 0x00100000.toInt() // Disables filling the stack with 0xFF on creation const val ClearStack = 0x00200000.toInt() // Clear the stack when the thread is deleted const val ValidMask = (LowFF or Vfpu or User or UsbWlan or Vsh or /*ScratchRamEnable |*/ NoFillStack or ClearStack or V0x2000 or V0x4000 or V0x400000 or V0x800000 or V0xf00000 or V0x8000000 or V0xf000000).toInt() }
mit
bb3d001bdae30ed868e42445914e3560
34.212349
216
0.625449
4.437275
false
false
false
false
TheContext/podcast-ci
src/main/kotlin/io/thecontext/podcaster/input/InputReader.kt
1
2429
package io.thecontext.podcaster.input import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException import io.reactivex.Scheduler import io.reactivex.Single import io.thecontext.podcaster.value.Episode import io.thecontext.podcaster.value.Person import io.thecontext.podcaster.value.Podcast import java.io.File interface InputReader { sealed class Result { data class Success(val podcast: Podcast, val episodes: List<Episode>, val people: List<Person>) : Result() data class Failure(val message: String) : Result() } fun read(peopleFile: File, podcastFile: File, episodeFiles: Map<File, File>): Single<Result> class Impl( private val yamlReader: YamlReader, private val textReader: TextReader, private val ioScheduler: Scheduler ) : InputReader { override fun read(peopleFile: File, podcastFile: File, episodeFiles: Map<File, File>) = Single .fromCallable { val podcast = try { yamlReader.readPodcast(podcastFile) } catch (e: MissingKotlinParameterException) { return@fromCallable Result.Failure("Podcast YAML is missing value for [${e.parameter.name}].") } val episodes = episodeFiles.map { (episodeFile, episodeNotesFile) -> val episodeSlug = episodeFile.parentFile.name val episodeNotes = textReader.read(episodeNotesFile) val episode = try { yamlReader.readEpisode(episodeFile) } catch (e: MissingKotlinParameterException) { return@fromCallable Result.Failure("Episode YAML [$episodeSlug] is missing value for [${e.parameter.name}].") } episode.copy(slug = episodeSlug, notesMarkdown = episodeNotes) } val people = try { yamlReader.readPeople(peopleFile).distinctBy { it.id } } catch (e: MissingKotlinParameterException) { return@fromCallable Result.Failure("People YAML is missing value for [${e.parameter.name}].") } Result.Success(podcast, episodes, people) } .subscribeOn(ioScheduler) } }
apache-2.0
2f18099cbfa566d02162afd2e2323d14
41.614035
137
0.589955
5.190171
false
false
false
false
Esri/arcgis-runtime-samples-android
kotlin/viewshed-location/src/main/java/com/esri/arcgisruntime/sample/viewshedlocation/MainActivity.kt
1
15186
/* * Copyright 2020 Esri * * 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.esri.arcgisruntime.sample.viewshedlocation import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.MotionEvent import android.widget.CheckBox import android.widget.SeekBar import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.geoanalysis.LocationViewshed import com.esri.arcgisruntime.geoanalysis.Viewshed import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.layers.ArcGISSceneLayer import com.esri.arcgisruntime.mapping.* import com.esri.arcgisruntime.mapping.view.* import com.esri.arcgisruntime.sample.viewshedlocation.databinding.ActivityMainBinding import java.util.concurrent.ExecutionException import kotlin.math.roundToInt class MainActivity : AppCompatActivity() { // initialize location viewshed parameters private val initHeading = 0 private val initPitch = 60 private val initHorizontalAngle = 75 private val initVerticalAngle = 90 private val initMinDistance = 0 private val initMaxDistance = 1500 private var minDistance: Int = 0 private var maxDistance: Int = 0 private lateinit var viewShed: LocationViewshed private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val sceneView: SceneView by lazy { activityMainBinding.sceneView } private val headingSeekBar: SeekBar by lazy { activityMainBinding.include.headingSeekBar } private val currHeading: TextView by lazy { activityMainBinding.include.currHeading } private val currPitch: TextView by lazy { activityMainBinding.include.currPitch } private val pitchSeekBar: SeekBar by lazy { activityMainBinding.include.pitchSeekBar } private val currHorizontalAngle: TextView by lazy { activityMainBinding.include.currHorizontalAngle } private val horizontalAngleSeekBar: SeekBar by lazy { activityMainBinding.include.horizontalAngleSeekBar } private val currVerticalAngle: TextView by lazy { activityMainBinding.include.currVerticalAngle } private val verticalAngleSeekBar: SeekBar by lazy { activityMainBinding.include.verticalAngleSeekBar } private val currMinimumDistance: TextView by lazy { activityMainBinding.include.currMinimumDistance } private val minDistanceSeekBar: SeekBar by lazy { activityMainBinding.include.minDistanceSeekBar } private val currMaximumDistance: TextView by lazy { activityMainBinding.include.currMaximumDistance } private val maxDistanceSeekBar: SeekBar by lazy { activityMainBinding.include.maxDistanceSeekBar } private val frustumVisibilityCheckBox: CheckBox by lazy { activityMainBinding.include.frustumVisibilityCheckBox } private val viewshedVisibilityCheckBox: CheckBox by lazy { activityMainBinding.include.viewshedVisibilityCheckBox } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to access basemaps and other // location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create a surface for elevation data val surface = Surface().apply { elevationSources.add(ArcGISTiledElevationSource(getString(R.string.elevation_service))) } // create a layer of buildings val buildingsSceneLayer = ArcGISSceneLayer(getString(R.string.buildings_layer)) // create a scene and add imagery basemap, elevation surface, and buildings layer to it val buildingsScene = ArcGISScene(BasemapStyle.ARCGIS_IMAGERY).apply { baseSurface = surface operationalLayers.add(buildingsSceneLayer) } val initLocation = Point(-4.50, 48.4, 1000.0) // create viewshed from the initial location viewShed = LocationViewshed( initLocation, initHeading.toDouble(), initPitch.toDouble(), initHorizontalAngle.toDouble(), initVerticalAngle.toDouble(), initMinDistance.toDouble(), initMaxDistance.toDouble() ).apply { setFrustumOutlineVisible(true) } Viewshed.setFrustumOutlineColor(Color.BLUE) sceneView.apply { // add the buildings scene to the sceneView scene = buildingsScene // add a camera and set it to orbit the starting location point of the frustum cameraController = OrbitLocationCameraController(initLocation, 5000.0) setViewpointCamera(Camera(initLocation, 20000000.0, 0.0, 55.0, 0.0)) } // create an analysis overlay to add the viewshed to the scene view val analysisOverlay = AnalysisOverlay().apply { analyses.add(viewShed) } sceneView.analysisOverlays.add(analysisOverlay) // initialize the UI controls handleUiElements() } /** * Handles double touch drag for movement of viewshed location point and listeners for * changes in seek bar progress. */ private fun handleUiElements() { sceneView.setOnTouchListener(object : DefaultSceneViewOnTouchListener(sceneView) { // double tap and hold second tap to drag viewshed to a new location override fun onDoubleTouchDrag(motionEvent: MotionEvent): Boolean { // convert from screen point to location point val screenPoint = android.graphics.Point( motionEvent.x.roundToInt(), motionEvent.y.roundToInt() ) val locationPointFuture = sceneView.screenToLocationAsync(screenPoint) locationPointFuture.addDoneListener { try { val locationPoint = locationPointFuture.get() // add 50 meters to location point and set to viewshed viewShed.location = Point(locationPoint.x, locationPoint.y, locationPoint.z + 50) } catch (e: InterruptedException) { logError("Error converting screen point to location point: " + e.message) } catch (e: ExecutionException) { logError("Error converting screen point to location point: " + e.message) } } // ignore default double touch drag gesture return true } }) // toggle visibility of the viewshed viewshedVisibilityCheckBox.setOnCheckedChangeListener { buttonView, isChecked -> viewShed.isVisible = isChecked } // toggle visibility of the frustum outline frustumVisibilityCheckBox.setOnCheckedChangeListener { buttonView, isChecked -> viewShed.setFrustumOutlineVisible(isChecked) } // heading range 0 - 360 headingSeekBar.max = 360 setHeading(initHeading) headingSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { setHeading(seekBar.progress) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // set arbitrary max to 180 to avoid nonsensical pitch values pitchSeekBar.max = 180 setPitch(initPitch) pitchSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { setPitch(seekBar.progress) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // horizontal angle range 1 - 120 horizontalAngleSeekBar.max = 120 setHorizontalAngle(initHorizontalAngle) horizontalAngleSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { val horizontalAngle = horizontalAngleSeekBar.progress if (horizontalAngle > 0) { // horizontal angle must be > 0 setHorizontalAngle(horizontalAngle) } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // vertical angle range 1 - 120 verticalAngleSeekBar.max = 120 setVerticalAngle(initVerticalAngle) verticalAngleSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { val verticalAngle = verticalAngleSeekBar.progress if (verticalAngle > 0) { // vertical angle must be > 0 setVerticalAngle(verticalAngle) } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // initialize the minimum distance minDistance = initMinDistance // set to 1000 below the arbitrary max minDistanceSeekBar.max = 8999 setMinDistance(initMinDistance) minDistanceSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { minDistance = seekBar.progress if (maxDistance - minDistance < 1000) { maxDistance = minDistance + 1000 setMaxDistance(maxDistance) } setMinDistance(minDistance) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // initialize the maximum distance maxDistance = initMaxDistance // set arbitrary max to 9999 to allow a maximum of 4 digits maxDistanceSeekBar.max = 9999 setMaxDistance(initMaxDistance) maxDistanceSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { maxDistance = seekBar.progress if (maxDistance - minDistance < 1000) { minDistance = if (maxDistance > 1000) { maxDistance - 1000 } else { 0 } setMinDistance(minDistance) } setMaxDistance(maxDistance) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) } /** * Set viewshed heading, seek bar progress, and current heading text view. * * @param heading in degrees */ private fun setHeading(heading: Int) { headingSeekBar.progress = heading currHeading.text = heading.toString() viewShed.heading = heading.toDouble() } /** * Set viewshed pitch, seek bar progress, and current pitch text view. * * @param pitch in degrees */ private fun setPitch(pitch: Int) { pitchSeekBar.progress = pitch currPitch.text = pitch.toString() viewShed.pitch = pitch.toDouble() } /** * Set viewshed horizontal angle, seek bar progress, and current horizontal angle text view. * * @param horizontalAngle in degrees, > 0 and <= 120 */ private fun setHorizontalAngle(horizontalAngle: Int) { if (horizontalAngle in 1..120) { horizontalAngleSeekBar.progress = horizontalAngle currHorizontalAngle.text = horizontalAngle.toString() viewShed.horizontalAngle = horizontalAngle.toDouble() } else { logError("Horizontal angle must be greater than 0 and less than or equal to 120.") } } /** * Set viewshed vertical angle, seek bar progress, and current vertical angle text view. * * @param verticalAngle in degrees, > 0 and <= 120 */ private fun setVerticalAngle(verticalAngle: Int) { if (verticalAngle in 1..120) { verticalAngleSeekBar.progress = verticalAngle currVerticalAngle.text = verticalAngle.toString() viewShed.verticalAngle = verticalAngle.toDouble() } else { logError("Vertical angle must be greater than 0 and less than or equal to 120.") } } /** * Set viewshed minimum distance, seek bar progress, and current minimum distance text view. * * @param minDistance in meters */ private fun setMinDistance(minDistance: Int) { minDistanceSeekBar.progress = minDistance currMinimumDistance.text = minDistance.toString() viewShed.minDistance = minDistance.toDouble() } /** * Set viewshed maximum distance, seek bar progress, and current maximum distance text view. * * @param maxDistance in meters */ private fun setMaxDistance(maxDistance: Int) { maxDistanceSeekBar.progress = maxDistance currMaximumDistance.text = maxDistance.toString() viewShed.maxDistance = maxDistance.toDouble() } override fun onPause() { sceneView.pause() super.onPause() } override fun onResume() { super.onResume() sceneView.resume() } override fun onDestroy() { sceneView.dispose() super.onDestroy() } /** * Log an error to logcat and to the screen via Toast. * @param message the text to log. */ private fun logError(message: String?) { message?.let { Log.e(TAG, message) Toast.makeText(this, message, Toast.LENGTH_LONG).show() } } companion object { private val TAG: String = MainActivity::class.java.simpleName } }
apache-2.0
127cdadca6fc52a885da133e8bfd951f
34.234339
100
0.648558
5.536274
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-monsters-bukkit/src/main/kotlin/com/rpkit/monsters/bukkit/monsterstat/RPKMonsterStatServiceImpl.kt
1
8433
/* * Copyright 2021 Ren Binden * 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.rpkit.monsters.bukkit.monsterstat import com.rpkit.core.expression.RPKExpressionService import com.rpkit.core.service.Services import com.rpkit.monsters.bukkit.RPKMonstersBukkit import com.rpkit.monsters.bukkit.monsterlevel.RPKMonsterLevelService import org.bukkit.ChatColor import org.bukkit.attribute.Attribute import org.bukkit.entity.EntityType import org.bukkit.entity.LivingEntity class RPKMonsterStatServiceImpl(override val plugin: RPKMonstersBukkit) : RPKMonsterStatService { override fun getMonsterHealth(monster: LivingEntity): Double { return monster.health } override fun setMonsterHealth(monster: LivingEntity, health: Double) { monster.health = health setMonsterNameplate(monster, health = health) } override fun getMonsterMaxHealth(monster: LivingEntity): Double { val monsterNameplate = monster.customName val monsterLevelService = Services[RPKMonsterLevelService::class.java] ?: return monster.health val maxHealth = if (monsterNameplate != null) { val maxHealthString = Regex("${ChatColor.RED}❤ ${ChatColor.WHITE}(\\d+\\.\\d+)/(\\d+\\.\\d+)") .find(monsterNameplate) ?.groupValues ?.get(2) if (maxHealthString != null) { try { maxHealthString.toDouble() } catch (ignored: NumberFormatException) { calculateMonsterMaxHealth(monster.type, monsterLevelService.getMonsterLevel(monster)) } } else { calculateMonsterMaxHealth(monster.type, monsterLevelService.getMonsterLevel(monster)) } } else { calculateMonsterMaxHealth(monster.type, monsterLevelService.getMonsterLevel(monster)) } monster.getAttribute(Attribute.GENERIC_MAX_HEALTH)?.baseValue = maxHealth return monster.getAttribute(Attribute.GENERIC_MAX_HEALTH)?.value ?: monster.health } override fun getMonsterMinDamageMultiplier(monster: LivingEntity): Double { return getMonsterMinDamage(monster) / (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0) } override fun setMonsterMinDamageMultiplier(monster: LivingEntity, minDamageMultiplier: Double) { setMonsterNameplate(monster, minDamageMultiplier = minDamageMultiplier) } override fun getMonsterMinDamage(monster: LivingEntity): Double { val monsterNameplate = monster.customName if (monsterNameplate != null) { val minDamage = Regex("${ChatColor.RED}⚔ ${ChatColor.WHITE}(\\d+\\.\\d+)-(\\d+\\.\\d+)") .find(monsterNameplate) ?.groupValues ?.get(1) if (minDamage != null) { try { return minDamage.toDouble() } catch (ignored: NumberFormatException) { } } } val monsterLevelService = Services[RPKMonsterLevelService::class.java] ?: return 1.0 return calculateMonsterMinDamageMultiplier(monster.type, monsterLevelService.getMonsterLevel(monster)) * (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0) } override fun setMonsterMinDamage(monster: LivingEntity, minDamage: Double) { setMonsterNameplate(monster, minDamage = minDamage) } override fun getMonsterMaxDamageMultiplier(monster: LivingEntity): Double { return getMonsterMaxDamage(monster) / (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0) } override fun setMonsterMaxDamageMultiplier(monster: LivingEntity, maxDamageMultiplier: Double) { setMonsterNameplate(monster, maxDamageMultiplier = maxDamageMultiplier) } override fun getMonsterMaxDamage(monster: LivingEntity): Double { val monsterNameplate = monster.customName if (monsterNameplate != null) { val maxDamage = Regex("${ChatColor.RED}⚔ ${ChatColor.WHITE}(\\d+\\.\\d+)-(\\d+\\.\\d+)") .find(monsterNameplate) ?.groupValues ?.get(2) if (maxDamage != null) { try { return maxDamage.toDouble() } catch (ignored: NumberFormatException) { } } } val monsterLevelService = Services[RPKMonsterLevelService::class.java] ?: return 1.0 return calculateMonsterMaxDamageMultiplier(monster.type, monsterLevelService.getMonsterLevel(monster)) * (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0) } override fun setMonsterMaxDamage(monster: LivingEntity, maxDamage: Double) { setMonsterNameplate(monster, maxDamage = maxDamage) } fun calculateMonsterMaxHealth(entityType: EntityType, level: Int): Double { val expressionService = Services[RPKExpressionService::class.java] ?: return 1.0 val expression = expressionService.createExpression(plugin.config.getString("monsters.$entityType.max-health") ?: plugin.config.getString("monsters.default.max-health") ?: return 1.0) return expression.parseDouble(mapOf( "level" to level.toDouble() )) ?: 1.0 } fun calculateMonsterMinDamageMultiplier(entityType: EntityType, level: Int): Double { val expressionService = Services[RPKExpressionService::class.java] ?: return 1.0 val expression = expressionService.createExpression(plugin.config.getString("monsters.$entityType.min-damage-multiplier") ?: plugin.config.getString("monsters.default.min-damage-multiplier") ?: return 1.0) return expression.parseDouble(mapOf( "level" to level.toDouble() )) ?: 1.0 } fun calculateMonsterMaxDamageMultiplier(entityType: EntityType, level: Int): Double { val expressionService = Services[RPKExpressionService::class.java] ?: return 1.0 val expression = expressionService.createExpression(plugin.config.getString("monsters.$entityType.max-damage-multiplier") ?: plugin.config.getString("monsters.default.max-damage-multiplier") ?: return 1.0) return expression.parseDouble(mapOf( "level" to level.toDouble() )) ?: 1.0 } fun setMonsterNameplate( monster: LivingEntity, level: Int = Services[RPKMonsterLevelService::class.java]?.getMonsterLevel(monster) ?: 1, health: Double = getMonsterHealth(monster), maxHealth: Double = getMonsterMaxHealth(monster), minDamageMultiplier: Double = getMonsterMinDamageMultiplier(monster), maxDamageMultiplier: Double = getMonsterMaxDamageMultiplier(monster), minDamage: Double = (minDamageMultiplier * (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0)), maxDamage: Double = (maxDamageMultiplier * (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0)) ) { val monsterName = monster.type.toString().lowercase().replace('_', ' ') val formattedHealth = String.format("%.2f", health) val formattedMaxHealth = String.format("%.2f", maxHealth) val formattedMinDamage = String.format("%.2f", minDamage) val formattedMaxDamage = String.format("%.2f", maxDamage) val nameplate = "${ChatColor.WHITE}Lv${ChatColor.YELLOW}$level " + "$monsterName " + "${ChatColor.RED}❤ ${ChatColor.WHITE}$formattedHealth/$formattedMaxHealth " + "${ChatColor.RED}⚔ ${ChatColor.WHITE}$formattedMinDamage-$formattedMaxDamage" monster.customName = nameplate monster.isCustomNameVisible = true } }
apache-2.0
886878e90f2aa594bd5b2b9f59a1f9ce
46.59322
174
0.661047
5.123479
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/set/CharacterSetCommand.kt
1
3158
/* * Copyright 2020 Ren Binden * * 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.rpkit.characters.bukkit.command.character.set import com.rpkit.characters.bukkit.RPKCharactersBukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender /** * Character set command. * Parent command for commands used to set character attributes. */ class CharacterSetCommand(private val plugin: RPKCharactersBukkit) : CommandExecutor { private val characterSetProfileCommand = CharacterSetProfileCommand(plugin) private val characterSetNameCommand = CharacterSetNameCommand(plugin) private val characterSetGenderCommand = CharacterSetGenderCommand(plugin) private val characterSetAgeCommand = CharacterSetAgeCommand(plugin) private val characterSetRaceCommand = CharacterSetRaceCommand(plugin) private val characterSetDescriptionCommand = CharacterSetDescriptionCommand(plugin) private val characterSetDeadCommand = CharacterSetDeadCommand(plugin) override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (args.isNotEmpty()) { val newArgs = args.drop(1).toTypedArray() if (args[0].equals("profile", ignoreCase = true)) { return characterSetProfileCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("name", ignoreCase = true)) { return characterSetNameCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("gender", ignoreCase = true)) { return characterSetGenderCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("age", ignoreCase = true)) { return characterSetAgeCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("race", ignoreCase = true)) { return characterSetRaceCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("description", ignoreCase = true) || args[0].equals("desc", ignoreCase = true)) { return characterSetDescriptionCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("dead", ignoreCase = true)) { return characterSetDeadCommand.onCommand(sender, command, label, newArgs) } else { sender.sendMessage(plugin.messages["character-set-usage"]) } } else { sender.sendMessage(plugin.messages["character-set-usage"]) } return true } }
apache-2.0
3b05d227617bd561acb9069a6c25b232
49.126984
119
0.70266
4.756024
false
false
false
false
droibit/quickly
app/src/main/kotlin/com/droibit/quickly/main/LoadAppInfoTask.kt
1
1739
package com.droibit.quickly.main import com.droibit.quickly.data.repository.appinfo.AppInfo import com.droibit.quickly.data.repository.appinfo.AppInfoRepository import com.droibit.quickly.data.repository.settings.ShowSettingsRepository import com.jakewharton.rxrelay.BehaviorRelay import com.jakewharton.rxrelay.PublishRelay import rx.Observable import rx.schedulers.Schedulers import timber.log.Timber class LoadAppInfoTask( private val appInfoRepository: AppInfoRepository, private val showSettingsRepository: ShowSettingsRepository, private val runningRelay: BehaviorRelay<Boolean>) : MainContract.LoadAppInfoTask { private var cachedApps: List<AppInfo>? = null @Suppress("HasPlatformType") override fun isRunning() = runningRelay.distinctUntilChanged() override fun requestLoad(forceReload: Boolean): Observable<List<AppInfo>> { Timber.d("requestLoad(forceReload=$forceReload)") // TODO: if forceReload, need delay 1sec val shouldRunningCall = forceReload || !appInfoRepository.hasCache return appInfoRepository.loadAll(forceReload) .map { apps -> apps.filter { filterIfOnlyInstalled(it) } } .filter { it != cachedApps } .doOnNext { cachedApps = it } .subscribeOn(Schedulers.io()) .doOnSubscribe { if (shouldRunningCall) runningRelay.call(true) } // TODO: need review .doOnUnsubscribe { if (shouldRunningCall) runningRelay.call(false) } // TODO: need review } private fun filterIfOnlyInstalled(appInfo: AppInfo): Boolean { if (showSettingsRepository.isShowSystem) { return true } return !appInfo.preInstalled } }
apache-2.0
b0f3bc95c909f861ef8b35ab59d9935a
40.428571
105
0.711328
4.898592
false
false
false
false
MaibornWolff/codecharta
analysis/import/MetricGardenerImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/metricgardenerimporter/MetricGardenerImporter.kt
1
3856
package de.maibornwolff.codecharta.importer.metricgardenerimporter import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.lordcodes.turtle.ShellLocation import com.lordcodes.turtle.shellRun import de.maibornwolff.codecharta.importer.metricgardenerimporter.json.MetricGardenerProjectBuilder import de.maibornwolff.codecharta.importer.metricgardenerimporter.model.MetricGardenerNodes import de.maibornwolff.codecharta.serialization.ProjectSerializer import de.maibornwolff.codecharta.tools.interactiveparser.InteractiveParser import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface import mu.KotlinLogging import picocli.CommandLine import java.io.File import java.io.IOException import java.io.PrintStream import java.nio.charset.Charset import java.nio.file.Paths import java.util.concurrent.Callable @CommandLine.Command( name = "metricgardenerimport", description = ["generates a cc.json file from a project parsed with metric-gardener"], footer = ["Copyright(c) 2022, MaibornWolff GmbH"] ) class MetricGardenerImporter( private val output: PrintStream = System.out ) : Callable<Void>, InteractiveParser { private val logger = KotlinLogging.logger {} private val mapper = jacksonObjectMapper() @CommandLine.Option( names = ["-h", "--help"], usageHelp = true, description = ["Specify: path/to/input/folder/or/file -o path/to/outputfile.json"] ) private var help = false @CommandLine.Parameters( arity = "1", paramLabel = "FOLDER or FILE", description = ["path for project folder or code file"] ) private var inputFile = File("") @CommandLine.Option(names = ["-j", "--is-json-file"], description = ["Input file is a MetricGardener JSON file"]) private var isJsonFile: Boolean = false @CommandLine.Option(names = ["-o", "--output-file"], description = ["output File"]) private var outputFile: String? = null @CommandLine.Option(names = ["-nc", "--not-compressed"], description = ["save uncompressed output File"]) private var compress = true @Throws(IOException::class) override fun call(): Void? { if (!inputFile.exists()) { printErrorLog() return null } if (!isJsonFile) { val tempMgOutput = File.createTempFile("MGOutput", ".json") tempMgOutput.deleteOnExit() val npm = if (isWindows()) "npm.cmd" else "npm" shellRun( command = npm, arguments = listOf( "exec", "-y", "metric-gardener", "--", "parse", inputFile.absolutePath, "--output-path", tempMgOutput.absolutePath ), workingDirectory = ShellLocation.CURRENT_WORKING ) inputFile = tempMgOutput } val metricGardenerNodes: MetricGardenerNodes = mapper.readValue(inputFile.reader(Charset.defaultCharset()), MetricGardenerNodes::class.java) val metricGardenerProjectBuilder = MetricGardenerProjectBuilder(metricGardenerNodes) val project = metricGardenerProjectBuilder.build() ProjectSerializer.serializeToFileOrStream(project, outputFile, output, compress) return null } private fun printErrorLog() { val path = Paths.get("").toAbsolutePath().toString() logger.error { "Current working directory = $path" } logger.error { "Could not find $inputFile" } } companion object { @JvmStatic fun main(args: Array<String>) { CommandLine(MetricGardenerImporter()).execute(*args) } } private fun isWindows(): Boolean { return System.getProperty("os.name").contains("win", ignoreCase = true) } override fun getDialog(): ParserDialogInterface = ParserDialog }
bsd-3-clause
10348ed05b435589f287128e6f0cecaf
36.076923
117
0.681017
4.838143
false
false
false
false
rectangle-dbmi/Realtime-Port-Authority
pat-static/src/main/kotlin/com/rectanglel/patstatic/model/AbstractDataManager.kt
1
3041
package com.rectanglel.patstatic.model import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import java.io.* import java.lang.reflect.Type import java.util.concurrent.locks.ReentrantReadWriteLock /** * Abstract class that has logic that helps with deciding to download from disk or from internet * * * Created by epicstar on 3/12/17. * @author Jeremy Jao */ abstract class AbstractDataManager<out T>(dataDirectory: File, private val staticData: StaticData, private val serializedType: Type, private val cacheFolderName: String) { private val rwl: ReentrantReadWriteLock = ReentrantReadWriteLock() protected val dataDirectory: File = File(dataDirectory, cacheFolderName) private val readLock: ReentrantReadWriteLock.ReadLock get() = rwl.readLock() private val writeLock: ReentrantReadWriteLock.WriteLock get() = rwl.writeLock() protected val gson: Gson get() = GsonBuilder().create() init { this.dataDirectory.mkdirs() } /** * Save the object to disk as JSON into the file * @param obj the object to save * @param file the file to save to * @throws IOException if the serialization fails */ @Throws(IOException::class) protected fun saveAsJson(obj: Any, file: File) { writeLock.lock() val fileWriter = FileWriter(file) val writer = JsonWriter(fileWriter) try { val gson = gson gson.toJson(obj, serializedType, writer) } finally { writer.flush() fileWriter.close() writer.close() writeLock.unlock() } } @Throws(IOException::class) protected fun getFromDisk(file: File): T { // file exists... get from disk if (file.exists()) { readLock.lock() val fileReader = FileReader(file) val jsonReader = JsonReader(fileReader) try { return gson.fromJson(jsonReader, serializedType) } finally { fileReader.close() jsonReader.close() readLock.unlock() } } // if file doesn't exist, save bundled file from installation to disk val fileName = String.format("%s/%s", cacheFolderName, file.name) copyStreamToFile(staticData.getInputStreamForFileName(fileName), file) return getFromDisk(file) } @Throws(IOException::class) protected fun copyStreamToFile(reader: InputStreamReader, file: File) { writeLock.lock() try { reader.use { input -> val fileWriter = FileWriter(file) fileWriter.use { input.copyTo(it) } } } finally { writeLock.unlock() } } }
gpl-3.0
6b5a9b033b7fc40c0e225ddb1eac1e90
29.41
96
0.591582
4.928687
false
false
false
false
kmizu/kollection
src/main/kotlin/com/github/kmizu/kollection/KListExtensions.kt
1
930
package com.github.kmizu.kollection import com.github.kmizu.kollection.type_classes.KMonoid infix fun <T> T.cons(other: KList<T>): KList<T> = KList.Cons(this, other) fun <T> KList(vararg elements: T): KList<T> = run { KList.make(*elements) } infix fun <T> KList<T>.concat(right: KList<T>): KList<T> = run { this.reverse().foldLeft(right){result, e -> e cons result} } fun <T> KList<KList<T>>.flatten(): KList<T> = run { this.flatMap {x -> x} } fun <T, U> KList<Pair<T, U>>.unzip(): Pair<KList<T>, KList<U>> = run { tailrec fun loop(rest: KList<Pair<T, U>>, a: KList<T>, b: KList<U>): Pair<KList<T>, KList<U>> = when(rest) { is KList.Nil -> Pair(a.reverse(), b.reverse()) is KList.Cons<Pair<T, U>> -> loop(rest.tl, rest.hd.first cons a, rest.hd.second cons b) } loop(this, KList.Nil, KList.Nil) } infix fun <T> KList<T>.contains(element: T): Boolean = this.exists {e -> e == element}
mit
ee0273e8d107d82c4ef4b848e9d621d6
33.444444
112
0.626882
2.759644
false
false
false
false
ansman/kotshi
tests/src/test/kotlin/se/ansman/kotshi/TestNullablesWithDefaults.kt
1
2459
package se.ansman.kotshi import com.squareup.moshi.JsonWriter import com.squareup.moshi.Moshi import okio.Buffer import org.junit.Before import org.junit.Test import kotlin.test.assertEquals class TestNullablesWithDefaults { private lateinit var moshi: Moshi @Before fun setup() { moshi = Moshi.Builder() .add(TestFactory) .build() } @Test fun withValues() { val json = """ |{ | "v1": 1, | "v2": "2", | "v3": 3, | "v4": 4, | "v5": 5, | "v6": 6.0, | "v7": 7.0, | "v8": "n/a", | "v9": [ | "Hello" | ] |} """.trimMargin() val expected = NullablesWithDefaults( v1 = 1, v2 = '2', v3 = 3, v4 = 4, v5 = 5L, v6 = 6f, v7 = 7.0, v8 = "n/a", v9 = listOf("Hello") ) expected.testFormatting(json) } @Test fun withNullValues() { val expected = NullablesWithDefaults( v1 = null, v2 = null, v3 = null, v4 = null, v5 = null, v6 = null, v7 = null, v8 = null, v9 = null ) val actual = moshi.adapter(NullablesWithDefaults::class.java).fromJson(""" |{ | "v1": null, | "v2": null, | "v3": null, | "v4": null, | "v5": null, | "v6": null, | "v7": null, | "v8": null, | "v9": null |} """.trimMargin()) assertEquals(expected, actual) } @Test fun withAbsentValues() { val expected = NullablesWithDefaults() val actual = moshi.adapter(NullablesWithDefaults::class.java).fromJson("{}") assertEquals(expected, actual) } private inline fun <reified T> T.testFormatting(json: String) { val adapter = moshi.adapter(T::class.java) val actual = adapter.fromJson(json) assertEquals(this, actual) assertEquals(json, Buffer() .apply { JsonWriter.of(this).run { indent = " " adapter.toJson(this, actual) } } .readUtf8()) } }
apache-2.0
16105ffbff9336841861447afba74bdf
22.653846
84
0.425783
3.966129
false
true
false
false
phxql/grpc-chat-kotlin
server/src/main/kotlin/de/mkammerer/grpcchat/server/Users.kt
1
2233
package de.mkammerer.grpcchat.server import com.google.common.cache.CacheBuilder import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit /** * A user. */ data class User(val username: String, val password: String) { override fun toString(): String = username } /** * A token. */ data class Token(val data: String) { override fun toString() = data } /** * Manages users. */ interface UserService { /** * Registeres a new user. * * @throws UserAlreadyExistsException If the user already exists. */ fun register(username: String, password: String): User /** * Logs the user with the given [username] and [password] in. Returns an access token. */ fun login(username: String, password: String): Token? /** * Validates the [token] and returns the corresponding user. */ fun validateToken(token: Token): User? /** * Determines if the user with the given [username] exists. */ fun exists(username: String): Boolean } /** * Is thrown if the user already exists. */ class UserAlreadyExistsException(username: String) : Exception("User '$username' already exists") class InMemoryUserService( private val tokenGenerator: TokenGenerator ) : UserService { private val users = ConcurrentHashMap<String, User>() private val loggedIn = CacheBuilder.newBuilder().expireAfterAccess(10, TimeUnit.MINUTES).build<Token, User>() override fun exists(username: String): Boolean { return users.containsKey(username) } override fun register(username: String, password: String): User { if (exists(username)) throw UserAlreadyExistsException(username) val user = User(username, password) users.put(user.username, user) return user } override fun login(username: String, password: String): Token? { val user = users[username] ?: return null if (user.password == password) { val token = Token(tokenGenerator.create()) loggedIn.put(token, user) return token } else return null } override fun validateToken(token: Token): User? { return loggedIn.getIfPresent(token) } }
lgpl-3.0
32ce47686f88b176023fdaf1d569e046
25.595238
113
0.664129
4.395669
false
false
false
false
ysl3000/PathfindergoalAPI
PathfinderAPI/src/main/java/com/github/ysl3000/bukkit/pathfinding/goals/PathfinderGoalMoveToLocation.kt
1
1687
package com.github.ysl3000.bukkit.pathfinding.goals import com.github.ysl3000.bukkit.pathfinding.entity.Insentient import com.github.ysl3000.bukkit.pathfinding.pathfinding.Navigation import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderGoal import org.bukkit.Location import org.bukkit.Material class PathfinderGoalMoveToLocation(private val pathfinderGoalEntity: Insentient, private val targetLocation: Location, private val walkSpeed: Double, private val distance: Double) : PathfinderGoal { private val navigation: Navigation = pathfinderGoalEntity.getNavigation() private var isAlreadySet = false override fun shouldExecute(): Boolean { return if (this.isAlreadySet) { false } else pathfinderGoalEntity.getBukkitEntity().location.distanceSquared(targetLocation) > distance } override fun shouldTerminate(): Boolean { isAlreadySet = !pathfinderGoalEntity.getNavigation().isDoneNavigating() return isAlreadySet } override fun init() { if (!this.isAlreadySet) { this.navigation.moveTo(this.targetLocation, walkSpeed) } } override fun execute() { if (pathfinderGoalEntity.getBukkitEntity().location.add(pathfinderGoalEntity.getBukkitEntity().location.direction.normalize()) .block.type != Material.AIR) { pathfinderGoalEntity.jump() } } override fun reset() {} private fun setMessage(message: String) { pathfinderGoalEntity.getBukkitEntity().customName = message pathfinderGoalEntity.getBukkitEntity().isCustomNameVisible = true } }
mit
be63bb1f5e8d613c0fe92e44795f1062
32.76
134
0.707765
5.441935
false
false
false
false